]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/loadsave.php
Remove rcs_id
[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     $_bodyAttr = @$WikiTheme->_MoreAttr['body'];
560     unset($WikiTheme->_MoreAttr['body']);
561
562     $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
563
564     // check if the dumped file will be accessible from outside
565     $doc_root = $request->get("DOCUMENT_ROOT");
566     if ($WikiTheme->DUMP_MODE == 'HTML') {
567         $ldir = NormalizeLocalFileName($directory);
568         $wikiroot = NormalizeLocalFileName('');
569         if (string_starts_with($ldir, $doc_root)) {
570             $link_prefix = substr($directory, strlen($doc_root))."/";
571         } elseif (string_starts_with($ldir, $wikiroot)) {
572             $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/";
573         } else {
574             $prefix = '';
575             if (isWindows()) {
576                 $prefix = '/'; // . substr($doc_root,0,2); // add drive where apache is installed
577             }
578             $link_prefix = "file://".$prefix.$directory."/";
579         }
580     } else {
581         $link_prefix = "";
582     }
583
584     $request_args = $request->args;
585     $timeout = (! $request->getArg('start_debug')) ? 60 : 240;
586     if ($directory) {
587         if (isWindows())
588             $directory = str_replace("\\", "/", $directory); // no Win95 support.
589         @mkdir("$directory/images");
590     }
591     $already = array();
592     $outfiles = array();
593     $already_images = array();
594
595     while ($page = $page_iter->next()) {
596         if (is_string($page)) {
597             $pagename = $page;
598             $page = $request->_dbi->getPage($pagename);
599         } else {
600             $pagename = $page->getName();
601         }
602         if (empty($firstpage)) $firstpage = $pagename;
603         if (array_key_exists($pagename, $already))
604             continue;
605         $already[$pagename] = 1;
606         $current = $page->getCurrentRevision();
607         //if ($current->getVersion() == 0)
608         //    continue;
609
610         $request->args = $request_args; // some plugins might change them (esp. on POST)
611         longer_timeout($timeout);       // Reset watchdog
612
613         if ($zip) {
614             $attrib = array('mtime'    => $current->get('mtime'),
615                             'is_ascii' => 1);
616             if ($page->get('locked'))
617                 $attrib['write_protected'] = 1;
618         } elseif (!$silent) {
619             if (!isa($request,'MockRequest')) {
620                 PrintXML(HTML::br(), $pagename, ' ... ');
621                 flush();
622             }
623         }
624         if (in_array($pagename, $excludeList)) {
625             if (!$silent and !isa($request,'MockRequest')) {
626                 PrintXML(_("Skipped."));
627                 flush();
628             }
629             continue;
630         }
631         $relative_base = '';
632         if ($WikiTheme->DUMP_MODE == 'PDFHTML')
633             $request->setArg('action', 'pdf');   // to omit cache headers
634         $request->setArg('pagename', $pagename); // Template::_basepage fix
635         $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
636         $args = array('revision'      => $current,
637                       'CONTENT'       => $current->getTransformedContent(),
638                       'relative_base' => $relative_base);
639         // For every %2F will need to mkdir -p dirname($pagename)
640         if (preg_match("/(%2F|\/)/", $filename)) {
641             // mkdir -p and set relative base for subdir pages
642             $filename = preg_replace("/%2F/", "/", $filename);
643             $count = substr_count($filename, "/");
644             $dirname = dirname($filename);
645             if ($directory)
646                 mkdir_p($directory."/".$dirname);
647             // Fails with "XX / YY", "XX" is created, "XX / YY" cannot be written
648             // if (isWindows()) // interesting Windows bug: cannot mkdir "bla "
649             // Since dumps needs to be copied, we have to disallow this for all platforms.
650             $filename = preg_replace("/ \//", "/", $filename);
651             $relative_base = "../";
652             while ($count > 1) {
653                 $relative_base .= "../";
654                 $count--;
655             }
656             $args['relative_base'] = $relative_base;
657         }
658         $msg = HTML();
659
660         $DUMP_MODE = $WikiTheme->DUMP_MODE;
661         $data = GeneratePageasXML(new Template('browse', $request, $args),
662                                  $pagename, $current, $args);
663         $WikiTheme->DUMP_MODE = $DUMP_MODE;
664
665         if (preg_match_all("/<img .*?src=\"(\/.+?)\"/", $data, $m)) {
666             // fix to local relative path for uploaded images, so that pdf will work
667             foreach ($m[1] as $img_file) {
668                 $base = basename($img_file);
669                 $data = str_replace('src="'.$img_file.'"','src="images/'.$base.'"', $data);
670                 if (array_key_exists($img_file, $already_images))
671                     continue;
672                 $already_images[$img_file] = 1;
673                 // resolve src from webdata to file
674                 $src = $doc_root . $img_file;
675                 if (file_exists($src) and $base) {
676                     if ($directory) {
677                         $target = "$directory/images/$base";
678                         if (copy($src, $target)) {
679                             if (!$silent)
680                                 _copyMsg($img_file, fmt("... copied to %s", $target));
681                         } else {
682                             if (!$silent)
683                                 _copyMsg($img_file, fmt("... not copied to %s", $target));
684                         }
685                     } else {
686                         $target = "images/$base";
687                         $zip->addSrcFile($target, $src);
688                     }
689                 }
690             }
691         }
692
693         if ($directory) {
694             $outfile = $directory."/".$filename;
695             if ( !($fd = fopen($outfile, "wb")) ) {
696                 $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
697                                                    $outfile)));
698                 $request->finish($msg);
699             }
700             $len = strlen($data);
701             $num = fwrite($fd, $data, $len);
702             if ($pagename != $filename) {
703                 $link = LinkURL($link_prefix.$filename, $filename);
704                 $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
705             }
706             $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
707             if (!$silent) {
708                 if (!isa($request, 'MockRequest')) {
709                     PrintXML($msg);
710                 }
711                 flush();
712                 $request->chunkOutput();
713             }
714             assert($num == $len);
715             fclose($fd);
716             $outfiles[] = $outfile;
717         } else {
718             $zip->addRegularFile($filename, $data, $attrib);
719         }
720
721         if (USECACHE) {
722             $request->_dbi->_cache->invalidate_cache($pagename);
723             unset ($request->_dbi->_cache->_pagedata_cache);
724             unset ($request->_dbi->_cache->_versiondata_cache);
725             unset ($request->_dbi->_cache->_glv_cache);
726         }
727         unset ($request->_dbi->_cache->_backend->_page_data);
728
729         unset($msg);
730         unset($current->_transformedContent);
731         unset($current);
732         if (!empty($template)) {
733             unset($template->_request);
734             unset($template);
735         }
736         unset($data);
737     }
738     $page_iter->free();
739
740     $attrib = false; //array('is_ascii' => 0);
741     if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
742         // @mkdir("$directory/images");
743         foreach ($WikiTheme->dumped_images as $img_file) {
744             if (array_key_exists($img_file, $already_images))
745                 continue;
746             $already_images[$img_file] = 1;
747             if ($img_file
748                 and ($from = $WikiTheme->_findFile($img_file, true))
749                 and basename($from))
750             {
751                 if ($directory) {
752                     $target = "$directory/images/".basename($from);
753                     if ($silent)
754                         copy($WikiTheme->_path . $from, $target);
755                     else {
756                         if (copy($WikiTheme->_path . $from, $target)) {
757                             _copyMsg($from, fmt("... copied to %s", $target));
758                         } else {
759                             _copyMsg($from, fmt("... not copied to %s", $target));
760                         }
761                     }
762                 } else {
763                     $target = "images/".basename($from);
764                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
765                 }
766             } elseif (!$silent) {
767                 _copyMsg($from, _("... not found"));
768             }
769         }
770     }
771
772     if (!empty($WikiTheme->dumped_buttons)
773          and is_array($WikiTheme->dumped_buttons))
774     {
775         // Buttons also
776         if ($directory)
777             @mkdir("$directory/images/buttons");
778         foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
779             if (array_key_exists($img_file, $already_images))
780                 continue;
781             $already_images[$img_file] = 1;
782             if ($img_file
783                 and ($from = $WikiTheme->_findFile($img_file, true))
784                 and basename($from))
785             {
786                 if ($directory) {
787                     $target = "$directory/images/buttons/".basename($from);
788                     if ($silent)
789                         copy($WikiTheme->_path . $from, $target);
790                     else {
791                         if (copy($WikiTheme->_path . $from, $target)) {
792                             _copyMsg($from, fmt("... copied to %s", $target));
793                         } else {
794                             _copyMsg($from, fmt("... not copied to %s", $target));
795                         }
796                     }
797                 } else {
798                     $target = "images/buttons/".basename($from);
799                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
800                 }
801             } elseif (!$silent) {
802                 _copyMsg($from, _("... not found"));
803             }
804         }
805     }
806     if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
807         foreach ($WikiTheme->dumped_css as $css_file) {
808             if (array_key_exists($css_file, $already_images))
809                 continue;
810             $already_images[$css_file] = 1;
811             if ($css_file
812                 and ($from = $WikiTheme->_findFile(basename($css_file), true))
813                 and basename($from))
814             {
815                 // TODO: fix @import url(main.css);
816                 if ($directory) {
817                     $target = "$directory/" . basename($css_file);
818                     if ($silent)
819                         copy($WikiTheme->_path . $from, $target);
820                     else {
821                         if (copy($WikiTheme->_path . $from, $target)) {
822                             _copyMsg($from, fmt("... copied to %s", $target));
823                         } else {
824                             _copyMsg($from, fmt("... not copied to %s", $target));
825                         }
826                     }
827                 } else {
828                     //$attrib = array('is_ascii' => 0);
829                     $target = basename($css_file);
830                     $zip->addSrcFile($target, $WikiTheme->_path . $from);
831                 }
832             } elseif (!$silent) {
833                 _copyMsg($from, _("... not found"));
834             }
835         }
836     }
837
838     if ($zip)
839         $zip->finish();
840
841     if ($WikiTheme->DUMP_MODE == 'PDFHTML') {
842         if (USE_EXTERNAL_HTML2PDF and $outfiles) {
843             $cmd = EXTERNAL_HTML2PDF_PAGELIST.' "'.join('" "', $outfiles).'"';
844             $filename = FilenameForPage($firstpage);
845             if (DEBUG) {
846                 $tmpfile = $directory . "/createpdf.bat";
847                 $fp = fopen($tmpfile, "wb");
848                 fwrite($fp, $cmd . " > $filename.pdf");
849                 fclose($fp);
850             }
851             if (!headers_sent()) {
852                 Header('Content-Type: application/pdf');
853                 passthru($cmd);
854             }
855             else {
856                 $tmpdir = getUploadFilePath();
857                 $s = passthru($cmd . " > $tmpdir/$filename.pdf");
858                 $errormsg = "<br />\nGenerated <a href=\"".getUploadDataPath()."$filename.pdf\">Upload:$filename.pdf</a>\n";
859                 $errormsg .= $s;
860                 echo $errormsg;
861             }
862             if (!DEBUG) {
863                 foreach($outfiles as $f) unlink($f);
864             }
865         }
866         if (!empty($errormsg)) {
867             $request->discardOutput();
868             $GLOBALS['ErrorManager']->_postponed_errors = array();
869         }
870     }
871
872     $ErrorManager->popErrorHandler();
873
874     $WikiTheme->HTML_DUMP_SUFFIX = '';
875     $WikiTheme->DUMP_MODE = false;
876     $WikiTheme->_MoreAttr['body'] = $_bodyAttr;
877 }
878
879
880 ////////////////////////////////////////////////////////////////
881 //
882 //  Functions for restoring.
883 //
884 ////////////////////////////////////////////////////////////////
885
886 function SavePage (&$request, &$pageinfo, $source, $filename)
887 {
888     static $overwite_all = false;
889     $pagedata    = $pageinfo['pagedata'];    // Page level meta-data.
890     $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
891
892     if (empty($pageinfo['pagename'])) {
893         PrintXML(HTML::p(HTML::strong(_("Empty pagename!"))));
894         return;
895     }
896
897     if (empty($versiondata['author_id']))
898         $versiondata['author_id'] = $versiondata['author'];
899
900     // remove invalid backend specific chars. utf8 issues mostly
901     $pagename_check = new WikiPagename($pageinfo['pagename']);
902     if (!$pagename_check->isValid()) {
903         PrintXML(HTML::p(HTML::strong(_("Invalid pagename!")." ".$pageinfo['pagename'])));
904         return;
905     }
906     $pagename = $pagename_check->getName();
907     $content  = $pageinfo['content'];
908
909     if ($pagename == _("InterWikiMap"))
910         $content = _tryinsertInterWikiMap($content);
911
912     $dbi =& $request->_dbi;
913     $page = $dbi->getPage($pagename);
914
915     // Try to merge if updated pgsrc contents are different. This
916     // whole thing is hackish
917     //
918     // TODO: try merge unless:
919     // if (current contents = default contents && pgsrc_version >=
920     // pgsrc_version) then just upgrade this pgsrc
921     $needs_merge = false;
922     $merging = false;
923     $overwrite = false;
924
925     if ($request->getArg('merge')) {
926         $merging = true;
927     }
928     else if ($request->getArg('overwrite')) {
929         $overwrite = true;
930     }
931
932     $current = $page->getCurrentRevision();
933     $skip = false;
934     $edit = $request->getArg('edit');
935     if ($merging) {
936         if (isset($edit['keep_old'])) {
937             $merging = false;
938             $skip = true;
939         }
940         elseif (isset($edit['overwrite'])) {
941             $merging = false;
942             $overwrite = true;
943         }
944         elseif ( $current and (! $current->hasDefaultContents())
945          && ($current->getPackedContent() != $content) )
946         {
947             include_once('lib/editpage.php');
948             $request->setArg('pagename', $pagename);
949             $v = $current->getVersion();
950             $request->setArg('revision', $current->getVersion());
951             $p = new LoadFileConflictPageEditor($request);
952             $p->_content = $content;
953             $p->_currentVersion = $v - 1;
954             $p->editPage($saveFailed = true);
955             return; //early return
956        }
957     }
958     if (!$skip)
959       foreach ($pagedata as $key => $value) {
960         if (!empty($value))
961             $page->set($key, $value);
962       }
963
964     $mesg = HTML::p(array('style' => 'text-indent: 3em;'));
965     if ($source)
966         $mesg->pushContent(' ', fmt("from %s", $source));
967
968     if (!$current) {
969         //FIXME: This should not happen! (empty vdata, corrupt cache or db)
970         $current = $page->getCurrentRevision();
971     }
972     if ($current->getVersion() == 0) {
973         $versiondata['author'] = ADMIN_USER;
974         $versiondata['author_id'] = ADMIN_USER;
975         $mesg->pushContent(' - ', _("New page"));
976         $isnew = true;
977     }
978     else {
979         if ( (! $current->hasDefaultContents())
980              && ($current->getPackedContent() != $content) ) {
981             if ($overwrite) {
982                 $mesg->pushContent(' ',
983                                    fmt("has edit conflicts - overwriting anyway"));
984                 $skip = false;
985                 if (substr_count($source, 'pgsrc')) {
986                     $versiondata['author'] = ADMIN_USER;
987                     // but leave authorid as userid who loaded the file
988                 }
989             }
990             else {
991                 if (isset($edit['keep_old'])) {
992                     $mesg->pushContent(' ', fmt("keep old"));
993                 } else {
994                     $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
995                     $needs_merge = true; // hackish, to display the buttons
996                 }
997                 $skip = true;
998             }
999         }
1000         else if ($current->getPackedContent() == $content) {
1001             // The page content is the same, we don't need a new revision.
1002             $mesg->pushContent(' ',
1003                                fmt("content is identical to current version %d - no new revision created",
1004                                    $current->getVersion()));
1005             $skip = true;
1006         }
1007         $isnew = false;
1008     }
1009
1010     if (! $skip ) {
1011         // in case of failures print the culprit:
1012         if (!isa($request,'MockRequest')) {
1013             PrintXML(HTML::p(WikiLink($pagename))); flush();
1014         }
1015         $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
1016         $dbi->touch();
1017         $mesg->pushContent(' ', fmt("- saved to database as version %d",
1018                                     $new->getVersion()));
1019     }
1020     if ($needs_merge) {
1021         $f = $source;
1022         // hackish, $source contains needed path+filename
1023         $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
1024         $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
1025         $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
1026         //check if uploaded file? they pass just the content, but the file is gone
1027         if (@stat($f)) {
1028             global $WikiTheme;
1029             $meb = Button(array('action' => 'loadfile',
1030                                 'merge'=> true,
1031                                 'source'=> $f),
1032                           _("Merge Edit"),
1033                           _("PhpWikiAdministration"),
1034                           'wikiadmin');
1035             $owb = Button(array('action' => 'loadfile',
1036                                 'overwrite'=> true,
1037                                 'source'=> $f),
1038                           _("Restore Anyway"),
1039                           _("PhpWikiAdministration"),
1040                           'wikiunsafe');
1041             $mesg->pushContent(' ', $meb, " ", $owb);
1042             if (!$overwite_all) {
1043                 $args = $request->getArgs();
1044                 $args['overwrite'] = 1;
1045                 $owb = Button($args,
1046                               _("Overwrite All"),
1047                               _("PhpWikiAdministration"),
1048                               'wikiunsafe');
1049                 $mesg->pushContent(HTML::span(array('class' => 'hint'), $owb));
1050                 $overwite_all = true;
1051             }
1052         } else {
1053             $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
1054         }
1055     }
1056
1057     if (!isa($request,'MockRequest')) {
1058       if ($skip)
1059         PrintXML(HTML::p(HTML::em(WikiLink($pagename))), $mesg);
1060       else
1061         PrintXML($mesg);
1062       flush();
1063     }
1064 }
1065
1066 // action=revert (by diff)
1067 function RevertPage (&$request)
1068 {
1069     $mesg = HTML::div();
1070     $pagename = $request->getArg('pagename');
1071     $version = $request->getArg('version');
1072     if (!$version) {
1073         PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1074                  HTML::p(_("missing required version argument")));
1075         return;
1076     }
1077     $dbi =& $request->_dbi;
1078     $page = $dbi->getPage($pagename);
1079     $current = $page->getCurrentRevision();
1080     $currversion = $current->getVersion();
1081     if ($currversion == 0) {
1082         $mesg->pushContent(' ', _("no page content"));
1083         PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1084                  $mesg);
1085         flush();
1086         return;
1087     }
1088     if ($currversion == $version) {
1089         $mesg->pushContent(' ', _("same version page"));
1090         PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1091                  $mesg);
1092         flush();
1093         return;
1094     }
1095     if ($request->getArg('cancel')) {
1096         $mesg->pushContent(' ', _("Cancelled"));
1097         PrintXML(HTML::p(fmt("Revert")," ",WikiLink($pagename)),
1098                  $mesg);
1099         flush();
1100         return;
1101     }
1102     if (!$request->getArg('verify')) {
1103         $mesg->pushContent(HTML::p(fmt("Are you sure to revert %s to version $version?", WikiLink($pagename))),
1104                            HTML::form(array('action' => $request->getPostURL(),
1105                                             'method' => 'post'),
1106                                       HiddenInputs($request->getArgs(), false, array('verify')),
1107                                       HiddenInputs(array('verify' => 1)),
1108                                       Button('submit:verify', _("Yes"), 'button'),
1109                                       HTML::Raw('&nbsp;'),
1110                                       Button('submit:cancel', _("Cancel"), 'button'))
1111                            );
1112         $rev = $page->getRevision($version);
1113         $html = HTML(HTML::fieldset($mesg), HTML::hr(), $rev->getTransformedContent());
1114         $template = Template('browse',
1115                              array('CONTENT' => $html));
1116         GeneratePage($template, $pagename, $rev);
1117         $request->checkValidators();
1118         flush();
1119         return;
1120     }
1121     $rev = $page->getRevision($version);
1122     $content = $rev->getPackedContent();
1123     $versiondata = $rev->_data;
1124     $versiondata['summary'] = sprintf(_("revert to version %d"), $version);
1125     $new = $page->save($content, $currversion + 1, $versiondata);
1126     $dbi->touch();
1127
1128     $mesg = HTML::span();
1129     $pagelink = WikiLink($pagename);
1130     $mesg->pushContent(fmt("Revert: %s", $pagelink),
1131                        fmt("- version %d saved to database as version %d",
1132                            $version, $new->getVersion()));
1133     // Force browse of current page version.
1134     $request->setArg('version', false);
1135     $template = Template('savepage', array());
1136     $template->replace('CONTENT', $new->getTransformedContent());
1137
1138     GeneratePage($template, $mesg, $new);
1139     flush();
1140 }
1141
1142 function _tryinsertInterWikiMap($content) {
1143     $goback = false;
1144     if (strpos($content, "<verbatim>")) {
1145         //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1146         $goback = true;
1147     }
1148     if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1149         $error_html = sprintf(" "._("%s: not defined"), "INTERWIKI_MAP_FILE");
1150         $goback = true;
1151     }
1152     $mapfile = FindFile(INTERWIKI_MAP_FILE,1);
1153     if (!$goback && !file_exists($mapfile)) {
1154         $error_html = sprintf(" "._("%s: file not found"), INTERWIKI_MAP_FILE);
1155         $goback = true;
1156     }
1157
1158     if (!empty($error_html))
1159         trigger_error(_("Default InterWiki map file not loaded.")
1160                       . $error_html, E_USER_NOTICE);
1161     if ($goback)
1162         return $content;
1163
1164     // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1165     if (!isa($GLOBALS['request'], 'MockRequest'))
1166         echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile),"<br />";
1167
1168     $fd = fopen ($mapfile, "rb");
1169     $data = fread ($fd, filesize($mapfile));
1170     fclose ($fd);
1171     $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1172     return $content;
1173 }
1174
1175 function ParseSerializedPage($text, $default_pagename, $user)
1176 {
1177     if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1178         return false;
1179
1180     $pagehash = unserialize($text);
1181
1182     // Split up pagehash into four parts:
1183     //   pagename
1184     //   content
1185     //   page-level meta-data
1186     //   revision-level meta-data
1187
1188     if (!defined('FLAG_PAGE_LOCKED'))
1189         define('FLAG_PAGE_LOCKED', 1);
1190     if (!defined('FLAG_PAGE_EXTERNAL'))
1191         define('FLAG_PAGE_EXTERNAL', 1);
1192     $pageinfo = array('pagedata'    => array(),
1193                       'versiondata' => array());
1194
1195     $pagedata = &$pageinfo['pagedata'];
1196     $versiondata = &$pageinfo['versiondata'];
1197
1198     // Fill in defaults.
1199     if (empty($pagehash['pagename']))
1200         $pagehash['pagename'] = $default_pagename;
1201     if (empty($pagehash['author'])) {
1202         $pagehash['author'] = $user->getId();
1203     }
1204
1205     foreach ($pagehash as $key => $value) {
1206         switch($key) {
1207             case 'pagename':
1208             case 'version':
1209             case 'hits':
1210                 $pageinfo[$key] = $value;
1211                 break;
1212             case 'content':
1213                 $pageinfo[$key] = join("\n", $value);
1214                 break;
1215             case 'flags':
1216                 if (($value & FLAG_PAGE_LOCKED) != 0)
1217                     $pagedata['locked'] = 'yes';
1218                 if (($value & FLAG_PAGE_EXTERNAL) != 0)
1219                     $pagedata['external'] = 'yes';
1220                 break;
1221             case 'owner':
1222             case 'created':
1223                 $pagedata[$key] = $value;
1224                 break;
1225             case 'acl':
1226             case 'perm':
1227                 $pagedata['perm'] = ParseMimeifiedPerm($value);
1228                 break;
1229             case 'lastmodified':
1230                 $versiondata['mtime'] = $value;
1231                 break;
1232             case 'author':
1233             case 'author_id':
1234             case 'summary':
1235                 $versiondata[$key] = $value;
1236                 break;
1237         }
1238     }
1239     if (empty($pagehash['charset']))
1240         $pagehash['charset'] = 'utf-8';
1241     // compare to target charset
1242     if (strtolower($pagehash['charset']) != strtolower($GLOBALS['charset'])) {
1243         $pageinfo['content'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['content']);
1244         $pageinfo['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['pagename']);
1245     }
1246     return $pageinfo;
1247 }
1248
1249 function SortByPageVersion ($a, $b) {
1250     return $a['version'] - $b['version'];
1251 }
1252
1253 /**
1254  * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1255  * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1256  * Detected by Santtu Jarvi.
1257  */
1258 function LoadFile (&$request, $filename, $text = false, $mtime = false)
1259 {
1260     if (preg_match("/config$/", dirname($filename))             // our or other config
1261         and preg_match("/config.*\.ini/", basename($filename))) // backups and other versions also
1262     {
1263         trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1264         return;
1265     }
1266     if (!is_string($text)) {
1267         // Read the file.
1268         $stat  = stat($filename);
1269         $mtime = $stat[9];
1270         $text  = implode("", file($filename));
1271     }
1272
1273     if (! $request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1274     else @set_time_limit(240);
1275
1276     // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1277     $basename = basename("/dummy/" . $filename);
1278
1279     if (!$mtime)
1280         $mtime = time();    // Last resort.
1281
1282     // DONE: check source - target charset for content and pagename
1283     // but only for pgsrc'ed content, not from the browser.
1284
1285     $default_pagename = rawurldecode($basename);
1286     if ( ($parts = ParseMimeifiedPages($text)) ) {
1287         if (count($parts) > 1)
1288             $overwrite = $request->getArg('overwrite');
1289         usort($parts, 'SortByPageVersion');
1290         foreach ($parts as $pageinfo) {
1291             // force overwrite
1292             if (count($parts) > 1)
1293                 $request->setArg('overwrite', 1);
1294             SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1295                                                   $filename), $basename);
1296     }
1297         if (count($parts) > 1)
1298             if ($overwrite)
1299                 $request->setArg('overwrite', $overwrite);
1300             else
1301                 unset($request->_args['overwrite']);
1302     }
1303     else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename,
1304                                                $request->getUser())) ) {
1305         SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1306                                               $filename), $basename);
1307     }
1308     else {
1309         // plain old file
1310         $user = $request->getUser();
1311
1312         $file_charset = 'utf-8';
1313         // compare to target charset
1314         if ($file_charset != strtolower($GLOBALS['charset'])) {
1315             $text = charset_convert($file_charset, $GLOBALS['charset'], $text);
1316             $default_pagename = charset_convert($file_charset, $GLOBALS['charset'], $default_pagename);
1317         }
1318
1319         // Assume plain text file.
1320         $pageinfo = array('pagename' => $default_pagename,
1321                           'pagedata' => array(),
1322                           'versiondata'
1323                           => array('author' => $user->getId()),
1324                           'content'  => preg_replace('/[ \t\r]*\n/', "\n",
1325                                                      chop($text))
1326                           );
1327         SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1328                  $basename);
1329     }
1330 }
1331
1332 function LoadZip (&$request, $zipfile, $files = false, $exclude = false) {
1333     $zip = new ZipReader($zipfile);
1334     $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1335     while (list ($fn, $data, $attrib) = $zip->readFile()) {
1336         // FIXME: basename("filewithnoslashes") seems to return
1337         // garbage sometimes.
1338         $fn = basename("/dummy/" . $fn);
1339         if ( ($files && !in_array($fn, $files))
1340              || ($exclude && in_array($fn, $exclude)) ) {
1341             PrintXML(HTML::p(WikiLink($fn)),
1342                      HTML::p(_("Skipping")));
1343             flush();
1344             continue;
1345         }
1346         longer_timeout($timeout);       // longer timeout per page
1347         LoadFile($request, $fn, $data, $attrib['mtime']);
1348     }
1349 }
1350
1351 function LoadDir (&$request, $dirname, $files = false, $exclude = false) {
1352     $fileset = new LimitedFileSet($dirname, $files, $exclude);
1353
1354     if (!$files and ($skiplist = $fileset->getSkippedFiles())) {
1355         PrintXML(HTML::p(HTML::strong(_("Skipping"))));
1356         $list = HTML::ul();
1357         foreach ($skiplist as $file)
1358             $list->pushContent(HTML::li(WikiLink($file)));
1359         PrintXML(HTML::p($list));
1360     }
1361
1362     // Defer HomePage loading until the end. If anything goes wrong
1363     // the pages can still be loaded again.
1364     $files = $fileset->getFiles();
1365     if (in_array(HOME_PAGE, $files)) {
1366         $files = array_diff($files, array(HOME_PAGE));
1367         $files[] = HOME_PAGE;
1368     }
1369     $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1370     foreach ($files as $file) {
1371         longer_timeout($timeout);       // longer timeout per page
1372         if (substr($file,-1,1) != '~')  // refuse to load backup files
1373             LoadFile($request, "$dirname/$file");
1374     }
1375 }
1376
1377 class LimitedFileSet extends FileSet {
1378     function LimitedFileSet($dirname, $_include, $exclude) {
1379         $this->_includefiles = $_include;
1380         $this->_exclude = $exclude;
1381         $this->_skiplist = array();
1382         parent::FileSet($dirname);
1383     }
1384
1385     function _filenameSelector($fn) {
1386         $incl = &$this->_includefiles;
1387         $excl = &$this->_exclude;
1388
1389         if ( ($incl && !in_array($fn, $incl))
1390              || ($excl && in_array($fn, $excl)) ) {
1391             $this->_skiplist[] = $fn;
1392             return false;
1393         } else {
1394             return true;
1395         }
1396     }
1397
1398     function getSkippedFiles () {
1399         return $this->_skiplist;
1400     }
1401 }
1402
1403
1404 function IsZipFile ($filename_or_fd)
1405 {
1406     // See if it looks like zip file
1407     if (is_string($filename_or_fd))
1408     {
1409         $fd    = fopen($filename_or_fd, "rb");
1410         $magic = fread($fd, 4);
1411         fclose($fd);
1412     }
1413     else
1414     {
1415         $fpos  = ftell($filename_or_fd);
1416         $magic = fread($filename_or_fd, 4);
1417         fseek($filename_or_fd, $fpos);
1418     }
1419
1420     return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
1421 }
1422
1423
1424 function LoadAny (&$request, $file_or_dir, $files = false, $exclude = false)
1425 {
1426     // Try urlencoded filename for accented characters.
1427     if (!file_exists($file_or_dir)) {
1428         // Make sure there are slashes first to avoid confusing phps
1429         // with broken dirname or basename functions.
1430         // FIXME: windows uses \ and :
1431         if (is_integer(strpos($file_or_dir, "/"))) {
1432             $newfile = FindFile($file_or_dir, true);
1433             // Panic. urlencoded by the browser (e.g. San%20Diego => San Diego)
1434             if (!$newfile)
1435                 $file_or_dir = dirname($file_or_dir) . "/"
1436                     . rawurlencode(basename($file_or_dir));
1437         } else {
1438             // This is probably just a file.
1439             $file_or_dir = rawurlencode($file_or_dir);
1440         }
1441     }
1442
1443     $type = filetype($file_or_dir);
1444     if ($type == 'link') {
1445         // For symbolic links, use stat() to determine
1446         // the type of the underlying file.
1447         list(,,$mode) = stat($file_or_dir);
1448         $type = ($mode >> 12) & 017;
1449         if ($type == 010)
1450             $type = 'file';
1451         elseif ($type == 004)
1452             $type = 'dir';
1453     }
1454
1455     if (! $type) {
1456         $request->finish(fmt("Empty or not existing source. Unable to load: %s", $file_or_dir));
1457     }
1458     else if ($type == 'dir') {
1459         LoadDir($request, $file_or_dir, $files, $exclude);
1460     }
1461     else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
1462     {
1463         $request->finish(fmt("Bad file type: %s", $type));
1464     }
1465     else if (IsZipFile($file_or_dir)) {
1466         LoadZip($request, $file_or_dir, $files, $exclude);
1467     }
1468     else /* if (!$files || in_array(basename($file_or_dir), $files)) */
1469     {
1470         LoadFile($request, $file_or_dir);
1471     }
1472 }
1473
1474 function LoadFileOrDir (&$request)
1475 {
1476     $source = $request->getArg('source');
1477     $finder = new FileFinder;
1478     $source = $finder->slashifyPath($source);
1479     StartLoadDump($request, 
1480         sprintf(_("Loading '%s'"), $source));
1481     LoadAny($request, $source);
1482     EndLoadDump($request);
1483 }
1484
1485 /**
1486  * HomePage was not found so first-time install is supposed to run.
1487  * - import all pgsrc pages.
1488  * - Todo: installer interface to edit config/config.ini settings
1489  * - Todo: ask for existing old index.php to convert to config/config.ini
1490  * - Todo: theme-specific pages:
1491  *   blog - HomePage, ADMIN_USER/Blogs
1492  */
1493 function SetupWiki (&$request)
1494 {
1495     global $GenericPages, $LANG;
1496
1497     //FIXME: This is a hack (err, "interim solution")
1498     // This is a bogo-bogo-login:  Login without
1499     // saving login information in session state.
1500     // This avoids logging in the unsuspecting
1501     // visitor as ADMIN_USER
1502     //
1503     // This really needs to be cleaned up...
1504     // (I'm working on it.)
1505     $real_user = $request->_user;
1506     if (ENABLE_USER_NEW)
1507         $request->_user = new _BogoUser(ADMIN_USER);
1508
1509     else
1510         $request->_user = new WikiUser($request, ADMIN_USER, WIKIAUTH_BOGO);
1511
1512     StartLoadDump($request, _("Loading up virgin wiki"));
1513
1514     $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1515     $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1516
1517     $request->setArg('overwrite', true);
1518     if ($default_pgsrc != $pgsrc) {
1519         LoadAny($request, $default_pgsrc, $GenericPages);
1520     }
1521     $request->setArg('overwrite', false);
1522     LoadAny($request, $pgsrc);
1523     $dbi =& $request->_dbi;
1524
1525     // Ensure that all mandatory pages are loaded
1526     $finder = new FileFinder;
1527
1528     if (!FUSIONFORGE) {
1529         $mandatory = explode(':','SandBox:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:Help/OldTextFormattingRules:Help/TextFormattingRules:PhpWikiAdministration');
1530     } else if (WIKI_NAME == "help") {
1531         $mandatory = explode(':','SandBox:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:Help/TextFormattingRules:PhpWikiAdministration');
1532     } else {
1533         $mandatory = explode(':','SandBox:Template/UserPage:Template/Category:Template/Talk:SpecialPages:CategoryCategory:CategoryActionPage:TextFormattingRules:PhpWikiAdministration');
1534     }
1535     foreach (array_merge($mandatory,
1536                          $GLOBALS['AllActionPages'],
1537                          array(constant('HOME_PAGE'))) as $f)
1538     {
1539         $page = gettext($f);
1540         $epage = urlencode($page);
1541         if (! $dbi->isWikiPage($page) ) {
1542             // translated version provided?
1543             if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1544                 LoadAny($request, $lf);
1545             } else { // load english version of required action page
1546                 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1547                 $page = $f;
1548             }
1549         }
1550         if (! $dbi->isWikiPage($page)) {
1551             trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1552                           E_USER_WARNING);
1553         }
1554     }
1555
1556     $pagename = _("InterWikiMap");
1557     $map = $dbi->getPage($pagename);
1558     $map->set('locked', true);
1559     PrintXML(HTML::p(HTML::em(WikiLink($pagename)), HTML::strong(" locked")));
1560     EndLoadDump($request);
1561 }
1562
1563 function LoadPostFile (&$request)
1564 {
1565     $upload = $request->getUploadedFile('file');
1566
1567     if (!$upload)
1568         $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1569
1570     // Dump http headers.
1571     StartLoadDump($request, sprintf(_("Uploading %s"), $upload->getName()));
1572
1573     $fd = $upload->open();
1574     if (IsZipFile($fd))
1575         LoadZip($request, $fd, false, array(_("RecentChanges")));
1576     else
1577         LoadFile($request, $upload->getName(), $upload->getContents());
1578
1579     EndLoadDump($request);
1580 }
1581
1582 // Local Variables:
1583 // mode: php
1584 // tab-width: 8
1585 // c-basic-offset: 4
1586 // c-hanging-comment-ender-p: nil
1587 // indent-tabs-mode: nil
1588 // End:
1589 ?>