Commit 537dfc86f92fee6872ddc032ca13bf853c821099

Authored by Neil Blakey-Milner
1 parent 0b330503

Add safeShellString, which converts an array of shell arguments to a

strings that's safe to pass to system, popen, exec, &c.


git-svn-id: https://kt-dms.svn.sourceforge.net/svnroot/kt-dms/trunk@3553 c91229c3-7414-0410-bfa2-8a42b809f60b
lib/util/ktutil.inc
... ... @@ -128,6 +128,27 @@ class KTUtil {
128 128 return array(join(" AND ", $aStrings), $aParams);
129 129 }
130 130 // }}}
  131 +
  132 + // function safeShellString
  133 + function safeShellString () {
  134 + $aArgs = func_get_args();
  135 + $aSafeArgs = array();
  136 + if (is_array($aArgs[0])) {
  137 + $aArgs = $aArgs[0];
  138 + }
  139 + $aSafeArgs[] = escapeshellarg(array_shift($aArgs));
  140 + if (is_array($aArgs[0])) {
  141 + $aArgs = $aArgs;
  142 + }
  143 + foreach ($aArgs as $sArg) {
  144 + if (empty($sArg)) {
  145 + $aSafeArgs[] = "''";
  146 + } else {
  147 + $aSafeArgs[] = escapeshellarg($sArg);
  148 + }
  149 + }
  150 + return join(" ", $aSafeArgs);
  151 + }
131 152 }
132 153 // }}}
133 154  
... ...
tests/util/ktutil/testSafeShellString.php 0 → 100644
  1 +<?php
  2 +
  3 +require_once("../../../config/dmsDefaults.php");
  4 +require_once(KT_LIB_DIR . "/util/ktutil.inc");
  5 +
  6 +$aSource = array(
  7 + array('unzip', "-q", "-j", "-n", "-d", '/tmp', '5 July 2005 Pricelist - Rectron(cpt).zip'),
  8 + array('unzip', "-q", "-j", "-n", "-d", '/tmp', "5'th July 2005 Pricelist - Rectron(cpt).zip"),
  9 + array('echo', ''),
  10 + array('echo', ' '),
  11 +);
  12 +
  13 +$aExpectedResults = array(
  14 + "'unzip' '-q' '-j' '-n' '-d' '/tmp' '5 July 2005 Pricelist - Rectron(cpt).zip'",
  15 + "'unzip' '-q' '-j' '-n' '-d' '/tmp' '5'\''th July 2005 Pricelist - Rectron(cpt).zip'",
  16 + "'echo' ''",
  17 + "'echo' ' '",
  18 +);
  19 +
  20 +$aResults = array();
  21 +
  22 +foreach ($aSource as $aArgs) {
  23 + $aResults[] = KTUtil::safeShellString($aArgs);
  24 +}
  25 +
  26 +if ($aResults === $aExpectedResults) {
  27 + print "Success!\n";
  28 +} else {
  29 + print "Failure!\n";
  30 + print "Received: " . print_r($aResults, true) . "\n";
  31 + print "Expected: " . print_r($aExpectedResults, true) . "\n";
  32 +}
  33 +
  34 +?>
... ...