5 Copyright 1999,2000,2001,2002,2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
6 Copyright (C) 2008-2009 Marc-Etienne Vargenau, Alcatel-Lucent
8 This file is part of PhpWiki.
10 PhpWiki is free software; you can redistribute it and/or modify
11 it under the terms of the GNU General Public License as published by
12 the Free Software Foundation; either version 2 of the License, or
13 (at your option) any later version.
15 PhpWiki is distributed in the hope that it will be useful,
16 but WITHOUT ANY WARRANTY; without even the implied warranty of
17 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 GNU General Public License for more details.
20 You should have received a copy of the GNU General Public License
21 along with PhpWiki; if not, write to the Free Software
22 Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
25 require_once("lib/ziplib.php");
26 require_once("lib/Template.php");
29 * ignore fatal errors during dump
31 function _dump_error_handler(&$error) {
32 if ($error->isFatal()) {
33 $error->errno = E_USER_WARNING;
36 return true; // Ignore error
38 if (preg_match('/Plugin/', $error->errstr))
41 // let the message come through: call the remaining handlers:
45 function StartLoadDump(&$request, $title, $html = '')
47 // MockRequest is from the unit testsuite, a faked request. (may be cmd-line)
48 // We are silent on unittests.
49 if (isa($request,'MockRequest'))
51 // FIXME: This is a hack. This really is the worst overall hack in phpwiki.
53 $html->pushContent('%BODY%');
54 $tmpl = Template('html', array('TITLE' => $title,
56 'CONTENT' => $html ? $html : '%BODY%'));
57 echo ereg_replace('%BODY%.*', '', $tmpl->getExpansion($html));
58 $request->chunkOutput();
60 // set marker for sendPageChangeNotification()
61 $request->_deferredPageChangeNotification = array();
64 function EndLoadDump(&$request)
68 if (isa($request,'MockRequest'))
70 $action = $request->getArg('action');
73 case 'zip': $label = _("ZIP files of database"); break;
74 case 'dumpserial': $label = _("Dump to directory"); break;
75 case 'upload': $label = _("Upload File"); break;
76 case 'loadfile': $label = _("Load File"); break;
77 case 'upgrade': $label = _("Upgrade"); break;
79 case 'ziphtml': $label = _("Dump pages as XHTML"); break;
81 if ($label) $label = str_replace(" ","_",$label);
82 if ($action == 'browse') // loading virgin
83 $pagelink = WikiLink(HOME_PAGE);
85 $pagelink = WikiLink(new WikiPageName(_("PhpWikiAdministration"),false,$label));
87 // do deferred sendPageChangeNotification()
88 if (!empty($request->_deferredPageChangeNotification)) {
89 $pages = $all_emails = $all_users = array();
90 foreach ($request->_deferredPageChangeNotification as $p) {
91 list($pagename, $emails, $userids) = $p;
93 $all_emails = array_unique(array_merge($all_emails, $emails));
94 $all_users = array_unique(array_merge($all_users, $userids));
96 $editedby = sprintf(_("Edited by: %s"), $request->_user->getId());
97 $content = "Loaded the following pages:\n" . join("\n", $pages);
98 if (mail(join(',',$all_emails),"[".WIKI_NAME."] "._("LoadDump"),
102 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
103 join("\n",$pages), join(',',$all_users)), E_USER_NOTICE);
105 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
106 join("\n",$pages), join(',',$all_users)), E_USER_WARNING);
111 unset($request->_deferredPageChangeNotification);
113 PrintXML(HTML::p(HTML::strong(_("Complete."))),
114 HTML::p(fmt("Return to %s", $pagelink)));
115 // Ugly hack to get valid XHTML code
116 if (isa($WikiTheme, 'WikiTheme_gforge')) {
123 echo "</body></html>\n";
127 ////////////////////////////////////////////////////////////////
129 // Functions for dumping.
131 ////////////////////////////////////////////////////////////////
135 * http://www.nacs.uci.edu/indiv/ehood/MIME/2045/rfc2045.html
136 * http://www.faqs.org/rfcs/rfc2045.html
137 * (RFC 1521 has been superceeded by RFC 2045 & others).
139 * Also see http://www.faqs.org/rfcs/rfc2822.html
141 function MailifyPage ($page, $nversions = 1)
143 $current = $page->getCurrentRevision(false);
146 if (STRICT_MAILABLE_PAGEDUMPS) {
147 $from = defined('SERVER_ADMIN') ? SERVER_ADMIN : 'foo@bar';
148 //This is for unix mailbox format: (not RFC (2)822)
149 // $head .= "From $from " . CTime(time()) . "\r\n";
150 $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
151 $head .= "From: $from (PhpWiki)\r\n";
152 // RFC 2822 requires only a Date: and originator (From:)
153 // field, however the obsolete standard RFC 822 also
154 // requires a destination field.
155 $head .= "To: $from (PhpWiki)\r\n";
157 $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
158 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
161 // This should just be entered by hand (or by script?)
162 // in the actual pgsrc files, since only they should have
164 //$head .= "X-Rcs-Id: \$Id\$\r\n";
166 $iter = $page->getAllRevisions();
168 while ($revision = $iter->next()) {
169 $parts[] = MimeifyPageRevision($page, $revision);
170 if ($nversions > 0 && count($parts) >= $nversions)
173 if (count($parts) > 1)
174 return $head . MimeMultipart($parts);
176 return $head . $parts[0];
180 * Compute filename to used for storing contents of a wiki page.
182 * Basically we do a rawurlencode() which encodes everything except
183 * ASCII alphanumerics and '.', '-', and '_'.
185 * But we also want to encode leading dots to avoid filenames like
186 * '.', and '..'. (Also, there's no point in generating "hidden" file
187 * names, like '.foo'.)
189 * We have to apply a different "/" logic for dumpserial, htmldump and zipdump.
190 * dirs are allowed for zipdump and htmldump, not for dumpserial
193 * @param $pagename string Pagename.
194 * @return string Filename for page.
196 function FilenameForPage ($pagename, $action = false)
198 $enc = rawurlencode($pagename);
201 $action = $request->getArg('action');
203 if ($action != 'dumpserial') { // zip, ziphtml, dumphtml
204 // For every %2F we will need to mkdir -p dirname($pagename)
205 $enc = preg_replace('/%2F/', '/', $enc);
207 $enc = preg_replace('/^\./', '%2E', $enc);
208 $enc = preg_replace('/%20/', ' ', $enc);
213 * The main() function which generates a zip archive of a PhpWiki.
215 * If $include_archive is false, only the current version of each page
216 * is included in the zip file; otherwise all archived versions are
219 function MakeWikiZip (&$request)
221 if ($request->getArg('include') == 'all') {
222 $zipname = WIKI_NAME . _("FullDump") . date('Ymd-Hi') . '.zip';
223 $include_archive = true;
226 $zipname = WIKI_NAME . _("LatestSnapshot") . date('Ymd-Hi') . '.zip';
227 $include_archive = false;
229 $include_empty = false;
230 if ($request->getArg('include') == 'empty') {
231 $include_empty = true;
234 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
236 /* ignore fatals in plugins */
237 if (check_php_version(4,1)) {
238 global $ErrorManager;
239 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
242 $dbi =& $request->_dbi;
243 $thispage = $request->getArg('pagename'); // for "Return to ..."
244 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
245 $excludeList = explodePageList($exclude);
247 $excludeList = array();
249 if ($pages = $request->getArg('pages')) { // which pagenames
250 if ($pages == '[]') // current page
252 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
254 $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
256 $request_args = $request->args;
257 $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
259 while ($page = $page_iter->next()) {
260 $request->args = $request_args; // some plugins might change them (esp. on POST)
261 longer_timeout($timeout); // Reset watchdog
263 $current = $page->getCurrentRevision();
264 if ($current->getVersion() == 0)
267 $pagename = $page->getName();
268 $wpn = new WikiPageName($pagename);
269 if (!$wpn->isValid())
271 if (in_array($page->getName(), $excludeList)) {
275 $attrib = array('mtime' => $current->get('mtime'),
277 if ($page->get('locked'))
278 $attrib['write_protected'] = 1;
280 if ($include_archive)
281 $content = MailifyPage($page, 0);
283 $content = MailifyPage($page);
285 $zip->addRegularFile( FilenameForPage($pagename),
289 if (check_php_version(4,1)) {
290 global $ErrorManager;
291 $ErrorManager->popErrorHandler();
295 function DumpToDir (&$request)
297 $directory = $request->getArg('directory');
298 if (empty($directory))
299 $directory = DEFAULT_DUMP_DIR; // See lib/plugin/WikiForm.php:87
300 if (empty($directory))
301 $request->finish(_("You must specify a directory to dump to"));
303 // see if we can access the directory the user wants us to use
304 if (! file_exists($directory)) {
305 if (! mkdir($directory, 0755))
306 $request->finish(fmt("Cannot create directory '%s'", $directory));
308 $html = HTML::p(fmt("Created directory '%s' for the page dump...",
311 $html = HTML::p(fmt("Using directory '%s'", $directory));
314 StartLoadDump($request, _("Dumping Pages"), $html);
316 $dbi =& $request->_dbi;
317 $thispage = $request->getArg('pagename'); // for "Return to ..."
318 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
319 $excludeList = explodePageList($exclude);
321 $excludeList = array();
323 $include_empty = false;
324 if ($request->getArg('include') == 'empty') {
325 $include_empty = true;
327 if ($pages = $request->getArg('pages')) { // which pagenames
328 if ($pages == '[]') // current page
330 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
332 $page_iter = $dbi->getAllPages($include_empty,false,false,$excludeList);
335 $request_args = $request->args;
336 $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
338 while ($page = $page_iter->next()) {
339 $request->args = $request_args; // some plugins might change them (esp. on POST)
340 longer_timeout($timeout); // Reset watchdog
342 $pagename = $page->getName();
343 if (!isa($request,'MockRequest')) {
344 PrintXML(HTML::br(), $pagename, ' ... ');
348 if (in_array($pagename, $excludeList)) {
349 if (!isa($request, 'MockRequest')) {
350 PrintXML(_("Skipped."));
355 $filename = FilenameForPage($pagename);
357 if($page->getName() != $filename) {
358 $msg->pushContent(HTML::small(fmt("saved as %s", $filename)),
362 if ($request->getArg('include') == 'all')
363 $data = MailifyPage($page, 0);
365 $data = MailifyPage($page);
367 if ( !($fd = fopen($directory."/".$filename, "wb")) ) {
368 $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
369 "$directory/$filename")));
370 $request->finish($msg);
373 $num = fwrite($fd, $data, strlen($data));
374 $msg->pushContent(HTML::small(fmt("%s bytes written", $num)));
375 if (!isa($request, 'MockRequest')) {
379 assert($num == strlen($data));
383 EndLoadDump($request);
386 function _copyMsg($page, $smallmsg) {
387 if (!isa($GLOBALS['request'], 'MockRequest')) {
388 if ($page) $msg = HTML(HTML::br(), HTML($page), HTML::small($smallmsg));
389 else $msg = HTML::small($smallmsg);
395 function mkdir_p($pathname, $permission = 0777) {
396 $arr = explode("/", $pathname);
398 return mkdir($pathname, $permission);
400 $s = array_shift($arr);
402 foreach ($arr as $p) {
405 $ok = mkdir($curr, $permission);
407 if (!$ok) return FALSE;
413 * Dump all pages as XHTML to a directory, as pagename.html.
414 * Copies all used css files to the directory, all used images to a
415 * "images" subdirectory, and all used buttons to a "images/buttons" subdirectory.
416 * The webserver must have write permissions to these directories.
417 * chown httpd HTML_DUMP_DIR; chmod u+rwx HTML_DUMP_DIR
420 * @param string directory (optional) path to dump to. Default: HTML_DUMP_DIR
421 * @param string pages (optional) Comma-seperated of glob-style pagenames to dump.
422 * Also array of pagenames allowed.
423 * @param string exclude (optional) Comma-seperated of glob-style pagenames to exclude
425 function DumpHtmlToDir (&$request)
428 $directory = $request->getArg('directory');
429 if (empty($directory))
430 $directory = HTML_DUMP_DIR; // See lib/plugin/WikiForm.php:87
431 if (empty($directory))
432 $request->finish(_("You must specify a directory to dump to"));
434 // See if we can access the directory the user wants us to use
435 if (! file_exists($directory)) {
436 if (! mkdir($directory, 0755))
437 $request->finish(fmt("Cannot create directory '%s'", $directory));
439 $html = HTML::p(fmt("Created directory '%s' for the page dump...",
442 $html = HTML::p(fmt("Using directory '%s'", $directory));
444 StartLoadDump($request, _("Dumping Pages"), $html);
445 $thispage = $request->getArg('pagename'); // for "Return to ..."
447 $dbi =& $request->_dbi;
448 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
449 $excludeList = explodePageList($exclude);
451 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
453 if ($pages = $request->getArg('pages')) { // which pagenames
454 if ($pages == '[]') // current page
456 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
457 // not at admin page: dump only the current page
458 } elseif ($thispage != _("PhpWikiAdministration")) {
459 $page_iter = new WikiDB_Array_generic_iter(array($thispage));
461 $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
464 $WikiTheme->DUMP_MODE = 'HTML';
465 _DumpHtmlToDir($directory, $page_iter, $request->getArg('exclude'));
466 $WikiTheme->DUMP_MODE = false;
468 $request->setArg('pagename',$thispage); // Template::_basepage fix
469 EndLoadDump($request);
472 /* Known problem: any plugins or other code which echo()s text will
473 * lead to a corrupted html zip file which may produce the following
474 * errors upon unzipping:
476 * warning [wikihtml.zip]: 2401 extra bytes at beginning or within zipfile
477 * file #58: bad zipfile offset (local header sig): 177561
478 * (attempting to re-compensate)
480 * However, the actual wiki page data should be unaffected.
482 function MakeWikiZipHtml (&$request)
485 if ($request->getArg('zipname')) {
486 $zipname = basename($request->getArg('zipname'));
487 if (!preg_match("/\.zip$/i", $zipname))
489 $request->setArg('zipname', false);
491 $zipname = "wikihtml.zip";
493 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
494 $dbi =& $request->_dbi;
495 $thispage = $request->getArg('pagename'); // for "Return to ..."
496 if ($pages = $request->getArg('pages')) { // which pagenames
497 if ($pages == '[]') // current page
499 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
501 $page_iter = $dbi->getAllPages(false,false,false,$request->getArg('exclude'));
504 $WikiTheme->DUMP_MODE = 'ZIPHTML';
505 _DumpHtmlToDir($zip, $page_iter, $request->getArg('exclude'));
506 $WikiTheme->DUMP_MODE = false;
510 * Internal html dumper. Used for dumphtml, ziphtml and pdf
512 function _DumpHtmlToDir ($target, $page_iter, $exclude = false)
514 global $WikiTheme, $request;
515 $silent = true; $zip = false; $directory = false;
516 if ($WikiTheme->DUMP_MODE == 'HTML') {
517 $directory = $target;
519 } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') {
520 $directory = $target;
521 } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML'
525 $request->_TemplatesProcessed = array();
526 if ($exclude) { // exclude which pagenames
527 $excludeList = explodePageList($exclude);
529 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
531 $WikiTheme->VALID_LINKS = array();
532 if ($request->getArg('format')) { // pagelist
533 $page_iter_sav = $page_iter;
534 foreach ($page_iter_sav->asArray() as $handle) {
535 $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName();
537 $page_iter_sav->reset();
540 if (defined('HTML_DUMP_SUFFIX'))
541 $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
542 $_bodyAttr = @$WikiTheme->_MoreAttr['body'];
543 unset($WikiTheme->_MoreAttr['body']);
545 if (check_php_version(4,1)) {
546 global $ErrorManager;
547 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
550 // check if the dumped file will be accessible from outside
551 $doc_root = $request->get("DOCUMENT_ROOT");
552 if ($WikiTheme->DUMP_MODE == 'HTML') {
553 $ldir = NormalizeLocalFileName($directory);
554 $wikiroot = NormalizeLocalFileName('');
555 if (string_starts_with($ldir, $doc_root)) {
556 $link_prefix = substr($directory, strlen($doc_root))."/";
557 } elseif (string_starts_with($ldir, $wikiroot)) {
558 $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/";
562 $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed
564 $link_prefix = "file://".$prefix.$directory."/";
570 $request_args = $request->args;
571 $timeout = (! $request->getArg('start_debug')) ? 60 : 240;
572 $SAVE_RCS_IDS = $GLOBALS['RCS_IDS'];
575 $directory = str_replace("\\", "/", $directory); // no Win95 support.
576 @mkdir("$directory/images");
580 $already_images = array();
582 while ($page = $page_iter->next()) {
583 if (is_string($page)) {
585 $page = $request->_dbi->getPage($pagename);
587 $pagename = $page->getName();
589 if (empty($firstpage)) $firstpage = $pagename;
590 if (array_key_exists($pagename, $already))
592 $already[$pagename] = 1;
593 $current = $page->getCurrentRevision();
594 //if ($current->getVersion() == 0)
597 $request->args = $request_args; // some plugins might change them (esp. on POST)
598 longer_timeout($timeout); // Reset watchdog
601 $attrib = array('mtime' => $current->get('mtime'),
603 if ($page->get('locked'))
604 $attrib['write_protected'] = 1;
605 } elseif (!$silent) {
606 if (!isa($request,'MockRequest')) {
607 PrintXML(HTML::br(), $pagename, ' ... ');
611 if (in_array($pagename, $excludeList)) {
612 if (!$silent and !isa($request,'MockRequest')) {
613 PrintXML(_("Skipped."));
619 if ($WikiTheme->DUMP_MODE == 'PDFHTML')
620 $request->setArg('action', 'pdf'); // to omit cache headers
621 $request->setArg('pagename', $pagename); // Template::_basepage fix
622 $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
623 $args = array('revision' => $current,
624 'CONTENT' => $current->getTransformedContent(),
625 'relative_base' => $relative_base);
626 // For every %2F will need to mkdir -p dirname($pagename)
627 if (preg_match("/(%2F|\/)/", $filename)) {
628 // mkdir -p and set relative base for subdir pages
629 $filename = preg_replace("/%2F/", "/", $filename);
630 $count = substr_count($filename, "/");
631 $dirname = dirname($filename);
633 mkdir_p($directory."/".$dirname);
634 // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written
635 // if (isWindows()) // interesting Windows bug: cannot mkdir "bla "
636 // Since dumps needs to be copied, we have to disallow this for all platforms.
637 $filename = preg_replace("/ \//", "/", $filename);
638 $relative_base = "../";
640 $relative_base .= "../";
643 $args['relative_base'] = $relative_base;
647 $DUMP_MODE = $WikiTheme->DUMP_MODE;
648 $data = GeneratePageasXML(new Template('browse', $request, $args),
649 $pagename, $current, $args);
650 $WikiTheme->DUMP_MODE = $DUMP_MODE;
652 if (preg_match_all("/<img .*?src=\"(\/.+?)\"/", $data, $m)) {
653 // fix to local relative path for uploaded images, so that pdf will work
654 foreach ($m[1] as $img_file) {
655 $base = basename($img_file);
656 $data = str_replace('src="'.$img_file.'"','src="images/'.$base.'"', $data);
657 if (array_key_exists($img_file, $already_images))
659 $already_images[$img_file] = 1;
660 // resolve src from webdata to file
661 $src = $doc_root . $img_file;
662 if (file_exists($src) and $base) {
664 $target = "$directory/images/$base";
665 if (copy($src, $target)) {
667 _copyMsg($img_file, fmt("... copied to %s", $target));
670 _copyMsg($img_file, fmt("... not copied to %s", $target));
673 $target = "images/$base";
674 $zip->addSrcFile($target, $src);
681 $outfile = $directory."/".$filename;
682 if ( !($fd = fopen($outfile, "wb")) ) {
683 $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
685 $request->finish($msg);
687 $len = strlen($data);
688 $num = fwrite($fd, $data, $len);
689 if ($pagename != $filename) {
690 $link = LinkURL($link_prefix.$filename, $filename);
691 $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
693 $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
695 if (!isa($request, 'MockRequest')) {
699 $request->chunkOutput();
701 assert($num == $len);
703 $outfiles[] = $outfile;
705 $zip->addRegularFile($filename, $data, $attrib);
709 $request->_dbi->_cache->invalidate_cache($pagename);
710 unset ($request->_dbi->_cache->_pagedata_cache);
711 unset ($request->_dbi->_cache->_versiondata_cache);
712 unset ($request->_dbi->_cache->_glv_cache);
714 unset ($request->_dbi->_cache->_backend->_page_data);
717 unset($current->_transformedContent);
719 if (!empty($template)) {
720 unset($template->_request);
725 $GLOBALS['RCS_IDS'] = $SAVE_RCS_IDS;
729 $attrib = false; //array('is_ascii' => 0);
730 if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
731 // @mkdir("$directory/images");
732 foreach ($WikiTheme->dumped_images as $img_file) {
733 if (array_key_exists($img_file, $already_images))
735 $already_images[$img_file] = 1;
737 and ($from = $WikiTheme->_findFile($img_file, true))
741 $target = "$directory/images/".basename($from);
743 copy($WikiTheme->_path . $from, $target);
745 if (copy($WikiTheme->_path . $from, $target)) {
746 _copyMsg($from, fmt("... copied to %s", $target));
748 _copyMsg($from, fmt("... not copied to %s", $target));
752 $target = "images/".basename($from);
753 $zip->addSrcFile($target, $WikiTheme->_path . $from);
755 } elseif (!$silent) {
756 _copyMsg($from, _("... not found"));
761 if (!empty($WikiTheme->dumped_buttons)
762 and is_array($WikiTheme->dumped_buttons))
766 @mkdir("$directory/images/buttons");
767 foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
768 if (array_key_exists($img_file, $already_images))
770 $already_images[$img_file] = 1;
772 and ($from = $WikiTheme->_findFile($img_file, true))
776 $target = "$directory/images/buttons/".basename($from);
778 copy($WikiTheme->_path . $from, $target);
780 if (copy($WikiTheme->_path . $from, $target)) {
781 _copyMsg($from, fmt("... copied to %s", $target));
783 _copyMsg($from, fmt("... not copied to %s", $target));
787 $target = "images/buttons/".basename($from);
788 $zip->addSrcFile($target, $WikiTheme->_path . $from);
790 } elseif (!$silent) {
791 _copyMsg($from, _("... not found"));
795 if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
796 foreach ($WikiTheme->dumped_css as $css_file) {
797 if (array_key_exists($css_file, $already_images))
799 $already_images[$css_file] = 1;
801 and ($from = $WikiTheme->_findFile(basename($css_file), true))
804 // TODO: fix @import url(main.css);
806 $target = "$directory/" . basename($css_file);
808 copy($WikiTheme->_path . $from, $target);
810 if (copy($WikiTheme->_path . $from, $target)) {
811 _copyMsg($from, fmt("... copied to %s", $target));
813 _copyMsg($from, fmt("... not copied to %s", $target));
817 //$attrib = array('is_ascii' => 0);
818 $target = basename($css_file);
819 $zip->addSrcFile($target, $WikiTheme->_path . $from);
821 } elseif (!$silent) {
822 _copyMsg($from, _("... not found"));
830 if ($WikiTheme->DUMP_MODE == 'PDFHTML') {
831 if (USE_EXTERNAL_HTML2PDF and $outfiles) {
832 $cmd = EXTERNAL_HTML2PDF_PAGELIST.' "'.join('" "', $outfiles).'"';
833 $filename = FilenameForPage($firstpage);
835 $tmpfile = $directory . "/createpdf.bat";
836 $fp = fopen($tmpfile, "wb");
837 fwrite($fp, $cmd . " > $filename.pdf");
840 if (!headers_sent()) {
841 Header('Content-Type: application/pdf');
845 $tmpdir = getUploadFilePath();
846 $s = passthru($cmd . " > $tmpdir/$filename.pdf");
847 $errormsg = "<br />\nGenerated <a href=\"".getUploadDataPath()."$filename.pdf\">Upload:$filename.pdf</a>\n";
852 foreach($outfiles as $f) unlink($f);
855 if (!empty($errormsg)) {
856 $request->discardOutput();
857 $GLOBALS['ErrorManager']->_postponed_errors = array();
861 if (check_php_version(4,1)) {
862 global $ErrorManager;
863 $ErrorManager->popErrorHandler();
866 $WikiTheme->HTML_DUMP_SUFFIX = '';
867 $WikiTheme->DUMP_MODE = false;
868 $WikiTheme->_MoreAttr['body'] = $_bodyAttr;
872 ////////////////////////////////////////////////////////////////
874 // Functions for restoring.
876 ////////////////////////////////////////////////////////////////
878 function SavePage (&$request, &$pageinfo, $source, $filename)
880 static $overwite_all = false;
881 $pagedata = $pageinfo['pagedata']; // Page level meta-data.
882 $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
884 if (empty($pageinfo['pagename'])) {
885 PrintXML(HTML::p(HTML::strong(_("Empty pagename!"))));
889 if (empty($versiondata['author_id']))
890 $versiondata['author_id'] = $versiondata['author'];
892 // remove invalid backend specific chars. utf8 issues mostly
893 $pagename_check = new WikiPagename($pageinfo['pagename']);
894 if (!$pagename_check->isValid()) {
895 PrintXML(HTML::p(HTML::strong(_("Invalid pagename!")." ".$pageinfo['pagename'])));
898 $pagename = $pagename_check->getName();
899 $content = $pageinfo['content'];
901 if ($pagename == _("InterWikiMap"))
902 $content = _tryinsertInterWikiMap($content);
904 $dbi =& $request->_dbi;
905 $page = $dbi->getPage($pagename);
907 // Try to merge if updated pgsrc contents are different. This
908 // whole thing is hackish
910 // TODO: try merge unless:
911 // if (current contents = default contents && pgsrc_version >=
912 // pgsrc_version) then just upgrade this pgsrc
913 $needs_merge = false;
917 if ($request->getArg('merge')) {
920 else if ($request->getArg('overwrite')) {
924 $current = $page->getCurrentRevision();
926 $edit = $request->getArg('edit');
928 if (isset($edit['keep_old'])) {
932 elseif (isset($edit['overwrite'])) {
936 elseif ( $current and (! $current->hasDefaultContents())
937 && ($current->getPackedContent() != $content) )
939 include_once('lib/editpage.php');
940 $request->setArg('pagename', $pagename);
941 $v = $current->getVersion();
942 $request->setArg('revision', $current->getVersion());
943 $p = new LoadFileConflictPageEditor($request);
944 $p->_content = $content;
945 $p->_currentVersion = $v - 1;
946 $p->editPage($saveFailed = true);
947 return; //early return
951 foreach ($pagedata as $key => $value) {
953 $page->set($key, $value);
956 $mesg = HTML::p(array('style' => 'text-indent: 3em;'));
958 $mesg->pushContent(' ', fmt("from %s", $source));
961 //FIXME: This should not happen! (empty vdata, corrupt cache or db)
962 $current = $page->getCurrentRevision();
964 if ($current->getVersion() == 0) {
965 $mesg->pushContent(' - ', _("New page"));
969 if ( (! $current->hasDefaultContents())
970 && ($current->getPackedContent() != $content) ) {
972 $mesg->pushContent(' ',
973 fmt("has edit conflicts - overwriting anyway"));
975 if (substr_count($source, 'pgsrc')) {
976 $versiondata['author'] = _("The PhpWiki programming team");
977 // but leave authorid as userid who loaded the file
981 if (isset($edit['keep_old'])) {
982 $mesg->pushContent(' ', fmt("keep old"));
984 $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
985 $needs_merge = true; // hackish, to display the buttons
990 else if ($current->getPackedContent() == $content
991 && $current->get('author') == $versiondata['author']) {
992 // The page metadata is already changed, we don't need a new revision.
993 // This was called previously "is identical to current version %d - skipped"
994 // which is wrong, since the pagedata was stored, not skipped.
995 $mesg->pushContent(' ',
996 fmt("content is identical to current version %d - no new revision created",
997 $current->getVersion()));
1004 // in case of failures print the culprit:
1005 if (!isa($request,'MockRequest')) {
1006 PrintXML(HTML::p(WikiLink($pagename))); flush();
1008 $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
1010 $mesg->pushContent(' ', fmt("- saved to database as version %d",
1011 $new->getVersion()));
1015 // hackish, $source contains needed path+filename
1016 $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
1017 $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
1018 $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
1019 //check if uploaded file? they pass just the content, but the file is gone
1022 $meb = Button(array('action' => 'loadfile',
1026 _("PhpWikiAdministration"),
1028 $owb = Button(array('action' => 'loadfile',
1031 _("Restore Anyway"),
1032 _("PhpWikiAdministration"),
1034 $mesg->pushContent(' ', $meb, " ", $owb);
1035 if (!$overwite_all) {
1036 $args = $request->getArgs();
1037 $args['overwrite'] = 1;
1038 $owb = Button($args,
1040 _("PhpWikiAdministration"),
1042 $mesg->pushContent(HTML::div(array('class' => 'hint'), $owb));
1043 $overwite_all = true;
1046 $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
1050 if (!isa($request,'MockRequest')) {
1052 PrintXML(HTML::p(HTML::em(WikiLink($pagename))), $mesg);
1059 // action=revert (by diff)
1060 function RevertPage (&$request)
1062 $mesg = HTML::div();
1063 $pagename = $request->getArg('pagename');
1064 $version = $request->getArg('version');
1066 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1067 HTML::p(_("missing required version argument")));
1070 $dbi =& $request->_dbi;
1071 $page = $dbi->getPage($pagename);
1072 $current = $page->getCurrentRevision();
1073 $currversion = $current->getVersion();
1074 if ($currversion == 0) {
1075 $mesg->pushContent(' ', _("no page content"));
1076 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1081 if ($currversion == $version) {
1082 $mesg->pushContent(' ', _("same version page"));
1083 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1088 if ($request->getArg('cancel')) {
1089 $mesg->pushContent(' ', _("Cancelled"));
1090 PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1095 if (!$request->getArg('verify')) {
1096 $mesg->pushContent(HTML::p(_("Are you sure?")),
1097 HTML::form(array('action' => $request->getPostURL(),
1098 'method' => 'post'),
1099 HiddenInputs($request->getArgs(), false, array('verify')),
1100 HiddenInputs(array('verify' => 1)),
1101 Button('submit:verify', _("Yes"), 'button'),
1102 HTML::Raw(' '),
1103 Button('submit:cancel', _("Cancel"), 'button')),
1105 $rev = $page->getRevision($version);
1106 $html = HTML(HTML::p(fmt("Revert %s to version $version", WikiLink($pagename))),
1108 $rev->getTransformedContent());
1109 $template = Template('browse',
1110 array('CONTENT' => $html));
1111 GeneratePage($template, $pagename, $rev);
1112 $request->checkValidators();
1116 $rev = $page->getRevision($version);
1117 $content = $rev->getPackedContent();
1118 $versiondata = $rev->_data;
1119 $versiondata['summary'] = sprintf(_("revert to version %d"), $version);
1120 $new = $page->save($content, $currversion + 1, $versiondata);
1123 $pagelink = WikiLink($pagename);
1124 $mesg->pushContent(fmt("Revert: %s", $pagelink),
1125 fmt("- version %d saved to database as version %d",
1126 $version, $new->getVersion()));
1127 // Force browse of current page version.
1128 $request->setArg('version', false);
1129 $template = Template('savepage', array());
1130 $template->replace('CONTENT', $new->getTransformedContent());
1132 GeneratePage($template, $mesg, $new);
1136 function _tryinsertInterWikiMap($content) {
1138 if (strpos($content, "<verbatim>")) {
1139 //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1142 if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1143 $error_html = sprintf(" "._("%s: not defined"), "INTERWIKI_MAP_FILE");
1146 $mapfile = FindFile(INTERWIKI_MAP_FILE,1);
1147 if (!$goback && !file_exists($mapfile)) {
1148 $error_html = sprintf(" "._("%s: file not found"), INTERWIKI_MAP_FILE);
1152 if (!empty($error_html))
1153 trigger_error(_("Default InterWiki map file not loaded.")
1154 . $error_html, E_USER_NOTICE);
1158 // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1159 if (!isa($GLOBALS['request'], 'MockRequest'))
1160 echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile),"<br />";
1162 $fd = fopen ($mapfile, "rb");
1163 $data = fread ($fd, filesize($mapfile));
1165 $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1169 function ParseSerializedPage($text, $default_pagename, $user)
1171 if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1174 $pagehash = unserialize($text);
1176 // Split up pagehash into four parts:
1179 // page-level meta-data
1180 // revision-level meta-data
1182 if (!defined('FLAG_PAGE_LOCKED'))
1183 define('FLAG_PAGE_LOCKED', 1);
1184 $pageinfo = array('pagedata' => array(),
1185 'versiondata' => array());
1187 $pagedata = &$pageinfo['pagedata'];
1188 $versiondata = &$pageinfo['versiondata'];
1190 // Fill in defaults.
1191 if (empty($pagehash['pagename']))
1192 $pagehash['pagename'] = $default_pagename;
1193 if (empty($pagehash['author'])) {
1194 $pagehash['author'] = $user->getId();
1197 foreach ($pagehash as $key => $value) {
1202 $pageinfo[$key] = $value;
1205 $pageinfo[$key] = join("\n", $value);
1208 if (($value & FLAG_PAGE_LOCKED) != 0)
1209 $pagedata['locked'] = 'yes';
1213 $pagedata[$key] = $value;
1217 $pagedata['perm'] = ParseMimeifiedPerm($value);
1219 case 'lastmodified':
1220 $versiondata['mtime'] = $value;
1225 $versiondata[$key] = $value;
1229 if (empty($pagehash['charset']))
1230 $pagehash['charset'] = 'iso-8859-1';
1231 // compare to target charset
1232 if (strtolower($pagehash['charset']) != strtolower($GLOBALS['charset'])) {
1233 $pageinfo['content'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['content']);
1234 $pageinfo['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['pagename']);
1239 function SortByPageVersion ($a, $b) {
1240 return $a['version'] - $b['version'];
1244 * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1245 * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1246 * Detected by Santtu Jarvi.
1248 function LoadFile (&$request, $filename, $text = false, $mtime = false)
1250 if (preg_match("/config$/", dirname($filename)) // our or other config
1251 and preg_match("/config.*\.ini/", basename($filename))) // backups and other versions also
1253 trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1256 if (!is_string($text)) {
1258 $stat = stat($filename);
1260 $text = implode("", file($filename));
1263 if (! $request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1264 else @set_time_limit(240);
1266 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1267 $basename = basename("/dummy/" . $filename);
1270 $mtime = time(); // Last resort.
1272 // DONE: check source - target charset for content and pagename
1273 // but only for pgsrc'ed content, not from the browser.
1275 $default_pagename = rawurldecode($basename);
1276 if ( ($parts = ParseMimeifiedPages($text)) ) {
1277 if (count($parts) > 1)
1278 $overwrite = $request->getArg('overwrite');
1279 usort($parts, 'SortByPageVersion');
1280 foreach ($parts as $pageinfo) {
1282 if (count($parts) > 1)
1283 $request->setArg('overwrite', 1);
1284 SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1285 $filename), $basename);
1287 if (count($parts) > 1)
1289 $request->setArg('overwrite', $overwrite);
1291 unset($request->_args['overwrite']);
1293 else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename,
1294 $request->getUser())) ) {
1295 SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1296 $filename), $basename);
1300 $user = $request->getUser();
1302 $file_charset = 'iso-8859-1';
1303 // compare to target charset
1304 if ($file_charset != strtolower($GLOBALS['charset'])) {
1305 $text = charset_convert($file_charset, $GLOBALS['charset'], $text);
1306 $default_pagename = charset_convert($file_charset, $GLOBALS['charset'], $default_pagename);
1309 // Assume plain text file.
1310 $pageinfo = array('pagename' => $default_pagename,
1311 'pagedata' => array(),
1313 => array('author' => $user->getId()),
1314 'content' => preg_replace('/[ \t\r]*\n/', "\n",
1317 SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1322 function LoadZip (&$request, $zipfile, $files = false, $exclude = false) {
1323 $zip = new ZipReader($zipfile);
1324 $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1325 while (list ($fn, $data, $attrib) = $zip->readFile()) {
1326 // FIXME: basename("filewithnoslashes") seems to return
1327 // garbage sometimes.
1328 $fn = basename("/dummy/" . $fn);
1329 if ( ($files && !in_array($fn, $files))
1330 || ($exclude && in_array($fn, $exclude)) ) {
1331 PrintXML(HTML::p(WikiLink($fn)),
1332 HTML::p(_("Skipping")));
1336 longer_timeout($timeout); // longer timeout per page
1337 LoadFile($request, $fn, $data, $attrib['mtime']);
1341 function LoadDir (&$request, $dirname, $files = false, $exclude = false) {
1342 $fileset = new LimitedFileSet($dirname, $files, $exclude);
1344 if (!$files and ($skiplist = $fileset->getSkippedFiles())) {
1345 PrintXML(HTML::p(HTML::strong(_("Skipping"))));
1347 foreach ($skiplist as $file)
1348 $list->pushContent(HTML::li(WikiLink($file)));
1349 PrintXML(HTML::p($list));
1352 // Defer HomePage loading until the end. If anything goes wrong
1353 // the pages can still be loaded again.
1354 $files = $fileset->getFiles();
1355 if (in_array(HOME_PAGE, $files)) {
1356 $files = array_diff($files, array(HOME_PAGE));
1357 $files[] = HOME_PAGE;
1359 $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1360 foreach ($files as $file) {
1361 longer_timeout($timeout); // longer timeout per page
1362 if (substr($file,-1,1) != '~') // refuse to load backup files
1363 LoadFile($request, "$dirname/$file");
1367 class LimitedFileSet extends FileSet {
1368 function LimitedFileSet($dirname, $_include, $exclude) {
1369 $this->_includefiles = $_include;
1370 $this->_exclude = $exclude;
1371 $this->_skiplist = array();
1372 parent::FileSet($dirname);
1375 function _filenameSelector($fn) {
1376 $incl = &$this->_includefiles;
1377 $excl = &$this->_exclude;
1379 if ( ($incl && !in_array($fn, $incl))
1380 || ($excl && in_array($fn, $excl)) ) {
1381 $this->_skiplist[] = $fn;
1388 function getSkippedFiles () {
1389 return $this->_skiplist;
1394 function IsZipFile ($filename_or_fd)
1396 // See if it looks like zip file
1397 if (is_string($filename_or_fd))
1399 $fd = fopen($filename_or_fd, "rb");
1400 $magic = fread($fd, 4);
1405 $fpos = ftell($filename_or_fd);
1406 $magic = fread($filename_or_fd, 4);
1407 fseek($filename_or_fd, $fpos);
1410 return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
1414 function LoadAny (&$request, $file_or_dir, $files = false, $exclude = false)
1416 // Try urlencoded filename for accented characters.
1417 if (!file_exists($file_or_dir)) {
1418 // Make sure there are slashes first to avoid confusing phps
1419 // with broken dirname or basename functions.
1420 // FIXME: windows uses \ and :
1421 if (is_integer(strpos($file_or_dir, "/"))) {
1422 $newfile = FindFile($file_or_dir, true);
1423 // Panic. urlencoded by the browser (e.g. San%20Diego => San Diego)
1425 $file_or_dir = dirname($file_or_dir) . "/"
1426 . rawurlencode(basename($file_or_dir));
1428 // This is probably just a file.
1429 $file_or_dir = rawurlencode($file_or_dir);
1433 $type = filetype($file_or_dir);
1434 if ($type == 'link') {
1435 // For symbolic links, use stat() to determine
1436 // the type of the underlying file.
1437 list(,,$mode) = stat($file_or_dir);
1438 $type = ($mode >> 12) & 017;
1441 elseif ($type == 004)
1446 $request->finish(fmt("Empty or not existing source. Unable to load: %s", $file_or_dir));
1448 else if ($type == 'dir') {
1449 LoadDir($request, $file_or_dir, $files, $exclude);
1451 else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
1453 $request->finish(fmt("Bad file type: %s", $type));
1455 else if (IsZipFile($file_or_dir)) {
1456 LoadZip($request, $file_or_dir, $files, $exclude);
1458 else /* if (!$files || in_array(basename($file_or_dir), $files)) */
1460 LoadFile($request, $file_or_dir);
1464 function LoadFileOrDir (&$request)
1466 $source = $request->getArg('source');
1467 $finder = new FileFinder;
1468 $source = $finder->slashifyPath($source);
1469 $page = rawurldecode(basename($source));
1470 StartLoadDump($request, fmt("Loading '%s'",
1471 HTML(dirname($source),
1472 dirname($source) ? "/" : "",
1473 WikiLink($page,'auto'))));
1475 LoadAny($request, $source);
1477 EndLoadDump($request);
1481 * HomePage was not found so first-time install is supposed to run.
1482 * - import all pgsrc pages.
1483 * - Todo: installer interface to edit config/config.ini settings
1484 * - Todo: ask for existing old index.php to convert to config/config.ini
1485 * - Todo: theme-specific pages:
1486 * blog - HomePage, ADMIN_USER/Blogs
1488 function SetupWiki (&$request)
1490 global $GenericPages, $LANG;
1492 //FIXME: This is a hack (err, "interim solution")
1493 // This is a bogo-bogo-login: Login without
1494 // saving login information in session state.
1495 // This avoids logging in the unsuspecting
1496 // visitor as "The PhpWiki programming team".
1498 // This really needs to be cleaned up...
1499 // (I'm working on it.)
1500 $real_user = $request->_user;
1501 if (ENABLE_USER_NEW)
1502 $request->_user = new _BogoUser(_("The PhpWiki programming team"));
1505 $request->_user = new WikiUser($request, _("The PhpWiki programming team"),
1508 StartLoadDump($request, _("Loading up virgin wiki"));
1510 $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1511 $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1513 $request->setArg('overwrite', true);
1514 if ($default_pgsrc != $pgsrc) {
1515 LoadAny($request, $default_pgsrc, $GenericPages);
1517 $request->setArg('overwrite', false);
1518 LoadAny($request, $pgsrc);
1519 $dbi =& $request->_dbi;
1521 // Ensure that all mandatory pages are loaded
1522 $finder = new FileFinder;
1523 foreach (array_merge(explode(':','Help/OldTextFormattingRules:Help/TextFormattingRules:PhpWikiAdministration'),
1524 $GLOBALS['AllActionPages'],
1525 array(constant('HOME_PAGE'))) as $f)
1527 $page = gettext($f);
1528 $epage = urlencode($page);
1529 if (! $dbi->isWikiPage($page) ) {
1530 // translated version provided?
1531 if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1532 LoadAny($request, $lf);
1533 } else { // load english version of required action page
1534 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1538 if (! $dbi->isWikiPage($page)) {
1539 trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1544 $pagename = _("InterWikiMap");
1545 $map = $dbi->getPage($pagename);
1546 $map->set('locked', true);
1547 PrintXML(HTML::p(HTML::em(WikiLink($pagename)), HTML::strong(" locked")));
1548 EndLoadDump($request);
1551 function LoadPostFile (&$request)
1553 $upload = $request->getUploadedFile('file');
1556 $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1559 // Dump http headers.
1560 StartLoadDump($request, sprintf(_("Uploading %s"), $upload->getName()));
1563 $fd = $upload->open();
1565 LoadZip($request, $fd, false, array(_("RecentChanges")));
1567 LoadFile($request, $upload->getName(), $upload->getContents());
1570 EndLoadDump($request);
1577 // c-basic-offset: 4
1578 // c-hanging-comment-ender-p: nil
1579 // indent-tabs-mode: nil