]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/loadsave.php
Upper case
[SourceForge/phpwiki.git] / lib / loadsave.php
1 <?php
2 /*
3  * Copyright 1999,2000,2001,2002,2004,2005,2006,2007 $ThePhpWikiProgrammingTeam
4  * Copyright 2008-2010 Marc-Etienne Vargenau, Alcatel-Lucent
5  *
6  * This file is part of PhpWiki.
7  *
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.
12  *
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.
17  *
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.
21  */
22
23 require_once 'lib/ziplib.php';
24 require_once 'lib/Template.php';
25
26 /**
27  * ignore fatal errors during dump
28  */
29 function _dump_error_handler($error)
30 {
31     if ($error->isFatal()) {
32         $error->errno = E_USER_WARNING;
33         return true;
34     }
35     return true; // Ignore error
36     /*
37     if (preg_match('/Plugin/', $error->errstr))
38         return true;
39     */
40     // let the message come through: call the remaining handlers:
41     // return false;
42 }
43
44 function StartLoadDump(&$request, $title, $html = '')
45 {
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'))
49         return;
50     // FIXME: This is a hack. This really is the worst overall hack in phpwiki.
51     if ($html)
52         $html->pushContent('%BODY%');
53     $tmpl = Template('html', array('TITLE' => $title,
54         'HEADER' => $title,
55         'CONTENT' => $html ? $html : '%BODY%'));
56     echo preg_replace('/%BODY%.*/s', '', $tmpl->getExpansion($html));
57     $request->chunkOutput();
58
59     // set marker for sendPageChangeNotification()
60     $request->_deferredPageChangeNotification = array();
61 }
62
63 function EndLoadDump(&$request)
64 {
65     global $WikiTheme;
66
67     if (isa($request, 'MockRequest'))
68         return;
69     $action = $request->getArg('action');
70     $label = '';
71     switch ($action) {
72         case 'zip':
73             $label = _("ZIP files of database");
74             break;
75         case 'dumpserial':
76             $label = _("Dump to directory");
77             break;
78         case 'upload':
79             $label = _("Upload File");
80             break;
81         case 'loadfile':
82             $label = _("Load File");
83             break;
84         case 'upgrade':
85             $label = _("Upgrade");
86             break;
87         case 'dumphtml':
88         case 'ziphtml':
89             $label = _("Dump Pages as XHTML");
90             break;
91     }
92     if ($label) $label = str_replace(" ", "_", $label);
93     if ($action == 'browse') // loading virgin
94         $pagelink = WikiLink(HOME_PAGE);
95     else
96         $pagelink = WikiLink(new WikiPageName(_("PhpWikiAdministration"), false, $label));
97
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));
106         }
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" .
111                 $editedby . "\n\n" .
112                 $content)
113         )
114             trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
115                 join("\n", $pages), join(',', $all_users)), E_USER_NOTICE);
116         else
117             trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
118                 join("\n", $pages), join(',', $all_users)), E_USER_WARNING);
119         unset($pages);
120         unset($all_emails);
121         unset($all_users);
122     }
123     unset($request->_deferredPageChangeNotification);
124
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')) {
129         echo "</div>\n";
130         echo "</div>\n";
131         echo "</article>\n";
132         echo "</div>\n";
133     } elseif (isa($WikiTheme, 'WikiTheme_Sidebar')
134         or isa($WikiTheme, 'WikiTheme_MonoBook')
135     ) {
136         echo "</div>\n";
137         echo "</div>\n";
138         echo "</div>\n";
139         echo "</div>\n";
140     } elseif (isa($WikiTheme, 'WikiTheme_wikilens')) {
141         echo "</div>\n";
142         echo "</td>\n";
143         echo "</tr>\n";
144         echo "</table>\n";
145     } elseif (isa($WikiTheme, 'WikiTheme_blog')) {
146         echo "</div>\n";
147         echo "</div>\n";
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')
153     ) {
154         echo "</div>\n";
155     }
156     echo "</body></html>\n";
157 }
158
159 ////////////////////////////////////////////////////////////////
160 //
161 //  Functions for dumping.
162 //
163 ////////////////////////////////////////////////////////////////
164
165 /**
166  * For reference see:
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).
170  *
171  * Also see http://www.faqs.org/rfcs/rfc2822.html
172  */
173 function MailifyPage($page, $nversions = 1)
174 {
175     $current = $page->getCurrentRevision(false);
176     $head = '';
177
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";
188     }
189     $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
190     $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
191         PHPWIKI_VERSION);
192
193     $iter = $page->getAllRevisions();
194     $parts = array();
195     while ($revision = $iter->next()) {
196         $parts[] = MimeifyPageRevision($page, $revision);
197         if ($nversions > 0 && count($parts) >= $nversions)
198             break;
199     }
200     if (count($parts) > 1)
201         return $head . MimeMultipart($parts);
202     assert($parts);
203     return $head . $parts[0];
204 }
205
206 /***
207  * Compute filename to used for storing contents of a wiki page.
208  *
209  * Basically we do a rawurlencode() which encodes everything except
210  * ASCII alphanumerics and '.', '-', and '_'.
211  *
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'.)
215  *
216  * We have to apply a different "/" logic for dumpserial, htmldump and zipdump.
217  * dirs are allowed for zipdump and htmldump, not for dumpserial
218  *
219  *
220  * @param $pagename string Pagename.
221  * @return string Filename for page.
222  */
223 function FilenameForPage($pagename, $action = false)
224 {
225     $enc = rawurlencode($pagename);
226     if (!$action) {
227         global $request;
228         $action = $request->getArg('action');
229     }
230     if ($action != 'dumpserial') { // zip, ziphtml, dumphtml
231         // For every %2F we will need to mkdir -p dirname($pagename)
232         $enc = preg_replace('/%2F/', '/', $enc);
233     }
234     $enc = preg_replace('/^\./', '%2E', $enc);
235     $enc = preg_replace('/%20/', ' ', $enc);
236     $enc = preg_replace('/\.$/', '%2E', $enc);
237     return $enc;
238 }
239
240 /**
241  * The main() function which generates a zip archive of a PhpWiki.
242  *
243  * If $include_archive is false, only the current version of each page
244  * is included in the zip file; otherwise all archived versions are
245  * included as well.
246  */
247 function MakeWikiZip(&$request)
248 {
249     global $ErrorManager;
250     if ($request->getArg('include') == 'all') {
251         $zipname = WIKI_NAME . _("FullDump") . date('Ymd-Hi') . '.zip';
252         $include_archive = true;
253     } else {
254         $zipname = WIKI_NAME . _("LatestSnapshot") . date('Ymd-Hi') . '.zip';
255         $include_archive = false;
256     }
257     $include_empty = false;
258     if ($request->getArg('include') == 'empty') {
259         $include_empty = true;
260     }
261
262     $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
263
264     /* ignore fatals in plugins */
265     $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
266
267     $dbi =& $request->_dbi;
268     $thispage = $request->getArg('pagename'); // for "Return to ..."
269     if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
270         $excludeList = explodePageList($exclude);
271     } else {
272         $excludeList = array();
273     }
274     if ($pages = $request->getArg('pages')) { // which pagenames
275         if ($pages == '[]') // current page
276             $pages = $thispage;
277         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
278     } else {
279         $page_iter = $dbi->getAllPages(false, false, false, $excludeList);
280     }
281     $request_args = $request->args;
282     $timeout = (!$request->getArg('start_debug')) ? 30 : 240;
283
284     while ($page = $page_iter->next()) {
285         $request->args = $request_args; // some plugins might change them (esp. on POST)
286         longer_timeout($timeout); // Reset watchdog
287
288         $current = $page->getCurrentRevision();
289         if ($current->getVersion() == 0)
290             continue;
291
292         $pagename = $page->getName();
293         $wpn = new WikiPageName($pagename);
294         if (!$wpn->isValid())
295             continue;
296         if (in_array($page->getName(), $excludeList)) {
297             continue;
298         }
299
300         $attrib = array('mtime' => $current->get('mtime'),
301             'is_ascii' => 1);
302         if ($page->get('locked'))
303             $attrib['write_protected'] = 1;
304
305         if ($include_archive)
306             $content = MailifyPage($page, 0);
307         else
308             $content = MailifyPage($page);
309
310         $zip->addRegularFile(FilenameForPage($pagename),
311             $content, $attrib);
312     }
313     $zip->finish();
314
315     $ErrorManager->popErrorHandler();
316 }
317
318 function DumpToDir(&$request)
319 {
320     $directory = $request->getArg('directory');
321     if (empty($directory))
322         $directory = DEFAULT_DUMP_DIR; // See lib/plugin/WikiForm.php:87
323     if (empty($directory))
324         $request->finish(_("You must specify a directory to dump to"));
325
326     // see if we can access the directory the user wants us to use
327     if (!file_exists($directory)) {
328         if (!mkdir($directory, 0755))
329             $request->finish(fmt("Cannot create directory ā€œ%sā€", $directory));
330         else
331             $html = HTML::p(fmt("Created directory ā€œ%sā€ for the page dump...",
332                 $directory));
333     } else {
334         $html = HTML::p(fmt("Using directory ā€œ%sā€", $directory));
335     }
336
337     StartLoadDump($request, _("Dumping Pages"), $html);
338
339     $dbi =& $request->_dbi;
340     $thispage = $request->getArg('pagename'); // for "Return to ..."
341     if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
342         $excludeList = explodePageList($exclude);
343     } else {
344         $excludeList = array();
345     }
346     $include_empty = false;
347     if ($request->getArg('include') == 'empty') {
348         $include_empty = true;
349     }
350     if ($pages = $request->getArg('pages')) { // which pagenames
351         if ($pages == '[]') // current page
352             $pages = $thispage;
353         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
354     } else {
355         $page_iter = $dbi->getAllPages($include_empty, false, false, $excludeList);
356     }
357
358     $request_args = $request->args;
359     $timeout = (!$request->getArg('start_debug')) ? 30 : 240;
360
361     while ($page = $page_iter->next()) {
362         $request->args = $request_args; // some plugins might change them (esp. on POST)
363         longer_timeout($timeout); // Reset watchdog
364
365         $pagename = $page->getName();
366         if (!isa($request, 'MockRequest')) {
367             PrintXML(HTML::br(), $pagename, ' ... ');
368             flush();
369         }
370
371         if (in_array($pagename, $excludeList)) {
372             if (!isa($request, 'MockRequest')) {
373                 PrintXML(_("Skipped."));
374                 flush();
375             }
376             continue;
377         }
378         $filename = FilenameForPage($pagename);
379         $msg = HTML();
380         if ($page->getName() != $filename) {
381             $msg->pushContent(HTML::small(fmt("saved as %s", $filename)),
382                 " ... ");
383         }
384
385         if ($request->getArg('include') == 'all')
386             $data = MailifyPage($page, 0);
387         else
388             $data = MailifyPage($page);
389
390         if (!($fd = fopen($directory . "/" . $filename, "wb"))) {
391             $msg->pushContent(HTML::strong(fmt("couldn't open file ā€œ%sā€ for writing",
392                 "$directory/$filename")));
393             $request->finish($msg);
394         }
395
396         $num = fwrite($fd, $data, strlen($data));
397         $msg->pushContent(HTML::small(fmt("%s bytes written", $num)));
398         if (!isa($request, 'MockRequest')) {
399             PrintXML($msg);
400             flush();
401         }
402         assert($num == strlen($data));
403         fclose($fd);
404     }
405
406     EndLoadDump($request);
407 }
408
409 function _copyMsg($page, $smallmsg)
410 {
411     if (!isa($GLOBALS['request'], 'MockRequest')) {
412         if ($page) $msg = HTML(HTML::br(), HTML($page), HTML::small($smallmsg));
413         else $msg = HTML::small($smallmsg);
414         PrintXML($msg);
415         flush();
416     }
417 }
418
419 function mkdir_p($pathname, $permission = 0777)
420 {
421     $arr = explode("/", $pathname);
422     if (empty($arr)) {
423         return mkdir($pathname, $permission);
424     }
425     $s = array_shift($arr);
426     $ok = TRUE;
427     foreach ($arr as $p) {
428         $curr = "$s/$p";
429         if (!is_dir($curr))
430             $ok = mkdir($curr, $permission);
431         $s = $curr;
432         if (!$ok) return FALSE;
433     }
434     return TRUE;
435 }
436
437 /**
438  * Dump all pages as XHTML to a directory, as pagename.html.
439  * Copies all used css files to the directory, all used images to a
440  * "images" subdirectory, and all used buttons to a "images/buttons" subdirectory.
441  * The webserver must have write permissions to these directories.
442  *   chown httpd HTML_DUMP_DIR; chmod u+rwx HTML_DUMP_DIR
443  * should be enough.
444  *
445  * @param string directory (optional) path to dump to. Default: HTML_DUMP_DIR
446  * @param string pages     (optional) Comma-separated of glob-style pagenames to dump.
447  *                                    Also array of pagenames allowed.
448  * @param string exclude   (optional) Comma-separated of glob-style pagenames to exclude
449  */
450 function DumpHtmlToDir(&$request)
451 {
452     global $WikiTheme;
453     $directory = $request->getArg('directory');
454     if (empty($directory))
455         $directory = HTML_DUMP_DIR; // See lib/plugin/WikiForm.php:87
456     if (empty($directory))
457         $request->finish(_("You must specify a directory to dump to"));
458
459     // See if we can access the directory the user wants us to use
460     if (!file_exists($directory)) {
461         if (!mkdir($directory, 0755))
462             $request->finish(fmt("Cannot create directory ā€œ%sā€", $directory));
463         else
464             $html = HTML::p(fmt("Created directory ā€œ%sā€ for the page dump...",
465                 $directory));
466     } else {
467         $html = HTML::p(fmt("Using directory ā€œ%sā€", $directory));
468     }
469     StartLoadDump($request, _("Dumping Pages"), $html);
470     $thispage = $request->getArg('pagename'); // for "Return to ..."
471
472     $dbi =& $request->_dbi;
473     if ($exclude = $request->getArg('exclude')) { // exclude which pagenames
474         $excludeList = explodePageList($exclude);
475     } else {
476         $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
477     }
478     if ($pages = $request->getArg('pages')) { // which pagenames
479         if ($pages == '[]') // current page
480             $pages = $thispage;
481         $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
482         // not at admin page: dump only the current page
483     } elseif ($thispage != _("PhpWikiAdministration")) {
484         $page_iter = new WikiDB_Array_generic_iter(array($thispage));
485     } else {
486         $page_iter = $dbi->getAllPages(false, false, false, $excludeList);
487     }
488
489     $WikiTheme->DUMP_MODE = 'HTML';
490     _DumpHtmlToDir($directory, $page_iter, $request->getArg('exclude'));
491     $WikiTheme->DUMP_MODE = false;
492
493     $request->setArg('pagename', $thispage); // Template::_basepage fix
494     EndLoadDump($request);
495 }
496
497 /* Known problem: any plugins or other code which echo()s text will
498  * lead to a corrupted html zip file which may produce the following
499  * errors upon unzipping:
500  *
501  * warning [wikihtml.zip]:  2401 extra bytes at beginning or within zipfile
502  * file #58:  bad zipfile offset (local header sig):  177561
503  *  (attempting to re-compensate)
504  *
505  * However, the actual wiki page data should be unaffected.
506  */
507 function MakeWikiZipHtml(&$request)
508 {
509     global $WikiTheme;
510     if ($request->getArg('zipname')) {
511         $zipname = basename($request->getArg('zipname'));
512         if (!preg_match("/\.zip$/i", $zipname))
513             $zipname .= ".zip";
514         $request->setArg('zipname', false);
515     } else {
516         $zipname = "wikihtml.zip";
517     }
518     $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
519     $dbi =& $request->_dbi;
520     $thispage = $request->getArg('pagename'); // for "Return to ..."
521     if ($pages = $request->getArg('pages')) { // which pagenames
522         if ($pages == '[]') // current page
523             $pages = $thispage;
524         $page_iter = new WikiDB_Array_generic_iter(explodePageList($pages));
525     } else {
526         $page_iter = $dbi->getAllPages(false, false, false, $request->getArg('exclude'));
527     }
528
529     $WikiTheme->DUMP_MODE = 'ZIPHTML';
530     _DumpHtmlToDir($zip, $page_iter, $request->getArg('exclude'));
531     $WikiTheme->DUMP_MODE = false;
532 }
533
534 /*
535  * Internal html dumper. Used for dumphtml, ziphtml and pdf
536  */
537 function _DumpHtmlToDir($target, $page_iter, $exclude = false)
538 {
539     global $WikiTheme, $request, $ErrorManager;
540     $silent = true;
541     $zip = false;
542     $directory = false;
543     if ($WikiTheme->DUMP_MODE == 'HTML') {
544         $directory = $target;
545         $silent = false;
546     } elseif ($WikiTheme->DUMP_MODE == 'PDFHTML') {
547         $directory = $target;
548     } elseif (is_object($target)) { // $WikiTheme->DUMP_MODE == 'ZIPHTML'
549         $zip = $target;
550     }
551
552     $request->_TemplatesProcessed = array();
553     if ($exclude) { // exclude which pagenames
554         $excludeList = explodePageList($exclude);
555     } else {
556         $excludeList = array('DebugAuthInfo', 'DebugGroupInfo', 'AuthInfo');
557     }
558     $WikiTheme->VALID_LINKS = array();
559     if ($request->getArg('format')) { // pagelist
560         $page_iter_sav = $page_iter;
561         foreach ($page_iter_sav->asArray() as $handle) {
562             $WikiTheme->VALID_LINKS[] = is_string($handle) ? $handle : $handle->getName();
563         }
564         $page_iter_sav->reset();
565     }
566
567     if (defined('HTML_DUMP_SUFFIX')) {
568         $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
569     }
570     if (isset($WikiTheme->_MoreAttr['body'])) {
571         $_bodyAttr = $WikiTheme->_MoreAttr['body'];
572         unset($WikiTheme->_MoreAttr['body']);
573     }
574
575     $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
576
577     // check if the dumped file will be accessible from outside
578     $doc_root = $request->get("DOCUMENT_ROOT");
579     if ($WikiTheme->DUMP_MODE == 'HTML') {
580         $ldir = NormalizeLocalFileName($directory);
581         $wikiroot = NormalizeLocalFileName('');
582         if (string_starts_with($ldir, $doc_root)) {
583             $link_prefix = substr($directory, strlen($doc_root)) . "/";
584         } elseif (string_starts_with($ldir, $wikiroot)) {
585             $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot))) . "/";
586         } else {
587             $prefix = '';
588             if (isWindows()) {
589                 $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed
590             }
591             $link_prefix = "file://" . $prefix . $directory . "/";
592         }
593     } else {
594         $link_prefix = "";
595     }
596
597     $request_args = $request->args;
598     $timeout = (!$request->getArg('start_debug')) ? 60 : 240;
599     if ($directory) {
600         if (isWindows())
601             $directory = str_replace("\\", "/", $directory); // no Win95 support.
602         if (!is_dir("$directory/images"))
603             mkdir("$directory/images");
604     }
605     $already = array();
606     $outfiles = array();
607     $already_images = array();
608
609     while ($page = $page_iter->next()) {
610         if (is_string($page)) {
611             $pagename = $page;
612             $page = $request->_dbi->getPage($pagename);
613         } else {
614             $pagename = $page->getName();
615         }
616         if (empty($firstpage)) $firstpage = $pagename;
617         if (array_key_exists($pagename, $already))
618             continue;
619         $already[$pagename] = 1;
620         $current = $page->getCurrentRevision();
621         //if ($current->getVersion() == 0)
622         //    continue;
623
624         $request->args = $request_args; // some plugins might change them (esp. on POST)
625         longer_timeout($timeout); // Reset watchdog
626
627         if ($zip) {
628             $attrib = array('mtime' => $current->get('mtime'),
629                 'is_ascii' => 1);
630             if ($page->get('locked'))
631                 $attrib['write_protected'] = 1;
632         } elseif (!$silent) {
633             if (!isa($request, 'MockRequest')) {
634                 PrintXML(HTML::br(), $pagename, ' ... ');
635                 flush();
636             }
637         }
638         if (in_array($pagename, $excludeList)) {
639             if (!$silent and !isa($request, 'MockRequest')) {
640                 PrintXML(_("Skipped."));
641                 flush();
642             }
643             continue;
644         }
645         $relative_base = '';
646         if ($WikiTheme->DUMP_MODE == 'PDFHTML')
647             $request->setArg('action', 'pdf'); // to omit cache headers
648         $request->setArg('pagename', $pagename); // Template::_basepage fix
649         $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
650         $args = array('revision' => $current,
651             'CONTENT' => $current->getTransformedContent(),
652             'relative_base' => $relative_base);
653         // For every %2F will need to mkdir -p dirname($pagename)
654         if (preg_match("/(%2F|\/)/", $filename)) {
655             // mkdir -p and set relative base for subdir pages
656             $filename = preg_replace("/%2F/", "/", $filename);
657             $count = substr_count($filename, "/");
658             $dirname = dirname($filename);
659             if ($directory)
660                 mkdir_p($directory . "/" . $dirname);
661             // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written
662             // if (isWindows()) // interesting Windows bug: cannot mkdir "bla "
663             // Since dumps needs to be copied, we have to disallow this for all platforms.
664             $filename = preg_replace("/ \//", "/", $filename);
665             $relative_base = "../";
666             while ($count > 1) {
667                 $relative_base .= "../";
668                 $count--;
669             }
670             $args['relative_base'] = $relative_base;
671         }
672         $msg = HTML();
673
674         $DUMP_MODE = $WikiTheme->DUMP_MODE;
675         $data = GeneratePageasXML(new Template('browse', $request, $args),
676             $pagename, $current, $args);
677         $WikiTheme->DUMP_MODE = $DUMP_MODE;
678
679         if (preg_match_all("/<img .*?src=\"(\/.+?)\"/", $data, $m)) {
680             // fix to local relative path for uploaded images, so that pdf will work
681             foreach ($m[1] as $img_file) {
682                 $base = basename($img_file);
683                 $data = str_replace('src="' . $img_file . '"', 'src="images/' . $base . '"', $data);
684                 if (array_key_exists($img_file, $already_images))
685                     continue;
686                 $already_images[$img_file] = 1;
687                 // resolve src from webdata to file
688                 $src = $doc_root . $img_file;
689                 if (file_exists($src) and $base) {
690                     if ($directory) {
691                         $target = "$directory/images/$base";
692                         if (copy($src, $target)) {
693                             if (!$silent)
694                                 _copyMsg($img_file, fmt("... copied to %s", $target));
695                         } else {
696                             if (!$silent)
697                                 _copyMsg($img_file, fmt("... not copied to %s", $target));
698                         }
699                     } else {
700                         $target = "images/$base";
701                         $zip->addSrcFile($target, $src);
702                     }
703                 }
704             }
705         }
706
707         if ($directory) {
708             $outfile = $directory . "/" . $filename;
709             if (!($fd = fopen($outfile, "wb"))) {
710                 $msg->pushContent(HTML::strong(fmt("couldn't open file ā€œ%sā€ for writing",
711                     $outfile)));
712                 $request->finish($msg);
713             }
714             $len = strlen($data);
715             $num = fwrite($fd, $data, $len);
716             if ($pagename != $filename) {
717                 $link = LinkURL($link_prefix . $filename, $filename);
718                 $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
719             }
720             $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
721             if (!$silent) {
722                 if (!isa($request, 'MockRequest')) {
723                     PrintXML($msg);
724                 }
725                 flush();
726                 $request->chunkOutput();
727             }
728             assert($num == $len);
729             fclose($fd);
730             $outfiles[] = $outfile;
731         } else {
732             $zip->addRegularFile($filename, $data, $attrib);
733         }
734
735         if (USECACHE) {
736             $request->_dbi->_cache->invalidate_cache($pagename);
737             unset ($request->_dbi->_cache->_pagedata_cache);
738             unset ($request->_dbi->_cache->_versiondata_cache);
739             unset ($request->_dbi->_cache->_glv_cache);
740         }
741         unset ($request->_dbi->_cache->_backend->_page_data);
742
743         unset($msg);
744         unset($current->_transformedContent);
745         unset($current);
746         if (!empty($template)) {
747             unset($template->_request);
748             unset($template);
749         }
750         unset($data);
751     }
752     $page_iter->free();
753
754     $attrib = false; //array('is_ascii' => 0);
755     if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
756         // @mkdir("$directory/images");
757         foreach ($WikiTheme->dumped_images as $img_file) {
758             if (array_key_exists($img_file, $already_images))
759                 continue;
760             $already_images[$img_file] = 1;
761             if ($img_file
762                 and ($from = $WikiTheme->_findFile($img_file, true))
763                     and basename($from)
764             ) {
765                 if ($directory) {
766                     $target = "$directory/images/" . basename($from);
767                     if ($silent)
768                         copy($WikiTheme->_path . $from, $target);
769                     else {
770                         if (copy($WikiTheme->_path . $from, $target)) {
771                             _copyMsg($from, fmt("... copied to %s", $target));
772                         } else {
773                             _copyMsg($from, fmt("... not copied to %s", $target));
774                         }
775                     }
776                 } else {
777                     $target = "images/" . basename($from);
778                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
779                 }
780             } elseif (!$silent) {
781                 _copyMsg($from, _("... not found"));
782             }
783         }
784     }
785
786     if (!empty($WikiTheme->dumped_buttons)
787         and is_array($WikiTheme->dumped_buttons)
788     ) {
789         // Buttons also
790         if ($directory && !is_dir("$directory/images/buttons"))
791             mkdir("$directory/images/buttons");
792         foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
793             if (array_key_exists($img_file, $already_images))
794                 continue;
795             $already_images[$img_file] = 1;
796             if ($img_file
797                 and ($from = $WikiTheme->_findFile($img_file, true))
798                     and basename($from)
799             ) {
800                 if ($directory) {
801                     $target = "$directory/images/buttons/" . basename($from);
802                     if ($silent)
803                         copy($WikiTheme->_path . $from, $target);
804                     else {
805                         if (copy($WikiTheme->_path . $from, $target)) {
806                             _copyMsg($from, fmt("... copied to %s", $target));
807                         } else {
808                             _copyMsg($from, fmt("... not copied to %s", $target));
809                         }
810                     }
811                 } else {
812                     $target = "images/buttons/" . basename($from);
813                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
814                 }
815             } elseif (!$silent) {
816                 _copyMsg($from, _("... not found"));
817             }
818         }
819     }
820     if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
821         foreach ($WikiTheme->dumped_css as $css_file) {
822             if (array_key_exists($css_file, $already_images))
823                 continue;
824             $already_images[$css_file] = 1;
825             if ($css_file
826                 and ($from = $WikiTheme->_findFile(basename($css_file), true))
827                     and basename($from)
828             ) {
829                 // TODO: fix @import url(main.css);
830                 if ($directory) {
831                     $target = "$directory/" . basename($css_file);
832                     if ($silent)
833                         copy($WikiTheme->_path . $from, $target);
834                     else {
835                         if (copy($WikiTheme->_path . $from, $target)) {
836                             _copyMsg($from, fmt("... copied to %s", $target));
837                         } else {
838                             _copyMsg($from, fmt("... not copied to %s", $target));
839                         }
840                     }
841                 } else {
842                     //$attrib = array('is_ascii' => 0);
843                     $target = basename($css_file);
844                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
845                 }
846             } elseif (!$silent) {
847                 _copyMsg($from, _("... not found"));
848             }
849         }
850     }
851
852     if ($zip)
853         $zip->finish();
854
855     if ($WikiTheme->DUMP_MODE == 'PDFHTML') {
856         if (USE_EXTERNAL_HTML2PDF and $outfiles) {
857             $cmd = EXTERNAL_HTML2PDF_PAGELIST . ' "' . join('" "', $outfiles) . '"';
858             $filename = FilenameForPage($firstpage);
859             if (DEBUG) {
860                 $tmpfile = $directory . "/createpdf.bat";
861                 $fp = fopen($tmpfile, "wb");
862                 fwrite($fp, $cmd . " > $filename.pdf");
863                 fclose($fp);
864             }
865             if (!headers_sent()) {
866                 Header('Content-Type: application/pdf');
867                 passthru($cmd);
868             } else {
869                 $tmpdir = getUploadFilePath();
870                 $s = passthru($cmd . " > $tmpdir/$filename.pdf");
871                 $errormsg = "<br />\nGenerated <a href=\"" . getUploadDataPath() . "$filename.pdf\">Upload:$filename.pdf</a>\n";
872                 $errormsg .= $s;
873                 echo $errormsg;
874             }
875             if (!DEBUG) {
876                 foreach ($outfiles as $f) unlink($f);
877             }
878         }
879         if (!empty($errormsg)) {
880             $request->discardOutput();
881             $GLOBALS['ErrorManager']->_postponed_errors = array();
882         }
883     }
884
885     $ErrorManager->popErrorHandler();
886
887     $WikiTheme->HTML_DUMP_SUFFIX = '';
888     $WikiTheme->DUMP_MODE = false;
889     $WikiTheme->_MoreAttr['body'] = isset($_bodyAttr) ? $_bodyAttr : '';
890 }
891
892 ////////////////////////////////////////////////////////////////
893 //
894 //  Functions for restoring.
895 //
896 ////////////////////////////////////////////////////////////////
897
898 function SavePage(&$request, &$pageinfo, $source, $filename)
899 {
900     static $overwite_all = false;
901     $pagedata = $pageinfo['pagedata']; // Page level meta-data.
902     $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
903
904     if (empty($pageinfo['pagename'])) {
905         PrintXML(HTML::p(HTML::strong(_("Empty pagename!"))));
906         return;
907     }
908
909     if (empty($versiondata['author_id']))
910         $versiondata['author_id'] = $versiondata['author'];
911
912     // remove invalid backend specific chars. utf8 issues mostly
913     $pagename_check = new WikiPagename($pageinfo['pagename']);
914     if (!$pagename_check->isValid()) {
915         PrintXML(HTML::p(HTML::strong(sprintf(_("ā€œ%sā€: Bad page name"), $pageinfo['pagename']))));
916         return;
917     }
918     $pagename = $pagename_check->getName();
919     $content = $pageinfo['content'];
920
921     if ($pagename == __("InterWikiMap"))
922         $content = _tryinsertInterWikiMap($content);
923
924     $dbi =& $request->_dbi;
925     $page = $dbi->getPage($pagename);
926
927     // Try to merge if updated pgsrc contents are different. This
928     // whole thing is hackish
929     $needs_merge = false;
930     $merging = false;
931     $overwrite = false;
932
933     if ($request->getArg('merge')) {
934         $merging = true;
935     } elseif ($request->getArg('overwrite')) {
936         $overwrite = true;
937     }
938
939     $current = $page->getCurrentRevision();
940     $skip = false;
941     $edit = $request->getArg('edit');
942     if ($merging) {
943         if (isset($edit['keep_old'])) {
944             $merging = false;
945             $skip = true;
946         } elseif (isset($edit['overwrite'])) {
947             $merging = false;
948             $overwrite = true;
949         } elseif ($current and (!$current->hasDefaultContents())
950             && ($current->getPackedContent() != $content)
951         ) {
952             include_once 'lib/editpage.php';
953             $request->setArg('pagename', $pagename);
954             $v = $current->getVersion();
955             $request->setArg('revision', $current->getVersion());
956             $p = new LoadFileConflictPageEditor($request);
957             $p->_content = $content;
958             $p->_currentVersion = $v - 1;
959             $p->editPage($saveFailed = true);
960             return; //early return
961         }
962     }
963     if (!$skip)
964         foreach ($pagedata as $key => $value) {
965             if (!empty($value))
966                 $page->set($key, $value);
967         }
968
969     $mesg = HTML::span();
970     if ($source) {
971         $mesg->pushContent(' ', fmt("from ā€œ%sā€", $source));
972     }
973     if (!$current) {
974         //FIXME: This should not happen! (empty vdata, corrupt cache or db)
975         $current = $page->getCurrentRevision();
976     }
977     if ($current->getVersion() == 0) {
978         $versiondata['author'] = ADMIN_USER;
979         $versiondata['author_id'] = ADMIN_USER;
980         $mesg->pushContent(' - ', _("New page"));
981         $isnew = true;
982     } else {
983         if ((!$current->hasDefaultContents())
984             && ($current->getPackedContent() != $content)
985         ) {
986             if ($overwrite) {
987                 $mesg->pushContent(' ',
988                     fmt("has edit conflicts - overwriting anyway"));
989                 $skip = false;
990                 if (substr_count($source, 'pgsrc')) {
991                     $versiondata['author'] = ADMIN_USER;
992                     // but leave authorid as userid who loaded the file
993                 }
994             } else {
995                 if (isset($edit['keep_old'])) {
996                     $mesg->pushContent(' ', fmt("keep old"));
997                 } else {
998                     $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
999                     $needs_merge = true; // hackish, to display the buttons
1000                 }
1001                 $skip = true;
1002             }
1003         } elseif ($current->getPackedContent() == $content) {
1004             // The page content is the same, we don't need a new revision.
1005             $mesg->pushContent(' ',
1006                 fmt("content is identical to current version %d - no new revision created",
1007                     $current->getVersion()));
1008             $skip = true;
1009         }
1010         $isnew = false;
1011     }
1012
1013     if (!$skip) {
1014         // in case of failures print the culprit:
1015         if (!isa($request, 'MockRequest')) {
1016             PrintXML(HTML::span(WikiLink($pagename)));
1017             flush();
1018         }
1019         $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
1020         $dbi->touch();
1021         $mesg->pushContent(' ', fmt("- saved to database as version %d",
1022             $new->getVersion()));
1023         $mesg->pushContent(HTML::br());
1024     }
1025     if ($needs_merge) {
1026         $f = $source;
1027         // hackish, $source contains needed path+filename
1028         $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
1029         $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
1030         $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
1031         //check if uploaded file? they pass just the content, but the file is gone
1032         if (@stat($f)) {
1033             global $WikiTheme;
1034             $meb = Button(array('action' => 'loadfile',
1035                     'merge' => true,
1036                     'source' => $f),
1037                 _("Merge Edit"),
1038                 _("PhpWikiAdministration"),
1039                 'wikiadmin');
1040             $owb = Button(array('action' => 'loadfile',
1041                     'overwrite' => true,
1042                     'source' => $f),
1043                 _("Restore Anyway"),
1044                 _("PhpWikiAdministration"),
1045                 'wikiunsafe');
1046             $mesg->pushContent(' ', $meb, " ", $owb);
1047             if (!$overwite_all) {
1048                 $args = $request->getArgs();
1049                 $args['overwrite'] = 1;
1050                 $owb = Button($args,
1051                     _("Overwrite All"),
1052                     _("PhpWikiAdministration"),
1053                     'wikiunsafe');
1054                 $mesg->pushContent(HTML::span(array('class' => 'hint'), $owb));
1055                 $overwite_all = true;
1056             }
1057         } else {
1058             $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
1059         }
1060     }
1061
1062     if (!isa($request, 'MockRequest')) {
1063         if ($skip)
1064             PrintXML(HTML::em(WikiLink($pagename)), $mesg);
1065         else
1066             PrintXML($mesg);
1067         flush();
1068     }
1069 }
1070
1071 // action=revert (by diff)
1072 function RevertPage(&$request)
1073 {
1074     $mesg = HTML::div();
1075     $pagename = $request->getArg('pagename');
1076     $version = $request->getArg('version');
1077     $dbi =& $request->_dbi;
1078     $page = $dbi->getPage($pagename);
1079     if (!$version) {
1080         $request->redirect(WikiURL($page,
1081             array('warningmsg' => _('Revert: missing required version argument'))));
1082         // noreturn
1083     }
1084     $current = $page->getCurrentRevision();
1085     $currversion = $current->getVersion();
1086     if ($currversion == 0) {
1087         $request->redirect(WikiURL($page,
1088             array('errormsg' => _('No revert: no page content'))));
1089         // noreturn
1090     }
1091     if ($currversion == $version) {
1092         $request->redirect(WikiURL($page,
1093             array('warningmsg' => _('No revert: same version page'))));
1094         // noreturn
1095     }
1096     if ($request->getArg('cancel')) {
1097         $request->redirect(WikiURL($page,
1098             array('warningmsg' => _('Revert cancelled'))));
1099         // noreturn
1100     }
1101     if (!$request->getArg('verify')) {
1102         $mesg->pushContent(HTML::p(fmt("Are you sure to revert %s to version $version?", WikiLink($pagename))),
1103             HTML::form(array('action' => $request->getPostURL(),
1104                     'method' => 'post'),
1105                 HiddenInputs($request->getArgs(), false, array('verify')),
1106                 HiddenInputs(array('verify' => 1)),
1107                 Button('submit:verify', _("Yes"), 'button'),
1108                 HTML::Raw('&nbsp;'),
1109                 Button('submit:cancel', _("Cancel"), 'button'))
1110         );
1111         $rev = $page->getRevision($version);
1112         $html = HTML(HTML::fieldset($mesg), HTML::hr(), $rev->getTransformedContent());
1113         $template = Template('browse',
1114             array('CONTENT' => $html));
1115         GeneratePage($template, $pagename, $rev);
1116         $request->checkValidators();
1117         flush();
1118         return;
1119     }
1120     $rev = $page->getRevision($version);
1121     $content = $rev->getPackedContent();
1122     $versiondata = $rev->_data;
1123     $versiondata['summary'] = sprintf(_("Revert to version %d"), $version);
1124     $versiondata['mtime'] = time();
1125     $versiondata['author'] = $request->getUser()->getId();
1126     $new = $page->save($content, $currversion + 1, $versiondata);
1127     $dbi->touch();
1128
1129     $mesg = HTML::span();
1130     $pagelink = WikiLink($pagename);
1131     $mesg->pushContent(fmt("Revert: %s", $pagelink),
1132         fmt("- version %d saved to database as version %d",
1133             $version, $new->getVersion()));
1134     // Force browse of current page version.
1135     $request->setArg('version', false);
1136     $template = Template('savepage', array());
1137     $template->replace('CONTENT', $new->getTransformedContent());
1138
1139     GeneratePage($template, $mesg, $new);
1140     flush();
1141 }
1142
1143 function _tryinsertInterWikiMap($content)
1144 {
1145     $goback = false;
1146     if (strpos($content, "<verbatim>")) {
1147         //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1148         $goback = true;
1149     }
1150     if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1151         $error_html = sprintf(" " . _("%s: not defined"), "INTERWIKI_MAP_FILE");
1152         $goback = true;
1153     }
1154     $mapfile = FindFile(INTERWIKI_MAP_FILE, 1);
1155     if (!$goback && !file_exists($mapfile)) {
1156         $error_html = sprintf(" " . _("%s: file not found"), INTERWIKI_MAP_FILE);
1157         $goback = true;
1158     }
1159
1160     if (!empty($error_html))
1161         trigger_error(_("Default InterWiki map file not loaded.")
1162             . $error_html, E_USER_NOTICE);
1163     if ($goback)
1164         return $content;
1165
1166     // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1167     if (!isa($GLOBALS['request'], 'MockRequest'))
1168         echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile), "<br />";
1169
1170     $fd = fopen($mapfile, "rb");
1171     $data = fread($fd, filesize($mapfile));
1172     fclose($fd);
1173     $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1174     return $content;
1175 }
1176
1177 function ParseSerializedPage($text, $default_pagename, $user)
1178 {
1179     if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1180         return false;
1181
1182     $pagehash = unserialize($text);
1183
1184     // Split up pagehash into four parts:
1185     //   pagename
1186     //   content
1187     //   page-level meta-data
1188     //   revision-level meta-data
1189
1190     if (!defined('FLAG_PAGE_LOCKED'))
1191         define('FLAG_PAGE_LOCKED', 1);
1192     if (!defined('FLAG_PAGE_EXTERNAL'))
1193         define('FLAG_PAGE_EXTERNAL', 1);
1194     $pageinfo = array('pagedata' => array(),
1195         'versiondata' => array());
1196
1197     $pagedata = &$pageinfo['pagedata'];
1198     $versiondata = &$pageinfo['versiondata'];
1199
1200     // Fill in defaults.
1201     if (empty($pagehash['pagename']))
1202         $pagehash['pagename'] = $default_pagename;
1203     if (empty($pagehash['author'])) {
1204         $pagehash['author'] = $user->getId();
1205     }
1206
1207     foreach ($pagehash as $key => $value) {
1208         switch ($key) {
1209             case 'pagename':
1210             case 'version':
1211             case 'hits':
1212                 $pageinfo[$key] = $value;
1213                 break;
1214             case 'content':
1215                 $pageinfo[$key] = join("\n", $value);
1216                 break;
1217             case 'flags':
1218                 if (($value & FLAG_PAGE_LOCKED) != 0)
1219                     $pagedata['locked'] = 'yes';
1220                 if (($value & FLAG_PAGE_EXTERNAL) != 0)
1221                     $pagedata['external'] = 'yes';
1222                 break;
1223             case 'owner':
1224             case 'created':
1225                 $pagedata[$key] = $value;
1226                 break;
1227             case 'acl':
1228             case 'perm':
1229                 $pagedata['perm'] = ParseMimeifiedPerm($value);
1230                 break;
1231             case 'lastmodified':
1232                 $versiondata['mtime'] = $value;
1233                 break;
1234             case 'author':
1235             case 'author_id':
1236             case 'summary':
1237                 $versiondata[$key] = $value;
1238                 break;
1239         }
1240     }
1241     return $pageinfo;
1242 }
1243
1244 function SortByPageVersion($a, $b)
1245 {
1246     return $a['version'] - $b['version'];
1247 }
1248
1249 /**
1250  * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1251  * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1252  * Detected by Santtu Jarvi.
1253  */
1254 function LoadFile(&$request, $filename, $text = false, $mtime = false)
1255 {
1256     if (preg_match("/config$/", dirname($filename)) // our or other config
1257         and preg_match("/config.*\.ini/", basename($filename))
1258     ) // backups and other versions also
1259     {
1260         trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1261         return;
1262     }
1263     if (!is_string($text)) {
1264         // Read the file.
1265         $stat = stat($filename);
1266         $mtime = $stat[9];
1267         $text = implode("", file($filename));
1268     }
1269
1270     if (!$request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1271     else @set_time_limit(240);
1272
1273     // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1274     $basename = basename("/dummy/" . $filename);
1275
1276     if (!$mtime)
1277         $mtime = time(); // Last resort.
1278
1279     $default_pagename = rawurldecode($basename);
1280     if (($parts = ParseMimeifiedPages($text))) {
1281         if (count($parts) > 1)
1282             $overwrite = $request->getArg('overwrite');
1283         usort($parts, 'SortByPageVersion');
1284         foreach ($parts as $pageinfo) {
1285             // force overwrite
1286             if (count($parts) > 1)
1287                 $request->setArg('overwrite', 1);
1288             SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1289                 $filename), $basename);
1290         }
1291         if (count($parts) > 1)
1292             if ($overwrite)
1293                 $request->setArg('overwrite', $overwrite);
1294             else
1295                 unset($request->_args['overwrite']);
1296     } elseif (($pageinfo = ParseSerializedPage($text, $default_pagename,
1297         $request->getUser()))
1298     ) {
1299         SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1300             $filename), $basename);
1301     } else {
1302         // plain old file
1303         $user = $request->getUser();
1304
1305         // Assume plain text file.
1306         $pageinfo = array('pagename' => $default_pagename,
1307             'pagedata' => array(),
1308             'versiondata'
1309             => array('author' => $user->getId()),
1310             'content' => preg_replace('/[ \t\r]*\n/', "\n",
1311                 chop($text))
1312         );
1313         SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1314             $basename);
1315     }
1316 }
1317
1318 function LoadZip(&$request, $zipfile, $files = false, $exclude = false)
1319 {
1320     $zip = new ZipReader($zipfile);
1321     $timeout = (!$request->getArg('start_debug')) ? 20 : 120;
1322     while (list ($fn, $data, $attrib) = $zip->readFile()) {
1323         // FIXME: basename("filewithnoslashes") seems to return
1324         // garbage sometimes.
1325         $fn = basename("/dummy/" . $fn);
1326         if (($files && !in_array($fn, $files))
1327             || ($exclude && in_array($fn, $exclude))
1328         ) {
1329             PrintXML(HTML::p(WikiLink($fn)),
1330                 HTML::p(_("Skipping")));
1331             flush();
1332             continue;
1333         }
1334         longer_timeout($timeout); // longer timeout per page
1335         LoadFile($request, $fn, $data, $attrib['mtime']);
1336     }
1337 }
1338
1339 function LoadDir(&$request, $dirname, $files = false, $exclude = false)
1340 {
1341     $fileset = new LimitedFileSet($dirname, $files, $exclude);
1342
1343     if (!$files and ($skiplist = $fileset->getSkippedFiles())) {
1344         PrintXML(HTML::p(HTML::strong(_("Skipping"))));
1345         $list = HTML::ul();
1346         foreach ($skiplist as $file)
1347             $list->pushContent(HTML::li(WikiLink($file)));
1348         PrintXML(HTML::p($list));
1349     }
1350
1351     // Defer HomePage loading until the end. If anything goes wrong
1352     // the pages can still be loaded again.
1353     $files = $fileset->getFiles();
1354     if (in_array(HOME_PAGE, $files)) {
1355         $files = array_diff($files, array(HOME_PAGE));
1356         $files[] = HOME_PAGE;
1357     }
1358     $timeout = (!$request->getArg('start_debug')) ? 20 : 120;
1359     foreach ($files as $file) {
1360         longer_timeout($timeout); // longer timeout per page
1361         if (substr($file, -1, 1) != '~') // refuse to load backup files
1362             LoadFile($request, "$dirname/$file");
1363     }
1364 }
1365
1366 class LimitedFileSet extends FileSet
1367 {
1368     function LimitedFileSet($dirname, $_include, $exclude)
1369     {
1370         $this->_includefiles = $_include;
1371         $this->_exclude = $exclude;
1372         $this->_skiplist = array();
1373         parent::FileSet($dirname);
1374     }
1375
1376     function _filenameSelector($fn)
1377     {
1378         $incl = &$this->_includefiles;
1379         $excl = &$this->_exclude;
1380
1381         if (($incl && !in_array($fn, $incl))
1382             || ($excl && in_array($fn, $excl))
1383         ) {
1384             $this->_skiplist[] = $fn;
1385             return false;
1386         } else {
1387             return true;
1388         }
1389     }
1390
1391     function getSkippedFiles()
1392     {
1393         return $this->_skiplist;
1394     }
1395 }
1396
1397 function IsZipFile($filename_or_fd)
1398 {
1399     // See if it looks like zip file
1400     if (is_string($filename_or_fd)) {
1401         $fd = fopen($filename_or_fd, "rb");
1402         $magic = fread($fd, 4);
1403         fclose($fd);
1404     } else {
1405         $fpos = ftell($filename_or_fd);
1406         $magic = fread($filename_or_fd, 4);
1407         fseek($filename_or_fd, $fpos);
1408     }
1409
1410     return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
1411 }
1412
1413 function LoadAny(&$request, $file_or_dir, $files = false, $exclude = false)
1414 {
1415     // Try urlencoded filename for accented characters.
1416     if (!file_exists($file_or_dir)) {
1417         // Make sure there are slashes first to avoid confusing phps
1418         // with broken dirname or basename functions.
1419         // FIXME: windows uses \ and :
1420         if (is_integer(strpos($file_or_dir, "/"))) {
1421             $newfile = FindFile($file_or_dir, true);
1422             // Panic. urlencoded by the browser (e.g. San%20Diego => San Diego)
1423             if (!$newfile)
1424                 $file_or_dir = dirname($file_or_dir) . "/"
1425                     . rawurlencode(basename($file_or_dir));
1426         } else {
1427             // This is probably just a file.
1428             $file_or_dir = rawurlencode($file_or_dir);
1429         }
1430     }
1431
1432     $type = filetype($file_or_dir);
1433     if ($type == 'link') {
1434         // For symbolic links, use stat() to determine
1435         // the type of the underlying file.
1436         list(, , $mode) = stat($file_or_dir);
1437         $type = ($mode >> 12) & 017;
1438         if ($type == 010)
1439             $type = 'file';
1440         elseif ($type == 004)
1441             $type = 'dir';
1442     }
1443
1444     if (!$type) {
1445         $request->finish(fmt("Empty or not existing source. Unable to load: %s", $file_or_dir));
1446     } elseif ($type == 'dir') {
1447         LoadDir($request, $file_or_dir, $files, $exclude);
1448     } elseif ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir)) {
1449         $request->finish(fmt("Bad file type: %s", $type));
1450     } elseif (IsZipFile($file_or_dir)) {
1451         LoadZip($request, $file_or_dir, $files, $exclude);
1452     } else /* if (!$files || in_array(basename($file_or_dir), $files)) */ {
1453         LoadFile($request, $file_or_dir);
1454     }
1455 }
1456
1457 function LoadFileOrDir(&$request)
1458 {
1459     $source = $request->getArg('source');
1460     $finder = new FileFinder;
1461     $source = $finder->slashifyPath($source);
1462     StartLoadDump($request,
1463         sprintf(_("Loading ā€œ%sā€"), $source));
1464     LoadAny($request, $source);
1465     EndLoadDump($request);
1466 }
1467
1468 /**
1469  * HomePage was not found so first-time install is supposed to run.
1470  * - import all pgsrc pages.
1471  * - Todo: installer interface to edit config/config.ini settings
1472  * - Todo: ask for existing old index.php to convert to config/config.ini
1473  * - Todo: theme-specific pages:
1474  *   blog - HomePage, ADMIN_USER/Blogs
1475  */
1476 function SetupWiki(&$request)
1477 {
1478     global $GenericPages, $LANG;
1479
1480     //FIXME: This is a hack (err, "interim solution")
1481     // This is a bogo-bogo-login:  Login without
1482     // saving login information in session state.
1483     // This avoids logging in the unsuspecting
1484     // visitor as ADMIN_USER
1485     //
1486     // This really needs to be cleaned up...
1487     // (I'm working on it.)
1488     $real_user = $request->_user;
1489     if (ENABLE_USER_NEW)
1490         $request->_user = new _BogoUser(ADMIN_USER);
1491
1492     else
1493         $request->_user = new WikiUser($request, ADMIN_USER, WIKIAUTH_BOGO);
1494
1495     StartLoadDump($request, _("Loading up virgin wiki"));
1496
1497     $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1498     $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1499
1500     $request->setArg('overwrite', true);
1501     if ($default_pgsrc != $pgsrc) {
1502         LoadAny($request, $default_pgsrc, $GenericPages);
1503     }
1504     $request->setArg('overwrite', false);
1505     LoadAny($request, $pgsrc);
1506     $dbi =& $request->_dbi;
1507
1508     // Ensure that all mandatory pages are loaded
1509     $finder = new FileFinder;
1510
1511     if (!(defined('FUSIONFORGE') and FUSIONFORGE)) {
1512         $mandatory = explode(':', 'SandBox:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:Help/OldTextFormattingRules:Help/TextFormattingRules:PhpWikiAdministration');
1513     } elseif (WIKI_NAME == "help") {
1514         $mandatory = explode(':', 'SandBox:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:Help/TextFormattingRules:PhpWikiAdministration');
1515     } else {
1516         $mandatory = explode(':', 'SandBox:Template/UserPage:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:TextFormattingRules:PhpWikiAdministration');
1517     }
1518     foreach (array_merge($mandatory,
1519         $GLOBALS['AllActionPages'],
1520         array(constant('HOME_PAGE'))) as $f) {
1521         $page = gettext($f);
1522         $epage = urlencode($page);
1523         if (!$dbi->isWikiPage($page)) {
1524             // translated version provided?
1525             if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1526                 LoadAny($request, $lf);
1527             } else { // load english version of required action page
1528                 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1529                 $page = $f;
1530             }
1531         }
1532         if (!$dbi->isWikiPage($page)) {
1533             trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1534                 E_USER_WARNING);
1535         }
1536     }
1537
1538     $pagename = __("InterWikiMap");
1539     $map = $dbi->getPage($pagename);
1540     $map->set('locked', true);
1541     PrintXML(HTML::p(HTML::em(WikiLink($pagename)), HTML::strong(" locked")));
1542     EndLoadDump($request);
1543 }
1544
1545 function LoadPostFile(&$request)
1546 {
1547     $upload = $request->getUploadedFile('file');
1548
1549     if (!$upload)
1550         $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1551
1552     // Dump http headers.
1553     StartLoadDump($request, sprintf(_("Uploading %s"), $upload->getName()));
1554
1555     $fd = $upload->open();
1556     if (IsZipFile($fd))
1557         LoadZip($request, $fd, false, array(_("RecentChanges")));
1558     else
1559         LoadFile($request, $upload->getName(), $upload->getContents());
1560
1561     EndLoadDump($request);
1562 }
1563
1564 // Local Variables:
1565 // mode: php
1566 // tab-width: 8
1567 // c-basic-offset: 4
1568 // c-hanging-comment-ender-p: nil
1569 // indent-tabs-mode: nil
1570 // End: