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