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