3 * Copyright 1999,2000,2001,2002,2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
4 * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
6 * This file is part of PhpWiki.
8 * PhpWiki is free software; you can redistribute it and/or modify
9 * it under the terms of the GNU General Public License as published by
10 * the Free Software Foundation; either version 2 of the License, or
11 * (at your option) any later version.
13 * PhpWiki is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
18 * You should have received a copy of the GNU General Public License along
19 * with PhpWiki; if not, write to the Free Software Foundation, Inc.,
20 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
23 require_once 'lib/ziplib.php';
24 require_once 'lib/Template.php';
27 * ignore fatal errors during dump
29 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 preg_replace('/%BODY%.*/s', '', $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');
73 $label = _("ZIP files of database");
76 $label = _("Dump to directory");
79 $label = _("Upload File");
82 $label = _("Load File");
85 $label = _("Upgrade");
89 $label = _("Dump Pages as XHTML");
92 if ($label) $label = str_replace(" ", "_", $label);
93 if ($action == 'browse') // loading virgin
94 $pagelink = WikiLink(HOME_PAGE);
96 $pagelink = WikiLink(new WikiPageName(_("PhpWikiAdministration"), false, $label));
98 // do deferred sendPageChangeNotification()
99 if (!empty($request->_deferredPageChangeNotification)) {
100 $pages = $all_emails = $all_users = array();
101 foreach ($request->_deferredPageChangeNotification as $p) {
102 list($pagename, $emails, $userids) = $p;
103 $pages[] = $pagename;
104 $all_emails = array_unique(array_merge($all_emails, $emails));
105 $all_users = array_unique(array_merge($all_users, $userids));
107 $editedby = sprintf(_("Edited by: %s"), $request->_user->getId());
108 $content = "Loaded the following pages:\n" . join("\n", $pages);
109 if (mail(join(',', $all_emails), "[" . WIKI_NAME . "] " . _("LoadDump"),
110 _("LoadDump") . "\n" .
114 trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
115 join("\n", $pages), join(',', $all_users)), E_USER_NOTICE);
117 trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
118 join("\n", $pages), join(',', $all_users)), E_USER_WARNING);
123 unset($request->_deferredPageChangeNotification);
125 PrintXML(HTML::p(HTML::strong(_("Complete."))),
126 HTML::p(fmt("Return to %s", $pagelink)));
127 // Ugly hack to get valid XHTML code
128 if (isa($WikiTheme, 'WikiTheme_fusionforge')) {
133 } elseif (isa($WikiTheme, 'WikiTheme_Sidebar')
134 or isa($WikiTheme, 'WikiTheme_MonoBook')
140 } elseif (isa($WikiTheme, 'WikiTheme_wikilens')) {
145 } elseif (isa($WikiTheme, 'WikiTheme_blog')) {
148 } elseif (isa($WikiTheme, 'WikiTheme_Crao')
149 or isa($WikiTheme, 'WikiTheme_Hawaiian')
150 or isa($WikiTheme, 'WikiTheme_MacOSX')
151 or isa($WikiTheme, 'WikiTheme_shamino_com')
152 or isa($WikiTheme, 'WikiTheme_smaller')
156 echo "</body></html>\n";
159 ////////////////////////////////////////////////////////////////
161 // Functions for dumping.
163 ////////////////////////////////////////////////////////////////
167 * http://www.nacs.uci.edu/indiv/ehood/MIME/2045/rfc2045.html
168 * http://www.faqs.org/rfcs/rfc2045.html
169 * (RFC 1521 has been superceeded by RFC 2045 & others).
171 * Also see http://www.faqs.org/rfcs/rfc2822.html
173 function MailifyPage($page, $nversions = 1)
175 $current = $page->getCurrentRevision(false);
178 if (STRICT_MAILABLE_PAGEDUMPS) {
179 $from = defined('SERVER_ADMIN') ? SERVER_ADMIN : 'foo@bar';
180 //This is for unix mailbox format: (not RFC (2)822)
181 // $head .= "From $from " . CTime(time()) . "\r\n";
182 $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
183 $head .= "From: $from (PhpWiki)\r\n";
184 // RFC 2822 requires only a Date: and originator (From:)
185 // field, however the obsolete standard RFC 822 also
186 // requires a destination field.
187 $head .= "To: $from (PhpWiki)\r\n";
189 $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
190 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
193 $iter = $page->getAllRevisions();
195 while ($revision = $iter->next()) {
196 $parts[] = MimeifyPageRevision($page, $revision);
197 if ($nversions > 0 && count($parts) >= $nversions)
200 if (count($parts) > 1)
201 return $head . MimeMultipart($parts);
203 return $head . $parts[0];
207 * Compute filename to used for storing contents of a wiki page.
209 * Basically we do a rawurlencode() which encodes everything except
210 * ASCII alphanumerics and '.', '-', and '_'.
212 * But we also want to encode leading dots to avoid filenames like
213 * '.', and '..'. (Also, there's no point in generating "hidden" file
214 * names, like '.foo'.)
216 * We have to apply a different "/" logic for dumpserial, htmldump and zipdump.
217 * dirs are allowed for zipdump and htmldump, not for dumpserial
220 * @param string $pagename Pagename.
221 * @param string $action.
222 * @return string Filename for page.
224 function FilenameForPage($pagename, $action = '')
226 $enc = rawurlencode($pagename);
229 $action = $request->getArg('action');
231 if ($action != 'dumpserial') { // zip, ziphtml, dumphtml
232 // For every %2F we will need to mkdir -p dirname($pagename)
233 $enc = preg_replace('/%2F/', '/', $enc);
235 $enc = preg_replace('/^\./', '%2E', $enc);
236 $enc = preg_replace('/%20/', ' ', $enc);
237 $enc = preg_replace('/\.$/', '%2E', $enc);
242 * The main() function which generates a zip archive of a PhpWiki.
244 * If $include_archive is false, only the current version of each page
245 * is included in the zip file; otherwise all archived versions are
248 function MakeWikiZip(&$request)
250 global $ErrorManager;
251 if ($request->getArg('include') == 'all') {
252 $zipname = WIKI_NAME . _("FullDump") . date('Ymd-Hi') . '.zip';
253 $include_archive = true;
255 $zipname = WIKI_NAME . _("LatestSnapshot") . date('Ymd-Hi') . '.zip';
256 $include_archive = false;
258 $include_empty = false;
259 if ($request->getArg('include') == 'empty') {
260 $include_empty = true;
263 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
265 /* ignore fatals in plugins */
266 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
268 $dbi =& $request->_dbi;
269 $thispage = $request->getArg('pagename'); // for "Return to ..."
270 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
271 $excludeList = explodePageList($exclude);
273 $excludeList = array();
275 if ($pages = $request->getArg('pages')) { // which pagenames
276 if ($pages == '[]') // current page
278 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
280 $page_iter = $dbi->getAllPages(false, false, false, $excludeList);
282 $request_args = $request->args;
283 $timeout = (!$request->getArg('start_debug')) ? 30 : 240;
285 while ($page = $page_iter->next()) {
286 $request->args = $request_args; // some plugins might change them (esp. on POST)
287 longer_timeout($timeout); // Reset watchdog
289 $current = $page->getCurrentRevision();
290 if ($current->getVersion() == 0)
293 $pagename = $page->getName();
294 $wpn = new WikiPageName($pagename);
295 if (!$wpn->isValid())
297 if (in_array($page->getName(), $excludeList)) {
301 $attrib = array('mtime' => $current->get('mtime'),
303 if ($page->get('locked'))
304 $attrib['write_protected'] = 1;
306 if ($include_archive)
307 $content = MailifyPage($page, 0);
309 $content = MailifyPage($page);
311 $zip->addRegularFile(FilenameForPage($pagename),
316 $ErrorManager->popErrorHandler();
319 function DumpToDir(&$request)
321 $directory = $request->getArg('directory');
322 if (empty($directory))
323 $directory = DEFAULT_DUMP_DIR; // See lib/plugin/WikiForm.php:87
324 if (empty($directory))
325 $request->finish(_("You must specify a directory to dump to"));
327 // see if we can access the directory the user wants us to use
328 if (!file_exists($directory)) {
329 if (!mkdir($directory, 0755))
330 $request->finish(fmt("Cannot create directory ā%sā", $directory));
332 $html = HTML::p(fmt("Created directory ā%sā for the page dump...",
335 $html = HTML::p(fmt("Using directory ā%sā", $directory));
338 StartLoadDump($request, _("Dumping Pages"), $html);
340 $dbi =& $request->_dbi;
341 $thispage = $request->getArg('pagename'); // for "Return to ..."
342 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
343 $excludeList = explodePageList($exclude);
345 $excludeList = array();
347 $include_empty = false;
348 if ($request->getArg('include') == 'empty') {
349 $include_empty = true;
351 if ($pages = $request->getArg('pages')) { // which pagenames
352 if ($pages == '[]') // current page
354 $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
356 $page_iter = $dbi->getAllPages($include_empty, false, false, $excludeList);
359 $request_args = $request->args;
360 $timeout = (!$request->getArg('start_debug')) ? 30 : 240;
362 while ($page = $page_iter->next()) {
363 $request->args = $request_args; // some plugins might change them (esp. on POST)
364 longer_timeout($timeout); // Reset watchdog
366 $pagename = $page->getName();
367 if (!isa($request, 'MockRequest')) {
368 PrintXML(HTML::br(), $pagename, ' ... ');
372 if (in_array($pagename, $excludeList)) {
373 if (!isa($request, 'MockRequest')) {
374 PrintXML(_("Skipped."));
379 $filename = FilenameForPage($pagename);
381 if ($page->getName() != $filename) {
382 $msg->pushContent(HTML::small(fmt("saved as %s", $filename)),
386 if ($request->getArg('include') == 'all')
387 $data = MailifyPage($page, 0);
389 $data = MailifyPage($page);
391 if (!($fd = fopen($directory . "/" . $filename, "wb"))) {
392 $msg->pushContent(HTML::strong(fmt("couldn't open file ā%sā for writing",
393 "$directory/$filename")));
394 $request->finish($msg);
397 $num = fwrite($fd, $data, strlen($data));
398 $msg->pushContent(HTML::small(fmt("%s bytes written", $num)));
399 if (!isa($request, 'MockRequest')) {
403 assert($num == strlen($data));
407 EndLoadDump($request);
410 function _copyMsg($page, $smallmsg)
412 if (!isa($GLOBALS['request'], 'MockRequest')) {
413 if ($page) $msg = HTML(HTML::br(), HTML($page), HTML::small($smallmsg));
414 else $msg = HTML::small($smallmsg);
420 function mkdir_p($pathname, $permission = 0777)
422 $arr = explode("/", $pathname);
424 return mkdir($pathname, $permission);
426 $s = array_shift($arr);
428 foreach ($arr as $p) {
431 $ok = mkdir($curr, $permission);
433 if (!$ok) return FALSE;
439 * Dump all pages as XHTML to a directory, as pagename.html.
440 * Copies all used css files to the directory, all used images to a
441 * "images" subdirectory, and all used buttons to a "images/buttons" subdirectory.
442 * The webserver must have write permissions to these directories.
443 * chown httpd HTML_DUMP_DIR; chmod u+rwx HTML_DUMP_DIR
446 * @param string directory (optional) path to dump to. Default: HTML_DUMP_DIR
447 * @param string pages (optional) Comma-separated of glob-style pagenames to dump.
448 * Also array of pagenames allowed.
449 * @param string exclude (optional) Comma-separated of glob-style pagenames to exclude
451 function DumpHtmlToDir(&$request)
454 $directory = $request->getArg('directory');
455 if (empty($directory))
456 $directory = HTML_DUMP_DIR; // See lib/plugin/WikiForm.php:87
457 if (empty($directory))
458 $request->finish(_("You must specify a directory to dump to"));
460 // See if we can access the directory the user wants us to use
461 if (!file_exists($directory)) {
462 if (!mkdir($directory, 0755))
463 $request->finish(fmt("Cannot create directory ā%sā", $directory));
465 $html = HTML::p(fmt("Created directory ā%sā for the page dump...",
468 $html = HTML::p(fmt("Using directory ā%sā", $directory));
470 StartLoadDump($request, _("Dumping Pages"), $html);
471 $thispage = $request->getArg('pagename'); // for "Return to ..."
473 $dbi =& $request->_dbi;
474 if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
475 $excludeList = explodePageList($exclude);
477 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
479 if ($pages = $request->getArg('pages')) { // which pagenames
480 if ($pages == '[]') // current page
482 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
483 // not at admin page: dump only the current page
484 } elseif ($thispage != _("PhpWikiAdministration")) {
485 $page_iter = new WikiDB_Array_generic_iter(array($thispage));
487 $page_iter = $dbi->getAllPages(false, false, false, $excludeList);
490 $WikiTheme->DUMP_MODE = 'HTML';
491 _DumpHtmlToDir($directory, $page_iter, $request->getArg('exclude'));
492 $WikiTheme->DUMP_MODE = false;
494 $request->setArg('pagename', $thispage); // Template::_basepage fix
495 EndLoadDump($request);
498 /* Known problem: any plugins or other code which echo()s text will
499 * lead to a corrupted html zip file which may produce the following
500 * errors upon unzipping:
502 * warning [wikihtml.zip]: 2401 extra bytes at beginning or within zipfile
503 * file #58: bad zipfile offset (local header sig): 177561
504 * (attempting to re-compensate)
506 * However, the actual wiki page data should be unaffected.
508 function MakeWikiZipHtml(&$request)
511 if ($request->getArg('zipname')) {
512 $zipname = basename($request->getArg('zipname'));
513 if (!preg_match("/\.zip$/i", $zipname))
515 $request->setArg('zipname', false);
517 $zipname = "wikihtml.zip";
519 $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
520 $dbi =& $request->_dbi;
521 $thispage = $request->getArg('pagename'); // for "Return to ..."
522 if ($pages = $request->getArg('pages')) { // which pagenames
523 if ($pages == '[]') // current page
525 $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
527 $page_iter = $dbi->getAllPages(false, false, false, $request->getArg('exclude'));
530 $WikiTheme->DUMP_MODE = 'ZIPHTML';
531 _DumpHtmlToDir($zip, $page_iter, $request->getArg('exclude'));
532 $WikiTheme->DUMP_MODE = false;
536 * Internal html dumper. Used for dumphtml, ziphtml and pdf
538 function _DumpHtmlToDir($target, $page_iter, $exclude = false)
540 global $WikiTheme, $request, $ErrorManager;
544 if ($WikiTheme->DUMP_MODE == 'HTML') {
545 $directory = $target;
547 } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') {
548 $directory = $target;
549 } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML'
553 $request->_TemplatesProcessed = array();
554 if ($exclude) { // exclude which pagenames
555 $excludeList = explodePageList($exclude);
557 $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
559 $WikiTheme->VALID_LINKS = array();
560 if ($request->getArg('format')) { // pagelist
561 $page_iter_sav = $page_iter;
562 foreach ($page_iter_sav->asArray() as $handle) {
563 $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName();
565 $page_iter_sav->reset();
568 if (defined('HTML_DUMP_SUFFIX')) {
569 $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
571 if (isset($WikiTheme->_MoreAttr['body'])) {
572 $_bodyAttr = $WikiTheme->_MoreAttr['body'];
573 unset($WikiTheme->_MoreAttr['body']);
576 $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
578 // check if the dumped file will be accessible from outside
579 $doc_root = $request->get("DOCUMENT_ROOT");
580 if ($WikiTheme->DUMP_MODE == 'HTML') {
581 $ldir = NormalizeLocalFileName($directory);
582 $wikiroot = NormalizeLocalFileName('');
583 if (string_starts_with($ldir, $doc_root)) {
584 $link_prefix = substr($directory, strlen($doc_root)) . "/";
585 } elseif (string_starts_with($ldir, $wikiroot)) {
586 $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot))) . "/";
590 $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed
592 $link_prefix = "file://" . $prefix . $directory . "/";
598 $request_args = $request->args;
599 $timeout = (!$request->getArg('start_debug')) ? 60 : 240;
602 $directory = str_replace("\\", "/", $directory); // no Win95 support.
603 if (!is_dir("$directory/images"))
604 mkdir("$directory/images");
608 $already_images = array();
610 while ($page = $page_iter->next()) {
611 if (is_string($page)) {
613 $page = $request->_dbi->getPage($pagename);
615 $pagename = $page->getName();
617 if (empty($firstpage)) $firstpage = $pagename;
618 if (array_key_exists($pagename, $already))
620 $already[$pagename] = 1;
621 $current = $page->getCurrentRevision();
622 //if ($current->getVersion() == 0)
625 $request->args = $request_args; // some plugins might change them (esp. on POST)
626 longer_timeout($timeout); // Reset watchdog
629 $attrib = array('mtime' => $current->get('mtime'),
631 if ($page->get('locked'))
632 $attrib['write_protected'] = 1;
633 } elseif (!$silent) {
634 if (!isa($request, 'MockRequest')) {
635 PrintXML(HTML::br(), $pagename, ' ... ');
639 if (in_array($pagename, $excludeList)) {
640 if (!$silent and !isa($request, 'MockRequest')) {
641 PrintXML(_("Skipped."));
647 if ($WikiTheme->DUMP_MODE == 'PDFHTML')
648 $request->setArg('action', 'pdf'); // to omit cache headers
649 $request->setArg('pagename', $pagename); // Template::_basepage fix
650 $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
651 $args = array('revision' => $current,
652 'CONTENT' => $current->getTransformedContent(),
653 'relative_base' => $relative_base);
654 // For every %2F will need to mkdir -p dirname($pagename)
655 if (preg_match("/(%2F|\/)/", $filename)) {
656 // mkdir -p and set relative base for subdir pages
657 $filename = preg_replace("/%2F/", "/", $filename);
658 $count = substr_count($filename, "/");
659 $dirname = dirname($filename);
661 mkdir_p($directory . "/" . $dirname);
662 // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written
663 // if (isWindows()) // interesting Windows bug: cannot mkdir "bla "
664 // Since dumps needs to be copied, we have to disallow this for all platforms.
665 $filename = preg_replace("/ \//", "/", $filename);
666 $relative_base = "../";
668 $relative_base .= "../";
671 $args['relative_base'] = $relative_base;
675 $DUMP_MODE = $WikiTheme->DUMP_MODE;
676 $data = GeneratePageasXML(new Template('browse', $request, $args),
677 $pagename, $current, $args);
678 $WikiTheme->DUMP_MODE = $DUMP_MODE;
680 if (preg_match_all("/<img .*?src=\"(\/.+?)\"/", $data, $m)) {
681 // fix to local relative path for uploaded images, so that pdf will work
682 foreach ($m[1] as $img_file) {
683 $base = basename($img_file);
684 $data = str_replace('src="' . $img_file . '"', 'src="images/' . $base . '"', $data);
685 if (array_key_exists($img_file, $already_images))
687 $already_images[$img_file] = 1;
688 // resolve src from webdata to file
689 $src = $doc_root . $img_file;
690 if (file_exists($src) and $base) {
692 $target = "$directory/images/$base";
693 if (copy($src, $target)) {
695 _copyMsg($img_file, fmt("... copied to %s", $target));
698 _copyMsg($img_file, fmt("... not copied to %s", $target));
701 $target = "images/$base";
702 $zip->addSrcFile($target, $src);
709 $outfile = $directory . "/" . $filename;
710 if (!($fd = fopen($outfile, "wb"))) {
711 $msg->pushContent(HTML::strong(fmt("couldn't open file ā%sā for writing",
713 $request->finish($msg);
715 $len = strlen($data);
716 $num = fwrite($fd, $data, $len);
717 if ($pagename != $filename) {
718 $link = LinkURL($link_prefix . $filename, $filename);
719 $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
721 $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
723 if (!isa($request, 'MockRequest')) {
727 $request->chunkOutput();
729 assert($num == $len);
731 $outfiles[] = $outfile;
733 $zip->addRegularFile($filename, $data, $attrib);
737 $request->_dbi->_cache->invalidate_cache($pagename);
738 unset ($request->_dbi->_cache->_pagedata_cache);
739 unset ($request->_dbi->_cache->_versiondata_cache);
740 unset ($request->_dbi->_cache->_glv_cache);
742 unset ($request->_dbi->_cache->_backend->_page_data);
745 unset($current->_transformedContent);
747 if (!empty($template)) {
748 unset($template->_request);
755 $attrib = false; //array('is_ascii' => 0);
756 if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
757 // @mkdir("$directory/images");
758 foreach ($WikiTheme->dumped_images as $img_file) {
759 if (array_key_exists($img_file, $already_images))
761 $already_images[$img_file] = 1;
763 and ($from = $WikiTheme->_findFile($img_file, true))
767 $target = "$directory/images/" . basename($from);
769 copy($WikiTheme->_path . $from, $target);
771 if (copy($WikiTheme->_path . $from, $target)) {
772 _copyMsg($from, fmt("... copied to %s", $target));
774 _copyMsg($from, fmt("... not copied to %s", $target));
778 $target = "images/" . basename($from);
779 $zip->addSrcFile($target, $WikiTheme->_path . $from);
781 } elseif (!$silent) {
782 _copyMsg($from, _("... not found"));
787 if (!empty($WikiTheme->dumped_buttons)
788 and is_array($WikiTheme->dumped_buttons)
791 if ($directory && !is_dir("$directory/images/buttons"))
792 mkdir("$directory/images/buttons");
793 foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
794 if (array_key_exists($img_file, $already_images))
796 $already_images[$img_file] = 1;
798 and ($from = $WikiTheme->_findFile($img_file, true))
802 $target = "$directory/images/buttons/" . basename($from);
804 copy($WikiTheme->_path . $from, $target);
806 if (copy($WikiTheme->_path . $from, $target)) {
807 _copyMsg($from, fmt("... copied to %s", $target));
809 _copyMsg($from, fmt("... not copied to %s", $target));
813 $target = "images/buttons/" . basename($from);
814 $zip->addSrcFile($target, $WikiTheme->_path . $from);
816 } elseif (!$silent) {
817 _copyMsg($from, _("... not found"));
821 if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
822 foreach ($WikiTheme->dumped_css as $css_file) {
823 if (array_key_exists($css_file, $already_images))
825 $already_images[$css_file] = 1;
827 and ($from = $WikiTheme->_findFile(basename($css_file), true))
830 // TODO: fix @import url(main.css);
832 $target = "$directory/" . basename($css_file);
834 copy($WikiTheme->_path . $from, $target);
836 if (copy($WikiTheme->_path . $from, $target)) {
837 _copyMsg($from, fmt("... copied to %s", $target));
839 _copyMsg($from, fmt("... not copied to %s", $target));
843 //$attrib = array('is_ascii' => 0);
844 $target = basename($css_file);
845 $zip->addSrcFile($target, $WikiTheme->_path . $from);
847 } elseif (!$silent) {
848 _copyMsg($from, _("... not found"));
856 if ($WikiTheme->DUMP_MODE == 'PDFHTML') {
857 if (USE_EXTERNAL_HTML2PDF and $outfiles) {
858 $cmd = EXTERNAL_HTML2PDF_PAGELIST . ' "' . join('" "', $outfiles) . '"';
859 $filename = FilenameForPage($firstpage);
861 $tmpfile = $directory . "/createpdf.bat";
862 $fp = fopen($tmpfile, "wb");
863 fwrite($fp, $cmd . " > $filename.pdf");
866 if (!headers_sent()) {
867 Header('Content-Type: application/pdf');
870 $tmpdir = getUploadFilePath();
871 $s = passthru($cmd . " > $tmpdir/$filename.pdf");
872 $errormsg = "<br />\nGenerated <a href=\"" . getUploadDataPath() . "$filename.pdf\">Upload:$filename.pdf</a>\n";
877 foreach ($outfiles as $f) unlink($f);
880 if (!empty($errormsg)) {
881 $request->discardOutput();
882 $GLOBALS['ErrorManager']->_postponed_errors = array();
886 $ErrorManager->popErrorHandler();
888 $WikiTheme->HTML_DUMP_SUFFIX = '';
889 $WikiTheme->DUMP_MODE = false;
890 $WikiTheme->_MoreAttr['body'] = isset($_bodyAttr) ? $_bodyAttr : '';
893 ////////////////////////////////////////////////////////////////
895 // Functions for restoring.
897 ////////////////////////////////////////////////////////////////
899 function SavePage(&$request, &$pageinfo, $source, $filename)
901 static $overwite_all = false;
902 $pagedata = $pageinfo['pagedata']; // Page level meta-data.
903 $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
905 if (empty($pageinfo['pagename'])) {
906 PrintXML(HTML::p(HTML::strong(_("Empty pagename!"))));
910 if (empty($versiondata['author_id']))
911 $versiondata['author_id'] = $versiondata['author'];
913 // remove invalid backend specific chars. utf8 issues mostly
914 $pagename_check = new WikiPagename($pageinfo['pagename']);
915 if (!$pagename_check->isValid()) {
916 PrintXML(HTML::p(HTML::strong(sprintf(_("ā%sā: Bad page name"), $pageinfo['pagename']))));
919 $pagename = $pagename_check->getName();
920 $content = $pageinfo['content'];
922 if ($pagename == __("InterWikiMap"))
923 $content = _tryinsertInterWikiMap($content);
925 $dbi =& $request->_dbi;
926 $page = $dbi->getPage($pagename);
928 // Try to merge if updated pgsrc contents are different. This
929 // whole thing is hackish
930 $needs_merge = false;
934 if ($request->getArg('merge')) {
936 } elseif ($request->getArg('overwrite')) {
940 $current = $page->getCurrentRevision();
942 $edit = $request->getArg('edit');
944 if (isset($edit['keep_old'])) {
947 } elseif (isset($edit['overwrite'])) {
950 } elseif ($current and (!$current->hasDefaultContents())
951 && ($current->getPackedContent() != $content)
953 include_once 'lib/editpage.php';
954 $request->setArg('pagename', $pagename);
955 $v = $current->getVersion();
956 $request->setArg('revision', $current->getVersion());
957 $p = new LoadFileConflictPageEditor($request);
958 $p->_content = $content;
959 $p->_currentVersion = $v - 1;
960 $p->editPage($saveFailed = true);
961 return; //early return
965 foreach ($pagedata as $key => $value) {
967 $page->set($key, $value);
970 $mesg = HTML::span();
972 $mesg->pushContent(' ', fmt("from ā%sā", $source));
975 //FIXME: This should not happen! (empty vdata, corrupt cache or db)
976 $current = $page->getCurrentRevision();
978 if ($current->getVersion() == 0) {
979 $versiondata['author'] = ADMIN_USER;
980 $versiondata['author_id'] = ADMIN_USER;
981 $mesg->pushContent(' - ', _("New page"));
984 if ((!$current->hasDefaultContents())
985 && ($current->getPackedContent() != $content)
988 $mesg->pushContent(' ',
989 fmt("has edit conflicts - overwriting anyway"));
991 if (substr_count($source, 'pgsrc')) {
992 $versiondata['author'] = ADMIN_USER;
993 // but leave authorid as userid who loaded the file
996 if (isset($edit['keep_old'])) {
997 $mesg->pushContent(' ', fmt("keep old"));
999 $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
1000 $needs_merge = true; // hackish, to display the buttons
1004 } elseif ($current->getPackedContent() == $content) {
1005 // The page content is the same, we don't need a new revision.
1006 $mesg->pushContent(' ',
1007 fmt("content is identical to current version %d - no new revision created",
1008 $current->getVersion()));
1015 // in case of failures print the culprit:
1016 if (!isa($request, 'MockRequest')) {
1017 PrintXML(HTML::span(WikiLink($pagename)));
1020 $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
1022 $mesg->pushContent(' ', fmt("- saved to database as version %d",
1023 $new->getVersion()));
1024 $mesg->pushContent(HTML::br());
1028 // hackish, $source contains needed path+filename
1029 $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
1030 $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
1031 $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
1032 //check if uploaded file? they pass just the content, but the file is gone
1035 $meb = Button(array('action' => 'loadfile',
1039 _("PhpWikiAdministration"),
1041 $owb = Button(array('action' => 'loadfile',
1042 'overwrite' => true,
1044 _("Restore Anyway"),
1045 _("PhpWikiAdministration"),
1047 $mesg->pushContent(' ', $meb, " ", $owb);
1048 if (!$overwite_all) {
1049 $args = $request->getArgs();
1050 $args['overwrite'] = 1;
1051 $owb = Button($args,
1053 _("PhpWikiAdministration"),
1055 $mesg->pushContent(HTML::span(array('class' => 'hint'), $owb));
1056 $overwite_all = true;
1059 $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
1063 if (!isa($request, 'MockRequest')) {
1065 PrintXML(HTML::em(WikiLink($pagename)), $mesg);
1072 // action=revert (by diff)
1073 function RevertPage(&$request)
1075 $mesg = HTML::div();
1076 $pagename = $request->getArg('pagename');
1077 $version = $request->getArg('version');
1078 $dbi =& $request->_dbi;
1079 $page = $dbi->getPage($pagename);
1081 $request->redirect(WikiURL($page,
1082 array('warningmsg' => _('Revert: missing required version argument'))));
1085 $current = $page->getCurrentRevision();
1086 $currversion = $current->getVersion();
1087 if ($currversion == 0) {
1088 $request->redirect(WikiURL($page,
1089 array('errormsg' => _('No revert: no page content'))));
1092 if ($currversion == $version) {
1093 $request->redirect(WikiURL($page,
1094 array('warningmsg' => _('No revert: same version page'))));
1097 if ($request->getArg('cancel')) {
1098 $request->redirect(WikiURL($page,
1099 array('warningmsg' => _('Revert cancelled'))));
1102 if (!$request->getArg('verify')) {
1103 $mesg->pushContent(HTML::p(fmt("Are you sure to revert %s to version $version?", WikiLink($pagename))),
1104 HTML::form(array('action' => $request->getPostURL(),
1105 'method' => 'post'),
1106 HiddenInputs($request->getArgs(), false, array('verify')),
1107 HiddenInputs(array('verify' => 1)),
1108 Button('submit:verify', _("Yes"), 'button'),
1109 HTML::Raw(' '),
1110 Button('submit:cancel', _("Cancel"), 'button'))
1112 $rev = $page->getRevision($version);
1113 $html = HTML(HTML::fieldset($mesg), HTML::hr(), $rev->getTransformedContent());
1114 $template = Template('browse',
1115 array('CONTENT' => $html));
1116 GeneratePage($template, $pagename, $rev);
1117 $request->checkValidators();
1121 $rev = $page->getRevision($version);
1122 $content = $rev->getPackedContent();
1123 $versiondata = $rev->_data;
1124 $versiondata['summary'] = sprintf(_("Revert to version %d"), $version);
1125 $versiondata['mtime'] = time();
1126 $versiondata['author'] = $request->getUser()->getId();
1127 $new = $page->save($content, $currversion + 1, $versiondata);
1130 $mesg = HTML::span();
1131 $pagelink = WikiLink($pagename);
1132 $mesg->pushContent(fmt("Revert: %s", $pagelink),
1133 fmt("- version %d saved to database as version %d",
1134 $version, $new->getVersion()));
1135 // Force browse of current page version.
1136 $request->setArg('version', false);
1137 $template = Template('savepage', array());
1138 $template->replace('CONTENT', $new->getTransformedContent());
1140 GeneratePage($template, $mesg, $new);
1144 function _tryinsertInterWikiMap($content)
1147 if (strpos($content, "<verbatim>")) {
1148 //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1151 if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1152 $error_html = sprintf(" " . _("%s: not defined"), "INTERWIKI_MAP_FILE");
1155 $mapfile = FindFile(INTERWIKI_MAP_FILE, 1);
1156 if (!$goback && !file_exists($mapfile)) {
1157 $error_html = sprintf(" " . _("%s: file not found"), INTERWIKI_MAP_FILE);
1161 if (!empty($error_html))
1162 trigger_error(_("Default InterWiki map file not loaded.")
1163 . $error_html, E_USER_NOTICE);
1167 // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1168 if (!isa($GLOBALS['request'], 'MockRequest'))
1169 echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile), "<br />";
1171 $fd = fopen($mapfile, "rb");
1172 $data = fread($fd, filesize($mapfile));
1174 $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1178 function ParseSerializedPage($text, $default_pagename, $user)
1180 if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1183 $pagehash = unserialize($text);
1185 // Split up pagehash into four parts:
1188 // page-level meta-data
1189 // revision-level meta-data
1191 if (!defined('FLAG_PAGE_LOCKED'))
1192 define('FLAG_PAGE_LOCKED', 1);
1193 if (!defined('FLAG_PAGE_EXTERNAL'))
1194 define('FLAG_PAGE_EXTERNAL', 1);
1195 $pageinfo = array('pagedata' => array(),
1196 'versiondata' => array());
1198 $pagedata = &$pageinfo['pagedata'];
1199 $versiondata = &$pageinfo['versiondata'];
1201 // Fill in defaults.
1202 if (empty($pagehash['pagename']))
1203 $pagehash['pagename'] = $default_pagename;
1204 if (empty($pagehash['author'])) {
1205 $pagehash['author'] = $user->getId();
1208 foreach ($pagehash as $key => $value) {
1213 $pageinfo[$key] = $value;
1216 $pageinfo[$key] = join("\n", $value);
1219 if (($value & FLAG_PAGE_LOCKED) != 0)
1220 $pagedata['locked'] = 'yes';
1221 if (($value & FLAG_PAGE_EXTERNAL) != 0)
1222 $pagedata['external'] = 'yes';
1226 $pagedata[$key] = $value;
1230 $pagedata['perm'] = ParseMimeifiedPerm($value);
1232 case 'lastmodified':
1233 $versiondata['mtime'] = $value;
1238 $versiondata[$key] = $value;
1245 function SortByPageVersion($a, $b)
1247 return $a['version'] - $b['version'];
1251 * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1252 * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1253 * Detected by Santtu Jarvi.
1255 function LoadFile(&$request, $filename, $text = false, $mtime = false)
1257 if (preg_match("/config$/", dirname($filename)) // our or other config
1258 and preg_match("/config.*\.ini/", basename($filename))
1259 ) // backups and other versions also
1261 trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1264 if (!is_string($text)) {
1266 $stat = stat($filename);
1268 $text = implode("", file($filename));
1271 if (!$request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1272 else @set_time_limit(240);
1274 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1275 $basename = basename("/dummy/" . $filename);
1278 $mtime = time(); // Last resort.
1280 $default_pagename = rawurldecode($basename);
1281 if (($parts = ParseMimeifiedPages($text))) {
1282 if (count($parts) > 1)
1283 $overwrite = $request->getArg('overwrite');
1284 usort($parts, 'SortByPageVersion');
1285 foreach ($parts as $pageinfo) {
1287 if (count($parts) > 1)
1288 $request->setArg('overwrite', 1);
1289 SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1290 $filename), $basename);
1292 if (count($parts) > 1)
1294 $request->setArg('overwrite', $overwrite);
1296 unset($request->_args['overwrite']);
1297 } elseif (($pageinfo = ParseSerializedPage($text, $default_pagename,
1298 $request->getUser()))
1300 SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1301 $filename), $basename);
1304 $user = $request->getUser();
1306 // Assume plain text file.
1307 $pageinfo = array('pagename' => $default_pagename,
1308 'pagedata' => array(),
1310 => array('author' => $user->getId()),
1311 'content' => preg_replace('/[ \t\r]*\n/', "\n",
1314 SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1319 function LoadZip(&$request, $zipfile, $files = false, $exclude = false)
1321 $zip = new ZipReader($zipfile);
1322 $timeout = (!$request->getArg('start_debug')) ? 20 : 120;
1323 while (list ($fn, $data, $attrib) = $zip->readFile()) {
1324 // FIXME: basename("filewithnoslashes") seems to return
1325 // garbage sometimes.
1326 $fn = basename("/dummy/" . $fn);
1327 if (($files && !in_array($fn, $files))
1328 || ($exclude && in_array($fn, $exclude))
1330 PrintXML(HTML::p(WikiLink($fn)),
1331 HTML::p(_("Skipping")));
1335 longer_timeout($timeout); // longer timeout per page
1336 LoadFile($request, $fn, $data, $attrib['mtime']);
1340 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
1369 function LimitedFileSet($dirname, $_include, $exclude)
1371 $this->_includefiles = $_include;
1372 $this->_exclude = $exclude;
1373 $this->_skiplist = array();
1374 parent::FileSet($dirname);
1377 function _filenameSelector($fn)
1379 $incl = &$this->_includefiles;
1380 $excl = &$this->_exclude;
1382 if (($incl && !in_array($fn, $incl))
1383 || ($excl && in_array($fn, $excl))
1385 $this->_skiplist[] = $fn;
1392 function getSkippedFiles()
1394 return $this->_skiplist;
1398 function IsZipFile($filename_or_fd)
1400 // See if it looks like zip file
1401 if (is_string($filename_or_fd)) {
1402 $fd = fopen($filename_or_fd, "rb");
1403 $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;
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));
1447 } elseif ($type == 'dir') {
1448 LoadDir($request, $file_or_dir, $files, $exclude);
1449 } elseif ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir)) {
1450 $request->finish(fmt("Bad file type: %s", $type));
1451 } elseif (IsZipFile($file_or_dir)) {
1452 LoadZip($request, $file_or_dir, $files, $exclude);
1453 } else /* if (!$files || in_array(basename($file_or_dir), $files)) */ {
1454 LoadFile($request, $file_or_dir);
1458 function LoadFileOrDir(&$request)
1460 $source = $request->getArg('source');
1461 $finder = new FileFinder;
1462 $source = $finder->slashifyPath($source);
1463 StartLoadDump($request,
1464 sprintf(_("Loading ā%sā"), $source));
1465 LoadAny($request, $source);
1466 EndLoadDump($request);
1470 * HomePage was not found so first-time install is supposed to run.
1471 * - import all pgsrc pages.
1472 * - Todo: installer interface to edit config/config.ini settings
1473 * - Todo: ask for existing old index.php to convert to config/config.ini
1474 * - Todo: theme-specific pages:
1475 * blog - HomePage, ADMIN_USER/Blogs
1477 function SetupWiki(&$request)
1479 global $GenericPages, $LANG;
1481 //FIXME: This is a hack (err, "interim solution")
1482 // This is a bogo-bogo-login: Login without
1483 // saving login information in session state.
1484 // This avoids logging in the unsuspecting
1485 // visitor as ADMIN_USER
1487 // This really needs to be cleaned up...
1488 // (I'm working on it.)
1489 $real_user = $request->_user;
1490 if (ENABLE_USER_NEW)
1491 $request->_user = new _BogoUser(ADMIN_USER);
1494 $request->_user = new WikiUser($request, ADMIN_USER, WIKIAUTH_BOGO);
1496 StartLoadDump($request, _("Loading up virgin wiki"));
1498 $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1499 $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1501 $request->setArg('overwrite', true);
1502 if ($default_pgsrc != $pgsrc) {
1503 LoadAny($request, $default_pgsrc, $GenericPages);
1505 $request->setArg('overwrite', false);
1506 LoadAny($request, $pgsrc);
1507 $dbi =& $request->_dbi;
1509 // Ensure that all mandatory pages are loaded
1510 $finder = new FileFinder;
1512 $mandatory = array('SandBox',
1513 'Template/Category',
1517 'CategoryActionPage',
1518 'PhpWikiAdministration');
1520 if ((defined('FUSIONFORGE') and FUSIONFORGE)) {
1521 $mandatory[] = 'Template/UserPage';
1523 $mandatory[] = 'Help/TextFormattingRules';
1526 $mandatory = array_merge($mandatory, $GLOBALS['AllActionPages']);
1527 $mandatory[] = constant('HOME_PAGE');
1529 foreach ($mandatory as $f) {
1530 $page = gettext($f);
1531 $epage = urlencode($page);
1532 if (!$dbi->isWikiPage($page)) {
1533 // translated version provided?
1534 if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1535 LoadAny($request, $lf);
1536 } else { // load english version of required action page
1537 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1541 if (!$dbi->isWikiPage($page)) {
1542 trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1547 $pagename = __("InterWikiMap");
1548 $map = $dbi->getPage($pagename);
1549 $map->set('locked', true);
1550 PrintXML(HTML::p(HTML::em(WikiLink($pagename)), HTML::strong(" locked")));
1551 EndLoadDump($request);
1554 function LoadPostFile(&$request)
1556 $upload = $request->getUploadedFile('file');
1559 $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1561 // Dump http headers.
1562 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());
1570 EndLoadDump($request);
1576 // c-basic-offset: 4
1577 // c-hanging-comment-ender-p: nil
1578 // indent-tabs-mode: nil