function imagePulldown($query, $case_exact = false, $regex = 'auto') { global $WikiTheme; $image_dir = getUploadFilePath(); $pd = new fileSet($image_dir, '*'); $images = $pd->getFiles(); unset($pd); if (UPLOAD_USERDIR) { $image_dir .= "/" . $request->_user->_userid; $pd = new fileSet($image_dir, '*'); $images = array_merge($images, $pd->getFiles()); unset($pd); } sort($images); if (!empty($images)) { $image_js = ''; foreach ($images as $image) { // Select only image and video files if (is_image($image) or is_video($image)) { $image_js .= ",['{$image}','{{" . $image . "}}']"; } } $image_js = substr($image_js, 1); $more_buttons = HTML::img(array('class' => "toolbar", 'id' => 'tb-images', 'src' => $WikiTheme->getImageURL("ed_image.png"), 'title' => _("Add Image or Video"), 'alt' => _("Add Image or Video"), 'onclick' => "showPulldown('" . _("Insert Image or Video") . "',[" . $image_js . "],'" . _("Insert") . "','" . _("Close") . "','tb-images')")); return HTML("\n", $more_buttons); } return ''; }
function link($link, $linktext = false) { global $WikiTheme; list($moniker, $page) = explode(":", $link, 2); if (!isset($this->_map[$moniker])) { return HTML::span(array('class' => 'bad-interwiki'), $linktext ? $linktext : $link); } $url = $this->_map[$moniker]; // localize Upload:links for WIKIDUMP if (!empty($WikiTheme->DUMP_MODE) and $moniker == 'Upload') { global $request; include_once "lib/config.php"; $url = getUploadFilePath(); // calculate to a relative local path to /uploads for pdf images. $doc_root = $request->get("DOCUMENT_ROOT"); $ldir = NormalizeLocalFileName($url); $wikiroot = NormalizeLocalFileName(''); if (isWindows()) { $ldir = strtolower($ldir); $doc_root = strtolower($doc_root); $wikiroot = strtolower($wikiroot); } if (string_starts_with($ldir, $doc_root)) { $link_prefix = substr($url, strlen($doc_root)); } elseif (string_starts_with($ldir, $wikiroot)) { $link_prefix = NormalizeWebFileName(substr($url, strlen($wikiroot))); } } // Urlencode page only if it's a query arg. // FIXME: this is a somewhat broken heuristic. if ($moniker == 'Upload') { $page_enc = $page; $page = rawurldecode($page); } else { $page_enc = strstr($url, '?') ? rawurlencode($page) : $page; } if (strstr($url, '%s')) { $url = sprintf($url, $page_enc); } else { $url .= $page_enc; } $link = HTML::a(array('href' => $url)); if (!$linktext) { $link->pushContent(PossiblyGlueIconToText('interwiki', "{$moniker}:"), HTML::span(array('class' => 'wikipage'), $page)); $link->setAttr('class', 'interwiki'); } else { $link->pushContent(PossiblyGlueIconToText('interwiki', $linktext)); $link->setAttr('class', 'named-interwiki'); } return $link; }
function text2png($args) { extract($args); /** * Basic image creation and caching * * You MUST delete the image cache yourself in /images if you * change the drawing routines! */ $filename = urlencode($text) . ".png"; // protect by urlencode!!! /** * FIXME: need something more elegant, and a way to gettext a * different language depending on any individual * user's locale preferences. */ if ($l == "C") { $l = "en"; //english=C } else { $l = urlencode($l); // who on earth forgot his? } $basedir = "text2png-image"; $filepath = getUploadFilePath() . "{$basedir}/{$l}"; if ($_force or !file_exists($filepath . $filename)) { if (!file_exists($filepath)) { $oldumask = umask(0); // permissions affected by user the www server is running as mkdir(getUploadFilePath() . $basedir, 0777); mkdir($filepath, 0777); umask($oldumask); } $filepath .= "/"; /** * prepare a new image * * FIXME: needs a dynamic image size depending on text * width and height */ // got this logic from GraphViz if (defined('TTFONT')) { $ttfont = TTFONT; } elseif (PHP_OS == "Darwin") { // Mac OS X $ttfont = "/System/Library/Frameworks/JavaVM.framework/Versions/1.3.1/Home/lib/fonts/LucidaSansRegular.ttf"; } elseif (isWindows()) { $ttfont = $_ENV['windir'] . '\\Fonts\\Arial.ttf'; } else { $ttfont = 'luximr'; // This is the only what sourceforge offered. //$ttfont = 'Helvetica'; } /* http://download.php.net/manual/en/function.imagettftext.php * array imagettftext (int im, int size, int angle, int x, int y, * int col, string fontfile, string text) */ // get ready to draw $s = ImageTTFBBox($fontsize, 0, $ttfont, $text); $im = @ImageCreate(abs($s[4]) + 20, abs($s[7]) + 10); if (empty($im)) { $error_html = _("PHP was unable to create a new GD image stream. Read 'lib/plugin/text2png.php' for details."); // FIXME: Error manager does not transform URLs passed // through it. $link = "http://www.php.net/manual/en/function.imagecreate.php"; $error_html .= sprintf(_("See %s"), $link) . "."; trigger_error($error_html, E_USER_NOTICE); return; } $rgb = $this->hexcolor($backcolor, array(255, 255, 255)); $bg_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); if ($with_shadow) { $rgb = $this->hexcolor($shadowcolor, array(175, 175, 175)); $text_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); // shadow is 1 pixel down and 2 pixels right ImageTTFText($im, $fontsize, 0, 12, abs($s[7]) + 6, $text_color, $ttfont, $text); } // draw text $rgb = $this->hexcolor($fontcolor, array(0, 0, 0)); $text_color = ImageColorAllocate($im, $rgb[0], $rgb[1], $rgb[2]); ImageTTFText($im, $fontsize, 0, 10, abs($s[7]) + 5, $text_color, $ttfont, $text); /** * An alternate text drawing method in case ImageTTFText * doesn't work. **/ //ImageString($im, 2, 10, 40, $text, $text_color); // To dump directly to browser: //header("Content-type: image/png"); //ImagePng($im); // to save to file: $success = ImagePng($im, $filepath . $filename); } else { $filepath .= "/"; $success = 2; } // create an <img src= tag to show the image! $html = HTML(); if ($success > 0) { if (defined('text2png_debug')) { switch ($success) { case 1: trigger_error(sprintf(_("Image saved to cache file: %s"), $filepath . $filename), E_USER_NOTICE); case 2: trigger_error(sprintf(_("Image loaded from cache file: %s"), $filepath . $filename), E_USER_NOTICE); } } $url = getUploadDataPath() . "{$basedir}/" . urlencode($l) . "/" . urlencode($filename); $html->pushContent(HTML::img(array('src' => $url, 'alt' => $text, 'title' => '"' . $text . '"' . _(" produced by ") . $this->getName()))); } else { trigger_error(sprintf(_("couldn't open file '%s' for writing"), $filepath . $filename), E_USER_NOTICE); } return $html; }
/** * Inline Images * * Syntax: [image.png size=50% border=n align= hspace= vspace= width= height=] * Disallows sizes which are too small. * Spammers may use such (typically invisible) image attributes to raise their GoogleRank. * * Handle embeddable objects, like svg, class, vrml, swf, svgz, pdf, avi, wmv especially. */ function LinkImage($url, $alt = "") { $force_img = "png|jpg|gif|jpeg|bmp|pl|cgi"; // Disallow tags in img src urls. Typical CSS attacks. // FIXME: Is this needed (or sufficient?) // FIXED: This was broken for moniker:TP30 test/image.png => url="moniker:TP30" attr="test/image.png" $ori_url = $url; // support new syntax: [prefix/image.jpg size=50% border=n] if (empty($alt)) { $alt = ""; } // Extract URL $arr = explode(' ', $url); if (!empty($arr)) { $url = $arr[0]; } if (!IsSafeURL($url)) { $link = HTML::span(array('class' => 'error'), _("BAD URL -- remove all of <, >, \"")); return $link; } // spaces in inline images must be %20 encoded! $link = HTML::img(array('src' => $url)); // Extract attributes $arr = parse_attributes(strstr($ori_url, " ")); foreach ($arr as $attr => $value) { // These attributes take strings: lang, id, title, alt if ($attr == "lang" || $attr == "id" || $attr == "title" || $attr == "alt") { $link->setAttr($attr, $value); } elseif ($attr == "align" && ($value == "bottom" || $value == "middle" || $value == "top" || $value == "left" || $value == "right")) { $link->setAttr($attr, $value); } elseif (($attr == "border" || $attr == "hspace" || $attr == "vspace") && is_numeric($value)) { $link->setAttr($attr, (int) $value); } elseif (($attr == "height" || $attr == "width") && preg_match('/\\d+[%p]?x?/', $value)) { $link->setAttr($attr, $value); } elseif ($attr == "size") { if (preg_match('/(\\d+%)/', $value, $m)) { $link->setAttr('width', $m[1]); $link->setAttr('height', $m[1]); } elseif (preg_match('/(\\d+)x(\\d+)/', $value, $m)) { $link->setAttr('width', $m[1]); $link->setAttr('height', $m[2]); } } else { $link = HTML::span(array('class' => 'error'), sprintf(_("Invalid image attribute \"%s\" %s=%s"), $url, $attr, $value)); return $link; } } // Correct silently the most common error if ($url != $ori_url and empty($arr) and !preg_match("/^http/", $url)) { // space belongs to the path $file = NormalizeLocalFileName($ori_url); if (file_exists($file)) { $link = HTML::img(array('src' => $ori_url)); trigger_error(sprintf(_("Invalid image link fixed %s => %s. Spaces must be quoted with %%20."), $url, $ori_url), E_USER_WARNING); } elseif (string_starts_with($ori_url, getUploadDataPath())) { $file = substr($file, strlen(getUploadDataPath())); $path = getUploadFilePath() . $file; if (file_exists($path)) { trigger_error(sprintf(_("Invalid image link fixed \"%s\" => \"%s\".\n Spaces must be quoted with %%20."), $url, $ori_url), E_USER_WARNING); $link->setAttr('src', getUploadDataPath() . $file); $url = $ori_url; } } } if (!$link->getAttr('alt')) { $link->setAttr('alt', $alt); } // Check width and height as spam countermeasure if ($width = $link->getAttr('width') and $height = $link->getAttr('height')) { //$width = (int) $width; // px or % or other suffix //$height = (int) $height; if ($width < 3 and $height < 10 or $height < 3 and $width < 20 or $height < 7 and $width < 7) { $link = HTML::span(array('class' => 'error'), _("Invalid image size")); return $link; } } else { $size = 0; // Prepare for getimagesize($url) // $url only valid for external urls, otherwise local path if (DISABLE_GETIMAGESIZE) { } elseif (!preg_match("/\\.{$force_img}\$/i", $url)) { } elseif (preg_match("/^http/", $url)) { // external url $size = @getimagesize($url); } else { // local file if (file_exists($file = NormalizeLocalFileName($url))) { // here $size = @getimagesize($file); } elseif (file_exists(NormalizeLocalFileName(urldecode($url)))) { $size = @getimagesize($file); $link->setAttr('src', rawurldecode($url)); } elseif (string_starts_with($url, getUploadDataPath())) { // there $file = substr($file, strlen(getUploadDataPath())); $path = getUploadFilePath() . rawurldecode($file); $size = @getimagesize($path); $link->setAttr('src', getUploadDataPath() . rawurldecode($file)); } else { // elsewhere global $request; $size = @getimagesize($request->get('DOCUMENT_ROOT') . urldecode($url)); } } if ($size) { $width = $size[0]; $height = $size[1]; if ($width < 3 and $height < 10 or $height < 3 and $width < 20 or $height < 7 and $width < 7) { $link = HTML::span(array('class' => 'error'), _("Invalid image size")); return $link; } } } $link->setAttr('class', 'inlineimage'); /* Check for inlined objects. Everything allowed in INLINE_IMAGES besides * png|jpg|gif|jpeg|bmp|pl|cgi. If no image it is an object to embed. * Note: Allow cgi's (pl,cgi) returning images. */ if (!preg_match("/\\.(" . $force_img . ")/i", $url)) { // HTML::img(array('src' => $url, 'alt' => $alt, 'title' => $alt)); // => HTML::object(array('src' => $url)) ...; return ImgObject($link, $ori_url); } return $link; }
/** * static workaround on broken Cache or broken dot executable, * called only if debug=static. * * @access private * @param url string url pointing to the image part of the map * @param map string <area> tags defining active * regions in the map * @param dbi WikiDB database abstraction class * @param argarray array complete (!) arguments to produce * image. It is not necessary to call * WikiPlugin->getArgs anymore. * @param request Request ??? * @return string html output */ function embedImg($url, &$dbi, $argarray, &$request) { if (!VISUALWIKI_ALLOWOPTIONS) { $argarray = $this->defaultarguments(); } $this->checkArguments($argarray); //extract($argarray); if ($argarray['help']) { return array($this->helpImage(), ' '); } // FIXME $this->createColors(); $this->extract_wikipages($dbi, $argarray); list($imagehandle, $content['html']) = $this->invokeDot($argarray); // write to uploads and produce static url $file_dir = getUploadFilePath(); $upload_dir = getUploadDataPath(); $tmpfile = tempnam($file_dir, "VisualWiki") . "." . $argarray['imgtype']; WikiPluginCached::writeImage($argarray['imgtype'], $imagehandle, $tmpfile); ImageDestroy($imagehandle); return WikiPluginCached::embedMap(1, $upload_dir . basename($tmpfile), $content['html'], $dbi, $argarray, $request); }
function _DumpHtmlToDir($target, $page_iter, $exclude = false) { global $WikiTheme, $request, $ErrorManager; $silent = true; $zip = false; $directory = false; if ($WikiTheme->DUMP_MODE == 'HTML') { $directory = $target; $silent = false; } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') { $directory = $target; } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML' $zip = $target; } $request->_TemplatesProcessed = array(); if ($exclude) { // exclude which pagenames $excludeList = explodePageList($exclude); } else { $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo'); } $WikiTheme->VALID_LINKS = array(); if ($request->getArg('format')) { // pagelist $page_iter_sav = $page_iter; foreach ($page_iter_sav->asArray() as $handle) { $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName(); } $page_iter_sav->reset(); } if (defined('HTML_DUMP_SUFFIX')) { $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX; } $_bodyAttr = @$WikiTheme->_MoreAttr['body']; unset($WikiTheme->_MoreAttr['body']); $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler')); // check if the dumped file will be accessible from outside $doc_root = $request->get("DOCUMENT_ROOT"); if ($WikiTheme->DUMP_MODE == 'HTML') { $ldir = NormalizeLocalFileName($directory); $wikiroot = NormalizeLocalFileName(''); if (string_starts_with($ldir, $doc_root)) { $link_prefix = substr($directory, strlen($doc_root)) . "/"; } elseif (string_starts_with($ldir, $wikiroot)) { $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot))) . "/"; } else { $prefix = ''; if (isWindows()) { $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed } $link_prefix = "file://" . $prefix . $directory . "/"; } } else { $link_prefix = ""; } $request_args = $request->args; $timeout = !$request->getArg('start_debug') ? 60 : 240; if ($directory) { if (isWindows()) { $directory = str_replace("\\", "/", $directory); } // no Win95 support. @mkdir("{$directory}/images"); } $already = array(); $outfiles = array(); $already_images = array(); while ($page = $page_iter->next()) { if (is_string($page)) { $pagename = $page; $page = $request->_dbi->getPage($pagename); } else { $pagename = $page->getName(); } if (empty($firstpage)) { $firstpage = $pagename; } if (array_key_exists($pagename, $already)) { continue; } $already[$pagename] = 1; $current = $page->getCurrentRevision(); //if ($current->getVersion() == 0) // continue; $request->args = $request_args; // some plugins might change them (esp. on POST) longer_timeout($timeout); // Reset watchdog if ($zip) { $attrib = array('mtime' => $current->get('mtime'), 'is_ascii' => 1); if ($page->get('locked')) { $attrib['write_protected'] = 1; } } elseif (!$silent) { if (!isa($request, 'MockRequest')) { PrintXML(HTML::br(), $pagename, ' ... '); flush(); } } if (in_array($pagename, $excludeList)) { if (!$silent and !isa($request, 'MockRequest')) { PrintXML(_("Skipped.")); flush(); } continue; } $relative_base = ''; if ($WikiTheme->DUMP_MODE == 'PDFHTML') { $request->setArg('action', 'pdf'); } // to omit cache headers $request->setArg('pagename', $pagename); // Template::_basepage fix $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX; $args = array('revision' => $current, 'CONTENT' => $current->getTransformedContent(), 'relative_base' => $relative_base); // For every %2F will need to mkdir -p dirname($pagename) if (preg_match("/(%2F|\\/)/", $filename)) { // mkdir -p and set relative base for subdir pages $filename = preg_replace("/%2F/", "/", $filename); $count = substr_count($filename, "/"); $dirname = dirname($filename); if ($directory) { mkdir_p($directory . "/" . $dirname); } // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written // if (isWindows()) // interesting Windows bug: cannot mkdir "bla " // Since dumps needs to be copied, we have to disallow this for all platforms. $filename = preg_replace("/ \\//", "/", $filename); $relative_base = "../"; while ($count > 1) { $relative_base .= "../"; $count--; } $args['relative_base'] = $relative_base; } $msg = HTML(); $DUMP_MODE = $WikiTheme->DUMP_MODE; $data = GeneratePageasXML(new Template('browse', $request, $args), $pagename, $current, $args); $WikiTheme->DUMP_MODE = $DUMP_MODE; if (preg_match_all("/<img .*?src=\"(\\/.+?)\"/", $data, $m)) { // fix to local relative path for uploaded images, so that pdf will work foreach ($m[1] as $img_file) { $base = basename($img_file); $data = str_replace('src="' . $img_file . '"', 'src="images/' . $base . '"', $data); if (array_key_exists($img_file, $already_images)) { continue; } $already_images[$img_file] = 1; // resolve src from webdata to file $src = $doc_root . $img_file; if (file_exists($src) and $base) { if ($directory) { $target = "{$directory}/images/{$base}"; if (copy($src, $target)) { if (!$silent) { _copyMsg($img_file, fmt("... copied to %s", $target)); } } else { if (!$silent) { _copyMsg($img_file, fmt("... not copied to %s", $target)); } } } else { $target = "images/{$base}"; $zip->addSrcFile($target, $src); } } } } if ($directory) { $outfile = $directory . "/" . $filename; if (!($fd = fopen($outfile, "wb"))) { $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing", $outfile))); $request->finish($msg); } $len = strlen($data); $num = fwrite($fd, $data, $len); if ($pagename != $filename) { $link = LinkURL($link_prefix . $filename, $filename); $msg->pushContent(HTML::small(_("saved as "), $link, " ... ")); } $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n")); if (!$silent) { if (!isa($request, 'MockRequest')) { PrintXML($msg); } flush(); $request->chunkOutput(); } assert($num == $len); fclose($fd); $outfiles[] = $outfile; } else { $zip->addRegularFile($filename, $data, $attrib); } if (USECACHE) { $request->_dbi->_cache->invalidate_cache($pagename); unset($request->_dbi->_cache->_pagedata_cache); unset($request->_dbi->_cache->_versiondata_cache); unset($request->_dbi->_cache->_glv_cache); } unset($request->_dbi->_cache->_backend->_page_data); unset($msg); unset($current->_transformedContent); unset($current); if (!empty($template)) { unset($template->_request); unset($template); } unset($data); } $page_iter->free(); $attrib = false; //array('is_ascii' => 0); if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) { // @mkdir("$directory/images"); foreach ($WikiTheme->dumped_images as $img_file) { if (array_key_exists($img_file, $already_images)) { continue; } $already_images[$img_file] = 1; if ($img_file and $from = $WikiTheme->_findFile($img_file, true) and basename($from)) { if ($directory) { $target = "{$directory}/images/" . basename($from); if ($silent) { copy($WikiTheme->_path . $from, $target); } else { if (copy($WikiTheme->_path . $from, $target)) { _copyMsg($from, fmt("... copied to %s", $target)); } else { _copyMsg($from, fmt("... not copied to %s", $target)); } } } else { $target = "images/" . basename($from); $zip->addSrcFile($target, $WikiTheme->_path . $from); } } elseif (!$silent) { _copyMsg($from, _("... not found")); } } } if (!empty($WikiTheme->dumped_buttons) and is_array($WikiTheme->dumped_buttons)) { // Buttons also if ($directory) { @mkdir("{$directory}/images/buttons"); } foreach ($WikiTheme->dumped_buttons as $text => $img_file) { if (array_key_exists($img_file, $already_images)) { continue; } $already_images[$img_file] = 1; if ($img_file and $from = $WikiTheme->_findFile($img_file, true) and basename($from)) { if ($directory) { $target = "{$directory}/images/buttons/" . basename($from); if ($silent) { copy($WikiTheme->_path . $from, $target); } else { if (copy($WikiTheme->_path . $from, $target)) { _copyMsg($from, fmt("... copied to %s", $target)); } else { _copyMsg($from, fmt("... not copied to %s", $target)); } } } else { $target = "images/buttons/" . basename($from); $zip->addSrcFile($target, $WikiTheme->_path . $from); } } elseif (!$silent) { _copyMsg($from, _("... not found")); } } } if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) { foreach ($WikiTheme->dumped_css as $css_file) { if (array_key_exists($css_file, $already_images)) { continue; } $already_images[$css_file] = 1; if ($css_file and $from = $WikiTheme->_findFile(basename($css_file), true) and basename($from)) { // TODO: fix @import url(main.css); if ($directory) { $target = "{$directory}/" . basename($css_file); if ($silent) { copy($WikiTheme->_path . $from, $target); } else { if (copy($WikiTheme->_path . $from, $target)) { _copyMsg($from, fmt("... copied to %s", $target)); } else { _copyMsg($from, fmt("... not copied to %s", $target)); } } } else { //$attrib = array('is_ascii' => 0); $target = basename($css_file); $zip->addSrcFile($target, $WikiTheme->_path . $from); } } elseif (!$silent) { _copyMsg($from, _("... not found")); } } } if ($zip) { $zip->finish(); } if ($WikiTheme->DUMP_MODE == 'PDFHTML') { if (USE_EXTERNAL_HTML2PDF and $outfiles) { $cmd = EXTERNAL_HTML2PDF_PAGELIST . ' "' . join('" "', $outfiles) . '"'; $filename = FilenameForPage($firstpage); if (DEBUG) { $tmpfile = $directory . "/createpdf.bat"; $fp = fopen($tmpfile, "wb"); fwrite($fp, $cmd . " > {$filename}.pdf"); fclose($fp); } if (!headers_sent()) { Header('Content-Type: application/pdf'); passthru($cmd); } else { $tmpdir = getUploadFilePath(); $s = passthru($cmd . " > {$tmpdir}/{$filename}.pdf"); $errormsg = "<br />\nGenerated <a href=\"" . getUploadDataPath() . "{$filename}.pdf\">Upload:{$filename}.pdf</a>\n"; $errormsg .= $s; echo $errormsg; } if (!DEBUG) { foreach ($outfiles as $f) { unlink($f); } } } if (!empty($errormsg)) { $request->discardOutput(); $GLOBALS['ErrorManager']->_postponed_errors = array(); } } $ErrorManager->popErrorHandler(); $WikiTheme->HTML_DUMP_SUFFIX = ''; $WikiTheme->DUMP_MODE = false; $WikiTheme->_MoreAttr['body'] = $_bodyAttr; }
function run($dbi, $argstr, &$request, $basepage) { $this->disallowed_extensions = explode("\n", "ad[ep]\nasd\nba[st]\nchm\ncmd\ncom\ncgi\ncpl\ncrt\ndll\neml\nexe\nhlp\nhta\nin[fs]\nisp\njse?\nlnk\nmd[betw]\nms[cipt]\nnws\nocx\nops\npcd\np[ir]f\nphp\npl\npy\nreg\nsc[frt]\nsh[bsm]?\nswf\nurl\nvb[esx]?\nvxd\nws[cfh]"); //removed "\{[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\}" $args = $this->getArgs($argstr, $request); extract($args); $file_dir = getUploadFilePath(); //$url_prefix = SERVER_NAME . DATA_PATH; $form = HTML::form(array('action' => $request->getPostURL(), 'enctype' => 'multipart/form-data', 'method' => 'post')); $contents = HTML::div(array('class' => 'wikiaction')); $contents->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'MAX_FILE_SIZE', 'value' => MAX_UPLOAD_SIZE))); /// MV add pv /// @todo: have a generic method to transmit pv if (!empty($_REQUEST['pv'])) { $contents->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'pv', 'value' => $_REQUEST['pv']))); } $contents->pushContent(HTML::input(array('name' => 'userfile', 'type' => 'file', 'size' => '50'))); $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), 'type' => 'submit'))); $form->pushContent($contents); $message = HTML(); if ($request->isPost() and $this->only_authenticated) { // Make sure that the user is logged in. $user = $request->getUser(); if (!$user->isAuthenticated()) { $message->pushContent(HTML::h2(_("ACCESS DENIED: You must log in to upload files.")), HTML::br(), HTML::br()); $result = HTML(); $result->pushContent($form); $result->pushContent($message); return $result; } } $userfile = $request->getUploadedFile('userfile'); if ($userfile) { $userfile_name = $userfile->getName(); $userfile_name = trim(basename($userfile_name)); $userfile_tmpname = $userfile->getTmpName(); $err_header = HTML::h2(fmt("ERROR uploading '%s': ", $userfile_name)); /// MV add /// Wiki attachments $wa = new WikiAttachment(GROUP_ID); $rev = $wa->createRevision($userfile_name, $userfile->getSize(), $userfile->getType(), $userfile->getTmpName()); if ($rev >= 0) { $prev = $rev + 1; $interwiki = new PageType_interwikimap(); $link = $interwiki->link("Upload:{$prev}/{$userfile_name}"); $message->pushContent(HTML::h2(_("File successfully uploaded."))); $message->pushContent(HTML::ul(HTML::li($link))); // the upload was a success and we need to mark this event in the "upload log" if ($logfile) { $upload_log = $file_dir . basename($logfile); $this->log($userfile, $upload_log, $message); } if ($autolink) { require_once "lib/loadsave.php"; $pagehandle = $dbi->getPage($page); if ($pagehandle->exists()) { // don't replace default contents $current = $pagehandle->getCurrentRevision(); $version = $current->getVersion(); $text = $current->getPackedContent(); $newtext = $text . "\n* [Upload:{$userfile_name}]"; $meta = $current->_data; $meta['summary'] = sprintf(_("uploaded %s"), $userfile_name); $pagehandle->save($newtext, $version + 1, $meta); } } } else { $message->pushContent($err_header); $message->pushContent(HTML::br(), _("Uploading failed."), HTML::br()); } } else { $message->pushContent(HTML::br(), HTML::br()); } /// {{{ Codendi Specific // URL arguments if (array_key_exists('offset', $_REQUEST)) { $offset = $_REQUEST['offset']; } else { $offset = 0; } if (array_key_exists('limit', $_REQUEST)) { $limit = $_REQUEST['limit']; } else { $limit = 10; } $attchTab = HTML::table(array('border' => '1', 'width' => '100%')); $attchTab->pushContent(HTML::tr(HTML::th(_("Attachment")), HTML::th(_("Number of revision")))); $wai =& WikiAttachment::getListWithCounter(GROUP_ID, user_getid(), array('offset' => $offset, 'nb' => $limit)); $wai->rewind(); while ($wai->valid()) { $wa =& $wai->current(); $filename = basename($wa->getFilename()); $url = getUploadDataPath() . urlencode($filename); $line = HTML::tr(); $line->pushContent(HTML::td(HTML::a(array('href' => $url), "Attach:" . $filename))); $line->pushContent(HTML::td($wa->count())); $attchTab->pushContent($line); $wai->next(); } $attchList = HTML(); $attchList->pushContent(HTML::hr(), HTML::h2(_("Attached files"))); $attchList->pushContent($attchTab); $url = WikiURL("UpLoad"); if (!empty($_REQUEST['pv'])) { $url .= '&pv=' . $_REQUEST['pv']; } $attchList->pushContent(HTML::a(array('href' => $url . '&offset=' . ($offset - $limit)), "<- Previous")); $attchList->pushContent(" - "); $attchList->pushContent(HTML::a(array('href' => $url . '&offset=' . ($offset + $limit)), "Next ->")); /// }}} //$result = HTML::div( array( 'class' => 'wikiaction' ) ); $result = HTML(); $result->pushContent($form); $result->pushContent($message); $result->pushContent($attchList); return $result; }
function run($dbi, $argstr, &$request, $basepage) { $disablemsg = HTML(); $disablemsg->pushContent(HTML::h2("Upload is temporarily disabled."), HTML::br()); return $disablemsg; $this->disallowed_extensions = explode("\n", "ad[ep]\nasd\nba[st]\nchm\ncmd\ncom\ncgi\ncpl\ncrt\ndll\neml\nexe\nhlp\nhta\nin[fs]\nisp\njse?\nlnk\nmd[betw]\nms[cipt]\nnws\nocx\nops\npcd\np[ir]f\nphp\npl\npy\nreg\nsc[frt]\nsh[bsm]?\nswf\nurl\nvb[esx]?\nvxd\nws[cfh]"); //removed "\{[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\}" $args = $this->getArgs($argstr, $request); extract($args); $file_dir = getUploadFilePath(); //$url_prefix = SERVER_NAME . DATA_PATH; $form = HTML::form(array('action' => $request->getPostURL(), 'enctype' => 'multipart/form-data', 'method' => 'post')); $contents = HTML::div(array('class' => 'wikiaction')); $contents->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'MAX_FILE_SIZE', 'value' => MAX_UPLOAD_SIZE))); $contents->pushContent(HTML::input(array('name' => 'userfile', 'type' => 'file', 'size' => '50'))); $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), 'type' => 'submit'))); $form->pushContent($contents); $message = HTML(); if ($request->isPost() and $this->only_authenticated) { // Make sure that the user is logged in. $user = $request->getUser(); if (!$user->isAuthenticated()) { $message->pushContent(HTML::h2(_("ACCESS DENIED: You must log in to upload files.")), HTML::br(), HTML::br()); $result = HTML(); $result->pushContent($form); $result->pushContent($message); return $result; } } $userfile = $request->getUploadedFile('userfile'); if ($userfile) { $userfile_name = $userfile->getName(); $userfile_name = trim(basename($userfile_name)); $userfile_tmpname = $userfile->getTmpName(); $err_header = HTML::h2(fmt("ERROR uploading '%s': ", $userfile_name)); if (preg_match("/(\\." . join("|\\.", $this->disallowed_extensions) . ")\$/", $userfile_name)) { $message->pushContent($err_header); $message->pushContent(fmt("Files with extension %s are not allowed.", join(", ", $this->disallowed_extensions)), HTML::br(), HTML::br()); } elseif (preg_match("/[^._a-zA-Z0-9-]/", $userfile_name)) { $message->pushContent($err_header); $message->pushContent(_("File names may only contain alphanumeric characters and dot, underscore or dash."), HTML::br(), HTML::br()); } elseif (file_exists($file_dir . $userfile_name)) { $message->pushContent($err_header); $message->pushContent(fmt("There is already a file with name %s uploaded.", $userfile_name), HTML::br(), HTML::br()); } elseif ($userfile->getSize() > MAX_UPLOAD_SIZE) { $message->pushContent($err_header); $message->pushContent(_("Sorry but this file is too big."), HTML::br(), HTML::br()); } elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name)) { $interwiki = new PageType_interwikimap(); $link = $interwiki->link("Upload:{$userfile_name}"); $message->pushContent(HTML::h2(_("File successfully uploaded."))); $message->pushContent(HTML::ul(HTML::li($link))); // the upload was a success and we need to mark this event in the "upload log" if ($logfile) { $upload_log = $file_dir . basename($logfile); $this->log($userfile, $upload_log, $message); } if ($autolink) { require_once "lib/loadsave.php"; $pagehandle = $dbi->getPage($page); if ($pagehandle->exists()) { // don't replace default contents $current = $pagehandle->getCurrentRevision(); $version = $current->getVersion(); $text = $current->getPackedContent(); $newtext = $text . "\n* [Upload:{$userfile_name}]"; $meta = $current->_data; $meta['summary'] = sprintf(_("uploaded %s"), $userfile_name); $pagehandle->save($newtext, $version + 1, $meta); } } } else { $message->pushContent($err_header); $message->pushContent(HTML::br(), _("Uploading failed."), HTML::br()); } } else { $message->pushContent(HTML::br(), HTML::br()); } //$result = HTML::div( array( 'class' => 'wikiaction' ) ); $result = HTML(); $result->pushContent($form); $result->pushContent($message); return $result; }
function run($dbi, $argstr, &$request, $basepage) { $args = $this->getArgs($argstr, $request); extract($args); if (!$file) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'file')); } if (!$display) { return $this->error(sprintf(_("A required argument '%s' is missing."), 'display')); } if (string_starts_with($file, "Upload:")) { $file = preg_replace("/^Upload:(.*)\$/", getUploadFilePath() . "\\1", $file); $is_Upload = 1; } $dir = getcwd(); if (defined('PHPWIKI_DIR')) { chdir(PHPWIKI_DIR); } if (!file_exists($file)) { if ($quiet) { return HTML::raw(''); } else { return $this->error(sprintf(_("File '%s' not found."), $file)); } } // sanify $file name $realfile = realpath($file); // Hmm, allow ADMIN to check a local file? Only if its locked if (string_starts_with($realfile, realpath(getUploadDataPath()))) { $isuploaded = 1; } else { $page = $dbi->getPage($basepage); $user = $request->getUser(); if ($page->getOwner() != ADMIN_USER or !$page->get('locked')) { // For convenience we warn the admin if ($quiet and $user->isAdmin()) { return HTML::span(array('title' => _("Output suppressed. FileInfoPlugin with local files require a locked page.")), HTML::em(_("page not locked"))); } else { return $this->error("Invalid path \"{$file}\". Only ADMIN can allow local paths, and the page must be locked."); } } } $s = array(); $modes = explode(",", $display); foreach ($modes as $mode) { switch ($mode) { case 'version': $s[] = $this->exeversion($file); break; case 'size': $s[] = filesize($file); break; case 'phonysize': $s[] = $this->phonysize(filesize($file)); break; case 'date': $s[] = strftime("%x %X", filemtime($file)); break; case 'mtime': $s[] = filemtime($file); break; case 'owner': $o = posix_getpwuid(fileowner($file)); $s[] = $o['name']; break; case 'group': $o = posix_getgrgid(filegroup($file)); $s[] = $o['name']; break; case 'name': $s[] = basename($file); break; case 'path': $s[] = $file; break; case 'dirname': $s[] = dirname($file); break; case 'magic': $s[] = $this->magic($file); break; case 'mime-typ': $s[] = $this->mime_type($file); break; case 'link': if ($is_Upload) { $s[] = " [" . $args['file'] . "]"; } elseif ($isuploaded) { // will fail with user uploads $s[] = " [Upload:" . basename($file) . "]"; } else { $s[] = " [" . basename($file) . "] "; } break; default: if (!$quiet) { return $this->error(sprintf(_("Unsupported argument: %s=%s"), 'display', $mode)); } else { return HTML::raw(''); } break; } } chdir($dir); if (!$format) { $format = ''; foreach ($s as $x) { $format .= " %s"; } } array_unshift($s, $format); // $x, array($i,$j) => sprintf($x, $i, $j) $result = call_user_func_array("sprintf", $s); if (in_array('link', $modes)) { require_once "lib/InlineParser.php"; return TransformInline($result, 2, $basepage); } else { return HTML::raw($result); } }
/** * fromFile - read pictures & descriptions (separated by ;) * from $src and return it in array $photos * * @param string $src path to dir or textfile (local or remote) * @param array $photos * @return string Error when bad url or file couldn't be opened */ function fromFile($src, &$photos, $webpath = '') { $src_bak = $src; if (preg_match("/^Upload:(.*)\$/", $src, $m)) { $src = getUploadFilePath() . $m[1]; $webpath = getUploadDataPath() . $m[1]; } //there has a big security hole... as loading config/config.ini ! if (!preg_match('/(\\.csv|\\.jpg|\\.jpeg|\\.png|\\.gif|\\/)$/', $src)) { return $this->error(_("File extension for csv file has to be '.csv'")); } if (!IsSafeURL($src)) { return $this->error(_("Bad url in src: remove all of <, >, \"")); } if (preg_match('/^(http|ftp|https):\\/\\//i', $src)) { $contents = url_get_contents($src); $web_location = 1; } else { $web_location = 0; if (string_ends_with($src, "/")) { $src = substr($src, 0, -1); } } if (!file_exists($src) and @file_exists(PHPWIKI_DIR . "/{$src}")) { $src = PHPWIKI_DIR . "/{$src}"; } // check if src is a directory if (file_exists($src) and filetype($src) == 'dir') { //all images $list = array(); foreach (array('jpeg', 'jpg', 'png', 'gif') as $ext) { $fileset = new fileSet($src, "*.{$ext}"); $list = array_merge($list, $fileset->getFiles()); } // convert dirname($src) (local fs path) to web path natcasesort($list); if (!$webpath) { // assume relative src. default: "themes/Hawaiian/images/pictures" $webpath = DATA_PATH . '/' . $src_bak; } foreach ($list as $file) { // convert local path to webpath $photos[] = array("src" => $file, "name" => $webpath . "/{$file}", "name_tile" => $src . "/{$file}", "src" => $src . "/{$file}", "desc" => ""); } return; } // check if $src is an image foreach (array('jpeg', 'jpg', 'png', 'gif') as $ext) { if (preg_match("/\\.{$ext}\$/", $src)) { if (!file_exists($src) and @file_exists(PHPWIKI_DIR . "/{$src}")) { $src = PHPWIKI_DIR . "/{$src}"; } if ($web_location == 1 and !empty($contents)) { $photos[] = array("src" => $src, "name" => $src, "name_tile" => $src, "src" => $src, "desc" => ""); return; } if (!file_exists($src)) { return $this->error(fmt("Unable to find src='%s'", $src)); } $photos[] = array("src" => $src, "name" => "../" . $src, "name_tile" => $src, "src" => $src, "desc" => ""); return; } } if ($web_location == 0) { $fp = @fopen($src, "r"); if (!$fp) { return $this->error(fmt("Unable to read src='%s'", $src)); } while ($data = fgetcsv($fp, 1024, ';')) { if (count($data) == 0 || empty($data[0]) || preg_match('/^#/', $data[0]) || preg_match('/^[[:space:]]*$/', $data[0])) { continue; } if (empty($data[1])) { $data[1] = ''; } $photos[] = array("name" => dirname($src) . "/" . trim($data[0]), "location" => "../" . dirname($src) . "/" . trim($data[0]), "desc" => trim($data[1]), "name_tile" => dirname($src) . "/" . trim($data[0])); } fclose($fp); } elseif ($web_location == 1) { //TODO: check if the file is an image $contents = preg_split('/\\n/', $contents); while (list($key, $value) = each($contents)) { $data = preg_split('/\\;/', $value); if (count($data) == 0 || empty($data[0]) || preg_match('/^#/', $data[0]) || preg_match('/^[[:space:]]*$/', $data[0])) { continue; } if (empty($data[1])) { $data[1] = ''; } $photos[] = array("name" => dirname($src) . "/" . trim($data[0]), "src" => dirname($src) . "/" . trim($data[0]), "desc" => trim($data[1]), "name_tile" => dirname($src) . "/" . trim($data[0])); } } }
function getUploadedFileInfo($params) { // localpath is the relative part after "Upload:" $ParamPath = $params->getParam(0); $localpath = short_string_decode($ParamPath->scalarval()); preg_replace("/^[\\ \\/ \\.]/", "", $localpath); // strip hacks $file = getUploadFilePath() . $localpath; if (file_exists($file)) { $size = filesize($file); $lastmodified = filemtime($file); } else { $size = 0; $lastmodified = 0; } return new xmlrpcresp(new xmlrpcval(array('lastModified' => new xmlrpcval(iso8601_encode($lastmodified, 1), "dateTime.iso8601"), 'size' => new xmlrpcval($size, "int")), "struct")); }
$properties["AUTHORPAGE_URL"] = new _define_commented_optional('AUTHORPAGE_URL', "http://phpwiki.org/ThePhpWikiProgrammingTeam", "\nDefault Author URL"); $properties["TOC_FULL_SYNTAX"] = new boolean_define_optional('TOC_FULL_SYNTAX'); $properties["ENABLE_MARKUP_COLOR"] = new boolean_define_optional('ENABLE_MARKUP_COLOR'); $properties["DISABLE_MARKUP_WIKIWORD"] = new boolean_define_optional('DISABLE_MARKUP_WIKIWORD'); $properties["ENABLE_MARKUP_DIVSPAN"] = new boolean_define_optional('ENABLE_MARKUP_DIVSPAN'); /////////////////// $properties["Part Six"] = new part('_part6', $SEPARATOR . "\n", "\n\nPart Six (optional):\nURL options -- you can probably skip this section.\n\nFor a pretty wiki (no index.php in the url) set a seperate DATA_PATH."); $properties["Server Name"] = new _define_commented_optional('SERVER_NAME', $_SERVER['SERVER_NAME'], "\nCanonical name of the server on which this PhpWiki resides."); $properties["Server Port"] = new numeric_define_commented('SERVER_PORT', $_SERVER['SERVER_PORT'], "\nCanonical httpd port of the server on which this PhpWiki resides.", "onchange=\"validate_ereg('Sorry, \\'%s\\' is no valid port number.', '^[0-9]+\$', 'SERVER_PORT', this);\""); $properties["Server Protocol"] = new _define_selection_optional_commented('SERVER_PROTOCOL', array('http' => 'http', 'https' => 'https')); $properties["Script Name"] = new _define_commented_optional('SCRIPT_NAME', $scriptname); $properties["Data Path"] = new _define_commented_optional('DATA_PATH', dirname($scriptname)); $properties["PhpWiki Install Directory"] = new _define_commented_optional('PHPWIKI_DIR', dirname(__FILE__)); $properties["Use PATH_INFO"] = new _define_selection_optional_commented('USE_PATH_INFO', array('' => 'automatic', 'true' => 'use PATH_INFO', 'false' => 'do not use PATH_INFO'), "\nPhpWiki will try to use short urls to pages, eg \nhttp://www.example.com/index.php/HomePage\nIf you want to use urls like \nhttp://www.example.com/index.php?pagename=HomePage\nthen define 'USE_PATH_INFO' as false by uncommenting the line below.\nNB: If you are using Apache >= 2.0.30, then you may need to to use\nthe directive \"AcceptPathInfo On\" in your Apache configuration file\n(or in an appropriate <.htaccess> file) for the short urls to work: \nSee http://httpd.apache.org/docs-2.0/mod/core.html#acceptpathinfo\n\nSee also http://phpwiki.sourceforge.net/phpwiki/PrettyWiki for more ideas\non prettifying your urls.\n\nDefault: PhpWiki will try to divine whether use of PATH_INFO\nis supported in by your webserver/PHP configuration, and will\nuse PATH_INFO if it thinks that is possible."); $properties["Virtual Path"] = new _define_commented_optional('VIRTUAL_PATH', '/SomeWiki', "\nVIRTUAL_PATH is the canonical URL path under which your your wiki\nappears. Normally this is the same as dirname(SCRIPT_NAME), however\nusing e.g. seperate starter scripts, apaches mod_actions (or mod_rewrite), \nyou can make it something different.\n\nIf you do this, you should set VIRTUAL_PATH here or in the starter scripts.\n\nE.g. your phpwiki might be installed at at /scripts/phpwiki/index.php,\nbut you've made it accessible through eg. /wiki/HomePage.\n\nOne way to do this is to create a directory named 'wiki' in your\nserver root. The directory contains only one file: an .htaccess\nfile which reads something like:\n<pre>\n Action x-phpwiki-page /scripts/phpwiki/index.php\n SetHandler x-phpwiki-page\n DirectoryIndex /scripts/phpwiki/index.php\n</pre>\nIn that case you should set VIRTUAL_PATH to '/wiki'.\n\n(VIRTUAL_PATH is only used if USE_PATH_INFO is true.)\n"); $upload_file_path = defined('UPLOAD_FILE_PATH') ? UPLOAD_FILE_PATH : getUploadFilePath(); new _define_optional('UPLOAD_FILE_PATH', $temp); $upload_data_path = defined('UPLOAD_DATA_PATH') ? UPLOAD_DATA_PATH : getUploadDataPath(); new _define_optional('UPLOAD_DATA_PATH', $temp); $temp = !empty($_ENV['TEMP']) ? $_ENV['TEMP'] : "/tmp"; $properties["TEMP_DIR"] = new _define_optional('TEMP_DIR', $temp); /////////////////// $properties["Part Seven"] = new part('_part7', $SEPARATOR . "\n", "\n\nPart Seven:\n\nMiscellaneous settings\n"); $properties["Strict Mailable Pagedumps"] = new boolean_define_optional('STRICT_MAILABLE_PAGEDUMPS', array('false' => "binary", 'true' => "quoted-printable")); $properties["Default local Dump Directory"] = new _define_optional('DEFAULT_DUMP_DIR'); $properties["Default local HTML Dump Directory"] = new _define_optional('HTML_DUMP_DIR'); $properties["HTML Dump Filename Suffix"] = new _define_optional('HTML_DUMP_SUFFIX'); $properties["Pagename of Recent Changes"] = new _define_optional('RECENT_CHANGES', "RecentChanges"); $properties["Disable HTTP Redirects"] = new boolean_define_commented_optional('DISABLE_HTTP_REDIRECT'); $properties["Disable GETIMAGESIZE"] = new boolean_define_commented_optional('DISABLE_GETIMAGESIZE'); $properties["EDITING_POLICY"] = new _define_optional('EDITING_POLICY');
/** * preg_replace over local file. * Only line-orientated matches possible. */ function fixLocalFile($match, $replace, $filename) { $o_filename = $filename; if (!file_exists($filename)) { $filename = FindFile($filename); } if (!file_exists($filename)) { return array(false, sprintf(_("file %s not found"), $o_filename)); } $found = false; if (is_writable($filename)) { $in = fopen($filename, "rb"); $out = fopen($tmp = tempnam(getUploadFilePath(), "cfg"), "wb"); if (isWindows()) { $tmp = str_replace("/", "\\", $tmp); } // Detect the existing linesep at first line. fgets strips it even if 'rb'. // Before we simply assumed \r\n on windows local files. $s = fread($in, 1024); rewind($in); $linesep = substr_count($s, "\r\n") > substr_count($s, "\n") ? "\r\n" : "\n"; //$linesep = isWindows() ? "\r\n" : "\n"; while ($s = fgets($in)) { // =>php-5.0.1 can fill count //$new = preg_replace($match, $replace, $s, -1, $count); $new = preg_replace($match, $replace, $s); if ($new != $s) { $s = $new . $linesep; $found = true; } fputs($out, $s); } fclose($in); fclose($out); if (!$found) { // todo: skip $reason = sprintf(_("%s not found in %s"), $match, $filename); unlink($out); return array($found, $reason); } else { @unlink("{$file}.bak"); @rename($file, "{$file}.bak"); if (!rename($tmp, $file)) { return array(false, sprintf(_("couldn't move %s to %s"), $tmp, $filename)); } return true; } } else { return array(false, sprintf(_("file %s is not writable"), $filename)); } }
function _do_syncwiki(&$request, $args) { global $charset; longer_timeout(240); if (!function_exists('wiki_xmlrpc_post')) { include_once "lib/XmlRpcClient.php"; } $userid = $request->_user->_userid; $dbh = $request->getDbh(); $merge_point = $dbh->get('mergepoint'); if (empty($merge_point)) { $page = $dbh->getPage("ReleaseNotes"); // this is usually the latest official page $last = $page->getCurrentRevision(false); $merge_point = $last->get("mtime"); // for testing: 1160396075 $dbh->set('mergepoint', $merge_point); } //TODO: remote auth, set session cookie $pagelist = wiki_xmlrpc_post('wiki.getRecentChanges', iso8601_encode($merge_point, 1), $args['url'], $args); $html = HTML(); //$html->pushContent(HTML::div(HTML::em("check RPC2 interface..."))); if (gettype($pagelist) === "array") { //$request->_deferredPageChangeNotification = array(); $request->discardOutput(); StartLoadDump($request, _("Syncing this PhpWiki")); PrintXML(HTML::strong(fmt("Download all externally changed sources."))); echo "<br />\n"; PrintXML(fmt("Retrieving from external url %s wiki.getRecentChanges(%s)...", $args['url'], iso8601_encode($merge_point, 1))); echo "<br />\n"; $ouriter = $dbh->mostRecent(array('since' => $merge_point)); //$ol = HTML::ol(); $done = array(); foreach ($pagelist as $ext) { $reaction = _("<unknown>"); // compare existance and dates with local page $extdate = iso8601_decode($ext['lastModified']->scalar, 1); // TODO: urldecode ??? $name = utf8_decode($ext['name']); $our = $dbh->getPage($name); $done[$name] = 1; $ourrev = $our->getCurrentRevision(false); $rel = '<=>'; if (!$our->exists()) { // we might have deleted or moved it on purpose? // check date of latest revision if there's one, and > mergepoint if ($ourrev->getVersion() > 1 and $ourrev->get('mtime') > $merge_point) { // our was deleted after sync, and changed after last sync. $this->_addConflict('delete', $args, $our, $extdate); $reaction = _(" skipped") . " (" . "locally deleted or moved" . ")"; } else { $reaction = $this->_import($args, $our, $extdate); } } else { $ourdate = $ourrev->get('mtime'); if ($extdate > $ourdate and $ourdate < $merge_point) { $rel = '>'; $reaction = $this->_import($args, $our, $extdate); } elseif ($extdate > $ourdate and $ourdate >= $merge_point) { $rel = '>'; // our is older then external but newer than last sync $reaction = $this->_addConflict('import', $args, $our, $extdate); } elseif ($extdate < $ourdate and $extdate < $merge_point) { $rel = '>'; $reaction = $this->_export($args, $our); } elseif ($extdate < $ourdate and $extdate >= $merge_point) { $rel = '>'; // our is newer and external is also newer $reaction = $this->_addConflict('export', $args, $our, $extdate); } else { $rel = '=='; $reaction = _("same date"); } } /*$ol->pushContent(HTML::li(HTML::strong($name)," ", $extdate,"<=>",$ourdate," ", HTML::strong($reaction))); */ PrintXML(HTML::strong($name), " ", $extdate, " {$rel} ", $ourdate, " ", HTML::strong($reaction), HTML::br()); $request->chunkOutput(); } //$html->pushContent($ol); } else { $html->pushContent("xmlrpc error: wiki.getRecentChanges returned " . "(" . gettype($pagelist) . ") " . $pagelist); trigger_error("xmlrpc error: wiki.getRecentChanges returned " . "(" . gettype($pagelist) . ") " . $pagelist, E_USER_WARNING); EndLoadDump($request); return $this->error($html); } if (empty($args['noexport'])) { PrintXML(HTML::strong(fmt("Now upload all locally newer pages."))); echo "<br />\n"; PrintXML(fmt("Checking all local pages newer than %s...", iso8601_encode($merge_point, 1))); echo "<br />\n"; while ($our = $ouriter->next()) { $name = $our->getName(); if ($done[$name]) { continue; } $reaction = _(" skipped"); $ext = wiki_xmlrpc_post('wiki.getPageInfo', $name, $args['url']); if (is_array($ext)) { $extdate = iso8601_decode($ext['lastModified']->scalar, 1); $ourdate = $our->get('mtime'); if ($extdate < $ourdate and $extdate < $merge_point) { $reaction = $this->_export($args, $our); } elseif ($extdate < $ourdate and $extdate >= $merge_point) { // our newer and external newer $reaction = $this->_addConflict($args, $our, $extdate); } } else { $reaction = 'xmlrpc error'; } PrintXML(HTML::strong($name), " ", $extdate, " < ", $ourdate, " ", HTML::strong($reaction), HTML::br()); $request->chunkOutput(); } PrintXML(HTML::strong(fmt("Now upload all locally newer uploads."))); echo "<br />\n"; PrintXML(fmt("Checking all local uploads newer than %s...", iso8601_encode($merge_point, 1))); echo "<br />\n"; $this->_fileList = array(); $prefix = getUploadFilePath(); $this->_dir($prefix); $len = strlen($prefix); foreach ($this->_fileList as $path) { // strip prefix $file = substr($path, $len); $ourdate = filemtime($path); $oursize = filesize($path); $reaction = _(" skipped"); $ext = wiki_xmlrpc_post('wiki.getUploadedFileInfo', $file, $args['url']); if (is_array($ext)) { $extdate = iso8601_decode($ext['lastModified']->scalar, 1); $extsize = $ext['size']; if (empty($extsize) or $extdate < $ourdate) { $timeout = $oursize * 0.0002; // assume 50kb/sec upload speed $reaction = $this->_upload($args, $path, $timeout); } } else { $reaction = 'xmlrpc error wiki.getUploadedFileInfo not supported'; } PrintXML(HTML::strong($name), " ", "{$extdate} ({$extsize}) < {$ourdate} ({$oursize})", HTML::strong($reaction), HTML::br()); $request->chunkOutput(); } } $dbh->set('mergepoint', time()); EndLoadDump($request); return ''; //$html; }
/** * Creates an image or image map depending on the plugin type. * @access static private * @param content array reference to created array which overwrite the keys * 'image', 'imagetype' and possibly 'html' * @param plugin WikiPluginCached plugin which is called to create image or map * @param dbi WikiDB handle to database * @param argarray array Contains all arguments needed by plugin * @param request Request ???? * @param errorformat string outputs errors in 'png', 'gif', 'jpg' or 'html' * @return boolean error status; true=ok; false=error */ function produceImage(&$content, $plugin, $dbi, $argarray, $request, $errorformat) { $plugin->resetError(); $content['html'] = $imagehandle = false; if ($plugin->getPluginType() == PLUGIN_CACHED_MAP) { list($imagehandle, $content['html']) = $plugin->getMap($dbi, $argarray, $request); } else { $imagehandle = $plugin->getImage($dbi, $argarray, $request); } $content['imagetype'] = $this->decideImgType($plugin->getImageType($dbi, $argarray, $request)); $errortext = $plugin->getError(); if (!$imagehandle || $errortext) { if (!$errortext) { $errortext = "'<?plugin " . $plugin->getName() . ' ' . $this->glueArgs($argarray) . " ?>' returned no image, " . " although no error was reported."; } $this->printError($errorformat, $errortext); return false; } // image handle -> image data if (!empty($this->_static)) { $ext = "." . $content['imagetype']; if (is_string($imagehandle) and file_exists($imagehandle)) { if (preg_match("/.(\\w+)\$/", $imagehandle, $m)) { $ext = "." . $m[1]; } } $tmpfile = tempnam(getUploadFilePath(), PLUGIN_CACHED_FILENAME_PREFIX . $ext); if (!strstr(basename($tmpfile), $ext)) { unlink($tmpfile); $tmpfile .= $ext; } $tmpfile = getUploadFilePath() . basename($tmpfile); if (is_string($imagehandle) and file_exists($imagehandle)) { rename($imagehandle, $tmpfile); } } else { $tmpfile = $this->tempnam(); } if (is_resource($imagehandle)) { $this->writeImage($content['imagetype'], $imagehandle, $tmpfile); ImageDestroy($imagehandle); sleep(0.2); } elseif (is_string($imagehandle)) { $content['file'] = getUploadFilePath() . basename($tmpfile); $content['url'] = getUploadDataPath() . basename($tmpfile); return true; } if (file_exists($tmpfile)) { $fp = fopen($tmpfile, 'rb'); $content['image'] = fread($fp, filesize($tmpfile)); fclose($fp); if (!empty($this->_static)) { // on static it is in "uploads/" but in wikicached also $content['file'] = $tmpfile; $content['url'] = getUploadDataPath() . basename($tmpfile); return true; } unlink($tmpfile); if ($content['image']) { return true; } } return false; }
function run($dbi, $argstr, &$request, $basepage) { $this->allowed_extensions = explode("\n", "7z\navi\nbmp\nbz2\nc\ncfg\ndiff\ndoc\ndocx\nflv\ngif\nh\nics\nini\njpeg\njpg\nkmz\nmp3\nodg\nodp\nods\nodt\nogg\npatch\npdf\npng\nppt\npptx\nrar\nsvg\ntar\ntar.gz\ntxt\nxls\nxlsx\nxml\nxsd\nzip"); $this->disallowed_extensions = explode("\n", "ad[ep]\nasd\nba[st]\nchm\ncmd\ncom\ncgi\ncpl\ncrt\ndll\neml\nexe\nhlp\nhta\nin[fs]\nisp\njse?\nlnk\nmd[betw]\nms[cipt]\nnws\nocx\nops\npcd\np[ir]f\nphp\\d?\nphtml\npl\npy\nreg\nsc[frt]\nsh[bsm]?\nswf\nurl\nvb[esx]?\nvxd\nws[cfh]"); //removed "\{[[:xdigit:]]{8}(?:-[[:xdigit:]]{4}){3}-[[:xdigit:]]{12}\}" $args = $this->getArgs($argstr, $request); extract($args); $file_dir = getUploadFilePath(); $file_dir .= "/"; $form = HTML::form(array('action' => $request->getPostURL(), 'enctype' => 'multipart/form-data', 'method' => 'post')); $contents = HTML::div(array('class' => 'wikiaction')); $contents->pushContent(HTML::input(array('type' => 'hidden', 'name' => 'MAX_FILE_SIZE', 'value' => MAX_UPLOAD_SIZE))); $contents->pushContent(HTML::input(array('name' => 'userfile', 'type' => 'file', 'size' => $size))); if ($mode == 'edit') { $contents->pushContent(HTML::input(array('name' => 'action', 'type' => 'hidden', 'value' => 'edit'))); $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), 'name' => 'edit[upload]', 'type' => 'submit'))); } else { $contents->pushContent(HTML::raw(" ")); $contents->pushContent(HTML::input(array('value' => _("Upload"), 'type' => 'submit'))); } $form->pushContent($contents); $message = HTML(); if ($request->isPost() and $this->only_authenticated) { // Make sure that the user is logged in. $user = $request->getUser(); if (!$user->isAuthenticated()) { if (defined('FUSIONFORGE') and FUSIONFORGE) { $message->pushContent(HTML::div(array('class' => 'error'), HTML::p(_("You cannot upload files.")), HTML::ul(HTML::li(_("Check you are logged in.")), HTML::li(_("Check you are in the right project.")), HTML::li(_("Check you are a member of the current project."))))); } else { $message->pushContent(HTML::div(array('class' => 'error'), HTML::p(_("ACCESS DENIED: You must log in to upload files.")))); } $result = HTML(); $result->pushContent($form); $result->pushContent($message); return $result; } } $userfile = $request->getUploadedFile('userfile'); if ($userfile) { $userfile_name = $userfile->getName(); $userfile_name = trim(basename($userfile_name)); if (UPLOAD_USERDIR) { $file_dir .= $request->_user->_userid; if (!file_exists($file_dir)) { mkdir($file_dir, 0775); } $file_dir .= "/"; $u_userfile = $request->_user->_userid . "/" . $userfile_name; } else { $u_userfile = $userfile_name; } $u_userfile = preg_replace("/ /", "%20", $u_userfile); $userfile_tmpname = $userfile->getTmpName(); $err_header = HTML::div(array('class' => 'error'), HTML::p(fmt("ERROR uploading '%s'", $userfile_name))); if (preg_match("/(\\." . join("|\\.", $this->disallowed_extensions) . ")(\\.|\$)/i", $userfile_name)) { $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("Files with extension %s are not allowed.", join(", ", $this->disallowed_extensions)))); } elseif (!DISABLE_UPLOAD_ONLY_ALLOWED_EXTENSIONS and !preg_match("/(\\." . join("|\\.", $this->allowed_extensions) . ")\$/i", $userfile_name)) { $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("Only files with the extension %s are allowed.", join(", ", $this->allowed_extensions)))); } elseif (preg_match("/[^._a-zA-Z0-9- ]/", strip_accents($userfile_name))) { $message->pushContent($err_header); $message->pushContent(HTML::p(_("Invalid filename. File names may only contain alphanumeric characters and dot, underscore, space or dash."))); } elseif (file_exists($file_dir . $userfile_name)) { $message->pushContent($err_header); $message->pushContent(HTML::p(fmt("There is already a file with name %s uploaded.", $u_userfile))); } elseif ($userfile->getSize() > MAX_UPLOAD_SIZE) { $message->pushContent($err_header); $message->pushContent(HTML::p(_("Sorry but this file is too big."))); } elseif (move_uploaded_file($userfile_tmpname, $file_dir . $userfile_name) or IsWindows() and rename($userfile_tmpname, $file_dir . $userfile_name)) { $interwiki = new PageType_interwikimap(); $link = $interwiki->link("Upload:{$u_userfile}"); $message->pushContent(HTML::div(array('class' => 'feedback'), HTML::p(_("File successfully uploaded.")), HTML::p($link))); // the upload was a success and we need to mark this event in the "upload log" if ($logfile) { $upload_log = $file_dir . basename($logfile); $this->log($userfile, $upload_log, $message); } if ($autolink) { require_once "lib/loadsave.php"; $pagehandle = $dbi->getPage($page); if ($pagehandle->exists()) { // don't replace default contents $current = $pagehandle->getCurrentRevision(); $version = $current->getVersion(); $text = $current->getPackedContent(); $newtext = $text . "\n* Upload:{$u_userfile}"; // don't inline images $meta = $current->_data; $meta['summary'] = sprintf(_("uploaded %s"), $u_userfile); $pagehandle->save($newtext, $version + 1, $meta); } } } else { $message->pushContent($err_header); $message->pushContent(HTML::br(), _("Uploading failed."), HTML::br()); } } else { $message->pushContent(HTML::br(), _("No file selected. Please select one."), HTML::br()); } //$result = HTML::div( array( 'class' => 'wikiaction' ) ); $result = HTML(); $result->pushContent($form); $result->pushContent($message); return $result; }
sendHttpReturnCodeAndJson(403, "The delete token is not valid."); } if (time() > $slotParameters['delete_token_valid_till']) { sendHttpReturnCodeAndJson(403, "The delete token is not valid anymore."); } if (!checkFilenameParameter($filename, $slotParameters)) { sendHttpReturnCodeAndJson(403, "Filename to delete differs from requested slot filename."); } $uploadFilePath = rawurldecode(getUploadFilePath($slotUUID, $config, $slotParameters['filename'])); if (!file_exists($uploadFilePath)) { sendHttpReturnCodeAndJson(404, "The file does not exist."); } // Delete file if (unlink($uploadFilePath)) { // Clean up the server - ignore errors @rmdir(getUploadFilePath($slotUUID, $config)); // return 204 for success sendHttpReturnCodeAndMessage(204); } else { sendHttpReturnCodeAndJson(500, "Could not delete file."); } break; default: sendHttpReturnCodeAndJson(403, "Access not allowed."); break; } function checkXmppServerKey($validXmppServerKeys, $xmppServerKey) { foreach ($validXmppServerKeys as $validXmppServerKey) { if ($validXmppServerKey == $xmppServerKey) { return true;