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