{(', '/(\\$\\{[^{}]*\\})/e', "WikiShExpand1Var(\$pagename, PSS('$1'))"); Markup('{earlymx(', '<{$var}', '/\\{earlymx(\\(\\w+\\b.*?\\))\\}/e', "MarkupExpression(\$pagename, PSS('$1'))"); define(WIKISH_ACTION_OPTIONS, 0x01); define(WIKISH_ACTION_VARIABLE, 0x02); define(WIKISH_ACTION_WILDCARD, 0x04); define(WIKISH_ACTION_DEFAULT, WIKISH_ACTION_VARIABLE|WIKISH_ACTION_OPTIONS); function WikiShCompatible($pagename,&$opt,&$args,$action=WIKISH_ACTION_DEFAULT) { if ($action & WIKISH_ACTION_OPTIONS) InitOpts($pagename,'', $opt, $args, ($action & WIKISH_ACTION_VARIABLE)); if ($action & WIKISH_ACTION_WILDCARD) ExpandWildcards($pagename, $opt, $args); } Markup('WikiShControlPanel', '<{$var}', '/\\(:wikish_controlpanel\\s*(\\w*):\\)/e', "WikiShControlPanel(\$pagename, strtoupper('$1'))"); function WikiShControlPanel($pagename, $method) { global $InputValues, $FmtPV, $WikiShVars; global $HTMLStylesFmt; $func = 'ControlPanel()'; $histwidth=95; if ($method == "GET") $method_array = $_GET; else { $method = 'POST'; $method_array = $_POST; } foreach ($method_array as $k=>$v) { $foo = htmlspecialchars(stripmagic($v),ENT_NOQUOTES); $InputValues[$k] = $foo; $foo = preg_replace('/\\\\/', '\\\\\\\\\\\\', $foo); $foo = preg_replace("/(?$WikiShVars['HISTSIZE']) $rtn.=" ''(NOTE: History file Needs purging: $histcnt)''"; $rtn .= "\n(:cell style='text-align:left; font-weight:bold;':)[[$WikiShVars[HISTFILE]?action=edit|Favorites]]\n"; $i = 0; $rtn .= "\n(:cellnr:) "; if ($histarray) { if (sizeof($histarray) > $WikiShVars['HISTSIZE']) $histarray = array_slice($histarray, -$WikiShVars['HISTSIZE']); foreach ($histarray as $hist) { if ($i != 0) $rtn .= "\n"; $tmp = str_replace(":", ":", $hist[1]); $rtn .= "(:input select name=hist value=$hist[0] label=\"" . htmlspecialchars((strlen($tmp) > $histwidth) ? substr($tmp, 0, $histwidth-3).'...' : mystr_pad($tmp, $histwidth, ' ')) . "\" " . (($i == 0) ? "size=5 style=\"width:95%\" size=5" : "") . ":)"; $i++; } } else $rtn .= "No History. Use \"Execute Command\" button to create history."; $i = 0; $rtn .= "\n(:cell:)"; if ($favsarray) foreach ($favsarray as $favs) { if ($i != 0) $rtn .= "\n"; $tmp = str_replace(":", ":", $favs[1]); $rtn .= "(:input select name=favs value=$favs[0] \"" . htmlspecialchars((strlen($tmp) > $histwidth) ? substr($tmp, 0, $histwidth-3).'...' : mystr_pad($tmp, $histwidth, ' ')) . "\" " . (($i == 0) ? "size=5 style=\"width:95%\"" : "") . ":)"; $i++; } else $rtn .= "No Favorites. Use \"Copy to Favorites\" button under history."; $rtn .= "\n\n"; $rtn .= "\n(:cellnr:)(:input submit do_hist \"Execute History Command\":) (:input submit load_hist \"Load History Command\":) (:input submit cp2favs \"Copy To Favorites\":)"; $rtn .= "\n(:cell:)(:input submit do_favs \"Execute Favorites Command\":) (:input submit load_favs \"Load Favorites Command\":) (:input submit del_favs \"Delete From Favorites\":)"; $rtn .= "\n(:tableend:)\n"; } $rtn .= "\n(:input default DEFAULT_DEBUG $WikiShVars[DEFAULT_DEBUG]:)"; $rtn .= "\n(:input default HISTSIZE $WikiShVars[HISTSIZE]:)"; $rtn .= "\n(:input default NOHIST $WikiShVars[NOHIST]:)"; $rtn .= "\n\n||"; $rtn .= "\n||! Control Panel Interface Settings ||||"; $rtn .= "\n|| Debug Level:||(:input text name=DEFAULT_DEBUG:) ''(1-5, 1=very detailed, 5=nothing)''||"; $rtn .= "\n|| Control Panel Debug:||(:input checkbox name=panel_dbg value=checked:)||"; $rtn .= "\n|| History Count:||(:input text name=HISTSIZE:)||\n"; $rtn .= "\n|| Suppress History & Favorites:||(:input checkbox name=NOHIST value=checked:) ''(Improves performance when HISTFILE is large)''||\n"; $rtn .= "\n\\\\\n\\\\\n====\nDEBUG\n(:messages:)\n"; $WikiShVars['DEBUGLEVEL'] = $WikiShVars['DEFAULT_DEBUG']; return($rtn); } $MarkupExpr["wikish_form"] = 'WikiShForm($pagename, @$argp, @$args)'; function WikiShForm($pagename, $opt, $args) { global $InputValues, $FmtPV, $WikiShVars; $func = 'WikiShForm()'; wdbg(4,"$func: Entering"); SDV($opt['method'], 'GET'); $rtn = ''; foreach ($args as $arg) { $arg = strtoupper($arg); switch ($arg) { case 'QUICKFORM': $rtn = "(:input form method=$method:)\n"; $rtn .= "(:input hidden name=n value={\$FullName}:)\n"; break; case 'REDIRECT': $target = array($opt['target']); ExpandVars($pagename, $opt, $target); Redirect(PSS($target[0])); return; break; case 'PROCESS': foreach ($_REQUEST as $k=>$v) { if (is_array($v)) { $foo = ''; foreach ($v as $i=>$val) { $tmp = htmlspecialchars($val,ENT_NOQUOTES); $InputValues[$k][$i] = $tmp; $foo .= (($foo)?',':'') . $tmp; } } else { $foo = htmlspecialchars($v,ENT_NOQUOTES); $InputValues[$k] = $foo; } $foo = preg_replace('/\\\\/', '\\\\\\\\\\\\', $foo); $foo = preg_replace("/(?= $len) return ($str); for ($i = strlen($str); $i < $len; $i++) $str .= ' '; return ($str); } $MarkupExpr['wikish'] = 'WikiSh($pagename, $params)'; function WikiSh($pagename, $expr) { if (WikiShNotNow()) return(Keep('', 'P')); wdbg(4,"WikiSh(): Entering"); unhtmlspecialchars($expr); $exiting = false; $rtn = WikiShRunExpr($pagename, $expr, $exiting); wdbg(4,"WikiSh(): Exiting"); return(Keep($rtn, 'P')); } function WikiShRunExpr($pagename, $expr, &$exiting) { global $WikiShVars; static $Level=-1; $Level++; $func = "WikiShRunExpr($Level)"; wdbg(4,"$func: Entering"); wdbg(3,"$func: expr=$expr"); $iffi = '(?>if\s+)([^;]+)(?>;\s*)' . '(?>then\s*;?\s*)' . '((?:(?:(?:(?!\bif\b)(?!\belse\b)(?!\bfi\b).)+)|(?R)+)+)\s*' . '(?:' . '(?>else\s*;?\s*)' . '((?:(?:(?:(?!\bif\b)(?!\belse\b)(?!\bfi\b).)+)|(?R)+)+)' . ')?\s*' . '(?>fi;?\s*)'; $dodonere= '(?>(?:while|for))\s+([^;]+);\s*'. '(?>do\s*;?\s*)'. '('. '(?:'. '(?:(?!\bfor\b)(?!\bwhile\b)(?!\bdone\b).)+'. '|'. '(?R)'. ')+'. ')\s*(?>done\s*;?\s*)'; $sourceit = "^source\s+([\w.#:\/]+)\s*([^;]*);?\s*"; $rtn = ''; $expr = preg_replace("/^\s*/", "", $expr); $lastexpr = 'x' . $expr; while (!$exiting && $expr && $lastexpr != $expr) { wdbg(3,"$func: Current wikish chunk: >>$expr<<"); $lastexpr = $expr; if (preg_match("/^if\b/", $expr) && preg_match("/$iffi/", $expr, $match)) { list($foo, $testexpr, $ifexpr, $elseexpr) = $match; wdbg(3,"$func: IF-THEN-ELSE MATCHED: $foo"); $rtn = WCS($rtn, WikiShRunExpr($pagename, $testexpr, $exiting)); if (!$exiting) { if ($WikiShVars['STATUS'] == 0) { $rtn = WCS($rtn, WikiShRunExpr($pagename, $ifexpr, $exiting)); } else { $rtn = WCS($rtn, WikiShRunExpr($pagename, $elseexpr, $exiting)); } } } elseif (preg_match("/^for\b/", $expr) && preg_match("/$dodonere/", $expr, $match)) { list($foo, $tmp, $doexpr) = $match; if (!preg_match("/(\w+)\s+in\s+(\S.*)$/", $tmp, $match)) { wdbg(4,"$func: ERROR: preg_match should not have failed >>$tmp<<"); $Level--; return (''); } list($tmp, $varname, $list) = $match; wdbg(3,"$func: FOR-IN-DO-DONE MATCHED: $foo"); $list = array($list); ExpandVars($pagename, $opt, $list); $list = explode(" ", implode(" ", $list)); ExpandWildcards($pagename, array(), $list, true, true, true); foreach ($list as $l) { $WikiShVars[$varname] = $l; $rtn = WCS($rtn, WikiShRunExpr($pagename, $doexpr, $exiting)); if ($exiting) break; } } elseif (preg_match("/^while\b/", $expr) && preg_match("/$dodonere/", $expr, $match)) { list($foo, $testexpr, $doexpr) = $match; wdbg(3,"$func: WHILE-DO MATCHED: $foo"); $rtn = WCS($rtn, WikiShRunExpr($pagename, $testexpr, $exiting)); while (!$exiting && $WikiShVars['STATUS'] == 0) { $rtn=WCS($rtn, WikiShRunExpr($pagename, $doexpr, $exiting)); if (!$exiting) $rtn=WCS($rtn, WikiShRunExpr($pagename, $testexpr, $exiting)); } } elseif (preg_match("/$sourceit/", $expr, $match)) { list($foo, $sourcefile, $args) = $match; wdbg(3,"$func: SOURCE MATCHED: $foo"); $WikiShVars[0] = $sourcefile; $i = 1; if ($args) { foreach (explode(" ", $args) as $arg) { $WikiShVars[$i++] = $arg; } } $WikiShVars['#'] = $i - 1; $page = ShReadPage($pagename, array(), WIKIPAGEID . $sourcefile, true); $code = WikiShParseCode(unhtmlspecialchars($page['text'])); $expr = substr($expr, 0, strlen($foo)) . $code . substr($expr, strlen($foo)); } elseif (preg_match("/^([^;]*)\s*\|\s*(?=while)/", $expr, $match)) { list($foo, $doexpr) = $match; wdbg(3,"$func: PIPE TO WHILE EXPR MATCHED: $foo"); WikiShRunExprNode($pagename, $doexpr, $rtn, $exiting, true); } elseif (preg_match("/^([^;]*)\s*;?\s*/", $expr, $match)) { list($foo, $doexpr) = $match; wdbg(3,"$func: SIMPLE EXPR MATCHED: $foo"); WikiShRunExprNode($pagename, $doexpr, $rtn, $exiting); } $expr = substr($expr, strlen($foo)); } $Level--; return($rtn); } function WCS($str1, $str2) { return ($str1 . (($str1 && $str2) ? "\n" : "") . $str2); } function WikiShRunExprNode($pagename, $expr, &$rtn, &$exiting, $grab_pipe=false) { global $WikiShPipeText, $WikiShPipeActive; global $WikiShVars; global $KeepToken, $KPV, $MarkupExpr; $func = 'WikiShRunExprNode()'; $rpat = "/$KeepToken(\\d+P)$KeepToken/e"; $rrep = '$KPV[\'$1\']'; $expr = preg_replace($rpat, '\'"\'.'.$rrep.'.\'"\'', $expr); while (preg_match("/`([^`]+)`/", $expr, $m)) { $tmp=''; wdbg(3,"$func: Expanding vars on \"$m[1]\""); $x = array($m[1]); ExpandVars($pagename, array(), $x); $m[1] = $x[0]; wdbg(3,"$func: Running backquotes on \"$m[1]\""); WikiShRunExprNode($pagename, $m[1], $tmp, $exiting); wdbg(3,"$func: Replacing >>$m[1]<< with >>$tmp<<"); $expr = str_replace($m[0], $tmp, $expr); wdbg(3,"$func: Resulting expr = \"$expr\""); } $expr = preg_replace('/([\'"])(.*?)\\1/e', "Keep(PSS('$2'),'P')", $expr); $exprlist = preg_split("/\s*;\s*/", $expr, -1, PREG_SPLIT_NO_EMPTY); foreach ($exprlist as $expr) { $explist = preg_split("/\s*(\|\||&&)\s*/", $expr, -1, PREG_SPLIT_NO_EMPTY|PREG_SPLIT_DELIM_CAPTURE); $exlist = array(); $lastop = ''; foreach ($explist as $exp) { if ($exp == '||' || $exp == '&&') { $lastop = $exp; continue; } $exlist[] = $lastop . $exp; } foreach ($exlist as $ex) { $First2 = substr($ex, 0, 2); if (($First2 == '&&' && $WikiShVars['STATUS'] != 0) || ($First2 == '||' && $WikiShVars['STATUS'] == 0)) continue; if ($First2 == '&&' || $First2 == '||') $ex = substr($ex, 2); if (!preg_match("/^\s*(!)?\s*(.*)$/s", $ex, $match)) WikiShStdErr($pagename, $opt, "ERROR: $func: Non-matching regex for negation. Attempting to continue"); $negate = $match[1]; $ex = $match[2]; $elist = preg_split("/\s*\|\s*/", $ex, -1, PREG_SPLIT_NO_EMPTY); foreach ($elist as $e) { if (preg_match("/^\s*exit(?:\s+(\d+))?\s*$/", $e, $m)) { wdbg(4,"$func: Found exit. Getting out of dodge..."); if (!$m || $m===0) $WikiShVars['STATUS'] = $m; $exiting = true; break 3; } else { $x = array($e); ExpandVars($pagename, array(), $x); $e = $x[0]; if (preg_match('/^\\s*(\\w+)\\b/', $e, $match) && !@$MarkupExpr[$match[0]]) { $tmp = "UNKNOWN MARKUP EXPRESSION COMMAND: $match[0]"; $WikiShVars['STATUS'] = 1; } else { $tmp = MarkupExpression($pagename, '(' . $e . ')'); } $WikiShPipeText = $tmp; $WikiShPipeActive = true; } } if ($negate) $WikiShVars['STATUS'] = !$WikiShVars['STATUS']; $WikiShPipeActive = $WikiShPipeText = false; } if ($rtn) $rtn .= "\n" . $tmp; else $rtn = $tmp; } if ($grab_pipe) { $WikiShPipeText = $rtn; $WikiShPipeActive = true; $rtn = ''; } } $MarkupExpr["${WikiShMXPrefix}basename"] = 'WikiShBasename($pagename, @$argp, @$args)'; function WikiShBasename($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $WikiShVars['STATUS'] = 0; return (basename($args[0])); } $MarkupExpr["${WikiShMXPrefix}cat"] = 'WikiShCat($pagename, @$argp, @$args)'; function WikiShCat($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func="Cat()"; wdbg(4,"Cat(): Entering"); InitOpts($pagename, '', $opt, $args); ExpandWildcards($pagename, $opt, $args, false, false, false); SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); $newrows = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } $textrows = explode("\n", $page['text']); if ($opt['file_prefix']) $array_prefix = array(WShReplace($opt, $page, $opt['file_prefix'])); else $array_prefix = array(); $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); if ($line_prefix || $line_suffix) for ($i = 0; $i < sizeof($textrows); $i++) { if (strstr($opt['line_prefix'], 'LINENO')) $line_prefix = WShReplace($opt, $page, $opt['line_prefix'], $i+1); $textrows[$i] = $line_prefix . $textrows[$i] . $line_suffix; } $newrows = array_merge($newrows, $array_prefix, $textrows); } $WikiShVars['STATUS'] = 0; return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}chmod"]='WikiShChmod($pagename, @$argp, @$args)'; function WikiShChmod() { $page = RetrieveAuthPage($pagename,$auth,$authprompt=true); $newpage=$page; $newpage["passwdedit"] = "@sysadmin"; UpdatePage($pagename,$page,$newpage); } $MarkupExpr["${WikiShMXPrefix}cp"] = 'WikiShCp($pagename, @$argp, @$args)'; function WikiShCp($pagename, $opt, $args) { global $EnableWikiShWritePage, $EnableWikiShOverwritePage, $EnableWikiShCreatePage; global $WorkDir; global $WikiShVars; if (WikiShNotNow()) return(''); $func = "cp(" . implode(" ", $args) . ")"; wdbg(4,"$func: Entering"); SDV($EnableWikiShWritePage, false); SDV($EnableWikiShOverwritePage, false); SDV($EnableWikiShCreatePage, false); if (!$EnableWikiShWritePage) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to write pages. Not enabled."); $WikiShVars['STATUS'] = 4; return (''); } InitOpts($pagename, '', $opt, $args); $Target = array_pop($args); ExpandWildcards($pagename, $opt, $args, false, false, true); SetDefaultOpt($opt, 'q', false); SetDefaultOpt($opt, 'trial', false); if (isatextfile('', $Target)) { $Target = substr($Target, strlen(TEXTFILEID)); $Target_Type = 'text'; if (file_exists($Target)) $TargetIsDir = is_dir($Target); else { $TargetIsDir = false; if (sizeof($args) > 1) { WikiShStdErr($pagename, $opt, "ERROR: $func: Cannot copy multiple files to non-directory destination $Target"); $WikiShVars['STATUS'] = 2; return (''); } } } else { $Target_Type = 'wiki'; if (!strstr($Target, '.') && !strstr($target, '/')) $TargetIsDir = true; } if (sizeof($args) > 1 && !$TargetIsDir) { WikiShStdErr($pagename, $opt, "ERROR: $func: Cannot copy multiple files to non-" . (($Target_Type == 'wiki') ? "group" : "directory") . " destination $Target"); $WikiShVars['STATUS'] = 2; return (''); } if (sizeof($args) < 1) { WikiShStdErr($pagename, $opt, "ERROR: $func: No Source file specified to copy to destination $Target"); $WikiShVars['STATUS'] = 2; return (''); } $newrows = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if ($page[filename] == '-' && $page['type'] == 'inline' && $TargetIsDir) { WikiShStdErr($pagename, $opt, "ERROR: $func: Cannot copy inline file to directory destination $Target"); continue; } if ($TargetIsDir) { if ($Target_Type == 'wiki') { $tmp = preg_replace("/^.*[\/\.]/", "", $page[filename]); $tgt = "$Target.$tmp"; } else $tgt = "$Target/$page[filename]"; } else $tgt = $Target; $page['type'] = $Target_Type; if ($opt['trial']) { if (!$opt['q']) $newrows[] = "TRIAL copying " . $page['filename'] . " to $tgt"; } else { if (!$opt['q']) $newrows[] = 'Copying: ' . $page['filename'] . " to $tgt"; if ($opt['encrypt'] && function_exists('WikiShEncrypt')) $page['text'] = WikiShEncrypt($pagename, $opt, $page['text']); if (!WikiShWrite($pagename, $opt, $tgt, $page['type'], $page['text'], $page)) { $WikiShVars['STATUS'] = 2; return(''); } } } $WikiShVars['STATUS'] = 0; return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}cut"] = 'WikiShCut($pagename, @$argp, @$args)'; function WikiShCut($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = 'Cut()'; wdbg(4,"$func: Entering"); InitOpts($pagename, 'd:f:c:', $opt, $args); SetDefaultOpt($opt, 'f', ''); SetDefaultOpt($opt, 'c', ''); SetDefaultOpt($opt, 'd', "\t"); SetDefaultOpt($opt, 'ofs', $opt['d']); if (is_array($opt['f'])) $flddef = implode(',', $opt['f']); else $flddef = $opt['f']; if (is_array($opt['c'])) $chardef = implode(',', $opt['c']); else $chardef = $opt['c']; ExpandWildcards($pagename, $opt, $args, false, false, false); SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); if (!$opt['f'] && !$opt['c']) { $WikiShVars['STATUS'] = 4; WikiShStdErr($pagename, $opt, "ERROR: $func: either -f or -c must be specified"); return(''); } $newrows = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } $textrows = explode("\n", $page['text']); if ($opt['file_prefix']) $array_prefix = array(WShReplace($opt, $page, $opt['file_prefix'])); else $array_prefix = array(); $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); for ($i = 0; $i < sizeof($textrows); $i++) { if (strstr($opt['line_prefix'], 'LINENO')) $line_prefix = WShReplace($opt, $page, $opt['line_prefix'], $i+1); $line = ''; if ($flddef) { $flds = explode(',', $flddef); $fldcnt=0; foreach ($flds as $fld) { $lineflds = split("$opt[d]", $textrows[$i]); if (strstr($fld, '-')) { if (!preg_match("/(\d+)-(\d*)/", $fld, $startend)) { WikiShStdErr($pagename, $opt, "ERROR: $func: Non-matching fld def $fld"); } else { if ($startend[2]) for ($j = $startend[1]-1; $j < $startend[2]; $j++) { $line .= (($fldcnt>0)?$opt['ofs']:'') . $lineflds[$j]; $fldcnt++; } else for ($j = $startend[1]-1; $j < sizeof($lineflds); $j++) { $line .= (($fldcnt>0)?$opt['ofs']:'') . $lineflds[$j]; $fldcnt++; } } } else { $line .= (($fldcnt>0)?$opt['ofs']:'') . $lineflds[$fld-1]; $fldcnt++; } } } if ($chardef) { $chars = explode(',', $chardef); foreach ($chars as $char) { if (strstr($char, '-')) { if (!preg_match("/(\d+)-(\d*)/", $char, $startend)) { WikiShStdErr($pagename, $opt, "ERROR: $func: Non-matching char def $char"); } else { if ($startend[2]) $line .= substr($textrows[$i], $startend[1]-1, ($startend[2]-$startend[1]+1)); else $line .= substr($textrows[$i], $startend[1]-1); } } else { $line .= substr($textrows[$i], $char-1, 1); } } } $textrows[$i] = $line_prefix . $line . $line_suffix; } $newrows = array_merge($newrows, $array_prefix, $textrows); } $WikiShVars['STATUS'] = 0; return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}diff"] = 'WikiShDiff($pagename, @$argp, @$args)'; function WikiShDiff($pagename, $opt, $args) { global $WikiShVars, $DiffFunction; if (WikiShNotNow()) return(''); $func = "Diff()"; wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $args); SetDefaultOpt($opt, 'q', false); ExpandWildcards($pagename, $opt, $args); if (sizeof($args) != 2) { WikiShStdErr($pagename, $opt, "ERROR: $func: Must specify exactly 2 pagenames."); $WikiShVars['STATUS'] = 2; return(''); } if (!($p1 = ShReadPage($pagename, $opt, $args[0]))) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to read page=$args[0]."); $WikiShVars['STATUS'] = 2; return(''); } if (!($p2 = ShReadPage($pagename, $opt, $args[1]))) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to read page=$args[1]."); $WikiShVars['STATUS'] = 2; return(''); } $diff_out = $DiffFunction($p1['text']."\n", $p2['text']."\n"); if ($diff_out) $WikiShVars['STATUS'] = 1; else $WikiShVars['STATUS'] = 0; if ($opt['q']) return(''); else return ($diff_out); } $MarkupExpr["${WikiShMXPrefix}dirname"] = 'WikiShDirname($pagename, @$argp, @$args)'; function WikiShDirname($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $WikiShVars['STATUS'] = 0; return (dirname($args[0])); } $MarkupExpr["${WikiShMXPrefix}echo"] = 'WikiShEcho($pagename, @$argp, @$args)'; function WikiShEcho($pagename, $opt, $args) { global $WikiShVars, $EnableWikiShRawEcho; if (WikiShNotNow()) return(''); $func = "Echo()"; wdbg(4,"$func: Entering: " . implode(" ", $args)); InitOpts($pagename, '', $opt, $args); if ($opt['w']) ExpandWildcards($pagename, $opt, $args, true, true); $out = ''; foreach ($args as $arg) { $out .= (($out) ? ' ' : '') . $arg; } $out = str_replace("\\t", "\t", $out); $out = explode("\\n", $out); $WikiShVars['STATUS'] = 0; if ($EnableWikiShRawEcho && $opt['raw']) echo print_r($out, true) . "
\n"; else return (ShPostProcess($pagename, $opt, $out)); } $MarkupExpr["${WikiShMXPrefix}false"] = 'WikiShFalse($pagename, @$argp, @$args)'; function WikiShFalse($pagename, $opt, $args) { global $WikiShVars; WikiShNotNow(); $func = "False()"; wdbg(4,"$func: Entering"); $WikiShVars['STATUS'] = 1; return(''); } $MarkupExpr["${WikiShMXPrefix}grep"] = 'WikiShGrep($pagename, @$argp, @$args)'; function WikiShGrep($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func="Grep()"; wdbg(4,"$func: Entering"); $WikiShVars['STATUS'] = 1; InitOpts($pagename, '', $opt, $args); $expr = array_shift($args); ExpandWildcards($pagename, $opt, $args, false, false, false); SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); SetDefaultOpt($opt, 'highlight', false); SetDefaultOpt($opt, 'fixed-strings', false); if (@$opt['F']) $opt['fixed-strings'] = true; SetDefaultOpt($opt, 'q', false); if ($expr == '' || sizeof($args) == 0) { $WikiShVars['STATUS'] = 2; return ''; } if (!isset($opt['files-with-matches'])) $opt['files-with-matches'] = @$opt['l']; $reverse = (@$opt['v'] || @$opt['reverse']); $regexopt = (@$opt['i'] || @$opt['ignorecase'] || @$opt['ic']) ? 'i' : ''; $newrows = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } if ($opt['targets']) $page['text'] = str_replace(",", "\n", $page['targets']); $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); $file_prefix = WShReplace($opt, $page, $opt['file_prefix']); if ($opt['files-with-matches']) { if (($opt['fixed-strings'] && strstr($page['text'], $expr)) || (!$opt['fixed-strings'] && preg_match("/$expr/m$regexopt", $page['text']))) { if (!$reverse) { if ($file_prefix) $newrows[] = $file_prefix; $newrows[] = $line_prefix . $page['filename'] . $line_suffix; $WikiShVars['STATUS'] = 0; } } elseif ($reverse) { if ($file_prefix) $newrows[] = $file_prefix; $newrows[] = $line_prefix . $page['filename'] . $line_suffix; $WikiShVars['STATUS'] = 0; } continue; } $textrows = explode("\n", $page['text']); $str = $textrows[0]; if ($file_prefix) $newrows[] = $file_prefix; foreach ($textrows as $row) { if (($opt['fixed-strings'] && strstr($row, $expr)) || (!$opt['fixed-strings'] && preg_match("/($expr)/$regexopt", $row))) { if (!$reverse) { if ($opt['highlight']) { $row = preg_replace("/($expr)/$regexopt", "'''$1'''", $row); } $newrows[] = $line_prefix . $row . $line_suffix; $WikiShVars['STATUS'] = 0; } } elseif ($reverse) { $newrows[] = $line_prefix . $row . $line_suffix; $WikiShVars['STATUS'] = 0; } } } if ($opt['q']) $newrows = array(); return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}head"] = 'WikiShHead($pagename, @$argp, @$args)'; function WikiShHead($pagename, $opt, $filelist) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = 'Head()'; wdbg(4,"$func: Entering"); InitOpts($pagename, 'n:', $opt, $filelist); SetDefaultOpt($opt, 'n', 10); $opt['startline'][] = 1; $opt['endline'][] = $opt['n']; $WikiShVars['STATUS'] = 0; return(ExtractLines($pagename, $opt, $filelist, $func)); } $MarkupExpr["${WikiShMXPrefix}ls"] = 'WikiShLs($pagename, @$argp, @$args)'; function WikiShLs($pagename, $opt, $args) { global $WikiShVars, $SearchPatterns, $WikiLibDirs; if (WikiShNotNow()) return(''); $WikiShVars['STATUS'] = 0; $func = "Ls():"; wdbg(4,"$func Entering"); InitOpts($pagename, '', $opt, $args); if (!$args) $args[] = '*.*'; if (sizeof($args) == 1 && $args[0] == '*.*' && !@$opt['line_prefix'] && !@$opt['line_suffix'] && !@$opt['file_prefix']) $QuickOptimize = true; if (!@$opt['list'] && @$opt['a']) $opt['list'] = 'all'; ExpandWildcards($pagename, $opt, $args, true, false, false); if ($opt['l'] || $opt['t'] || $opt['S']) { foreach ($args as $k => $arg) { if ($opt['OS'] || $opt['os'] || isatextfile('', $arg)) { $fileinfo = false; if (isatextfile('', $arg)) { $arg = $args[$k] = substr($arg, strlen(TEXTFILEID)); if (file_exists($arg)) $fileinfo = stat($arg); } else { foreach ($WikiLibDirs as $dir) { $pagefile = $dir->pagefile($arg); if (file_exists($pagefile) && $fileinfo = stat($pagefile)) break; } } if (@$fileinfo) { if (@$foo < 3) { $foo = @$foo+1; } $size[$k] = $fileinfo['size']; $author[$k] = $fileinfo['uid']; $time[$k]=($opt['c'] ? $fileinfo['ctime'] : $fileinfo['mtime']); } else { $WikiShVars['STATUS'] = 2; $args[$k] = "FILE NOT FOUND: $arg"; $size[$k] = 0; $author[$k] = 'UnKnOwN'; $time[$k] = 0; } } else { if (PageExists($arg)) $page = RetrieveAuthPage($arg, 'read', false); else $page = false; if (!$page) { $WikiShVars['STATUS'] = 2; $args[$k] = "PAGE NOT FOUND: $arg"; $size[$k] = 0; $author[$k] = 'UnKnOwN'; $time[$k] = 0; } else { $size[$k] = strlen($page['text']); if ($opt['c']) { $author[$k] = ($page['cauthor']?$page['cauthor']:$page['author']); $time[$k] = $page['ctime']; } else { $author[$k] = $page['author']; $time[$k] = $page['time']; } } } } } else { foreach ($args as $k => $arg) { if (isatextfile('', $arg)) { $args[$k] = $arg = substr($arg, strlen(TEXTFILEID)); if (!file_exists($arg)) $args[$k] = "FILE NOT FOUND: $arg"; } else { if (isabadfile('', $arg) || !PageExists($arg)) { $WikiShVars['STATUS'] = 2; $args[$k] = "PAGE NOT FOUND: $arg"; } } } } if ($opt['sort'] !== false) { if (!$opt['t'] && !$opt['S'] && !$opt['l']) { if ($opt['r']) rsort($args); else sort($args); } else { if ($opt['t']) { $k1 = &$time; $k2 = &$args; $k3 = &$size; $k4 = &$author; $k1a= SORT_NUMERIC; $k2a=SORT_STRING; $k1b = ($opt['r']?SORT_ASC:SORT_DESC); } elseif ($opt['S']) { $k1 = &$size; $k2 = &$args; $k3 = &$time; $k4 = &$author; $k1a= SORT_NUMERIC; $k2a=SORT_STRING; $k1b = ($opt['r']?SORT_ASC:SORT_DESC); } else { $k1 = &$args; $k2 = &$size; $k3 = &$time; $k4 = &$author; $k1a= SORT_STRING; $k2a=SORT_NUMERIC; $k1b = ($opt['r']?SORT_DESC:SORT_ASC); } array_multisort($k1, $k1a, $k1b, $k2, $k2a, $k3, $k4); } } if ($QuickOptimize) { $newrows = $args; } else { $regexopt = (@$opt['i'] || @$opt['ignorecase'] || @$opt['ic']) ? 'i' : ''; $newrows = array(); foreach ($args as $k => $filename) { $page['filename'] = $filename; $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); $file_prefix = WShReplace($opt, $page, $opt['file_prefix']); if ($file_prefix) $newrows[] = $file_prefix; if ($opt['l']) { $newrows[] = $line_prefix . sprintf("%15.15s%8d %s %s", $author[$k], $size[$k], strftime("%b %d %H:%M", $time[$k]), $filename) . $line_suffix; } else { $newrows[] = $line_prefix . $filename . $line_suffix; } } } return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}mv"] = 'WikiShMv($pagename, @$argp, @$args)'; function WikiShMv($pagename, $opt, $filelist) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = "Mv()"; wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $filelist); WikiShCp($pagename, $opt, $filelist); if ($WikiShVars['STATUS'] != 0) { WikiShStdErr($pagename, $opt, "ERROR: $func: NOT removing source files. Errors creating destination files."); return(''); } $Target = array_pop($filelist); WikiShRm($pagename, $opt, $filelist); return(''); } $MarkupExpr["${WikiShMXPrefix}null"] = 'WikiShNull($pagename, @$argp, @$args)'; function WikiShNull($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = "Null()"; wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $args); $WikiShVars['STATUS'] = 0; return(''); } $MarkupExpr["${WikiShMXPrefix}read"] = 'WikiShRead($pagename, @$argp, @$args)'; function WikiShRead($pagename, $opt, $args) { global $WikiShVars, $WikiShPipeActive, $WikiShPipeText; static $ReadSet; if (WikiShNotNow()) return(''); $func = "Read()"; wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $args, true, false); if (@$opt['clear']) { unset($ReadSet[$set]); return(''); } foreach ($args as $var) $WikiShVars[$var] = ''; if ($opt['set']) $set = $opt['set']; else $set = 0; if ($opt['restoreset']) { if(!session_id()) session_start(); if (!isset($_SESSION['WIKISH_READ'][$set])) $WikiShVars['STATUS'] = 3; $ReadSet[$set] = $_SESSION['WIKISH_READ'][$set]; if (!@$opt['prev'] && !@$opt['next'] && !@$opt['goto'] && !@$opt['rewind'] && !@$opt['linecount'] && !@$opt['status'] && !@$opt['initialize']) { return(''); } } if (@$opt['initialize']) unset($ReadSet[$set]); if (!@$opt['prev'] && !isset($opt['next']) && !@$opt['goto'] && !@$opt['rewind'] && !@$opt['linecount'] && !@$opt['status'] && !@$opt['initialize'] && isset($ReadSet[$set])) $opt['next'] = 1; if (@$opt['clearset']) { if(!session_id()) session_start(); unset($_SESSION['WIKISH_READ'][$set]); if (!@$opt['prev'] && !@$opt['next'] && !@$opt['goto'] && !@$opt['rewind'] && !@$opt['linecount'] && !@$opt['status'] && !@$opt['initialize']) { return(''); } } if (!isset($ReadSet[$set]) && $opt['initialize'] !== false) { wdbg(4,"$func: Initializing"); if (!isset($opt['stdin']) && !$WikiShPipeActive) { if (@$opt['status'] || @$opt['linecount']) { return (ShPostProcess($pagename, $opt, array(''))); } wdbg(4,"$func: stdin not set. exiting with error"); WikiShStdErr($pagename, $opt, "ERROR: $func: stdin not set"); $WikiShVars['STATUS'] = 2; return(''); } if ($WikiShPipeActive) { $page['text'] = $WikiShPipeText; $WikiShPipeText = $WikiShPipeActive = false; } else { if (!isawikipage('', $opt['stdin']) && !isatextfile('', $opt['stdin'])) $opt['stdin'] = WIKIPAGEID . $opt['stdin']; $page = ShReadPage($pagename, $opt, $opt['stdin']); } if (strstr($page['text'], "\r")) $ReadSet[$set]['text'] = explode("\r\n", $page['text']); else $ReadSet[$set]['text'] = explode("\n", $page['text']); $ReadSet[$set]['curline'] = 0; if (isset($opt['IFS'])) $ReadSet[$set]['IFS'] = $opt['IFS']; else $ReadSet[$set]['IFS'] = '\s'; } if ($opt['next']) { if ($opt['next'] === true) $opt['next'] = 1; if (is_numeric($opt['next'])) $ReadSet[$set]['curline'] += $opt['next']; else { $found = false; for ($i = $ReadSet[$set]['curline']+1; $i <= sizeof($ReadSet[$set]['text']); $i++) { if ($opt['next'][0] == '/') { if (preg_match($opt['next'], $ReadSet[$set]['text'][$i])) { $ReadSet[$set]['curline'] = $i; $found = true; break; } } else { if (strstr($ReadSet[$set]['text'][$i], $opt['next'])) { $ReadSet[$set]['curline'] = $i; $found = true; break; } } } if (!$found) { $ReadSet[$set]['curline'] = sizeof($ReadSet[$set]['text'])+1; } } } if ($opt['prev']) { if ($opt['prev'] === true) $opt['prev'] = 1; if (is_numeric($opt['prev'])) $ReadSet[$set]['curline'] -= $opt['prev']; else { $found = false; for ($i = $ReadSet[$set]['curline']-1; $i >= 0; $i--) { if ($opt['prev'][0] == '/') { if (preg_match($opt['prev'], $ReadSet[$set]['text'][$i])) { $ReadSet[$set]['curline'] = $i; $found = true; break; } } else { if (strstr($ReadSet[$set]['text'][$i], $opt['prev'])) { $ReadSet[$set]['curline'] = $i; $found = true; break; } } } if (!$found) { $ReadSet[$set]['curline'] = -1; } } } if (@$opt['rewind']) $opt['goto'] = 0; if (@$opt['goto']) { $ReadSet[$set]['curline'] = $opt['goto']; } $WikiShVars['STATUS'] = 0; if ($ReadSet[$set]['curline'] >= sizeof($ReadSet[$set]['text'])) { if (@$opt['clear'] === false) $ReadSet[$set]['curline'] = sizeof($ReadSet[$set]['text']); else unset($ReadSet[$set]); wdbg(4,"$func: returning EOF (idx=".$ReadSet[$set]['curline'].")"); $WikiShVars['STATUS'] = 2; } if ($ReadSet[$set]['curline'] < 0) { if (@$opt['clear'] ===false) $ReadSet[$set]['curline'] = -1; else unset($ReadSet[$set]); wdbg(4,"$func: returning BOF (idx=".$ReadSet[$set]['curline'].")"); $WikiShVars['STATUS'] = 1; } if ($opt['saveset']) { if(!session_id()) session_start(); $_SESSION['WIKISH_READ'][$set] = $ReadSet[$set]; } if ($WikiShVars['STATUS']) return(''); if (@$opt['linecount']) { if (isset($ReadSet[$set])) return (ShPostProcess($pagename, $opt, array(sizeof($ReadSet[$set]['text'])))); else return (ShPostProcess($pagename, $opt, array(''))); } if (@$opt['status']) { if (isset($ReadSet[$set])) return (ShPostProcess($pagename, $opt, array($ReadSet[$set]['curline']))); else return (ShPostProcess($pagename, $opt, array(''))); } if ($opt['stdout']) { return (ShPostProcess($pagename, $opt, array($ReadSet[$set]['text'][$ReadSet[$set]['curline']]))); } elseif ($args) { $idx = $ReadSet[$set]['curline']; wdbg(3,"$func: Line to split (idx=$idx): >>" . $ReadSet[$set]['text'][$idx] . "<<"); $fields = preg_split("/" . $ReadSet[$set]['IFS'] . "/", $ReadSet[$set]['text'][$idx], -1, PREG_SPLIT_OFFSET_CAPTURE); if (sizeof($args) > 1) { for ($i = 0; $i < sizeof($args)-1; $i++) { $WikiShVars[$args[$i]] = $fields[$i][0]; } } else $i = 0; if (sizeof($fields) >= sizeof($args)) $leftover=substr($ReadSet[$set]['text'][$idx], $fields[$i][1]); else $leftover=''; $WikiShVars[$args[$i]] = $leftover; } $WikiShVars['STATUS'] = 0; wdbg(4,"$func: returning next line ($idx): " . $ReadSet[$set]['text'][$idx]); return(''); } $MarkupExpr["${WikiShMXPrefix}rm"] = 'WikiShRm($pagename, @$argp, @$args)'; function WikiShRm($pagename, $opt, $args) { global $DeleteKeyPattern; #hmm... this is the pattern, but how to go global $DeleteKey; global $EnableWikiShRemove, $EnableWikiShRemoveFully, $EnableWikiShTextWrite; global $WikiShTextWriteList; global $WorkDir, $WikiShVars; if (WikiShNotNow()) return(''); $func = "rm()"; SDV($EnableWikiShRemove, false); SDV($EnableWikiShRemoveFully, false); wdbg(4,"$func: Entering"); if (!$EnableWikiShRemove) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to remove files. Not enabled."); $WikiShVars['STATUS'] = 4; return (''); } SDV($DeleteKey, 'delete'); InitOpts($pagename, '', $opt, $args); ExpandWildcards($pagename, $opt, $args); SetDefaultOpt($opt, 'f', false); SetDefaultOpt($opt, 'trial', false); $newrows = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if ($page[filename] == '-' && $page['type'] == 'inline') { WikiShStdErr($pagename, $opt, "ERROR: $func: File not found: $filename"); continue; } if ($opt['trial']) { $newrows[] = $page['filename']; } else { if ($page['type'] == 'wiki') { $newrows[] = 'Deleted: ' . $page['filename']; if (!WikiShWrite($pagename, $opt, $page['filename'], $page['type'], $DeleteKey, $page)) { $WikiShVars['STATUS'] = 2; return(''); } if ($opt['f']) { if (!$EnableWikiShRemoveFully) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to remove file fully. Not enabled."); $WikiShVars['STATUS'] = 4; return(''); } foreach(glob("$WorkDir/$page[filename],del-*") as $File2Del) { $newrows[] = "Permanently Deleted: $page[filename] ($File2Del)"; unlink($File2Del); } } } elseif ($page['type'] == 'text') { if (!$EnableWikiShTextWrite) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to remove text files. Not enabled."); $WikiShVars['STATUS'] = 4; return(''); } if (!WikiShMatchPageName($page['filename'], $WikiShTextWriteList, true)) { WikiShStdErr($pagename, $opt, "ERROR: $func: Unable to remove $page[filename]. Not in \$WikiShTextWriteList."); $WikiShVars['STATUS'] = 4; return(''); } $newrows[] = "Deleted textfile: $page[filename]"; unlink($page['filename']); } elseif ($page['type'] == 'session') { unset($_SESSION[$page['filename']]); } else { WikiShStdErr($pagename, $opt, "ERROR: Lazy me didn't implement rm() for $page[filename] -> $page[type] type files. Sorry."); } } } $WikiShVars['STATUS'] = 0; return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}sed"] = 'WikiShSed($pagename, @$argp, @$args)'; function WikiShSed($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = "Sed()"; wdbg(4,"$func: Entering"); $args = str_replace('$p', '$p', $args); InitOpts($pagename, 'e:', $opt, $args); if (@$opt['i']) { $opt['inplaceedit'] = $opt['i']; unset($opt['i']); } if (!isset($opt['e'])) { $opt['e'][] = array_shift($args); } if (!is_array($opt['e'])) { $opt['e'][] = $opt['e']; } $opt['e'] = str_replace('$p', '$p', $opt['e']); foreach ($opt['e'] as $k => $e) wdbg(2, "$k => " . debug_space($e)); foreach ($opt['e'] as $expr) { if (preg_match("/^(\d+|\/[^\/]+\/[iADUX]*),(\d+|\\$|\/[^\/]+\/[iADUX]*)p/", $expr, $m)) { $opt['startline'][] = $m[1]; $opt['endline'][] = $m[2]; } elseif (preg_match("/^s((.)(?:[^\\2]|\\\\\\2)+\\2)((?:[^\\2]|\\\\\\2)*)\\2([gFiADUXu]*)$/", $expr, $m)) { $m[1] = str_replace('\n', "\n", $m[1]); if (strstr($m[4], 'F')) { $opt['find'][] = substr($m[1], 1, -1); if (!strstr($m[4], 'g')) WikiShStdErr($pagename, $opt, "$func: ERROR: F flag requires g flag. Continuing as if g was specified."); } else $opt['find'][] = $m[1] . str_replace(array('F', 'g'), array('', ''), $m[4]); $m[3] = str_replace('\n', "\n", $m[3]); $opt['repl'][] = $m[3]; if (strstr($m[4], 'g')) $opt['replcnt'][] = -1; else $opt['replcnt'][] = 1; $opt['flag'][] = $m[4]; } else { WikiShStdErr($pagename, $opt, "$func: ERROR: Unknown expression: >>$expr<<"); } } $opt['printall'] = (isset($opt['n']) && $opt['n']) ? false : true; $WikiShVars['STATUS'] = 0; return(ExtractLines($pagename, $opt, $args, $func)); } $MarkupExpr["${WikiShMXPrefix}set"] = 'WikiShSet($pagename, @$argp, @$args)'; function WikiShSet($pagename, $opt, $args) { global $WikiShVars; global $MxCalcMathChars, $MxCalcMathFunctions, $MxCalcMathFunc1; global $FmtPV; if (WikiShNotNow()) return(''); $Ops = array("=","+=","-=","*=","/=",".=","%=","<","<=",">",">=","++","--"); $func = "Set()"; wdbg(4,"$func: Entering: setting: " . implode(" ", $args)); InitOpts($pagename, '', $opt, $args); if (!in_array($args[1], $Ops)) { WikiShStdErr($pagename, $opt, "ERROR: $func: Invalid assignment operator \"$args[1]\". No assignment possible. (set " . implode(" ", $args) . ")"); return(''); } SetDefaultOpt($opt, 'v', false); SetDefaultOpt($opt, 's', false); SDV($MxCalcMathChars, "/^[-+*,\\/% ()0-9.^=]+$/"); SDV($MxCalcMathFunctions, array( 'pow','sqrt','sin','cos','tan','asin','acos','atan','log', 'max','min','abs','ceil','floor','round','rand','fmod', 'pi','deg2rad','rad2deg', )); SDV($MxCalcMathFunc1, array( 'sqrt','sin','cos','tan','asin','acos','atan','log', 'abs','ceil','floor','round','deg2rad','rad2deg', )); if (@$opt['session']) { if(!session_id()) session_start(); $v = $_SESSION[$args[0]]; } elseif (@$opt['pv']) $v = $FmtPV['$'.$args[0]]; else $v = $WikiShVars[$args[0]]; if ($opt['s']) { $op = $args[1]; $expr = str_replace("'", "\\'", implode(" ", array_slice($args, 2))); $expr = $op . " '" . $expr . "'"; } else { $expr = implode(" ", array_slice($args, 1)); $str = $expr; foreach($MxCalcMathFunctions as $fn) { $str = str_replace($fn, '', $str); } if ($str!='' && !preg_match($MxCalcMathChars, $str, $m)) { WikiShStdErr($pagename, $opt, "ERROR: $func: illegal functions ($str) (did you forget -s?)"); $WikiShVars['STATUS'] = 4; return ''; } $expr = str_replace('pi', M_PI, $expr); $expr = preg_replace("/(\-?[\d.]+)\^(\-?[\d.]+)/", "pow($1, $2)", $expr); foreach($MxCalcMathFunc1 as $fn) $expr = preg_replace("/{$fn}\\s*(\-?[\d.]+)/", "{$fn}($1)", $expr); } wdbg(3,"$func: v=$v, eval'ing >>\\$v $expr;<<"); eval("\$v $expr;"); wdbg(4,"$func: after eval, v=" . $v); if ($opt['pv']) { if ($opt['s']) $FmtPV['$'.$args[0]] = "'" . $v . "'"; else $FmtPV['$'.$args[0]] = $v; foreach ($FmtPV as $key => $val) wdbg(1,"[" . debug_space($key) . "] => " . debug_space($val)); } elseif (@$opt['session']) { $_SESSION[$args[0]] = $v; } else { $WikiShVars[$args[0]] = $v; } $WikiShVars['STATUS'] = 0; if ($opt['v']) return($v); else return(''); } $MarkupExpr["${WikiShMXPrefix}sleep"] = 'WikiShSleep($pagename, @$argp, @$args)'; function WikiShSleep($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = "Sleep()"; wdbg(4,"$func: Entering: args[0]=$args[0]"); InitOpts($pagename, '', $opt, $args); $seconds = $args[0]; if (!is_numeric($seconds)) { $WikiShVars['STATUS'] = 4; WikiShStdErr($pagename, $opt, "ERROR: $func: non-numeric sleep argument: $seconds"); return(''); } usleep(floor($seconds*1000000)); $WikiShVars['STATUS'] = 0; return(''); } $MarkupExpr["${WikiShMXPrefix}sort"] = 'WikiShSort($pagename, @$argp, @$args)'; function WikiShSort($pagename, $opt, $args) { global $WikiShVars; $func = 'sort()'; if (WikiShNotNow()) return(''); wdbg(4,"$func: Entering"); InitOpts($pagename, 't:k:', $opt, $args); ExpandWildcards($pagename, $opt, $args, false, false, false); SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); $general_opt = ''; if (@$opt['d'] || @$opt['dictionary-order']) $general_opt .= 'd'; if (@$opt['b'] || @$opt['ignore-leading-blanks']) $general_opt .= 'b'; if (@$opt['f'] || @$opt['ignore-case']) $general_opt .= 'f'; if (@$opt['u']) $opt['unique'] = true; SDVA($opt, array('unique' => false, 'duplicated' => false, 'only-unique' => false, 'count' => false)); if (isset($opt['k'])) $opt['key'] = $opt['k']; SetDefaultOpt($opt, 'key', '1.1'); if (!is_array($opt['key'])) $opt['key'] = array($opt['key']); $keys = array(); foreach ($opt['key'] as $key) { if (preg_match("/^(\d+)(?:\.(\d+))?(?:,(\d+)(?:\.(\d+))?)?([bdf]*)$/", $key, $match)) { if (!$match[1]) $match[1] = 0; else $match[1]--; if (!$match[2]) $match[2] = 0; else $match[2]--; if ($match[3]) $match[3]--; $keys[] = array($match[1], $match[2], $match[3], $match[4], $match[5]); } else { WikiShStdErr($pagename, $opt, "$func: ERROR: incorrectly specified key: >>$key<<"); $keys[] = array(0,0,"",""); } } $ofs = CHR(1); if (isset($opt['t'])) $opt['field-separator'] = $opt['t']; SetDefaultOpt($opt, 'field-separator', '\s+'); $ifs = $opt['field-separator']; $newrows = array(); $to_sort = array(); foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } $textrows = explode("\n", $page['text']); if ($opt['file_prefix']) $array_prefix = array(WShReplace($opt, $page, $opt['file_prefix'])); else $array_prefix = array(); $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); if ($line_prefix || $line_suffix) for ($i = 0; $i < sizeof($textrows); $i++) { if (strstr($opt['line_prefix'], 'LINENO')) $line_prefix = WShReplace($opt, $page, $opt['line_prefix'], $i+1); $textrows[$i] = $line_prefix . $textrows[$i] . $line_suffix; } $newrows = array_merge($newrows, $array_prefix, $textrows); } foreach($newrows as $origstr) { $fields = preg_split("/$ifs/", $origstr); $line2sort = ''; foreach ($keys as $key) { $tmp = ''; if ($key[0] === $key[2] && ($key[2] || $key[2] === 0)) { if ($key[3]) { $tmp .= substr($fields[$key[0]], $key[1], $key[3]); } else { $tmp .= substr($fields[$key[0]], $key[1]); } } else { $tmp .= substr($fields[$key[0]], $key[1]); $maxidx = ($key[2] || $key[2] === 0) ? $key[2] : sizeof($fields); for ($i = $key[0]+1; $i < $maxidx; $i++) { $tmp .= $ofs . $fields[$i]; } if ($key[2] || $key[2] === 0) { if ($key[3]) { $tmp .= $ofs . substr($fields[$key[2]], 0, $key[3]); } else { $tmp .= $ofs . $fields[$key[2]]; } } } if (strpos($general_opt . $key[4], 'd') !== false) $tmp = preg_replace("/[^${ofs}A-Za-z0-9 \t]/", "", $tmp); if (strpos($general_opt . $key[4], 'b') !== false) $tmp = preg_replace("/^[ \t]*/", "", $tmp); if (strpos($general_opt . $key[4], 'f') !== false) { $tmp = strtolower($tmp); } $line2sort .= $ofs . $tmp; } $to_sort[] = array($line2sort, $origstr); } if (!@$opt['no-sort']) { $WikiShVars['STATUS'] = 0; if (@$opt['r'] || @$opt['reverse']) { if (!rsort($to_sort)) { $WikiShVars['STATUS'] = 4; return(''); } } else { if (!sort($to_sort)) { $WikiShVars['STATUS'] = 4; return(''); } } } $newrows = array(); if ($opt['unique'] || $opt['duplicated'] || $opt['only-unique'] || $opt['count']) { $lastval = false; $lastline = false; $dupcnt = 0; foreach ($to_sort as $cur_line) { if ($lastval === $cur_line[0]) { $dupcnt++; } else { if ($lastval !== false && (($opt['duplicated'] && $dupcnt > 1) || ($opt['only-unique'] && $dupcnt == 1) || (!$opt['duplicated'] && !$opt['only-unique']))) { $newrows[] = (($opt['count']) ? "$dupcnt: ":'') . $lastline; } $lastval = $cur_line[0]; $lastline = $cur_line[1]; $dupcnt = 1; } } if ($lastval !== false && (($opt['duplicated'] && $dupcnt > 1) || ($opt['only-unique'] && $dupcnt == 1) || (!$opt['duplicated'] && !$opt['only-unique']))) { $newrows[] = ($opt['count']?"$dupcnt: ":'') . $lastline; } } else { foreach($to_sort as $tinyarray) { $newrows[] = $tinyarray[1]; } } return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr["${WikiShMXPrefix}tail"] = 'WikiShTail($pagename, @$argp, @$args)'; function WikiShTail($pagename, $opt, $filelist) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = 'Tail()'; wdbg(4,"$func: Entering"); InitOpts($pagename, 'n:', $opt, $filelist); SetDefaultOpt($opt, 'n', -10); if ($opt['n'] > 0) $opt['n'] *= -1; $opt['startline'][] = $opt['n']; $opt['endline'][] = '$'; $WikiShVars['STATUS'] = 0; return(ExtractLines($pagename, $opt, $filelist, $func)); } $MarkupExpr["${WikiShMXPrefix}test"] = 'WikiShTest($pagename, @$argp, @$args)'; function WikiShTest($pagename, $opt, $args) { global $WikiShVars; $func = "Test()"; wdbg(4,"$func: Entering args=>>" . implode(" ", $args) . "<<"); if (WikiShNotNow(true)) return(''); $oplist = array('-d','-e','-f','-g','-r','-s','-w', '-n','-z', '-ot','-nt', '-eq','-ne','-lt','-le','-gt','-ge', '==','!=','<','>', '>=', '<=', '~='); $state = 0; $rtn = false; ExpandVars($pagename, $opt, $args); array_push($args, ''); foreach ($args as $arg) { if ($state == 3) continue; if ($state == 2) { $arg2 = $arg; switch ($op) { case '-ne': case '-eq': case '-lt': case '-le': case '-gt': case '-ge': if (!is_numeric($arg1)) $arg1 = 0; if (!is_numeric($arg2)) $arg2 = 0; switch ($op) { case '-eq': $rtn = ($arg1 == $arg2); break; case '-ne': $rtn = ($arg1 != $arg2); break; case '-lt': $rtn = ($arg1 < $arg2); break; case '-le': $rtn = ($arg1 <= $arg2); break; case '-gt': $rtn = ($arg1 > $arg2); break; case '-ge': $rtn = ($arg1 >= $arg2); break; } $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '==': case '!=': case '>=': case '<=': case '~=': case '<': case '>': case '-z': case '-n': switch ($op) { case '==': $rtn = (strcmp($arg1, $arg2) == 0); break; case '!=': $rtn = (strcmp($arg1, $arg2) != 0); break; case '>=': $rtn = (strcmp($arg1, $arg2) >= 0); break; case '<=': $rtn = (strcmp($arg1, $arg2) <= 0); break; case '~=': wdbg(3,"$func: doing preg_match(\"$arg2\", \"$arg1\")"); $rtn = (preg_match($arg2, $arg1)); break; case '<': $rtn = (strcmp($arg1, $arg2) < 0); break; case '>': $rtn = (strcmp($arg1, $arg2) > 0); break; case '-z': $rtn = (strlen($arg2) == 0); break; case '-n': $rtn = (strlen($arg2) > 0); break; } $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '-d': case '-g': $arg2 = $arg2 . '.*'; case '-e': case '-f': $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg2)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename = $tmparg[0]; $rtn = PageExists($filename); wdbg(2,"$func: -f|-g PageExists() returns " . ($rtn?"TRUE":"FALSE") . " (negop=$negop)"); $rtn = (($rtn && !$negop) || ($negop && !$rtn)); $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '-r': $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg2)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename = $tmparg[0]; $rtn = (PageExists($filename) && CondAuth($filename, 'read')); wdbg(2,"$func: -r PageExists() && CondAuth() return " . ($rtn?"TRUE":"FALSE") . " (negop=$negop)"); $rtn = (($rtn && !$negop) || ($negop && !$rtn)); $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '-w': $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg2)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename = $tmparg[0]; $rtn = (PageExists($filename) && CondAuth($filename, 'edit')); wdbg(2,"$func: -w PageExists() && CondAuth() return " . ($rtn?"TRUE":"FALSE") . " (negop=$negop)"); $rtn = (($rtn && !$negop) || ($negop && !$rtn)); $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '-s': $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg2)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename = $tmparg[0]; $rtn = (PageExists($filename) && CondAuth($filename, 'read')); if (!$rtn) { WikiShStdErr($pagename, $opt, "$func: ERROR: page does not exist or no read privilege"); $WikiShVars['STATUS'] = 2; return (''); } $page = RetrieveAuthPage($filename, 'read', false); if (!$page) { WikiShStdErr($pagename, $opt, "$func: ERROR: error reading page >>$filename<<"); $WikiShVars['STATUS'] = 2; return (''); } $rtn = (boolean)$page['text']; wdbg(2,"$func: -s PageExists() && CondAuth() return " . ($rtn?"TRUE":"FALSE") . " (negop=$negop)"); if ($negop) $rtn = !$rtn; $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; case '-ot': $tmp = $arg1; $arg1 = $arg2; $arg2 = $tmp; case '-nt': $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg1)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename1 = $tmparg[0]; $tmparg = array(WikiShFmtPagename($pagename, $opt, $arg2)); ExpandWildcards($pagename, $opt, $tmparg, true, true); $filename2 = $tmparg[0]; $rtn1=(PageExists($filename1) && CondAuth($filename1, 'read')); $rtn2=(PageExists($filename2) && CondAuth($filename2, 'read')); if (!$rtn1) { WikiShStdErr($pagename, $opt, "$func: ERROR: page $filename1 does not exist or no read privilege"); $WikiShVars['STATUS'] = 2; return (''); } $page1 = RetrieveAuthPage($filename1, 'read', false); if (!$rtn2) { WikiShStdErr($pagename, $opt, "$func: ERROR: page $filename2 does not exist or no read privilege"); $WikiShVars['STATUS'] = 2; return (''); } $page2 = RetrieveAuthPage($filename2, 'read', false); if (!$page1) { WikiShStdErr($pagename, $opt, "$func: ERROR: error reading page >>$filename1<<"); $WikiShVars['STATUS'] = 2; return(''); } if (!$page2) { WikiShStdErr($pagename, $opt, "$func: ERROR: error reading page >>$filename2<<"); $WikiShVars['STATUS'] = 2; return(''); } $rtn = ($page1['time']+0 > $page2['time']+0); $arg1 = $op = $arg2 = $negop = ''; $state = 3; break; default: WikiShStdErr($pagename, $opt, "$func: ERROR: Unknown operator option \"$op\""); } continue; } if ($arg == '!') { $negop = true; continue; } elseif (in_array($arg, $oplist)) { if ($state > 1) { WikiShStdErr($pagename, $opt, "$func: ERROR: Argument mismatch. $arg unexpected."); $WikiShVars['STATUS'] = 4; return(''); } $op = $arg; $state = 2; continue; } else { $arg1 = $arg; $state = 1; continue; } } wdbg(4,"$func: Returning " . ($rtn ? "TRUE" : "FALSE")); $WikiShVars['STATUS'] = ($rtn ? 0 : 1); return(''); } $MarkupExpr["${WikiShMXPrefix}true"] = 'WikiShTrue($pagename, @$argp, @$args)'; function WikiShTrue($pagename, $opt, $args) { global $WikiShVars; WikiShNotNow(); $func = "True()"; wdbg(4,"$func: Entering"); $WikiShVars['STATUS'] = 0; return(''); } $MarkupExpr["${WikiShMXPrefix}uniq"] = 'WikiShUniq($pagename, @$argp, @$args)'; function WikiShUniq($pagename, $opt, $args) { global $WikiShVars; $func = 'uniq()'; if (WikiShNotNow()) return(''); wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $args); if (@$opt['i']) { $opt['ignore-case'] = true; unset($opt['i']); } if (@$opt['c'] || @$opt['count']) { $opt['count'] = true; unset($opt['c']); } if (@$opt['d'] || @$opt['duplicated']) { $opt['duplicated'] = true; unset($opt['d']); } if (@$opt['u'] || @$opt['unique']) { $opt['only-unique'] = true; unset($opt['u']); unset($opt['unique']); } $opt['no-sort'] = true; $opt['unique'] = true; return (WikiShSort($pagename, $opt, $args)); } $MarkupExpr["${WikiShMXPrefix}wc"] = 'WikiShWc($pagename, @$argp, @$args)'; function WikiShWc($pagename, $opt, $args) { global $WikiShVars; if (WikiShNotNow()) return(''); $func = 'wc()'; wdbg(4,"$func: Entering"); InitOpts($pagename, '', $opt, $args); ExpandWildcards($pagename, $opt, $args, false, false, false); SetDefaultOpt($opt, 'only_total', false); SetDefaultOpt($opt, 'total_only', false); if ($opt['total_only']) $opt['only_total'] = $opt['total_only']; SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); SetDefaultOpt($opt, 'l', false); SetDefaultOpt($opt, 'w', false); SetDefaultOpt($opt, 'c', false); SetDefaultOpt($opt, 'q', false); if (!$opt['l'] && !$opt['w'] && !$opt['c']) $opt['l'] = $opt['w'] = $opt['c'] = true; $newrows = array(); $total_wc = $total_lc = $total_cc = $wordcnt = $linecnt = $charcnt = 0; foreach ($args as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } if ($opt['l']) $linecnt = substr_count($page['text'], "\n") + 1; if ($opt['c']) $charcnt = strlen($page['text']) - $linecnt; if ($opt['w']) $wordcnt = str_word_count($page['text']); $total_wc += $wordcnt; $total_lc += $linecnt; $total_cc += $charcnt; if (!$opt['only_total']) { if ($opt['file_prefix']) { $file_prefix = WShReplace($opt, $page, $opt['file_prefix']); $newrows[] = $file_prefix; } $myline = WShReplace($opt, $page, $opt['line_prefix']); if ($opt['l']) $myline .= (($opt['q']) ? "" : "lines: ") . "$linecnt "; if ($opt['w']) $myline .= (($opt['q']) ? "" : "words: ") . "$wordcnt "; if ($opt['c']) $myline .= (($opt['q']) ? "" : "characters: ") . "$charcnt "; $myline .= WShReplace($opt, $page, $opt['line_suffix']); $newrows[] = $myline; } } if (sizeof($args) > 1) { $funnypage['filename'] = 'TOTAL'; $funnypage['title'] = 'TOTAL'; if ($opt['file_prefix']) { $file_prefix = WShReplace($opt, $funnypage, $opt['file_prefix']); $newrows[] = $file_prefix; } $myline = WShReplace($opt, $funnypage, $opt['line_prefix']); if ($opt['l']) $myline .= (($opt['q']) ? "" : "lines: ") . "$total_lc "; if ($opt['w']) $myline .= (($opt['q']) ? "" : "words: ") . "$total_wc "; if ($opt['c']) $myline .= (($opt['q']) ? "" : "characters: ") . "$total_cc "; $myline .= WShReplace($opt, $funnypage, $opt['line_suffix']); $newrows[] = $myline; } $WikiShVars['STATUS'] = 0; return (ShPostProcess($pagename, $opt, $newrows, $page)); } $MarkupExpr['wikish_active'] = 'WikiShActive($pagename, preg_replace($rpat, $rrep, $params))'; function WikiShActive($pagename, $expr) { global $WikiShVars; if (WikiShNotNow(true)) return(Keep('', 'P')); $func = "wikishactive()"; wdbg(4,"$func: Entering"); $expr = substr($expr, 1); $expr = '(' . $expr . ')'; wdbg(4,"$func: evaling \"$expr\""); $rtn = MarkupExpression($pagename, $expr); if ($WikiShVars['STATUS'] == 0) { $WikiShVars['ACTIVE'] = true; } else { $WikiShVars['ACTIVE'] = false; } return(Keep($rtn, 'P')); } $MarkupExpr["wikish_button"] = 'WikiShButton($pagename, @$argp, @$args)'; function WikiShButton($pagename, $opt, $args) { global $WikiShVars, $WikiShFormStarted; if (WikiShNotNow(true)) return (''); $func = 'wikish_button()'; wdbg(4,"$func: Entering"); InitOpts($pagename, "", $opt, $args); SetDefaultOpt($opt, 'r', false); SetDefaultOpt($opt, 'q', false); if (!@$args[1]) $args[1] = $args[0]; $args[0] = preg_replace("/[^A-Za-z_-]/", "", $args[0]); SDV($WikiShFormStarted, false); $rtn = ''; if (!$WikiShFormStarted && !$opt['q']) { $rtn .= '(:input form method="GET":)'."\n".'(:input hidden name=n value="{*$FullName}":)'; $WikiShFormStarted = true; } if (!$opt['q']) $rtn .= "(:input submit abc name=\"$args[0]\" value=\"$args[1]\":)"; if ($_GET[$args[0]]) { $WikiShVars['ACTIVE'] = true; } else { $WikiShVars['ACTIVE'] = false; } return($rtn); } $MarkupExpr["wikish_once"] = 'WikiShOnce($pagename, @$argp, @$args)'; function WikiShOnce($pagename, $opt, $args) { global $WikiShVars, $WikiShControlPage; if (WikiShNotNow(true)) return (''); $func = 'once()'; wdbg(4,"$func: Entering"); InitOpts($pagename, 'c:', $opt, $args); SetDefaultOpt($opt, 'r', false); if ($opt['c']) $ControlPage = $opt['c']; else $ControlPage = $WikiShControlPage; if (!strpos($ControlPage, '.') && !strpos($ControlPage, '/')) { $Grp = PageVar($pagename, '$Group'); $ControlPage = $Grp . '.' . $ControlPage; } $pat = ':' . $pagename; if (sizeof($args) > 1) { $pat .= '-' . array_shift($args); } $pat .= ':' . implode(" ", $args); $rtn = ''; WikiShGrep($pagename, array('q'=>true), array("^$pat$", $ControlPage)); if ($WikiShVars['STATUS'] == 0) { $WikiShVars['STATUS'] = 1; wdbg(4,"$func: Returning (a) with STATUS=" . $WikiShVars['STATUS']); return($opt['r'] ? '0' : ''); } else { WikiShEcho($pagename, array('stdout'=>$ControlPage, 'stdout_append'=>true), array("$pat")); wdbg(4,"$func: Returning (b) with STATUS=" . $WikiShVars['STATUS']); return($opt['r'] ? '1' : ''); } } function WikiShSystemCall($pagename, $opt, $dir, $cmd, $args, $security = "SEMI-ARGS", $SafeVars = array()) { global $WikiShVars; $func = 'WikiShSystemCall()'; wdbg(4,"$func: Entering: $cmd " . implode(" ", $args)); $cmd = array($cmd); $rtn = ExpandVars($pagename, $opt, $cmd, $SafeVars); $cmd = $cmd[0]; $rtn = $rtn && ExpandVars($pagename, $opt, $args, $SafeVars); if ($cmd) $command = $cmd; else $command = array_shift($args); if (!$rtn) { WikiShStdErr($pagename, $opt, "ERROR: $func: Insecure variable. System call aborted."); return(''); } foreach ($args as $arg) { switch ($security) { case "FULL-ARGS": $command .= ' ' . escapeshellarg($arg); break; case "SPACE-ARGS": if (strstr($arg, ' ')) $command .= ' ' . escapeshellarg($arg); else $command .= ' ' . $arg; break; case "SEMI-ARGS": if (preg_match("/[ |><;`(){}]/", $arg)) $command .= ' ' . escapeshellarg($arg); else $command .= ' ' . $arg; break; default: $command .= ' ' . $arg; break; } wdbg(3,"$func: Handling arg=$arg - now command = " . debug_space($command)); } $rtn = array(); $status = 0; if ("FULL-LINE" == $security) $command = escapeshellcmd(str_replace('`', '\"', $command)); wdbg(4,"$func: Running this commmand >>" . debug_space($command). "<<"); if ($dir) { $odir = getcwd(); wdbg(3,"$func: chdir'ing to this dir: $dir (from $odir)"); chdir($dir); } exec($command, $rtn, $status); if ($dir) { wdbg(3,"$func: chdir'ing back to this dir: $odir"); chdir($odir); } $WikiShVars['STATUS'] = $status; return (ShPostProcess($pagename, $opt, $rtn)); } function WikiShExpand1Var($pagename, $text) { $arrtext = array($text); ExpandVars($pagename, array(), $arrtext); return($arrtext[0]); } function ExpandVars($pagename, $opt, &$args, $secure = array()) { global $WikiShVars, $MarkupTable, $Version, $RecipeInfo; $func="ExpandVars()"; $rtn = true; wdbg(3,"$func: Entering."); for ($i=0; $i< sizeof($args); $i++) { wdbg(3,"$func: Working with " . debug_space($args[$i])); $id = '{$var}'; if (stristr($WikiShVars['PAGEVARS'], 'pre')) { $RefPage = (@$opt['refpage'] ? $opt['refpage'] : (@$WikiShVars['REFPAGE'] ? $WikiShVars['REFPAGE'] : $pagename)); $args[$i] = FmtPageName($args[$i], $RefPage, true); } $pat = "/(?[!~])|(?P#))?(?P(?:#|\w+))(?:(?P[*@])|(?P#{1,2}|%{1,2})(?P[^}]+)|:(?P[-=+])(?P[^}]*)|\\/(?P[^\\/]+)\\/(?P[^\\}]*)|[:,](?P[-\\d]+)(?:[:,](?P[-\\d]+))?)?\\}/"; while (preg_match($pat, $args[$i], $m)) { $var = $m['var']; if ((@$var||$var===0||$var==='0') && isset($WikiShVars[$var])) { if (!$secure[$var] || WikiShMatchPageName($WikiShVars[$var], $secure[$var])) { $val = $WikiShVars[$var]; } else { WikiShStdErr($pagename, $opt, "ERROR: $func: Insecure value $WikiShVars[$var] for variable \${$var}."); $val = '!!ERROR!!'; $rtn = false; } } else { switch ($var) { case 'PWD': case 'CWD': $val = getcwd(); break; case 'WIKISH_VERSION': $val = $RecipeInfo['WikiSh']['Version']; break; case 'PMWIKI_VERSION': $val = $Version; break; case 'RANDOM': $val=rand($WikiShVars['RANDOM_MIN'], $WikiShVars['RANDOM_MAX']); break; case 'SECONDS': $val = microtime(true) - $WikiShVars['SECONDS_START']; break; case 'SECONDSLEFT': $val = ini_get('max_execution_time') - (microtime(true) - $WikiShVars['SECONDSLEFT_START']); break; case 'NOW': $val = microtime(true); break; case 'HOSTIP': $val=gethostbyname($_SERVER["SERVER_NAME"]); break; case 'HOSTNAME': $val=gethostbyaddr(gethostbyname($_SERVER["SERVER_NAME"])); break; case 'SESSIONID': $val= session_id(); break; default: $val = ''; break; } } if ($m['prefix']=='!' && $m['prefix_op']) { $val = implode(" ", preg_grep("/^$var/", array_keys($WikiShVars))); } elseif ($m['prefix'] == '!') { $val = $_REQUEST[$var]; } elseif ($m['prefix'] == '~') { if(!session_id()) session_start(); $val = $_SESSION[$var]; } if ($m['default']) { if ($val) { if ($m['default_op'] == '+') $val = $m['default']; } else { if ($m['default_op'] == '-' || $m['default_op'] == '=') $val = $m['default']; if ($m['default_op'] == '=') $WikiShVars[$var] = $val; } } if ($m['search']) { $search = WikiShGlobToPCRE($m['search']); $val = preg_replace("/$search/", $m['replace'], $val); } elseif ($m['offset'] !== null) { if ($m['length']!==null) $val = substr($val, $m['offset'], $m['length']); else $val = substr($val, $m['offset']); } elseif ($m['delete']) { $delete = WikiShGlobToPCRE($m['delete'], ($m['delete_op'][0] == '#'?true:false), ($m['delete_op'][0] == '%'?true:false), (strlen($m['delete_op'])>1 ? true : false)); if ($m['delete_op'] == '%') $val = preg_replace("/(.*)$delete/", '$1', $val); else $val = preg_replace("/$delete/", '', $val); } if ($m['strlen']) { $val = strlen($val); } $fullpat = preg_quote($m[0], '/'); $args[$i] = preg_replace("/(?>" . debug_space($args[$i]) . "<<"); } if (stristr($WikiShVars['PAGEVARS'], 'post')) { while (preg_match("/\\{([\\w.\\/]*)\\$:([\\w 0-9]+)\\}/", $args[$i], $m)) { $pn = ($m[1] ? $m[1] : $pagename); $ptv = $m[2]; $val = PageTextVar($pn, $ptv); $args[$i] = str_replace($m[0], $val, $args[$i]); } $RefPage = (@$opt['refpage'] ? $opt['refpage'] : (@$WikiShVars['REFPAGE'] ? $WikiShVars['REFPAGE'] : $pagename)); $args[$i] = FmtPageName($args[$i], $RefPage, true); } } return($rtn); } function debug_space($foo) { global $WikiShVars; if ($WikiShVars['DEBUGLEVEL'] >= 5) return(''); if (!$WikiShVars['DEBUG_OD']) return($foo); $repl = array(':' => 'COLON', ';' => 'SEMI-COLON', '/'=>'SLASH', '(' => 'OPEN-PAREN', ' '=>' _ ', '@' => 'AT', '\\' => 'BACKSLASH', CHR(10)=>'LF', CHR(13)=>'CR', ')'=>'CLOSE-PAREN', '.' => 'DOT', '{'=>'OPEN-CURLY', '}'=>'CLOSE-CURLY', '='=>'EQUALS', '|' => 'VERT', '#'=>'POUND', ','=>'COMMA', '$'=>'DOLLAR', '-'=>'DASH', '+'=>'PLUS', '"' => 'DOUBLE-QUOTE', "'" => 'SINGLE-QUOTE', '!' => 'BANG', '?' => 'QUESTION', '<' => 'OPEN-ANGLE', '>' => 'CLOSE-ANGLE', '*' => 'ASTERISK', '&' => 'AMPERSAND'); $rtn = ''; for ($i = 0; $i < strlen($foo); $i++) if (in_array($foo[$i], array_keys($repl))) { $rtn .= ' ' . $repl[$foo[$i]] . ' '; } elseif (ord($foo[$i]) < 65 && (ord($foo[$i])<48 || ord($foo[$i])>57)) $rtn .= 'CHR(' . ord($foo[$i]). ')'; else $rtn .= $foo[$i]; return($rtn); } function InitOpts($pagename, $ValidOpts, &$opt, &$args, $ExpandVars = true, $ProcPipe=true) { global $WikiShVars; global $WikiShPipeText, $WikiShPipeActive; $func = 'InitOpts'; wdbg(3,"$func: Entering: args array follows:"); wdbg(1,$args); if ($ExpandVars) { ExpandVars($pagename, $opt, $args); } for($i=0; $i 2) { $foo = substr($myarg, 2); if ($colon_pos = strpos($foo, ':')) { $opt[substr($foo, 0, $colon_pos)] = substr($foo, $colon_pos+1); } else { if (strlen($foo) == 1 && strstr($ValidOpts, $foo.':')) { $opt[$foo] = $args[$i+1]; $i++; } else { if (substr($foo, 0, 2) == 'no') { $foo = substr($foo, 2); $opt[$foo] = false; } else { $opt[$foo] = true; } } } } elseif ($myarg[0] == '-') { for ($j=1; $j 0) { for ($arg = end($args); $arg !== false && preg_match("/^(?:<|>|>|<)[\w.\/<>#-]+$/", $arg); $arg = end($args)) { $arg = str_replace(array(">", "<"), array(">", "<"), array_pop($args)); if ($arg[0] == '>') { $opt['stdout'] = $arg; if (isatextfile('', $opt['stdout'], ($arg[1] == '>' ? 2 : 1))) { $opt['stdout'] = str_replace(TEXTFILEID, "", $arg); $opt['stdout_type'] = 'text'; } elseif (isasessionfile('', $opt['stdout'], ($arg[1] == '>' ? 2 : 1)) || isasessiongroup(substr($opt['stdout'], ($arg[1] == '>' ? 2:1)))) { if (isasessionfile('', $opt['stdout'])) $opt['stdout'] = str_replace(SESSFILEID, "", $arg); $opt['stdout_type'] = 'session'; } else SetDefaultOpt($opt, 'stdout_type', 'wiki'); } elseif ($arg[0] == '<') { $opt['stdin'] = substr($arg, 1); } } } if (@$opt['timeout'] > 0) set_time_limit($opt['timeout']); if (isset($opt['debug'])) $WikiShVars['DEBUGLEVEL'] = $opt['debug']; $args = array_slice($args, $i); if ($ProcPipe && $WikiShPipeActive) { if (!$opt['xargs']) $args[] = '-'; $args[] = $WikiShPipeText; $WikiShPipeActive = false; } } function ExpandWildcards($pagename, $opt, &$args, $NoPageID = false, $NoTextID = false, $NoBadID = false, $NoSessID = false) { global $WikiShVars, $SearchPatterns; $func = "ExpandWildCards()"; wdbg(3,"$func: Entering"); if ($opt['list']) $list = $opt['list']; elseif ($WikiShVars['LIST']) $list = $WikiShVars['LIST']; elseif (isset($SearchPatterns['default'])) $list = 'default'; else $list = ''; $grp = PageVar($pagename, '$Group'); $FileList = array(); for ($i = 0; $i < sizeof($args); $i++) { $myarglist = explode("\n", $args[$i]); foreach ($myarglist as $myarg) { if ($myarg == '-') { $FileList[] = $args[$i+1]; $i++; continue; } elseif (isasessionfile('', $myarg) || isasessiongroup($myarg)) { if (isasessionfile('', $myarg)) $myarg = substr($myarg, strlen(SESSFILEID)); $orig_arg = $myarg; if (strstr($myarg, '#')) { if (preg_match("/(#.*)$/", $myarg, $matches)) $mysection = $matches[1]; $myarg = MakePageName($pagename, $myarg); } else $mysection = ''; $prpat = GlobToPCRE(FixGlob($myarg)); wdbg(3,"$func: session pattern=$prpat[0]"); if(!session_id()) session_start(); $ShortList = preg_grep("/$prpat[0]/i", array_keys($_SESSION)); foreach ($ShortList as $filename) { if ($mysection) $filename .= $mysection; wdbg(3, "$func: session file: $filename"); $FileList[] = ((!$NoSessID) ? SESSFILEID : '') . $filename; } } elseif (strncmp($myarg, TEXTFILEID, strlen(TEXTFILEID)) == 0) { $pat = substr($myarg, strlen(TEXTFILEID)); $ShortList = glob("$pat"); if ($ShortList) { foreach ($ShortList as $filename) { $FileList[] = ((!$NoTextID) ? TEXTFILEID : '') . $filename; } } else { $FileList[] = $myarg; } continue; } else { $orig_arg = $myarg; if (strstr($myarg, '#')) { if (preg_match("/(#.*)$/", $myarg, $matches)) $mysection = $matches[1]; $myarg = MakePageName($pagename, $myarg); } else $mysection = ''; if (strstr($myarg,'.')) $pat = $myarg; else $pat = $grp.".".$myarg; $prpat = GlobToPCRE(FixGlob($pat)); $ShortList = ListPages("/$prpat[0]/i"); if ($ShortList) { if ($list) { $ShortList = MatchPageNames($ShortList, $SearchPatterns[$list]); } foreach ($ShortList as $filename) { if ($mysection) $filename .= $mysection; $FileList[] = ((!$NoPageID) ? WIKIPAGEID : '') . $filename; } } else { $FileList[] = ($NoBadID?'':BADFILEID) . $myarg; } } } } $args = $FileList; } function ShReadPage($pagename, $opt, $filename, $onlyfile=false) { global $EnableWikiShTextRead, $WikiShTextReadList; $func = "ShReadPage()"; wdbg(3,"ShReadpage($pagename, ..., $filename): Entering"); SDV($EnableWikiShTextRead, false); $orig_filename = $filename; if (isasessionfile('', $filename) || isasessiongroup($filename)) { if (isasessionfile('', $filename)) $filename = substr($filename, strlen(SESSFILEID)); if(!session_id()) session_start(); if (isset($_SESSION[$filename])) { $page = $_SESSION[$filename]; $page['filename'] = $filename; $page['type'] = 'session'; } else { $page = array('text'=>'', 'filename' => $filename, 'type' => 'bad'); } } elseif (isawikipage('', $filename)) { $filename = substr($filename, strlen(WIKIPAGEID)); $filename = WikiShFmtPagename($pagename, $opt, $filename); if (strstr($filename, '#')) $filename = MakePageName($pagename, $filename); if (!strpos($filename, '.') && !strpos($filename, '/')) { $Grp = PageVar($pagename, '$Group'); $filename = $Grp . '.' . $filename; } $page = RetrieveAuthPage($filename, 'read', false); if (strstr($orig_filename, '#')) { $page['text'] = TextSection($page['text'], $orig_filename); } $page['filename'] = $filename; $page['type'] = 'wiki'; } elseif (isatextfile('', $filename)) { $filename = substr($filename, strlen(TEXTFILEID)); $tmp = $WikiShTextReadList; ExpandVars($pagename, $opt, $tmp); if ($EnableWikiShTextRead && WikiShMatchPageName($filename, $tmp, true)) { if (file_exists($filename) && ($fh = fopen($filename, 'r'))) { $page['text'] = fread($fh, filesize($filename)); fclose($fh); $page['filename'] = $filename; $page['type'] = 'text'; $page['ctime'] = $Now; $page['time'] = $Now; $page['title'] = '$filename'; } else { $page['text'] = ''; $page['filename'] = $filename; $page['type'] = 'bad'; } } else { if (!$EnableWikiShTextRead) $msg = 'Text Reading not enabled. See $EnableWikiShTextRead configuration'; else $msg = "Text Reading not enabled for $filename. See \$WikiShTextReadList configuration"; WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Read: Unable to read from text file. $msg"); } } elseif (isabadfile('', $filename)) { $filename = substr($filename, strlen(BADFILEID)); WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Read: Unable to read $filename. Does not exist."); $page = array('filename' => $filename, 'type' => 'bad'); } else { $page = array(); $page['filename'] = '-'; $page['ctime'] = $Now; $page['time'] = $Now; $page['title'] = '-'; $page['type'] = 'inline'; if ($onlyfile) { WikiShStdErr($pagename, $opt, "ERROR: ShReadPage: page $filename does not exist."); $page['text'] = ''; } else { $page['text'] = $filename; } } if ($opt['decrypt'] && function_exists('WikiShDecrypt')) $page['text'] = WikiShDecrypt($pagename, $opt, $page['text']); return($page); } function WikiShWrite($pagename, $opt, $filename, $type, $newtext, $page) { global $EnableWikiShTextWrite, $EnableWikiShWritePage, $WikiShWriting; global $EnableWikiShCreatePage, $EnableWikiShOverwritePage; global $Author, $WikiShVars, $WikiShWriteList, $WikiShTextWriteList; $func = 'WikiShWrite'; SDV($EnableWikiShTextWrite, false); SDV($EnableWikiShWritePage, false); SDV($EnableWikiShCreatePage, false); SDV($EnableWikiShOverwritePage, false); if (substr($filename, 0, strlen(TEXTFILEID)) == TEXTFILEID) { $filename = substr($filename, strlen(TEXTFILEID)); if ($type != 'text') { WikiShStdErr($pagename, $opt, "ERROR: Write to $filename: file ID (TEXTFILEID) and type ($type) do not match. Attempting to continue."); } } if (substr($filename, 0, strlen(WIKIPAGEID)) == WIKIPAGEID) { $filename = substr($filename, strlen(WIKIPAGEID)); if ($type != 'wiki') { WikiShStdErr($pagename, $opt, "ERROR: Write to $filename: file ID (WIKIPAGEID) and type ($type) do not match. Attempting to continue."); } } if ($filename == "/dev/null" || $filename == "null" || $filename == "nul") { return (true); } if (strstr($filename, '#')) { WikiShStdErr($pagename, $opt, "Writing to sections not yet implemented. Aborting write to $filename"); return (false); } if (isasessionfile('', $filename) || isasessiongroup($filename)) { if (isasessionfile('', $filename)) $filename = substr($filename, strlen(SESSFILEID)); $newpage = $page; $newpage['text'] = $newtext; $newpage['csum'] = "WikiSh automatic edit"; $newpage['filename'] = $filename; $newpage['type'] = 'session'; if(!session_id()) session_start(); $_SESSION[$filename] = $newpage; } elseif (isawikipage(array('type'=>$type))) { if (!$EnableWikiShWritePage) { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to write to wiki pages. Not enabled."); return (false); } $filename = WikiShFmtPagename($pagename, $opt, $filename); $page_exists = PageExists($filename); if (!is_array($page)) { if ($page_exists) { if (!($page = RetrieveAuthPage($filename, 'edit', false))) { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: RetrieveAuthPage($filename, 'edit', ...) failed."); return(false); } } else { $page = array(); } } $newpage = $page; $newpage['text'] = $newtext; $newpage['csum'] = "WikiSh automatic edit"; if ((!$EnableWikiShCreatePage && !$page_exists) || !$EnableWikiShOverwritePage && $page_exists) { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to create/overwrite pages. Not enabled."); return(false); } if ($WikiShWriteList && !WikiShMatchPageName($filename, $WikiShWriteList)) { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: That page ($filename) is not on the write list for WikiSh (see \$WikiShWriteList setting)."); return(false); } if (!CondAuth($filename, 'edit')) { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to write to $filename. No pmwiki authorization for 'edit'."); return(false); } if (!isset($Author) || empty($Author)) $Author = $WikiShVars['AUTHOR']; if ($WikiShWriting) { } else { $WikiShWriting = true; if (!UpdatePage($filename, $page, $newpage)) { $WikiShWriting = false; WikiShStdErr($pagename, $opt, "ERROR: $func: Failure writing to $filename"); return(false); } $WikiShWriting = false; } } elseif (isatextfile(array('type'=>$type))) { $tmp = $WikiShTextWriteList; ExpandVars($pagename, $opt, $tmp); if ($EnableWikiShTextWrite && WikiShMatchPageName($filename, $tmp, true)) { if ($fp = @fopen("$filename", "w")) { $fwstat = fwrite($fp, $newtext); fclose($fp); if ($fwstat !== false) return(true); else { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to fwrite to $filename."); return(false); } } else { WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to open $filename."); return(false); } } else { if (!$EnableWikiShTextWrite) $msg = 'Text Writing not enabled. See $EnableWikiShTextWrite configuration'; else $msg = "Text Writing not enabled for $filename. See \$WikiShTextWriteList configuration"; WikiShStdErr($pagename, $opt, "ERROR: WikiSh.Write: Unable to write to text file. $msg"); } } else { WikiShStdErr($pagename, $opt, "ERROR: WikiShWrite: Unknown file type=$type"); } return(true); } function WikiShReadHist($pagename, $opt, $logfile, $ifs=':', $fldcnt=2) { global $WikiShVars; $page = RetrieveAuthPage($logfile, 'read', false); if ($page) $text = $page['text']; else $text = ''; while (preg_match("/^\s*\(:([^:\s]+)\s*(\S+)\s*:\)(?:\n)?/", $text, $m)) { $text = substr($text, strlen($m[0])); } if (isset($WikiShVars['HIST_PREFIX']) && substr($text, 0, strlen($WikiShVars['HIST_PREFIX'])) == $WikiShVars['HIST_PREFIX']) $text = substr($text, strlen($WikiShVars['HIST_PREFIX'])); $lines = explode("\n", $text); $favs = $hist = array(); foreach ($lines as $line) { $flds = split($ifs, $line, $fldcnt); if ($flds[0] && $flds[1]) { if ($flds[0] < 30000) $favs[] = $flds; else $hist[] = $flds; } } return(array($favs, $hist)); } function WikiShWriteHist($pagename, $opt, $histfile, $histflds, $action, $match=false, $matchlines=false, $matchaction=false, $ifs=':') { global $WikiShVars, $WikiShWriteList, $MessagesFmt; $func = 'WikiShWriteHist'; if (!WikiShMatchPageName($WikiShVars['HISTFILE'], $WikiShWriteList)) { $MessagesFmt[] = "!!CONTROL PANEL MESSAGE: History file ($WikiShVars[HISTFILE]) not included in \$WikiShWriteList. History/Favorites writing suppressed."; return (''); } wdbg(3,"$func: Entering (histflds follows)"); $nl = ((isset($opt['newline'])) ? $opt['newline'] : "\n"); $stdout = $histfile; if ($action == 'prepend') { $stdout_op = '<'; $stdout_loc = '_TOP'; } elseif ($action == 'append') { $stdout_op = '>'; $stdout_loc = '_END'; } else { $stdout_op = $stdout_loc = false; } if ($stdout_op) if ((substr($stdout, 0, strlen(TEXTFILEID)) != TEXTFILEID) && (substr($stdout, 0, strlen(WIKIPAGEID)) != WIKIPAGEID)) $stdout = WIKIPAGEID . $stdout; $oldpage = ShReadPage($pagename, $opt, $stdout); if ($oldpage) $final = $oldpage['text']; else $final = ''; $histvars = array(); if ($final) { while (preg_match("/^\s*\(:([^:\s]+)\s*:\s*(\S+)\s*:\)(?:\n)?/", $final, $m)) { $histvars[$m[1]] = $m[2]; $final = substr($final, strlen($m[0])); } if (isset($WikiShVars['HIST_PREFIX']) && substr($final, 0, strlen($WikiShVars['HIST_PREFIX'])) == $WikiShVars['HIST_PREFIX']) { $final = substr($final, strlen($WikiShVars['HIST_PREFIX'])); } } foreach($histflds as $k => $h) { if (preg_match("/^\s*AUTOINC\((\w+)\)\s*$/", $h, $m)) { if (isset($histvars[$m[1]])) $histflds[$k] = ++$histvars[$m[1]]; else { $histflds[$k] = 1; $histvars[$m[1]] = 1; } } elseif (strstr($h, 'NOW()')) $histflds[$k] = time(); } $histtext = implode($ifs, $histflds); if (!$match) { if ($action == 'append') $final .= $nl . $histtext; else $final = $histtext . $nl . $final; } else { if ($final) $lines = explode("\n", $final); else $lines = array(); if ($matchlines == 0) { $start = 0; $end = sizeof($lines); } elseif ($matchlines > 0) { $start = 0; $end = $matchlines; } else { $start = sizeof($lines) + $matchlines; $end = sizeof($lines); } $unique = true; for ($i = $start; $i < $end; $i++) { $flds = explode($ifs, $lines[$i]); $matched = false; for ($j = 0; $j < sizeof($flds); $j++) { if ($match[$j] && $match[$j] === $flds[$j]) { $matched = true; } else { } } if ($matched) { switch ($matchaction) { case 'delete': unset($lines[$i]); break; case 'replace': $lines[$i] = $histtext; break; case 'unique': $unique = false; break 2; } } } if ($unique) { if ($action == 'append') $lines[] = $histtext; else array_unshift($lines, $histtext); } $final = implode("\n", $lines); } if (isset($WikiShVars['HIST_PREFIX'])) $final = $WikiShVars['HIST_PREFIX'] . $final; foreach ($histvars as $k => $v) { $final = "(:$k:$v:)\n" . $final; } if (!WikiShWrite($pagename, $opt, $stdout, 'wiki', $final, $oldpage)) { $WikiShVars['STATUS'] = 2; return(''); } return (''); } function ShPostProcess($pagename, $opt, $outrows, $page = array('type' => 'inline', 'text' => '', 'filename' => '-')) { global $WikiShVars; $func = 'ShPostProcess'; $nl = ((isset($opt['newline'])) ? $opt['newline'] : "\n"); if ($outrows) $final = implode($nl, $outrows); else $outrows = ''; if (isset($opt['markup'])) { $final = str_replace( array('{', '}', '(', ')', '<', '>'), array('{','}','(',')','‹', '›'), $final); } $rtn = $final; if (isset($opt['stdout'])) { if (!isset($opt['stdout_type'])) { if (isatextfile('', $opt['stdout'])) $opt['stdout_type'] = 'text'; elseif (isasessionfile('', $opt['stdout']) || isasessiongroup($opt['stdout'])) $opt['stdout_type'] = 'session'; else $opt['stdout_type'] = 'wiki'; } if (isset($opt['stdout_op']) && isset($opt['stdout_loc'])) { $stdout = $opt['stdout']; $stdout_op = $opt['stdout_op']; $stdout_loc = $opt['stdout_loc']; } elseif (preg_match("/^>>([\w.\/]+)$/", $opt['stdout'], $match)) { $stdout = $match[1]; if (isatextfile('', $stdout)) $stdout = substr($stdout, strlen(TEXTFILEID)); if (isasessionfile('', $stdout)) $stdout = substr($stdout, strlen(SESSFILEID)); $stdout_op = '>'; $stdout_loc = '_END'; } elseif (preg_match("/^>([\w.\/]+)(?:([<>])(\w+))?$/", $opt['stdout'], $match)) { $stdout = $match[1]; $stdout_op = $match[2]; $stdout_loc = $match[3]; } else $stdout = $opt['stdout']; if ($stdout_op) { if (!isatextfile('', $stdout) && !isasessionfile('', $stdout) && !isawikipage('', $stdout)) { if ($opt['stdout_type'] == 'text') $tmp_stdout = TEXTFILEID . $stdout; elseif ($opt['stdout_type'] == 'session') $tmp_stdout = SESSFILEID . $stdout; else $tmp_stdout = WIKIPAGEID . $stdout; } $oldpage = ShReadPage($pagename, $opt, $tmp_stdout); if ($oldpage['text']) { if ($stdout_op == '>' && ($stdout_loc == '_END' || $stdout_loc == '_BOTTOM')) { $final = $oldpage['text'] . "\n" . $final; } elseif ($stdout_op == '<' && ($stdout_loc == '_TOP' || $stdout_loc == '_BEGIN')) { $final = $final . "\n" . $oldpage['text']; } else { $rows = explode("\n", $oldpage['text']); if ($stdout_loc == '_TOP' || $stdout_loc == '_BEGIN') { $rowloc = 0; } elseif ($stdout_loc == '_END' || $stdout_loc == '_BOTTOM') { $rowloc = sizeof($rows); } else { for ($i = 0; $i < sizeof($rows); $i++) { $foundrow = false; if (preg_match("/$stdout_loc/", $rows[$i])) { $rowloc = $i; $foundrow = true; break; } } if (!$foundrow) { if ($stdout_op == '<') $rowloc = 0; else $rowloc = sizeof($rows); } } if ($stdout_op == '>') $rowloc++; if ($rowloc > 0) $final = implode("\n", array_slice($rows, 0, $rowloc)) . "\n" . $final; if ($rowloc < sizeof($rows)) $final .= "\n" . implode("\n", array_slice($rows, $rowloc)); } } } if ($opt['encrypt'] && function_exists('WikiShEncrypt')) $final = WikiShEncrypt($pagename, $opt, $final); if (!WikiShWrite($pagename, $opt, $stdout, $opt['stdout_type'], $final, $page)) { $WikiShVars['STATUS'] = 2; return(''); } if (!@$opt['tee']) { $final = ''; $rtn = ''; } } return ($rtn); } function SetDefaultOpt(&$opt, $key, $val) { if (!isset($opt[$key])) $opt[$key] = $val; } function ExtractLines($pagename, $opt, $filelist, $func) { wdbg(3,"ExtractLines(): Entering"); $func .= '-EL'; ExpandWildcards($pagename, $opt, $filelist, false, false, false); SetDefaultOpt($opt, 'file_prefix', ''); SetDefaultOpt($opt, 'line_prefix', ''); SetDefaultOpt($opt, 'line_suffix', ''); SetDefaultOpt($opt, 'inplaceedit', false); SetDefaultOpt($opt, 'printall', false); if ($opt['repl']) { foreach ($opt['repl'] as $k => $v) { $opt['repl'][$k] = preg_replace("/\\\\(.)/", "$1", $v); } } $newrows = array(); $postrows = array(); foreach ($filelist as $filename) { $page = ShReadPage($pagename, $opt, $filename); if (isabadfile($page)) { WikiShStdErr($pagename, $opt, "ERROR: $func: No such page: $page[filename]"); continue; } $textrows = explode("\n", $page['text']); $file_prefix_printed = false; $line_prefix = WShReplace($opt, $page, $opt['line_prefix']); $line_suffix = WShReplace($opt, $page, $opt['line_suffix']); $startlines = $opt['startline']; $endlines = $opt['endline']; for ($i=0; $i= $start[$i]) || (!is_numeric($start[$i]) && preg_match($start[$i], $line))) $matchstatus[$i] = 1; if ($matchstatus[$i] == 1) $matched = true; if (!is_numeric($end[$i]) && preg_match($end[$i], $line)) $matchstatus[$i] = 0; if (is_numeric($end[$i]) && $curlineno >= $end[$i]) $matchstatus[$i] = 2; } return($matched); } function WShReplace($opt, $page, $string, $lineno='') { if ($string == '') return ''; $find_str = array('PAGENAME', 'PAGELINK'); $repl_str = array($page['filename'], "[[" . $page['filename'] . "]]"); if (is_numeric($lineno)) { $find_str[] = 'LINENO'; $repl_str[] = $lineno; } if (strstr($string, 'PAGETITLE')) { $find_str[] = 'PAGETITLE'; $repl_str[] = PageVar($page['filename'], '$Title'); } $string = str_replace($find_str, $repl_str, $string); return($string); } function WikiShNotNow($OverrideActive = false) { global $WikiShVars, $WikiShRCPages, $action, $WikiShWriting, $MXWhileEditing; static $RCDone = false; $OKActions = array('browse', 'search', 'approvesites'); if (!$RCDone) { $OldDfltDbg = $WikiShVars['DEFAULT_DEBUG']; $OldDbg = $WikiShVars['DEBUGLEVEL']; $WikiShVars['DEBUGLEVEL'] = $WikiShVars['RC_DEBUG']; foreach ($WikiShRCPages as $k => $rcpagename) { if (isset($WikiShVars[$rcpagename])) { $tmp = $WikiShVars[$rcpagename]; unset($WikiShRCPages[$k]); MarkupExpression($rcpagename, "(wikish source $tmp)"); } } if ($OldDfltDbg == $WikiShVars['DEFAULT_DEBUG']) $WikiShVars['DEBUGLEVEL'] = $OldDbg; else $WikiShVars['DEBUGLEVEL'] = $WikiShVars['DEFAULT_DEBUG']; $RCDone = true; } if ((!$OverrideActive && !$WikiShVars['ACTIVE']) || (!in_array($action, $OKActions) && !$MXWhileEditing) || ($MXWhileEditing && $action != 'edit') || $WikiShWriting) { return(true); } else { return(false); } } function WikiShFmtPagename($pagename, $opt, $tgt) { return(MakePageName($pagename, $tgt)); } function unhtmlspecialchars(&$str) { $rplc = array( '<' => '<', '≤' => '<=', '>' => '>', '≥' => '>=', ' ' => ' ', '&' => '&'); $str = str_replace(array_keys($rplc), array_values($rplc), $str); return($str); } function WikiShTextSection($text, $sections, &$pre, &$post, $args = NULL) { $args = (array)$args; $npat = '[[:alpha:]][-\\w*]*'; if (!preg_match("/#($npat)?(\\.\\.)?(#($npat)?)?/", $sections, $match)) return $text; @list($x, $aa, $dots, $b, $bb) = $match; if (!$dots && !$b) $bb = $npat; if ($aa) { $pos = strpos($text, "[[#$aa]]"); if ($pos === false) return false; if (@$args['anchors']) while ($pos > 0 && $text[$pos-1] != "\n") $pos--; else $pos += strlen("[[#$aa]]"); $pre = substr($text, 0, $pos); $text = substr($text, $pos); } if ($bb) { $post = $text; $text = preg_replace("/(\n)[^\n]*\\[\\[#$bb\\]\\](.*)$/s", '$1', $text, 1); $post = substr($post, strlen($text)); } return $text; } function WikiShParseCode($code, $SuppressKeep = false) { global $KeepToken, $KPV, $MarkupExpr; $rpat = "/$KeepToken(\\d+P)$KeepToken/e"; $rrep = '$KPV[\'$1\']'; $func = "ParseCode"; $newlines = array(); $codelines = explode("\n", $code); foreach ($codelines as $line) { if ($SuppressKeep) { $line = preg_replace('/(([\'"]).*?\\2)/e', "Keep(PSS('$1'),'P')", $line); } else { $line = preg_replace('/([\'"])(.*?)\\1/e', "Keep(PSS('$2'),'P')", $line); $line = preg_replace('/\\(\\W/e', "Keep(PSS('$2'),'P')", $line); } $line = preg_replace("/(?:^|\s)\s*#.*$/", "", $line); if ($SuppressKeep) { $line = preg_replace($rpat, $rrep, $line); } if ($line && !preg_match("/^\s*$/", $line)) $newlines[] = $line; } $newcode = implode(";", $newlines); $newcode = preg_replace("/;*$/", "", $newcode) . ';'; return($newcode); } function WikiShStdErr($pagename, $opt, $text) { global $MessagesFmt; SDV($opt['stderr'], 'echo'); switch ($opt['stderr']) { case 'messages': if (is_array($text)) { $MessagesFmt[] = "
" . print_r($text,true) . "

\n"; } else { $MessagesFmt[] = $text . "\n"; } break; case 'echo': if (is_array($text)) { echo "
" . print_r($text,true) . "

\n"; } else { echo $text . "
\n"; } break; case 'nul': case 'null': case '/dev/null': break; default: echo "ERROR: Unhandled stderr=$opt[stderr]
\n"; } } if (!function_exists("wdbg")) { function wdbg($printlevel, $text, $txt2 = '', $txt3 = '') { global $MessagesFmt, $WikiShVars; if ($printlevel<$WikiShVars['DEBUGLEVEL']) return; foreach (array($text, $txt2, $txt3) as $txt) { if ($txt == '') break; elseif (is_array($text)) { $MessagesFmt[] = "
" . print_r($text,true) . "
" . ($newline ? "\n" : ""); } else { $suffix = ""; for ($i = 4-$printlevel; $i > 0; $i--) { $prefix .= "
"; $suffix .= "
"; } $prefix .= "
  • "; $MessagesFmt[] = $prefix . $text . $suffix . "\n"; } } } } $MarkupExpr["wikish_devtest"] = 'WikiShDevTest($pagename, @$argp, @$args)'; function WikiShDevTest($page, $opts, $args) { global $WikiShVars, $InputValues, $FmtV, $foo; echo "PRE: " . print_r($opts,true) . "
    \n"; } function WikiShMatchPageName($page, $pat, $allowslash = false) { $MatchedInclusive = false; foreach((array)$pat as $p) { if (!$p) continue; switch ($p{0}) { case '/': if (preg_match($p, $page)) $MatchedInclusive = true; continue; case '!': if (preg_match($p, $page)) return(false); continue; default: if ($allowslash) list($inclp, $exclp) = GlobToPCRE($p); else list($inclp, $exclp) = GlobToPCRE(str_replace('/', '.', $p)); if ($exclp && preg_match("/$exclp/i", $page)) return(false); if ($inclp && preg_match("/$inclp/i", $page)) $MatchedInclusive = true; } } return $MatchedInclusive; } function WikiShGlobToPCRE($pat, $anchor_beg=false, $anchor_end=false, $greedy=true) { $pat = preg_quote($pat, '/'); $pat = str_replace(array('\\*', '\\?', '\\[', '\\]', '\\^'), array('.*' . ($greedy?'':'?'), '.', '[', ']', '^'), $pat); $incl = array(); foreach(preg_split('/,+\s?/', $pat, -1, PREG_SPLIT_NO_EMPTY) as $p) { $incl[] = ($anchor_beg?'^':'') . "$p" . ($anchor_end?'$':''); } return (implode('|', $incl)); }