5 Copyright 1999,2000,2001,2002,2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
7 This file is part of PhpWiki.
9 PhpWiki is free software; you can redistribute it and/or modify
10 it under the terms of the GNU General Public License as published by
11 the Free Software Foundation; either version 2 of the License, or
12 (at your option) any later version.
14 PhpWiki is distributed in the hope that it will be useful,
15 but WITHOUT ANY WARRANTY; without even the implied warranty of
16 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 GNU General Public License for more details.
19 You should have received a copy of the GNU General Public License
20 along with PhpWiki; if not, write to the Free Software
21 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 require_once("lib/ziplib.php");
25 require_once("lib/Template.php");
28 * ignore fatal errors during dump
30 function _dump_error_handler(&$error) {
31 if ($error->isFatal()) {
32 $error->errno = E_USER_WARNING;
35 return true; // Ignore error
37 if (preg_match('/Plugin/', $error->errstr))
40 // let the message come through: call the remaining handlers:
44 function StartLoadDump(&$request, $title, $html = '')
46 // MockRequest is from the unit testsuite, a faked request. (may be cmd-line)
47 // We are silent on unittests.
48 if (isa($request,'MockRequest'))
50 // FIXME: This is a hack. This really is the worst overall hack in phpwiki.
52 $html->pushContent('%BODY%');
53 $tmpl = Template('html', array('TITLE' => $title,
55 'CONTENT' => $html ? $html : '%BODY%'));
56 echo ereg_replace('%BODY%.*', '', $tmpl->getExpansion($html));
57 $request->chunkOutput();
59 // set marker for sendPageChangeNotification()
60 $request->_deferredPageChangeNotification = array();
63 function EndLoadDump(&$request)
67 if (isa($request,'MockRequest'))
69 $action = $request->getArg('action');
72 case 'zip': $label = _("ZIP files of database"); break;
73 case 'dumpserial': $label = _("Dump to directory"); break;
74 case 'upload': $label = _("Upload File"); break;
75 case 'loadfile': $label = _("Load File"); break;
76 case 'upgrade': $label = _("Upgrade"); break;
78 case 'ziphtml': $label = _("Dump pages as XHTML"); break;
80 if ($label) $label = str_replace(" ","_",$label);
81 if ($action == 'browse') // loading virgin
82 $pagelink = WikiLink(HOME_PAGE);
84 $pagelink = WikiLink(new WikiPageName(_("PhpWikiAdministration"),false,$label));
86 // do deferred sendPageChangeNotification()
87 if (!empty($request->_deferredPageChangeNotification)) {
88 $pages = $all_emails = $all_users = array();
89 foreach ($request->_deferredPageChangeNotification as $p) {
90 list($pagename, $emails, $userids) = $p;
92 $all_emails = array_unique(array_merge($all_emails, $emails));
93 $all_users = array_unique(array_merge($all_users, $userids));
95 $editedby = sprintf(_("Edited by: %s"), $request->_user->getId());
96 $content = "Loaded the following pages:\n" . join("\n", $pages);
97 if (mail(join(',',$all_emails),"[".WIKI_NAME."] "._("LoadDump"),
101 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
102 join("\n",$pages), join(',',$all_users)), E_USER_NOTICE);
104 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
105 join("\n",$pages), join(',',$all_users)), E_USER_WARNING);
110 unset($request->_deferredPageChangeNotification);
112 PrintXML(HTML::p(HTML::strong(_("Complete."))),
113 HTML::p(fmt("Return to %s", $pagelink)));
114 // Ugly hack to get valid XHTML code
115 if (isa($WikiTheme, 'WikiTheme_gforge')) {
122 echo "</body></html>\n";
126 ////////////////////////////////////////////////////////////////
128 // Functions for dumping.
130 ////////////////////////////////////////////////////////////////
134 * http://www.nacs.uci.edu/indiv/ehood/MIME/2045/rfc2045.html
135 * http://www.faqs.org/rfcs/rfc2045.html
136 * (RFC 1521 has been superceeded by RFC 2045 & others).
138 * Also see http://www.faqs.org/rfcs/rfc2822.html
140 function MailifyPage ($page, $nversions = 1)
142 $current = $page->getCurrentRevision(false);
145 if (STRICT_MAILABLE_PAGEDUMPS) {
146 $from = defined('SERVER_ADMIN') ? SERVER_ADMIN : 'foo@bar';
147 //This is for unix mailbox format: (not RFC (2)822)
148 // $head .= "From $from " . CTime(time()) . "\r\n";
149 $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
150 $head .= "From: $from (PhpWiki)\r\n";
151 // RFC 2822 requires only a Date: and originator (From:)
152 // field, however the obsolete standard RFC 822 also
153 // requires a destination field.
154 $head .= "To: $from (PhpWiki)\r\n";
156 $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
157 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
160 // This should just be entered by hand (or by script?)
161 // in the actual pgsrc files, since only they should have
163 //$head .= "X-Rcs-Id: \$Id\$\r\n";
165 $iter = $page->getAllRevisions();
167 while ($revision = $iter->next()) {
168 $parts[] = MimeifyPageRevision($page, $revision);
169 if ($nversions > 0 && count($parts) >= $nversions)
172 if (count($parts) > 1)
173 return $head . MimeMultipart($parts);
175 return $head . $parts[0];
179 * Compute filename to used for storing contents of a wiki page.
181 * Basically we do a rawurlencode() which encodes everything except
182 * ASCII alphanumerics and '.', '-', and '_'.
184 * But we also want to encode leading dots to avoid filenames like
185 * '.', and '..'. (Also, there's no point in generating "hidden" file
186 * names, like '.foo'.)
188 * We have to apply a different "/" logic for dumpserial, htmldump and zipdump.
189 * dirs are allowed for zipdump and htmldump, not for dumpserial
192 * @param $pagename string Pagename.
193 * @return string Filename for page.
195 function FilenameForPage ($pagename, $action = false)
197 $enc = rawurlencode($pagename);
200 $action = $request->getArg('action');
202 if ($action != 'dumpserial') { // zip, ziphtml, dumphtml
203 // For every %2F we will need to mkdir -p dirname($pagename)
204 $enc = preg_replace('/%2F/', '/', $enc);
206 $enc = preg_replace('/^\./', '%2E', $enc);
207 $enc = preg_replace('/%20/', ' ', $enc);
212 * The main() function which generates a zip archive of a PhpWiki.
214 * If $include_archive is false, only the current version of each page
215 * is included in the zip file; otherwise all archived versions are
218 function MakeWikiZip (&$request)
220 if ($request->getArg('include') == 'all') {
221 $zipname = WIKI_NAME . _("FullDump") . date('Ymd-Hi') . '.zip';
222 $include_archive = true;
225 $zipname = WIKI_NAME . _("LatestSnapshot") . date('Ymd-Hi') . '.zip';
226 $include_archive = false;
228 $include_empty = false;
229 if ($request->getArg('include') == 'empty') {
230 $include_empty = true;
233 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
235 /* ignore fatals in plugins */
236 if (check_php_version(4,1)) {
237 global $ErrorManager;
238 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
241 $dbi =& $request->_dbi;
242 $thispage = $request->getArg('pagename'); // for "Return to ..."
243 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
244 $excludeList = explodePageList($exclude);
246 $excludeList = array();
248 if ($pages = $request->getArg('pages')) { // which pagenames
249 if ($pages == '[]') // current page
251 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
253 $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
255 $request_args = $request->args;
256 $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
258 while ($page = $page_iter->next()) {
259 $request->args = $request_args; // some plugins might change them (esp. on POST)
260 longer_timeout($timeout); // Reset watchdog
262 $current = $page->getCurrentRevision();
263 if ($current->getVersion() == 0)
266 $pagename = $page->getName();
267 $wpn = new WikiPageName($pagename);
268 if (!$wpn->isValid())
270 if (in_array($page->getName(), $excludeList)) {
274 $attrib = array('mtime' => $current->get('mtime'),
276 if ($page->get('locked'))
277 $attrib['write_protected'] = 1;
279 if ($include_archive)
280 $content = MailifyPage($page, 0);
282 $content = MailifyPage($page);
284 $zip->addRegularFile( FilenameForPage($pagename),
288 if (check_php_version(4,1)) {
289 global $ErrorManager;
290 $ErrorManager->popErrorHandler();
294 function DumpToDir (&$request)
296 $directory = $request->getArg('directory');
297 if (empty($directory))
298 $directory = DEFAULT_DUMP_DIR; // See lib/plugin/WikiForm.php:87
299 if (empty($directory))
300 $request->finish(_("You must specify a directory to dump to"));
302 // see if we can access the directory the user wants us to use
303 if (! file_exists($directory)) {
304 if (! mkdir($directory, 0755))
305 $request->finish(fmt("Cannot create directory '%s'", $directory));
307 $html = HTML::p(fmt("Created directory '%s' for the page dump...",
310 $html = HTML::p(fmt("Using directory '%s'", $directory));
313 StartLoadDump($request, _("Dumping Pages"), $html);
315 $dbi =& $request->_dbi;
316 $thispage = $request->getArg('pagename'); // for "Return to ..."
317 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
318 $excludeList = explodePageList($exclude);
320 $excludeList = array();
322 $include_empty = false;
323 if ($request->getArg('include') == 'empty') {
324 $include_empty = true;
326 if ($pages = $request->getArg('pages')) { // which pagenames
327 if ($pages == '[]') // current page
329 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
331 $page_iter = $dbi->getAllPages($include_empty,false,false,$excludeList);
334 $request_args = $request->args;
335 $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
337 while ($page = $page_iter->next()) {
338 $request->args = $request_args; // some plugins might change them (esp. on POST)
339 longer_timeout($timeout); // Reset watchdog
341 $pagename = $page->getName();
342 if (!isa($request,'MockRequest')) {
343 PrintXML(HTML::br(), $pagename, ' ... ');
347 if (in_array($pagename, $excludeList)) {
348 if (!isa($request, 'MockRequest')) {
349 PrintXML(_("Skipped."));
354 $filename = FilenameForPage($pagename);
356 if($page->getName() != $filename) {
357 $msg->pushContent(HTML::small(fmt("saved as %s", $filename)),
361 if ($request->getArg('include') == 'all')
362 $data = MailifyPage($page, 0);
364 $data = MailifyPage($page);
366 if ( !($fd = fopen($directory."/".$filename, "wb")) ) {
367 $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
368 "$directory/$filename")));
369 $request->finish($msg);
372 $num = fwrite($fd, $data, strlen($data));
373 $msg->pushContent(HTML::small(fmt("%s bytes written", $num)));
374 if (!isa($request, 'MockRequest')) {
378 assert($num == strlen($data));
382 EndLoadDump($request);
385 function _copyMsg($page, $smallmsg) {
386 if (!isa($GLOBALS['request'], 'MockRequest')) {
387 if ($page) $msg = HTML(HTML::br(), HTML($page), HTML::small($smallmsg));
388 else $msg = HTML::small($smallmsg);
394 function mkdir_p($pathname, $permission = 0777) {
395 $arr = explode("/", $pathname);
397 return mkdir($pathname, $permission);
399 $s = array_shift($arr);
401 foreach ($arr as $p) {
404 $ok = mkdir($curr, $permission);
406 if (!$ok) return FALSE;
412 * Dump all pages as XHTML to a directory, as pagename.html.
413 * Copies all used css files to the directory, all used images to a
414 * "images" subdirectory, and all used buttons to a "images/buttons" subdirectory.
415 * The webserver must have write permissions to these directories.
416 * chown httpd HTML_DUMP_DIR; chmod u+rwx HTML_DUMP_DIR
419 * @param string directory (optional) path to dump to. Default: HTML_DUMP_DIR
420 * @param string pages (optional) Comma-seperated of glob-style pagenames to dump.
421 * Also array of pagenames allowed.
422 * @param string exclude (optional) Comma-seperated of glob-style pagenames to exclude
424 function DumpHtmlToDir (&$request)
427 $directory = $request->getArg('directory');
428 if (empty($directory))
429 $directory = HTML_DUMP_DIR; // See lib/plugin/WikiForm.php:87
430 if (empty($directory))
431 $request->finish(_("You must specify a directory to dump to"));
433 // See if we can access the directory the user wants us to use
434 if (! file_exists($directory)) {
435 if (! mkdir($directory, 0755))
436 $request->finish(fmt("Cannot create directory '%s'", $directory));
438 $html = HTML::p(fmt("Created directory '%s' for the page dump...",
441 $html = HTML::p(fmt("Using directory '%s'", $directory));
443 StartLoadDump($request, _("Dumping Pages"), $html);
444 $thispage = $request->getArg('pagename'); // for "Return to ..."
446 $dbi =& $request->_dbi;
447 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
448 $excludeList = explodePageList($exclude);
450 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
452 if ($pages = $request->getArg('pages')) { // which pagenames
453 if ($pages == '[]') // current page
455 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
456 // not at admin page: dump only the current page
457 } elseif ($thispage != _("PhpWikiAdministration")) {
458 $page_iter = new WikiDB_Array_generic_iter(array($thispage));
460 $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
463 $WikiTheme->DUMP_MODE = 'HTML';
464 _DumpHtmlToDir($directory, $page_iter, $request->getArg('exclude'));
465 $WikiTheme->DUMP_MODE = false;
467 $request->setArg('pagename',$thispage); // Template::_basepage fix
468 EndLoadDump($request);
471 /* Known problem: any plugins or other code which echo()s text will
472 * lead to a corrupted html zip file which may produce the following
473 * errors upon unzipping:
475 * warning [wikihtml.zip]: 2401 extra bytes at beginning or within zipfile
476 * file #58: bad zipfile offset (local header sig): 177561
477 * (attempting to re-compensate)
479 * However, the actual wiki page data should be unaffected.
481 function MakeWikiZipHtml (&$request)
484 if ($request->getArg('zipname')) {
485 $zipname = basename($request->getArg('zipname'));
486 if (!preg_match("/\.zip$/i", $zipname))
488 $request->setArg('zipname', false);
490 $zipname = "wikihtml.zip";
492 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
493 $dbi =& $request->_dbi;
494 $thispage = $request->getArg('pagename'); // for "Return to ..."
495 if ($pages = $request->getArg('pages')) { // which pagenames
496 if ($pages == '[]') // current page
498 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
500 $page_iter = $dbi->getAllPages(false,false,false,$request->getArg('exclude'));
503 $WikiTheme->DUMP_MODE = 'ZIPHTML';
504 _DumpHtmlToDir($zip, $page_iter, $request->getArg('exclude'));
505 $WikiTheme->DUMP_MODE = false;
509 * Internal html dumper. Used for dumphtml, ziphtml and pdf
511 function _DumpHtmlToDir ($target, $page_iter, $exclude = false)
513 global $WikiTheme, $request;
514 $silent = true; $zip = false; $directory = false;
515 if ($WikiTheme->DUMP_MODE == 'HTML') {
516 $directory = $target;
518 } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') {
519 $directory = $target;
520 } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML'
524 $request->_TemplatesProcessed = array();
525 if ($exclude) { // exclude which pagenames
526 $excludeList = explodePageList($exclude);
528 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
530 $WikiTheme->VALID_LINKS = array();
531 if ($request->getArg('format')) { // pagelist
532 $page_iter_sav = $page_iter;
533 foreach ($page_iter_sav->asArray() as $handle) {
534 $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName();
536 $page_iter_sav->reset();
539 if (defined('HTML_DUMP_SUFFIX'))
540 $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
541 $_bodyAttr = @$WikiTheme->_MoreAttr['body'];
542 unset($WikiTheme->_MoreAttr['body']);
544 if (check_php_version(4,1)) {
545 global $ErrorManager;
546 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
549 // check if the dumped file will be accessible from outside
550 $doc_root = $request->get("DOCUMENT_ROOT");
551 if ($WikiTheme->DUMP_MODE == 'HTML') {
552 $ldir = NormalizeLocalFileName($directory);
553 $wikiroot = NormalizeLocalFileName('');
554 if (string_starts_with($ldir, $doc_root)) {
555 $link_prefix = substr($directory, strlen($doc_root))."/";
556 } elseif (string_starts_with($ldir, $wikiroot)) {
557 $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/";
561 $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed
563 $link_prefix = "file://".$prefix.$directory."/";
569 $request_args = $request->args;
570 $timeout = (! $request->getArg('start_debug')) ? 60 : 240;
571 $SAVE_RCS_IDS = $GLOBALS['RCS_IDS'];
574 $directory = str_replace("\\", "/", $directory); // no Win95 support.
575 @mkdir("$directory/images");
579 $already_images = array();
581 while ($page = $page_iter->next()) {
582 if (is_string($page)) {
584 $page = $request->_dbi->getPage($pagename);
586 $pagename = $page->getName();
588 if (empty($firstpage)) $firstpage = $pagename;
589 if (array_key_exists($pagename, $already))
591 $already[$pagename] = 1;
592 $current = $page->getCurrentRevision();
593 //if ($current->getVersion() == 0)
596 $request->args = $request_args; // some plugins might change them (esp. on POST)
597 longer_timeout($timeout); // Reset watchdog
600 $attrib = array('mtime' => $current->get('mtime'),
602 if ($page->get('locked'))
603 $attrib['write_protected'] = 1;
604 } elseif (!$silent) {
605 if (!isa($request,'MockRequest')) {
606 PrintXML(HTML::br(), $pagename, ' ... ');
610 if (in_array($pagename, $excludeList)) {
611 if (!$silent and !isa($request,'MockRequest')) {
612 PrintXML(_("Skipped."));
618 if ($WikiTheme->DUMP_MODE == 'PDFHTML')
619 $request->setArg('action', 'pdf'); // to omit cache headers
620 $request->setArg('pagename', $pagename); // Template::_basepage fix
621 $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
622 $args = array('revision' => $current,
623 'CONTENT' => $current->getTransformedContent(),
624 'relative_base' => $relative_base);
625 // For every %2F will need to mkdir -p dirname($pagename)
626 if (preg_match("/(%2F|\/)/", $filename)) {
627 // mkdir -p and set relative base for subdir pages
628 $filename = preg_replace("/%2F/", "/", $filename);
629 $count = substr_count($filename, "/");
630 $dirname = dirname($filename);
632 mkdir_p($directory."/".$dirname);
633 // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written
634 // if (isWindows()) // interesting Windows bug: cannot mkdir "bla "
635 // Since dumps needs to be copied, we have to disallow this for all platforms.
636 $filename = preg_replace("/ \//", "/", $filename);
637 $relative_base = "../";
639 $relative_base .= "../";
642 $args['relative_base'] = $relative_base;
646 $DUMP_MODE = $WikiTheme->DUMP_MODE;
647 $data = GeneratePageasXML(new Template('browse', $request, $args),
648 $pagename, $current, $args);
649 $WikiTheme->DUMP_MODE = $DUMP_MODE;
651 if (preg_match_all("/<img .*?src=\"(\/.+?)\"/", $data, $m)) {
652 // fix to local relative path for uploaded images, so that pdf will work
653 foreach ($m[1] as $img_file) {
654 $base = basename($img_file);
655 $data = str_replace('src="'.$img_file.'"','src="images/'.$base.'"', $data);
656 if (array_key_exists($img_file, $already_images))
658 $already_images[$img_file] = 1;
659 // resolve src from webdata to file
660 $src = $doc_root . $img_file;
661 if (file_exists($src) and $base) {
663 $target = "$directory/images/$base";
664 if (copy($src, $target)) {
666 _copyMsg($img_file, fmt("... copied to %s", $target));
669 _copyMsg($img_file, fmt("... not copied to %s", $target));
672 $target = "images/$base";
673 $zip->addSrcFile($target, $src);
680 $outfile = $directory."/".$filename;
681 if ( !($fd = fopen($outfile, "wb")) ) {
682 $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
684 $request->finish($msg);
686 $len = strlen($data);
687 $num = fwrite($fd, $data, $len);
688 if ($pagename != $filename) {
689 $link = LinkURL($link_prefix.$filename, $filename);
690 $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
692 $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
694 if (!isa($request, 'MockRequest')) {
698 $request->chunkOutput();
700 assert($num == $len);
702 $outfiles[] = $outfile;
704 $zip->addRegularFile($filename, $data, $attrib);
708 $request->_dbi->_cache->invalidate_cache($pagename);
709 unset ($request->_dbi->_cache->_pagedata_cache);
710 unset ($request->_dbi->_cache->_versiondata_cache);
711 unset ($request->_dbi->_cache->_glv_cache);
713 unset ($request->_dbi->_cache->_backend->_page_data);
716 unset($current->_transformedContent);
718 if (!empty($template)) {
719 unset($template->_request);
724 $GLOBALS['RCS_IDS'] = $SAVE_RCS_IDS;
728 $attrib = false; //array('is_ascii' => 0);
729 if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
730 // @mkdir("$directory/images");
731 foreach ($WikiTheme->dumped_images as $img_file) {
732 if (array_key_exists($img_file, $already_images))
734 $already_images[$img_file] = 1;
736 and ($from = $WikiTheme->_findFile($img_file, true))
740 $target = "$directory/images/".basename($from);
742 copy($WikiTheme->_path . $from, $target);
744 if (copy($WikiTheme->_path . $from, $target)) {
745 _copyMsg($from, fmt("... copied to %s", $target));
747 _copyMsg($from, fmt("... not copied to %s", $target));
751 $target = "images/".basename($from);
752 $zip->addSrcFile($target, $WikiTheme->_path . $from);
754 } elseif (!$silent) {
755 _copyMsg($from, _("... not found"));
760 if (!empty($WikiTheme->dumped_buttons)
761 and is_array($WikiTheme->dumped_buttons))
765 @mkdir("$directory/images/buttons");
766 foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
767 if (array_key_exists($img_file, $already_images))
769 $already_images[$img_file] = 1;
771 and ($from = $WikiTheme->_findFile($img_file, true))
775 $target = "$directory/images/buttons/".basename($from);
777 copy($WikiTheme->_path . $from, $target);
779 if (copy($WikiTheme->_path . $from, $target)) {
780 _copyMsg($from, fmt("... copied to %s", $target));
782 _copyMsg($from, fmt("... not copied to %s", $target));
786 $target = "images/buttons/".basename($from);
787 $zip->addSrcFile($target, $WikiTheme->_path . $from);
789 } elseif (!$silent) {
790 _copyMsg($from, _("... not found"));
794 if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
795 foreach ($WikiTheme->dumped_css as $css_file) {
796 if (array_key_exists($css_file, $already_images))
798 $already_images[$css_file] = 1;
800 and ($from = $WikiTheme->_findFile(basename($css_file), true))
803 // TODO: fix @import url(main.css);
805 $target = "$directory/" . basename($css_file);
807 copy($WikiTheme->_path . $from, $target);
809 if (copy($WikiTheme->_path . $from, $target)) {
810 _copyMsg($from, fmt("... copied to %s", $target));
812 _copyMsg($from, fmt("... not copied to %s", $target));
816 //$attrib = array('is_ascii' => 0);
817 $target = basename($css_file);
818 $zip->addSrcFile($target, $WikiTheme->_path . $from);
820 } elseif (!$silent) {
821 _copyMsg($from, _("... not found"));
829 if ($WikiTheme->DUMP_MODE == 'PDFHTML') {
830 if (USE_EXTERNAL_HTML2PDF and $outfiles) {
831 $cmd = EXTERNAL_HTML2PDF_PAGELIST.' "'.join('" "', $outfiles).'"';
832 $filename = FilenameForPage($firstpage);
834 $tmpfile = $directory . "/createpdf.bat";
835 $fp = fopen($tmpfile, "wb");
836 fwrite($fp, $cmd . " > $filename.pdf");
839 if (!headers_sent()) {
840 Header('Content-Type: application/pdf');
844 $tmpdir = getUploadFilePath();
845 $s = passthru($cmd . " > $tmpdir/$filename.pdf");
846 $errormsg = "<br />\nGenerated <a href=\"".getUploadDataPath()."$filename.pdf\">Upload:$filename.pdf</a>\n";
851 foreach($outfiles as $f) unlink($f);
854 if (!empty($errormsg)) {
855 $request->discardOutput();
856 $GLOBALS['ErrorManager']->_postponed_errors = array();
860 if (check_php_version(4,1)) {
861 global $ErrorManager;
862 $ErrorManager->popErrorHandler();
865 $WikiTheme->HTML_DUMP_SUFFIX = '';
866 $WikiTheme->DUMP_MODE = false;
867 $WikiTheme->_MoreAttr['body'] = $_bodyAttr;
871 ////////////////////////////////////////////////////////////////
873 // Functions for restoring.
875 ////////////////////////////////////////////////////////////////
877 function SavePage (&$request, &$pageinfo, $source, $filename)
879 static $overwite_all = false;
880 $pagedata = $pageinfo['pagedata']; // Page level meta-data.
881 $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
883 if (empty($pageinfo['pagename'])) {
884 PrintXML(HTML::p(HTML::strong(_("Empty pagename!"))));
888 if (empty($versiondata['author_id']))
889 $versiondata['author_id'] = $versiondata['author'];
891 // remove invalid backend specific chars. utf8 issues mostly
892 $pagename_check = new WikiPagename($pageinfo['pagename']);
893 if (!$pagename_check->isValid()) {
894 PrintXML(HTML::p(HTML::strong(_("Invalid pagename!")." ".$pageinfo['pagename'])));
897 $pagename = $pagename_check->getName();
898 $content = $pageinfo['content'];
900 if ($pagename == _("InterWikiMap"))
901 $content = _tryinsertInterWikiMap($content);
903 $dbi =& $request->_dbi;
904 $page = $dbi->getPage($pagename);
906 // Try to merge if updated pgsrc contents are different. This
907 // whole thing is hackish
909 // TODO: try merge unless:
910 // if (current contents = default contents && pgsrc_version >=
911 // pgsrc_version) then just upgrade this pgsrc
912 $needs_merge = false;
916 if ($request->getArg('merge')) {
919 else if ($request->getArg('overwrite')) {
923 $current = $page->getCurrentRevision();
925 $edit = $request->getArg('edit');
927 if (isset($edit['keep_old'])) {
931 elseif (isset($edit['overwrite'])) {
935 elseif ( $current and (! $current->hasDefaultContents())
936 && ($current->getPackedContent() != $content) )
938 include_once('lib/editpage.php');
939 $request->setArg('pagename', $pagename);
940 $v = $current->getVersion();
941 $request->setArg('revision', $current->getVersion());
942 $p = new LoadFileConflictPageEditor($request);
943 $p->_content = $content;
944 $p->_currentVersion = $v - 1;
945 $p->editPage($saveFailed = true);
946 return; //early return
950 foreach ($pagedata as $key => $value) {
952 $page->set($key, $value);
955 $mesg = HTML::p(array('style' => 'text-indent: 3em;'));
957 $mesg->pushContent(' ', fmt("from %s", $source));
960 //FIXME: This should not happen! (empty vdata, corrupt cache or db)
961 $current = $page->getCurrentRevision();
963 if ($current->getVersion() == 0) {
964 $mesg->pushContent(' - ', _("New page"));
968 if ( (! $current->hasDefaultContents())
969 && ($current->getPackedContent() != $content) ) {
971 $mesg->pushContent(' ',
972 fmt("has edit conflicts - overwriting anyway"));
974 if (substr_count($source, 'pgsrc')) {
975 $versiondata['author'] = _("The PhpWiki programming team");
976 // but leave authorid as userid who loaded the file
980 if (isset($edit['keep_old'])) {
981 $mesg->pushContent(' ', fmt("keep old"));
983 $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
984 $needs_merge = true; // hackish, to display the buttons
989 else if ($current->getPackedContent() == $content
990 && $current->get('author') == $versiondata['author']) {
991 // The page metadata is already changed, we don't need a new revision.
992 // This was called previously "is identical to current version %d - skipped"
993 // which is wrong, since the pagedata was stored, not skipped.
994 $mesg->pushContent(' ',
995 fmt("content is identical to current version %d - no new revision created",
996 $current->getVersion()));
1003 // in case of failures print the culprit:
1004 if (!isa($request,'MockRequest')) {
1005 PrintXML(HTML::p(WikiLink($pagename))); flush();
1007 $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
1009 $mesg->pushContent(' ', fmt("- saved to database as version %d",
1010 $new->getVersion()));
1014 // hackish, $source contains needed path+filename
1015 $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
1016 $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
1017 $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
1018 //check if uploaded file? they pass just the content, but the file is gone
1021 $meb = Button(array('action' => 'loadfile',
1025 _("PhpWikiAdministration"),
1027 $owb = Button(array('action' => 'loadfile',
1030 _("Restore Anyway"),
1031 _("PhpWikiAdministration"),
1033 $mesg->pushContent(' ', $meb, " ", $owb);
1034 if (!$overwite_all) {
1035 $args = $request->getArgs();
1036 $args['overwrite'] = 1;
1037 $owb = Button($args,
1039 _("PhpWikiAdministration"),
1041 $mesg->pushContent(HTML::div(array('class' => 'hint'), $owb));
1042 $overwite_all = true;
1045 $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
1049 if (!isa($request,'MockRequest')) {
1051 PrintXML(HTML::p(HTML::em(WikiLink($pagename))), $mesg);
1058 // action=revert (by diff)
1059 function RevertPage (&$request)
1062 $pagename = $request->getArg('pagename');
1063 $version = $request->getArg('version');
1065 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1066 HTML::p(_("missing required version argument")));
1069 $dbi =& $request->_dbi;
1070 $page = $dbi->getPage($pagename);
1071 $current = $page->getCurrentRevision();
1072 $currversion = $current->getVersion();
1073 if ($currversion == 0) {
1074 $mesg->pushContent(' ', _("no page content"));
1075 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1080 if ($currversion == $version) {
1081 $mesg->pushContent(' ', _("same version page"));
1082 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1087 if ($request->getArg('cancel')) {
1088 $mesg->pushContent(' ', _("Cancelled"));
1089 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1094 if (!$request->getArg('verify')) {
1095 $mesg->pushContent(HTML::br(),
1098 HTML::form(array('action' => $request->getPostURL(),
1099 'method' => 'post'),
1100 HiddenInputs($request->getArgs(), false, array('verify')),
1101 HiddenInputs(array('verify' => 1)),
1102 Button('submit:verify', _("Yes"), 'button'),
1103 HTML::Raw(' '),
1104 Button('submit:cancel', _("Cancel"), 'button')),
1106 $rev = $page->getRevision($version);
1107 $html = HTML(HTML::p(fmt("Revert %s to version $version", WikiLink($pagename))),
1109 $rev->getTransformedContent());
1110 $template = Template('browse',
1111 array('CONTENT' => $html));
1112 GeneratePage($template, $pagename, $rev);
1113 $request->checkValidators();
1117 $rev = $page->getRevision($version);
1118 $content = $rev->getPackedContent();
1119 $versiondata = $rev->_data;
1120 $versiondata['summary'] = sprintf(_("revert to version %d"), $version);
1121 $new = $page->save($content, $currversion + 1, $versiondata);
1124 $pagelink = WikiLink($pagename);
1125 $mesg->pushContent(fmt("Revert: %s", $pagelink),
1126 fmt("- version %d saved to database as version %d",
1127 $version, $new->getVersion()));
1128 // Force browse of current page version.
1129 $request->setArg('version', false);
1130 $template = Template('savepage', array());
1131 $template->replace('CONTENT', $new->getTransformedContent());
1133 GeneratePage($template, $mesg, $new);
1137 function _tryinsertInterWikiMap($content) {
1139 if (strpos($content, "<verbatim>")) {
1140 //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1143 if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1144 $error_html = sprintf(" "._("%s: not defined"), "INTERWIKI_MAP_FILE");
1147 $mapfile = FindFile(INTERWIKI_MAP_FILE,1);
1148 if (!$goback && !file_exists($mapfile)) {
1149 $error_html = sprintf(" "._("%s: file not found"), INTERWIKI_MAP_FILE);
1153 if (!empty($error_html))
1154 trigger_error(_("Default InterWiki map file not loaded.")
1155 . $error_html, E_USER_NOTICE);
1159 // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1160 if (!isa($GLOBALS['request'], 'MockRequest'))
1161 echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile),"<br />";
1163 $fd = fopen ($mapfile, "rb");
1164 $data = fread ($fd, filesize($mapfile));
1166 $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1170 function ParseSerializedPage($text, $default_pagename, $user)
1172 if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1175 $pagehash = unserialize($text);
1177 // Split up pagehash into four parts:
1180 // page-level meta-data
1181 // revision-level meta-data
1183 if (!defined('FLAG_PAGE_LOCKED'))
1184 define('FLAG_PAGE_LOCKED', 1);
1185 $pageinfo = array('pagedata' => array(),
1186 'versiondata' => array());
1188 $pagedata = &$pageinfo['pagedata'];
1189 $versiondata = &$pageinfo['versiondata'];
1191 // Fill in defaults.
1192 if (empty($pagehash['pagename']))
1193 $pagehash['pagename'] = $default_pagename;
1194 if (empty($pagehash['author'])) {
1195 $pagehash['author'] = $user->getId();
1198 foreach ($pagehash as $key => $value) {
1203 $pageinfo[$key] = $value;
1206 $pageinfo[$key] = join("\n", $value);
1209 if (($value & FLAG_PAGE_LOCKED) != 0)
1210 $pagedata['locked'] = 'yes';
1214 $pagedata[$key] = $value;
1218 $pagedata['perm'] = ParseMimeifiedPerm($value);
1220 case 'lastmodified':
1221 $versiondata['mtime'] = $value;
1226 $versiondata[$key] = $value;
1230 if (empty($pagehash['charset']))
1231 $pagehash['charset'] = 'iso-8859-1';
1232 // compare to target charset
1233 if (strtolower($pagehash['charset']) != strtolower($GLOBALS['charset'])) {
1234 $pageinfo['content'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['content']);
1235 $pageinfo['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['pagename']);
1240 function SortByPageVersion ($a, $b) {
1241 return $a['version'] - $b['version'];
1245 * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1246 * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1247 * Detected by Santtu Jarvi.
1249 function LoadFile (&$request, $filename, $text = false, $mtime = false)
1251 if (preg_match("/config$/", dirname($filename)) // our or other config
1252 and preg_match("/config.*\.ini/", basename($filename))) // backups and other versions also
1254 trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1257 if (!is_string($text)) {
1259 $stat = stat($filename);
1261 $text = implode("", file($filename));
1264 if (! $request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1265 else @set_time_limit(240);
1267 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1268 $basename = basename("/dummy/" . $filename);
1271 $mtime = time(); // Last resort.
1273 // DONE: check source - target charset for content and pagename
1274 // but only for pgsrc'ed content, not from the browser.
1276 $default_pagename = rawurldecode($basename);
1277 if ( ($parts = ParseMimeifiedPages($text)) ) {
1278 if (count($parts) > 1)
1279 $overwrite = $request->getArg('overwrite');
1280 usort($parts, 'SortByPageVersion');
1281 foreach ($parts as $pageinfo) {
1283 if (count($parts) > 1)
1284 $request->setArg('overwrite', 1);
1285 SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1286 $filename), $basename);
1288 if (count($parts) > 1)
1290 $request->setArg('overwrite', $overwrite);
1292 unset($request->_args['overwrite']);
1294 else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename,
1295 $request->getUser())) ) {
1296 SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1297 $filename), $basename);
1301 $user = $request->getUser();
1303 $file_charset = 'iso-8859-1';
1304 // compare to target charset
1305 if ($file_charset != strtolower($GLOBALS['charset'])) {
1306 $text = charset_convert($file_charset, $GLOBALS['charset'], $text);
1307 $default_pagename = charset_convert($file_charset, $GLOBALS['charset'], $default_pagename);
1310 // Assume plain text file.
1311 $pageinfo = array('pagename' => $default_pagename,
1312 'pagedata' => array(),
1314 => array('author' => $user->getId()),
1315 'content' => preg_replace('/[ \t\r]*\n/', "\n",
1318 SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1323 function LoadZip (&$request, $zipfile, $files = false, $exclude = false) {
1324 $zip = new ZipReader($zipfile);
1325 $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1326 while (list ($fn, $data, $attrib) = $zip->readFile()) {
1327 // FIXME: basename("filewithnoslashes") seems to return
1328 // garbage sometimes.
1329 $fn = basename("/dummy/" . $fn);
1330 if ( ($files && !in_array($fn, $files))
1331 || ($exclude && in_array($fn, $exclude)) ) {
1332 PrintXML(HTML::p(WikiLink($fn)),
1333 HTML::p(_("Skipping")));
1337 longer_timeout($timeout); // longer timeout per page
1338 LoadFile($request, $fn, $data, $attrib['mtime']);
1342 function LoadDir (&$request, $dirname, $files = false, $exclude = false) {
1343 $fileset = new LimitedFileSet($dirname, $files, $exclude);
1345 if (!$files and ($skiplist = $fileset->getSkippedFiles())) {
1346 PrintXML(HTML::p(HTML::strong(_("Skipping"))));
1348 foreach ($skiplist as $file)
1349 $list->pushContent(HTML::li(WikiLink($file)));
1350 PrintXML(HTML::p($list));
1353 // Defer HomePage loading until the end. If anything goes wrong
1354 // the pages can still be loaded again.
1355 $files = $fileset->getFiles();
1356 if (in_array(HOME_PAGE, $files)) {
1357 $files = array_diff($files, array(HOME_PAGE));
1358 $files[] = HOME_PAGE;
1360 $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1361 foreach ($files as $file) {
1362 longer_timeout($timeout); // longer timeout per page
1363 if (substr($file,-1,1) != '~') // refuse to load backup files
1364 LoadFile($request, "$dirname/$file");
1368 class LimitedFileSet extends FileSet {
1369 function LimitedFileSet($dirname, $_include, $exclude) {
1370 $this->_includefiles = $_include;
1371 $this->_exclude = $exclude;
1372 $this->_skiplist = array();
1373 parent::FileSet($dirname);
1376 function _filenameSelector($fn) {
1377 $incl = &$this->_includefiles;
1378 $excl = &$this->_exclude;
1380 if ( ($incl && !in_array($fn, $incl))
1381 || ($excl && in_array($fn, $excl)) ) {
1382 $this->_skiplist[] = $fn;
1389 function getSkippedFiles () {
1390 return $this->_skiplist;
1395 function IsZipFile ($filename_or_fd)
1397 // See if it looks like zip file
1398 if (is_string($filename_or_fd))
1400 $fd = fopen($filename_or_fd, "rb");
1401 $magic = fread($fd, 4);
1406 $fpos = ftell($filename_or_fd);
1407 $magic = fread($filename_or_fd, 4);
1408 fseek($filename_or_fd, $fpos);
1411 return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
1415 function LoadAny (&$request, $file_or_dir, $files = false, $exclude = false)
1417 // Try urlencoded filename for accented characters.
1418 if (!file_exists($file_or_dir)) {
1419 // Make sure there are slashes first to avoid confusing phps
1420 // with broken dirname or basename functions.
1421 // FIXME: windows uses \ and :
1422 if (is_integer(strpos($file_or_dir, "/"))) {
1423 $newfile = FindFile($file_or_dir, true);
1424 // Panic. urlencoded by the browser (e.g. San%20Diego => San Diego)
1426 $file_or_dir = dirname($file_or_dir) . "/"
1427 . rawurlencode(basename($file_or_dir));
1429 // This is probably just a file.
1430 $file_or_dir = rawurlencode($file_or_dir);
1434 $type = filetype($file_or_dir);
1435 if ($type == 'link') {
1436 // For symbolic links, use stat() to determine
1437 // the type of the underlying file.
1438 list(,,$mode) = stat($file_or_dir);
1439 $type = ($mode >> 12) & 017;
1442 elseif ($type == 004)
1447 $request->finish(fmt("Empty or not existing source. Unable to load: %s", $file_or_dir));
1449 else if ($type == 'dir') {
1450 LoadDir($request, $file_or_dir, $files, $exclude);
1452 else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
1454 $request->finish(fmt("Bad file type: %s", $type));
1456 else if (IsZipFile($file_or_dir)) {
1457 LoadZip($request, $file_or_dir, $files, $exclude);
1459 else /* if (!$files || in_array(basename($file_or_dir), $files)) */
1461 LoadFile($request, $file_or_dir);
1465 function LoadFileOrDir (&$request)
1467 $source = $request->getArg('source');
1468 $finder = new FileFinder;
1469 $source = $finder->slashifyPath($source);
1470 $page = rawurldecode(basename($source));
1471 StartLoadDump($request, fmt("Loading '%s'",
1472 HTML(dirname($source),
1473 dirname($source) ? "/" : "",
1474 WikiLink($page,'auto'))));
1476 LoadAny($request, $source);
1478 EndLoadDump($request);
1482 * HomePage was not found so first-time install is supposed to run.
1483 * - import all pgsrc pages.
1484 * - Todo: installer interface to edit config/config.ini settings
1485 * - Todo: ask for existing old index.php to convert to config/config.ini
1486 * - Todo: theme-specific pages:
1487 * blog - HomePage, ADMIN_USER/Blogs
1489 function SetupWiki (&$request)
1491 global $GenericPages, $LANG;
1493 //FIXME: This is a hack (err, "interim solution")
1494 // This is a bogo-bogo-login: Login without
1495 // saving login information in session state.
1496 // This avoids logging in the unsuspecting
1497 // visitor as "The PhpWiki programming team".
1499 // This really needs to be cleaned up...
1500 // (I'm working on it.)
1501 $real_user = $request->_user;
1502 if (ENABLE_USER_NEW)
1503 $request->_user = new _BogoUser(_("The PhpWiki programming team"));
1506 $request->_user = new WikiUser($request, _("The PhpWiki programming team"),
1509 StartLoadDump($request, _("Loading up virgin wiki"));
1511 $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1512 $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1514 $request->setArg('overwrite', true);
1515 if ($default_pgsrc != $pgsrc) {
1516 LoadAny($request, $default_pgsrc, $GenericPages);
1518 $request->setArg('overwrite', false);
1519 LoadAny($request, $pgsrc);
1520 $dbi =& $request->_dbi;
1522 // Ensure that all mandatory pages are loaded
1523 $finder = new FileFinder;
1524 foreach (array_merge(explode(':','Help/OldTextFormattingRules:Help/TextFormattingRules:PhpWikiAdministration'),
1525 $GLOBALS['AllActionPages'],
1526 array(constant('HOME_PAGE'))) as $f)
1528 $page = gettext($f);
1529 $epage = urlencode($page);
1530 if (! $dbi->isWikiPage($page) ) {
1531 // translated version provided?
1532 if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1533 LoadAny($request, $lf);
1534 } else { // load english version of required action page
1535 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1539 if (! $dbi->isWikiPage($page)) {
1540 trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1545 $pagename = _("InterWikiMap");
1546 $map = $dbi->getPage($pagename);
1547 $map->set('locked', true);
1548 PrintXML(HTML::p(HTML::em(WikiLink($pagename)), HTML::strong(" locked")));
1549 EndLoadDump($request);
1552 function LoadPostFile (&$request)
1554 $upload = $request->getUploadedFile('file');
1557 $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1560 // Dump http headers.
1561 StartLoadDump($request, sprintf(_("Uploading %s"), $upload->getName()));
1564 $fd = $upload->open();
1566 LoadZip($request, $fd, false, array(_("RecentChanges")));
1568 LoadFile($request, $upload->getName(), $upload->getContents());
1571 EndLoadDump($request);
1578 // c-basic-offset: 4
1579 // c-hanging-comment-ender-p: nil
1580 // indent-tabs-mode: nil