]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/loadsave.php
Use WikiPagename treatment for imported pagenames
[SourceForge/phpwiki.git] / lib / loadsave.php
1 <?php //-*-php-*-
2 rcs_id('$Id: loadsave.php,v 1.150 2007-01-20 15:53:42 rurban Exp $');
3
4 /*
5  Copyright 1999,2000,2001,2002,2004,2005,2006 $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     if (isa($request,'MockRequest'))
66         return;
67     $action = $request->getArg('action');
68     $label = '';
69     switch ($action) {
70     case 'zip':        $label = _("ZIP files of database"); break;
71     case 'dumpserial': $label = _("Dump to directory"); break;
72     case 'upload':     $label = _("Upload File"); break;
73     case 'loadfile':   $label = _("Load File"); break;
74     case 'upgrade':    $label = _("Upgrade"); break;
75     case 'dumphtml': 
76     case 'ziphtml':    $label = _("Dump pages as XHTML"); break;
77     }
78     if ($label) $label = str_replace(" ","_",$label);
79     if ($action == 'browse') // loading virgin 
80         $pagelink = WikiLink(HOME_PAGE);
81     else
82         $pagelink = WikiLink(new WikiPageName(_("PhpWikiAdministration"),false,$label));
83
84     // do deferred sendPageChangeNotification()
85     if (!empty($request->_deferredPageChangeNotification)) {
86         $pages = $all_emails = $all_users = array();
87         foreach ($request->_deferredPageChangeNotification as $p) {
88             list($pagename, $emails, $userids) = $p;
89             $pages[] = $pagename;
90             $all_emails = array_unique(array_merge($all_emails, $emails));
91             $all_users = array_unique(array_merge($all_users, $userids));
92         }
93         $editedby = sprintf(_("Edited by: %s"), $request->_user->getId());
94         $content = "Loaded the following pages:\n" . join("\n", $pages);
95         if (mail(join(',',$all_emails),"[".WIKI_NAME."] "._("LoadDump"), 
96                  _("LoadDump")."\n".
97                  $editedby."\n\n".
98                  $content))
99             trigger_error(sprintf(_("PageChange Notification of %s sent to %s"),
100                                   join("\n",$pages), join(',',$all_users)), E_USER_NOTICE);
101         else
102             trigger_error(sprintf(_("PageChange Notification Error: Couldn't send %s to %s"),
103                                   join("\n",$pages), join(',',$all_users)), E_USER_WARNING);
104         unset($pages);
105         unset($all_emails);
106         unset($all_users);
107     }
108     unset($request->_deferredPageChangeNotification);
109
110     PrintXML(HTML::p(HTML::strong(_("Complete."))),
111              HTML::p(fmt("Return to %s", $pagelink)));
112     echo "</body></html>\n";
113 }
114
115
116 ////////////////////////////////////////////////////////////////
117 //
118 //  Functions for dumping.
119 //
120 ////////////////////////////////////////////////////////////////
121
122 /**
123  * For reference see:
124  * http://www.nacs.uci.edu/indiv/ehood/MIME/2045/rfc2045.html
125  * http://www.faqs.org/rfcs/rfc2045.html
126  * (RFC 1521 has been superceeded by RFC 2045 & others).
127  *
128  * Also see http://www.faqs.org/rfcs/rfc2822.html
129  */
130 function MailifyPage ($page, $nversions = 1)
131 {
132     $current = $page->getCurrentRevision(false);
133     $head = '';
134
135     if (STRICT_MAILABLE_PAGEDUMPS) {
136         $from = defined('SERVER_ADMIN') ? SERVER_ADMIN : 'foo@bar';
137         //This is for unix mailbox format: (not RFC (2)822)
138         // $head .= "From $from  " . CTime(time()) . "\r\n";
139         $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
140         $head .= "From: $from (PhpWiki)\r\n";
141         // RFC 2822 requires only a Date: and originator (From:)
142         // field, however the obsolete standard RFC 822 also
143         // requires a destination field.
144         $head .= "To: $from (PhpWiki)\r\n";
145     }
146     $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
147     $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
148                      PHPWIKI_VERSION);
149
150     // This should just be entered by hand (or by script?)
151     // in the actual pgsrc files, since only they should have
152     // RCS ids.
153     //$head .= "X-Rcs-Id: \$Id\$\r\n";
154
155     $iter = $page->getAllRevisions();
156     $parts = array();
157     while ($revision = $iter->next()) {
158         $parts[] = MimeifyPageRevision($page, $revision);
159         if ($nversions > 0 && count($parts) >= $nversions)
160             break;
161     }
162     if (count($parts) > 1)
163         return $head . MimeMultipart($parts);
164     assert($parts);
165     return $head . $parts[0];
166 }
167
168 /***
169  * Compute filename to used for storing contents of a wiki page.
170  *
171  * Basically we do a rawurlencode() which encodes everything except
172  * ASCII alphanumerics and '.', '-', and '_'.
173  *
174  * But we also want to encode leading dots to avoid filenames like
175  * '.', and '..'. (Also, there's no point in generating "hidden" file
176  * names, like '.foo'.)
177  *
178  * @param $pagename string Pagename.
179  * @return string Filename for page.
180  */
181 function FilenameForPage ($pagename)
182 {
183     $enc = rawurlencode($pagename);
184     // For every %2F will need to mkdir -p dirname($pagename)
185     return preg_replace('/^\./', '%2E', $enc);
186 }
187
188 /**
189  * The main() function which generates a zip archive of a PhpWiki.
190  *
191  * If $include_archive is false, only the current version of each page
192  * is included in the zip file; otherwise all archived versions are
193  * included as well.
194  */
195 function MakeWikiZip (&$request)
196 {
197     if ($request->getArg('include') == 'all') {
198         $zipname         = WIKI_NAME . _("FullDump") . date('Ymd-Hi') . '.zip';
199         $include_archive = true;
200     }
201     else {
202         $zipname         = WIKI_NAME . _("LatestSnapshot") . date('Ymd-Hi') . '.zip';
203         $include_archive = false;
204     }
205
206
207     $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
208
209     /* ignore fatals in plugins */
210     if (check_php_version(4,1)) {
211         global $ErrorManager;
212         $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
213     }
214
215     $dbi =& $request->_dbi;
216     $thispage = $request->getArg('pagename'); // for "Return to ..."
217     if ($exclude = $request->getArg('exclude')) {   // exclude which pagenames
218         $excludeList = explodePageList($exclude); 
219     } else {
220         $excludeList = array();
221     }
222     if ($pages = $request->getArg('pages')) {  // which pagenames
223         if ($pages == '[]') // current page
224             $pages = $thispage;
225         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
226     } else {
227         $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
228     }
229     $request_args = $request->args;
230     $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
231     
232     while ($page = $page_iter->next()) {
233         $request->args = $request_args; // some plugins might change them (esp. on POST)
234         longer_timeout($timeout);       // Reset watchdog
235
236         $current = $page->getCurrentRevision();
237         if ($current->getVersion() == 0)
238             continue;
239
240         $pagename = $page->getName();
241         $wpn = new WikiPageName($pagename);
242         if (!$wpn->isValid())
243             continue;
244         if (in_array($page->getName(), $excludeList)) {
245             continue;
246         }
247
248         $attrib = array('mtime'    => $current->get('mtime'),
249                         'is_ascii' => 1);
250         if ($page->get('locked'))
251             $attrib['write_protected'] = 1;
252
253         if ($include_archive)
254             $content = MailifyPage($page, 0);
255         else
256             $content = MailifyPage($page);
257
258         $zip->addRegularFile( FilenameForPage($pagename),
259                               $content, $attrib);
260     }
261     $zip->finish();
262     if (check_php_version(4,1)) {
263         global $ErrorManager;
264         $ErrorManager->popErrorHandler();
265     }
266 }
267
268 function DumpToDir (&$request)
269 {
270     $directory = $request->getArg('directory');
271     if (empty($directory))
272         $directory = DEFAULT_DUMP_DIR; // See lib/plugin/WikiForm.php:87
273     if (empty($directory))
274         $request->finish(_("You must specify a directory to dump to"));
275
276     // see if we can access the directory the user wants us to use
277     if (! file_exists($directory)) {
278         if (! mkdir($directory, 0755))
279             $request->finish(fmt("Cannot create directory '%s'", $directory));
280         else
281             $html = HTML::p(fmt("Created directory '%s' for the page dump...",
282                                 $directory));
283     } else {
284         $html = HTML::p(fmt("Using directory '%s'", $directory));
285     }
286
287     StartLoadDump($request, _("Dumping Pages"), $html);
288
289     $dbi =& $request->_dbi;
290     $thispage = $request->getArg('pagename'); // for "Return to ..."
291     if ($exclude = $request->getArg('exclude')) {   // exclude which pagenames
292         $excludeList = explodePageList($exclude); 
293     } else {
294         $excludeList = array();
295     }
296     if ($pages = $request->getArg('pages')) {  // which pagenames
297         if ($pages == '[]') // current page
298             $pages = $thispage;
299         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
300     } else {
301         $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
302     }
303
304     $request_args = $request->args;
305     $timeout = (! $request->getArg('start_debug')) ? 30 : 240;
306
307     while ($page = $page_iter->next()) {
308         $request->args = $request_args; // some plugins might change them (esp. on POST)
309         longer_timeout($timeout);       // Reset watchdog
310
311         $pagename = $page->getName();
312         if (!isa($request,'MockRequest')) {
313             PrintXML(HTML::br(), $pagename, ' ... ');
314             flush();
315         }
316
317         if (in_array($pagename, $excludeList)) {
318             if (!isa($request, 'MockRequest')) {
319                 PrintXML(_("Skipped."));
320                 flush();
321             }
322             continue;
323         }
324         $filename = FilenameForPage($pagename);
325         $msg = HTML();
326         if($page->getName() != $filename) {
327             $msg->pushContent(HTML::small(fmt("saved as %s", $filename)),
328                               " ... ");
329         }
330
331         if ($request->getArg('include') == 'all')
332             $data = MailifyPage($page, 0);
333         else
334             $data = MailifyPage($page);
335
336         if ( !($fd = fopen($directory."/".$filename, "wb")) ) {
337             $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
338                                                "$directory/$filename")));
339             $request->finish($msg);
340         }
341
342         $num = fwrite($fd, $data, strlen($data));
343         $msg->pushContent(HTML::small(fmt("%s bytes written", $num)));
344         if (!isa($request, 'MockRequest')) {
345             PrintXML($msg);
346             flush();
347         }
348         assert($num == strlen($data));
349         fclose($fd);
350     }
351
352     EndLoadDump($request);
353 }
354
355 function _copyMsg($page, $smallmsg) {
356     if (!isa($GLOBALS['request'], 'MockRequest')) {
357         if ($page) $msg = HTML(HTML::br(), HTML($page), HTML::small($smallmsg));
358         else $msg = HTML::small($smallmsg);
359         PrintXML($msg);
360         flush();
361     }
362 }
363
364 function mkdir_p($pathname, $permission = 0777) {
365     $arr = explode("/", $pathname);
366     if (empty($arr)) {
367         return mkdir($pathname, $permission);
368     }
369     $s = array_shift($arr);
370     $ok = TRUE;
371     foreach ($arr as $p) {
372         $curr = "$s/$p";
373         if (!is_dir($curr))
374             $ok = mkdir($curr, $permission);
375         $s = $curr;
376         if (!$ok) return FALSE;
377     }
378     return TRUE;
379 }
380
381 /**
382  * Dump all pages as XHTML to a directory, as pagename.html.
383  * Copies all used css files to the directory, all used images to a 
384  * "images" subdirectory, and all used buttons to a "images/buttons" subdirectory.
385  * The webserver must have write permissions to these directories. 
386  *   chown httpd HTML_DUMP_DIR; chmod u+rwx HTML_DUMP_DIR 
387  * should be enough.
388  *
389  * @param string directory (optional) path to dump to. Default: HTML_DUMP_DIR
390  * @param string pages     (optional) Comma-seperated of glob-style pagenames to dump
391  * @param string exclude   (optional) Comma-seperated of glob-style pagenames to exclude
392  */
393 function DumpHtmlToDir (&$request)
394 {
395     $directory = $request->getArg('directory');
396     if (empty($directory))
397         $directory = HTML_DUMP_DIR; // See lib/plugin/WikiForm.php:87
398     if (empty($directory))
399         $request->finish(_("You must specify a directory to dump to"));
400
401     // see if we can access the directory the user wants us to use
402     if (! file_exists($directory)) {
403         if (! mkdir($directory, 0755))
404             $request->finish(fmt("Cannot create directory '%s'", $directory));
405         else
406             $html = HTML::p(fmt("Created directory '%s' for the page dump...",
407                                 $directory));
408     } else {
409         $html = HTML::p(fmt("Using directory '%s'", $directory));
410     }
411     $request->_TemplatesProcessed = array();
412     StartLoadDump($request, _("Dumping Pages"), $html);
413     $thispage = $request->getArg('pagename'); // for "Return to ..."
414
415     $dbi =& $request->_dbi;
416     if ($exclude = $request->getArg('exclude')) {   // exclude which pagenames
417         $excludeList = explodePageList($exclude); 
418     } else {
419         $excludeList = array();
420     }
421     if ($pages = $request->getArg('pages')) {  // which pagenames
422         if ($pages == '[]') // current page
423             $pages = $thispage;
424         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
425     // not at admin page: dump only the current page
426     } elseif ($thispage != _("PhpWikiAdministration")) { 
427         $page_iter = new WikiDB_Array_PageIterator(array($thispage));
428     } else {
429         $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
430     }
431
432     global $WikiTheme;
433     if (defined('HTML_DUMP_SUFFIX'))
434         $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
435     $WikiTheme->DUMP_MODE = 'HTML';
436     $_bodyAttr = @$WikiTheme->_MoreAttr['body'];
437     unset($WikiTheme->_MoreAttr['body']);
438
439     // check if the dumped file will be accessible from outside
440     $doc_root = $request->get("DOCUMENT_ROOT");
441     $ldir = NormalizeLocalFileName($directory);
442     $wikiroot = NormalizeLocalFileName('');
443     if (string_starts_with($ldir, $doc_root)) {
444         $link_prefix = substr($directory, strlen($doc_root))."/";
445     } elseif (string_starts_with($ldir, $wikiroot)) {
446         $link_prefix = NormalizeWebFileName(substr($directory, strlen($wikiroot)))."/";
447     } else {
448         $prefix = '';
449         if (isWindows()) {
450             $prefix = '/' . substr($doc_root,0,2); // add drive where apache is installed
451         }
452         $link_prefix = "file://".$prefix.$directory."/";
453     }
454
455     $request_args = $request->args;
456     $timeout = (! $request->getArg('start_debug')) ? 20 : 240;
457     
458     while ($page = $page_iter->next()) {
459         $request->args = $request_args; // some plugins might change them (esp. on POST)
460         longer_timeout($timeout);       // Reset watchdog
461           
462         $pagename = $page->getName();
463         if (!isa($request,'MockRequest')) {
464             PrintXML(HTML::br(), $pagename, ' ... ');
465             flush();
466         }
467         if (in_array($pagename, $excludeList)) {
468             if (!isa($request,'MockRequest')) {
469                 PrintXML(_("Skipped."));
470                 flush();
471             }
472             continue;
473         }
474         $relative_base = '';
475         $request->setArg('pagename', $pagename); // Template::_basepage fix
476         $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
477         $revision = $page->getCurrentRevision();
478         $args = array('revision' => $revision,
479                       'CONTENT' => $revision->getTransformedContent(),
480                       'relative_base' => $relative_base);
481         // For every %2F will need to mkdir -p dirname($pagename)
482         if (preg_match("/%2F/", $filename)) {
483             // mkdir -p and set relative base for subdir pages
484             $count = substr_count($filename, "%2F");
485             $filename = preg_replace("/%2F/", "/", $filename);
486             $dirname = dirname($filename);
487             mkdir_p($directory."/".$dirname);
488             $relative_base = "../";
489             while ($count > 1) {
490                 $relative_base .= "../";
491                 $count--;
492             }
493             $args['relative_base'] = $relative_base;
494         }
495         $msg = HTML();
496         $template = new Template('browse', $request, $args);
497
498         $data = GeneratePageasXML($template, $pagename, $revision, $args);
499
500         if ( !($fd = fopen($directory."/".$filename, "wb")) ) {
501             $msg->pushContent(HTML::strong(fmt("couldn't open file '%s' for writing",
502                                                "$directory/$filename")));
503             $request->finish($msg);
504         }
505         $len = strlen($data);
506         $num = fwrite($fd, $data, $len);
507         if ($page->getName() != $filename) {
508             $link = LinkURL($link_prefix.$filename, $filename);
509             $msg->pushContent(HTML::small(_("saved as "), $link, " ... "));
510         }
511         $msg->pushContent(HTML::small(fmt("%s bytes written", $num), "\n"));
512         if (!isa($request, 'MockRequest')) {
513             PrintXML($msg);
514         }
515         flush();
516         $request->chunkOutput();
517
518         assert($num == $len);
519         fclose($fd);
520
521         if (USECACHE) {
522             $request->_dbi->_cache->invalidate_cache($pagename);
523             unset ($request->_dbi->_cache->_pagedata_cache);
524             unset ($request->_dbi->_cache->_versiondata_cache);
525             unset ($request->_dbi->_cache->_glv_cache);
526         }
527         unset ($request->_dbi->_cache->_backend->_page_data);
528
529         unset($msg);
530         unset($revision->_transformedContent);
531         unset($revision);
532         unset($template->_request);
533         unset($template);
534         unset($data);
535     }
536     $page_iter->free();
537
538     if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
539         @mkdir("$directory/images");
540         foreach ($WikiTheme->dumped_images as $img_file) {
541             if ($img_file 
542                 and ($from = $WikiTheme->_findFile($img_file, true)) 
543                 and basename($from)) 
544             {
545                 $target = "$directory/images/".basename($img_file);
546                 if (copy($WikiTheme->_path . $from, $target)) {
547                     _copyMsg($from, fmt("... copied to %s", $target));
548                 } else {
549                     _copyMsg($from, fmt("... not copied to %s", $target));
550                 }
551             } else {
552                 _copyMsg($from, _("... not found"));
553             }
554         }
555     }
556     if (!empty($WikiTheme->dumped_buttons) and is_array($WikiTheme->dumped_buttons)) {
557         // Buttons also
558         @mkdir("$directory/images/buttons");
559         foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
560             if ($img_file 
561                 and ($from = $WikiTheme->_findFile($img_file, true)) 
562                 and basename($from)) 
563             {
564                 $target = "$directory/images/buttons/".basename($img_file);
565                 if (copy($WikiTheme->_path . $from, $target)) {
566                     _copyMsg($from, fmt("... copied to %s", $target));
567                 } else {
568                     _copyMsg($from, fmt("... not copied to %s", $target));
569                 }
570             } else {
571                 _copyMsg($from, _("... not found"));
572             }
573         }
574     }
575     if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
576         foreach ($WikiTheme->dumped_css as $css_file) {
577             if ($css_file 
578                 and ($from = $WikiTheme->_findFile(basename($css_file), true)) 
579                 and basename($from)) 
580             {
581                 $target = "$directory/" . basename($css_file);
582                 if (copy($WikiTheme->_path . $from, $target)) {
583                     _copyMsg($from, fmt("... copied to %s", $target));
584                 } else {
585                     _copyMsg($from, fmt("... not copied to %s", $target));
586                 }
587             } else {
588                 _copyMsg($from, _("... not found"));
589             }
590         }
591     }
592     $WikiTheme->HTML_DUMP_SUFFIX = '';
593     $WikiTheme->DUMP_MODE = false;
594     $WikiTheme->_MoreAttr['body'] = $_bodyAttr;
595
596     $request->setArg('pagename',$thispage); // Template::_basepage fix
597     EndLoadDump($request);
598 }
599
600 /* Known problem: any plugins or other code which echo()s text will
601  * lead to a corrupted html zip file which may produce the following
602  * errors upon unzipping:
603  *
604  * warning [wikihtml.zip]:  2401 extra bytes at beginning or within zipfile
605  * file #58:  bad zipfile offset (local header sig):  177561
606  *  (attempting to re-compensate)
607  *
608  * However, the actual wiki page data should be unaffected.
609  */
610 function MakeWikiZipHtml (&$request)
611 {
612     $request->_TemplatesProcessed = array();
613     $zipname = "wikihtml.zip";
614     $zip = new ZipWriter("Created by PhpWiki " . PHPWIKI_VERSION, $zipname);
615     $dbi =& $request->_dbi;
616     $thispage = $request->getArg('pagename'); // for "Return to ..."
617     if ($exclude = $request->getArg('exclude')) {   // exclude which pagenames
618         $excludeList = explodePageList($exclude); 
619     } else {
620         $excludeList = array();
621     }
622     if ($pages = $request->getArg('pages')) {  // which pagenames
623         if ($pages == '[]') // current page
624             $pages = $thispage;
625         $page_iter = new WikiDB_Array_PageIterator(explodePageList($pages));
626     } else {
627         $page_iter = $dbi->getAllPages(false,false,false,$excludeList);
628     }
629
630     global $WikiTheme;
631     if (defined('HTML_DUMP_SUFFIX'))
632         $WikiTheme->HTML_DUMP_SUFFIX = HTML_DUMP_SUFFIX;
633     $WikiTheme->DUMP_MODE = 'ZIPHTML';
634     $_bodyAttr = @$WikiTheme->_MoreAttr['body'];
635     unset($WikiTheme->_MoreAttr['body']);
636
637     /* ignore fatals in plugins */
638     if (check_php_version(4,1)) {
639         global $ErrorManager;
640         $ErrorManager->pushErrorHandler(new WikiFunctionCb('_dump_error_handler'));
641     }
642
643     $request_args = $request->args;
644     $timeout = (! $request->getArg('start_debug')) ? 20 : 240;
645     
646     while ($page = $page_iter->next()) {
647         $request->args = $request_args; // some plugins might change them (esp. on POST)
648         longer_timeout($timeout);       // Reset watchdog
649
650         $current = $page->getCurrentRevision();
651         if ($current->getVersion() == 0)
652             continue;
653         $pagename = $page->getName();
654         if (in_array($pagename, $excludeList)) {
655             continue;
656         }
657
658         $attrib = array('mtime'    => $current->get('mtime'),
659                         'is_ascii' => 1);
660         if ($page->get('locked'))
661             $attrib['write_protected'] = 1;
662
663         $request->setArg('pagename', $pagename); // Template::_basepage fix
664         $filename = FilenameForPage($pagename) . $WikiTheme->HTML_DUMP_SUFFIX;
665         $revision = $page->getCurrentRevision();
666
667         $transformedContent = $revision->getTransformedContent();
668
669         $template = new Template('browse', $request,
670                                  array('revision' => $revision,
671                                        'CONTENT' => $transformedContent));
672
673         $data = GeneratePageasXML($template, $pagename);
674
675         $zip->addRegularFile( $filename, $data, $attrib );
676         
677         if (USECACHE) {
678             $request->_dbi->_cache->invalidate_cache($pagename);
679             unset ($request->_dbi->_cache->_pagedata_cache);
680             unset ($request->_dbi->_cache->_versiondata_cache);
681             unset ($request->_dbi->_cache->_glv_cache);
682         }
683         unset ($request->_dbi->_cache->_backend->_page_data);
684
685         unset($revision->_transformedContent);
686         unset($revision);
687         unset($template->_request);
688         unset($template);
689         unset($data);
690     }
691     $page_iter->free();
692
693     $attrib = false;
694     // Deal with css and images here.
695     if (!empty($WikiTheme->dumped_images) and is_array($WikiTheme->dumped_images)) {
696         // dirs are created automatically
697         //if ($WikiTheme->dumped_images) $zip->addRegularFile("images", "", $attrib);
698         foreach ($WikiTheme->dumped_images as $img_file) {
699             if (($from = $WikiTheme->_findFile($img_file, true)) and basename($from)) {
700                 $target = "images/".basename($img_file);
701                 if (check_php_version(4,3))
702                     $zip->addRegularFile($target, file_get_contents($WikiTheme->_path . $from), $attrib);
703                 else
704                     $zip->addRegularFile($target, join('', file($WikiTheme->_path . $from)), $attrib);
705             }
706         }
707     }
708     if (!empty($WikiTheme->dumped_buttons) and is_array($WikiTheme->dumped_buttons)) {
709         //if ($WikiTheme->dumped_buttons) $zip->addRegularFile("images/buttons", "", $attrib);
710         foreach ($WikiTheme->dumped_buttons as $text => $img_file) {
711             if (($from = $WikiTheme->_findFile($img_file, true)) and basename($from)) {
712                 $target = "images/buttons/".basename($img_file);
713                 if (check_php_version(4,3))
714                     $zip->addRegularFile($target, file_get_contents($WikiTheme->_path . $from), $attrib);
715                 else
716                     $zip->addRegularFile($target, join('', file($WikiTheme->_path . $from)), $attrib);
717             }
718         }
719     }
720     if (!empty($WikiTheme->dumped_css) and is_array($WikiTheme->dumped_css)) {
721         foreach ($WikiTheme->dumped_css as $css_file) {
722             if (($from = $WikiTheme->_findFile(basename($css_file), true)) and basename($from)) {
723                 $target = basename($css_file);
724                 if (check_php_version(4,3))
725                     $zip->addRegularFile($target, file_get_contents($WikiTheme->_path . $from), $attrib);
726                 else
727                     $zip->addRegularFile($target, join('', file($WikiTheme->_path . $from)), $attrib);
728             }
729         }
730     }
731
732     $zip->finish();
733     if (check_php_version(4,1)) {
734         global $ErrorManager;
735         $ErrorManager->popErrorHandler();
736     }
737     $WikiTheme->HTML_DUMP_SUFFIX = '';
738     $WikiTheme->DUMP_MODE = false;
739     $WikiTheme->_MoreAttr['body'] = $_bodyAttr;
740 }
741
742
743 ////////////////////////////////////////////////////////////////
744 //
745 //  Functions for restoring.
746 //
747 ////////////////////////////////////////////////////////////////
748
749 function SavePage (&$request, &$pageinfo, $source, $filename)
750 {
751     static $overwite_all = false;
752     $pagedata    = $pageinfo['pagedata'];    // Page level meta-data.
753     $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
754
755     if (empty($pageinfo['pagename'])) {
756         PrintXML(HTML::dt(HTML::strong(_("Empty pagename!"))));
757         return;
758     }
759
760     if (empty($versiondata['author_id']))
761         $versiondata['author_id'] = $versiondata['author'];
762
763     // remove invalid backend specific chars. utf8 issues mostly
764     $pagename_check = new WikiPagename($pageinfo['pagename']);
765     if (!$pagename_check->isValid()) {
766         PrintXML(HTML::dt(HTML::strong(_("Invalid pagename!")." ".$pageinfo['pagename'])));
767         return;
768     }
769     $pagename = $pagename_check->getName();
770     $content  = $pageinfo['content'];
771
772     if ($pagename == _("InterWikiMap"))
773         $content = _tryinsertInterWikiMap($content);
774
775     $dbi =& $request->_dbi;
776     $page = $dbi->getPage($pagename);
777
778     // Try to merge if updated pgsrc contents are different. This
779     // whole thing is hackish
780     //
781     // TODO: try merge unless:
782     // if (current contents = default contents && pgsrc_version >=
783     // pgsrc_version) then just upgrade this pgsrc
784     $needs_merge = false;
785     $merging = false;
786     $overwrite = false;
787
788     if ($request->getArg('merge')) {
789         $merging = true;
790     }
791     else if ($request->getArg('overwrite')) {
792         $overwrite = true;
793     }
794
795     $current = $page->getCurrentRevision();
796     $skip = false;
797     $edit = $request->getArg('edit');
798     if ($merging) { 
799         if (isset($edit['keep_old'])) {
800             $merging = false;
801             $skip = true;
802         }
803         elseif (isset($edit['overwrite'])) {
804             $merging = false;
805             $overwrite = true;
806         }
807         elseif ( $current and (! $current->hasDefaultContents())
808          && ($current->getPackedContent() != $content) ) 
809         {
810             include_once('lib/editpage.php');
811             $request->setArg('pagename', $pagename);
812             $v = $current->getVersion();
813             $request->setArg('revision', $current->getVersion());
814             $p = new LoadFileConflictPageEditor($request);
815             $p->_content = $content;
816             $p->_currentVersion = $v - 1;
817             $p->editPage($saveFailed = true);
818             return; //early return
819        }
820     }
821     if (!$skip)
822       foreach ($pagedata as $key => $value) {
823         if (!empty($value))
824             $page->set($key, $value);
825       }
826
827     $mesg = HTML::dd();
828     if ($source)
829         $mesg->pushContent(' ', fmt("from %s", $source));
830
831
832     if (!$current) {
833         //FIXME: This should not happen! (empty vdata, corrupt cache or db)
834         $current = $page->getCurrentRevision();
835     }
836     if ($current->getVersion() == 0) {
837         $mesg->pushContent(' - ', _("New page"));
838         $isnew = true;
839     }
840     else {
841         if ( (! $current->hasDefaultContents())
842              && ($current->getPackedContent() != $content) ) {
843             if ($overwrite) {
844                 $mesg->pushContent(' ',
845                                    fmt("has edit conflicts - overwriting anyway"));
846                 $skip = false;
847                 if (substr_count($source, 'pgsrc')) {
848                     $versiondata['author'] = _("The PhpWiki programming team");
849                     // but leave authorid as userid who loaded the file
850                 }
851             }
852             else {
853                 if (isset($edit['keep_old'])) {
854                     $mesg->pushContent(' ', fmt("keep old"));
855                 } else {
856                     $mesg->pushContent(' ', fmt("has edit conflicts - skipped"));
857                     $needs_merge = true; // hackish, to display the buttons
858                 }
859                 $skip = true;
860             }
861         }
862         else if ($current->getPackedContent() == $content
863                  && $current->get('author') == $versiondata['author']) {
864             // The page metadata is already changed, we don't need a new revision.
865             // This was called previously "is identical to current version %d - skipped"
866             // which is wrong, since the pagedata was stored, not skipped.
867             $mesg->pushContent(' ',
868                                fmt("content is identical to current version %d - no new revision created",
869                                    $current->getVersion()));
870             $skip = true;
871         }
872         $isnew = false;
873     }
874
875     if (! $skip ) {
876         // in case of failures print the culprit:
877         if (!isa($request,'MockRequest')) {
878             PrintXML(HTML::dt(WikiLink($pagename))); flush();
879         }
880         $new = $page->save($content, WIKIDB_FORCE_CREATE, $versiondata);
881         $dbi->touch();
882         $mesg->pushContent(' ', fmt("- saved to database as version %d",
883                                     $new->getVersion()));
884     }
885     if ($needs_merge) {
886         $f = $source;
887         // hackish, $source contains needed path+filename
888         $f = str_replace(sprintf(_("MIME file %s"), ''), '', $f);
889         $f = str_replace(sprintf(_("Serialized file %s"), ''), '', $f);
890         $f = str_replace(sprintf(_("plain file %s"), ''), '', $f);
891         //check if uploaded file? they pass just the content, but the file is gone
892         if (@stat($f)) {
893             global $WikiTheme;
894             $meb = Button(array('action' => 'loadfile',
895                                 'merge'=> true,
896                                 'source'=> $f),
897                           _("Merge Edit"),
898                           _("PhpWikiAdministration"),
899                           'wikiadmin');
900             $owb = Button(array('action' => 'loadfile',
901                                 'overwrite'=> true,
902                                 'source'=> $f),
903                           _("Restore Anyway"),
904                           _("PhpWikiAdministration"),
905                           'wikiunsafe');
906             $mesg->pushContent(' ', $meb, " ", $owb);
907             if (!$overwite_all) {
908                 $args = $request->getArgs();
909                 $args['overwrite'] = 1;
910                 $owb = Button($args,
911                               _("Overwrite All"),
912                               _("PhpWikiAdministration"),
913                               'wikiunsafe');
914                 $mesg->pushContent(HTML::div(array('class' => 'hint'), $owb));
915                 $overwite_all = true;
916             }
917         } else {
918             $mesg->pushContent(HTML::em(_(" Sorry, cannot merge.")));
919         }
920     }
921
922     if (!isa($request,'MockRequest')) {
923       if ($skip)
924         PrintXML(HTML::dt(HTML::em(WikiLink($pagename))), $mesg);
925       else
926         PrintXML($mesg);
927       flush();
928     }
929 }
930
931 // action=revert (by diff)
932 function RevertPage (&$request)
933 {
934     $mesg = HTML::dd();
935     $pagename = $request->getArg('pagename');
936     $version = $request->getArg('version');
937     if (!$version) {
938         PrintXML(HTML::dt(fmt("Revert")," ",WikiLink($pagename)),
939                  HTML::dd(_("missing required version argument")));
940         return;
941     }
942     $dbi =& $request->_dbi;
943     $page = $dbi->getPage($pagename);
944     $current = $page->getCurrentRevision();
945     $currversion = $current->getVersion();
946     if ($currversion == 0) {
947         $mesg->pushContent(' ', _("no page content"));
948         PrintXML(HTML::dt(fmt("Revert")," ",WikiLink($pagename)),
949                  $mesg);
950         flush();
951         return;
952     }
953     if ($currversion == $version) {
954         $mesg->pushContent(' ', _("same version page"));
955         PrintXML(HTML::dt(fmt("Revert")," ",WikiLink($pagename)),
956                  $mesg);
957         flush();
958         return;
959     }
960     if ($request->getArg('cancel')) {
961         $mesg->pushContent(' ', _("Cancelled"));
962         PrintXML(HTML::dt(fmt("Revert")," ",WikiLink($pagename)),
963                  $mesg);
964         flush();
965         return;
966     }
967     if (!$request->getArg('verify')) {
968         $mesg->pushContent(HTML::br(),
969                            _("Are you sure?"),
970                            HTML::br(),
971                            HTML::form(array('action' => $request->getPostURL(),
972                                             'method' => 'post'),
973                                       HiddenInputs($request->getArgs(), false, array('verify')),
974                                       HiddenInputs(array('verify' => 1)),
975                                       Button('submit:verify', _("Yes"), 'button'),
976                                       HTML::Raw('&nbsp;'),
977                                       Button('submit:cancel', _("Cancel"), 'button')),
978                            HTML::hr());
979         $rev = $page->getRevision($version);
980         $html = HTML(HTML::dt(fmt("Revert %s to version $version", WikiLink($pagename))), 
981                      $mesg,
982                      $rev->getTransformedContent()); 
983         $template = Template('browse', 
984                              array('CONTENT' => $html));
985         GeneratePage($template, $pagename, $rev);
986         $request->checkValidators();
987         flush();
988         return;
989     }
990     $rev = $page->getRevision($version);
991     $content = $rev->getPackedContent();
992     $versiondata = $rev->_data;
993     $versiondata['summary'] = sprintf(_("revert to version %d"), $version);
994     $new = $page->save($content, $currversion + 1, $versiondata);
995     $dbi->touch();
996     
997     $pagelink = WikiLink($pagename);
998     $mesg->pushContent(fmt("Revert: %s", $pagelink), 
999                        fmt("- version %d saved to database as version %d",
1000                            $version, $new->getVersion()));
1001     // Force browse of current page version.
1002     $request->setArg('version', false);
1003     $template = Template('savepage', array());
1004     $template->replace('CONTENT', $new->getTransformedContent());
1005     
1006     GeneratePage($template, $mesg, $new);
1007     flush();
1008 }
1009
1010 function _tryinsertInterWikiMap($content) {
1011     $goback = false;
1012     if (strpos($content, "<verbatim>")) {
1013         //$error_html = " The newly loaded pgsrc already contains a verbatim block.";
1014         $goback = true;
1015     }
1016     if (!$goback && !defined('INTERWIKI_MAP_FILE')) {
1017         $error_html = sprintf(" "._("%s: not defined"), "INTERWIKI_MAP_FILE");
1018         $goback = true;
1019     }
1020     $mapfile = FindFile(INTERWIKI_MAP_FILE,1);
1021     if (!$goback && !file_exists($mapfile)) {
1022         $error_html = sprintf(" "._("%s: file not found"), INTERWIKI_MAP_FILE);
1023         $goback = true;
1024     }
1025
1026     if (!empty($error_html))
1027         trigger_error(_("Default InterWiki map file not loaded.")
1028                       . $error_html, E_USER_NOTICE);
1029     if ($goback)
1030         return $content;
1031
1032     // if loading from virgin setup do echo, otherwise trigger_error E_USER_NOTICE
1033     if (!isa($GLOBALS['request'], 'MockRequest'))
1034         echo sprintf(_("Loading InterWikiMap from external file %s."), $mapfile),"<br />";
1035
1036     $fd = fopen ($mapfile, "rb");
1037     $data = fread ($fd, filesize($mapfile));
1038     fclose ($fd);
1039     $content = $content . "\n<verbatim>\n$data</verbatim>\n";
1040     return $content;
1041 }
1042
1043 function ParseSerializedPage($text, $default_pagename, $user)
1044 {
1045     if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
1046         return false;
1047
1048     $pagehash = unserialize($text);
1049
1050     // Split up pagehash into four parts:
1051     //   pagename
1052     //   content
1053     //   page-level meta-data
1054     //   revision-level meta-data
1055
1056     if (!defined('FLAG_PAGE_LOCKED'))
1057         define('FLAG_PAGE_LOCKED', 1);
1058     $pageinfo = array('pagedata'    => array(),
1059                       'versiondata' => array());
1060
1061     $pagedata = &$pageinfo['pagedata'];
1062     $versiondata = &$pageinfo['versiondata'];
1063
1064     // Fill in defaults.
1065     if (empty($pagehash['pagename']))
1066         $pagehash['pagename'] = $default_pagename;
1067     if (empty($pagehash['author'])) {
1068         $pagehash['author'] = $user->getId();
1069     }
1070
1071     foreach ($pagehash as $key => $value) {
1072         switch($key) {
1073             case 'pagename':
1074             case 'version':
1075             case 'hits':
1076                 $pageinfo[$key] = $value;
1077                 break;
1078             case 'content':
1079                 $pageinfo[$key] = join("\n", $value);
1080                 break;
1081             case 'flags':
1082                 if (($value & FLAG_PAGE_LOCKED) != 0)
1083                     $pagedata['locked'] = 'yes';
1084                 break;
1085             case 'owner':
1086             case 'created':
1087                 $pagedata[$key] = $value;
1088                 break;
1089             case 'acl':
1090             case 'perm':
1091                 $pagedata['perm'] = ParseMimeifiedPerm($value);
1092                 break;
1093             case 'lastmodified':
1094                 $versiondata['mtime'] = $value;
1095                 break;
1096             case 'author':
1097             case 'author_id':
1098             case 'summary':
1099                 $versiondata[$key] = $value;
1100                 break;
1101         }
1102     }
1103     if (empty($pagehash['charset']))
1104         $pagehash['charset'] = 'iso-8859-1';
1105     // compare to target charset
1106     if (strtolower($pagehash['charset']) != strtolower($GLOBALS['charset'])) {
1107         $pageinfo['content'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['content']);
1108         $pageinfo['pagename'] = charset_convert($params['charset'], $GLOBALS['charset'], $pageinfo['pagename']);
1109     }
1110     return $pageinfo;
1111 }
1112
1113 function SortByPageVersion ($a, $b) {
1114     return $a['version'] - $b['version'];
1115 }
1116
1117 /**
1118  * Security alert! We should not allow to import config.ini into our wiki (or from a sister wiki?)
1119  * because the sql passwords are in plaintext there. And the webserver must be able to read it.
1120  * Detected by Santtu Jarvi.
1121  */
1122 function LoadFile (&$request, $filename, $text = false, $mtime = false)
1123 {
1124     if (preg_match("/config$/", dirname($filename))             // our or other config
1125         and preg_match("/config.*\.ini/", basename($filename))) // backups and other versions also
1126     {
1127         trigger_error(sprintf("Refused to load %s", $filename), E_USER_WARNING);
1128         return;
1129     }
1130     if (!is_string($text)) {
1131         // Read the file.
1132         $stat  = stat($filename);
1133         $mtime = $stat[9];
1134         $text  = implode("", file($filename));
1135     }
1136
1137     if (! $request->getArg('start_debug')) @set_time_limit(30); // Reset watchdog
1138     else @set_time_limit(240);
1139
1140     // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
1141     $basename = basename("/dummy/" . $filename);
1142
1143     if (!$mtime)
1144         $mtime = time();    // Last resort.
1145
1146     // DONE: check source - target charset for content and pagename
1147     // but only for pgsrc'ed content, not from the browser.
1148
1149     $default_pagename = rawurldecode($basename);
1150     if ( ($parts = ParseMimeifiedPages($text)) ) {
1151         if (count($parts) > 1)
1152             $overwrite = $request->getArg('overwrite');
1153         usort($parts, 'SortByPageVersion');
1154         foreach ($parts as $pageinfo) {
1155             // force overwrite
1156             if (count($parts) > 1)
1157                 $request->setArg('overwrite', 1);
1158             SavePage($request, $pageinfo, sprintf(_("MIME file %s"),
1159                                                   $filename), $basename);
1160     }
1161         if (count($parts) > 1)
1162             if ($overwrite) 
1163                 $request->setArg('overwrite', $overwrite);
1164             else     
1165                 unset($request->_args['overwrite']);
1166     }
1167     else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename,
1168                                                $request->getUser())) ) {
1169         SavePage($request, $pageinfo, sprintf(_("Serialized file %s"),
1170                                               $filename), $basename);
1171     }
1172     else {
1173         // plain old file
1174         $user = $request->getUser();
1175
1176         $file_charset = 'iso-8859-1';
1177         // compare to target charset
1178         if ($file_charset != strtolower($GLOBALS['charset'])) {
1179             $text = charset_convert($file_charset, $GLOBALS['charset'], $text);
1180             $default_pagename = charset_convert($file_charset, $GLOBALS['charset'], $default_pagename);
1181         }
1182
1183         // Assume plain text file.
1184         $pageinfo = array('pagename' => $default_pagename,
1185                           'pagedata' => array(),
1186                           'versiondata'
1187                           => array('author' => $user->getId()),
1188                           'content'  => preg_replace('/[ \t\r]*\n/', "\n",
1189                                                      chop($text))
1190                           );
1191         SavePage($request, $pageinfo, sprintf(_("plain file %s"), $filename),
1192                  $basename);
1193     }
1194 }
1195
1196 function LoadZip (&$request, $zipfile, $files = false, $exclude = false) {
1197     $zip = new ZipReader($zipfile);
1198     $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1199     while (list ($fn, $data, $attrib) = $zip->readFile()) {
1200         // FIXME: basename("filewithnoslashes") seems to return
1201         // garbage sometimes.
1202         $fn = basename("/dummy/" . $fn);
1203         if ( ($files && !in_array($fn, $files))
1204              || ($exclude && in_array($fn, $exclude)) ) {
1205             PrintXML(HTML::dt(WikiLink($fn)),
1206                      HTML::dd(_("Skipping")));
1207             flush();
1208             continue;
1209         }
1210         longer_timeout($timeout);       // longer timeout per page
1211         LoadFile($request, $fn, $data, $attrib['mtime']);
1212     }
1213 }
1214
1215 function LoadDir (&$request, $dirname, $files = false, $exclude = false) {
1216     $fileset = new LimitedFileSet($dirname, $files, $exclude);
1217
1218     if (!$files and ($skiplist = $fileset->getSkippedFiles())) {
1219         PrintXML(HTML::dt(HTML::strong(_("Skipping"))));
1220         $list = HTML::ul();
1221         foreach ($skiplist as $file)
1222             $list->pushContent(HTML::li(WikiLink($file)));
1223         PrintXML(HTML::dd($list));
1224     }
1225
1226     // Defer HomePage loading until the end. If anything goes wrong
1227     // the pages can still be loaded again.
1228     $files = $fileset->getFiles();
1229     if (in_array(HOME_PAGE, $files)) {
1230         $files = array_diff($files, array(HOME_PAGE));
1231         $files[] = HOME_PAGE;
1232     }
1233     $timeout = (! $request->getArg('start_debug')) ? 20 : 120;
1234     foreach ($files as $file) {
1235         longer_timeout($timeout);       // longer timeout per page
1236         if (substr($file,-1,1) != '~')  // refuse to load backup files
1237             LoadFile($request, "$dirname/$file");
1238     }
1239 }
1240
1241 class LimitedFileSet extends FileSet {
1242     function LimitedFileSet($dirname, $_include, $exclude) {
1243         $this->_includefiles = $_include;
1244         $this->_exclude = $exclude;
1245         $this->_skiplist = array();
1246         parent::FileSet($dirname);
1247     }
1248
1249     function _filenameSelector($fn) {
1250         $incl = &$this->_includefiles;
1251         $excl = &$this->_exclude;
1252
1253         if ( ($incl && !in_array($fn, $incl))
1254              || ($excl && in_array($fn, $excl)) ) {
1255             $this->_skiplist[] = $fn;
1256             return false;
1257         } else {
1258             return true;
1259         }
1260     }
1261
1262     function getSkippedFiles () {
1263         return $this->_skiplist;
1264     }
1265 }
1266
1267
1268 function IsZipFile ($filename_or_fd)
1269 {
1270     // See if it looks like zip file
1271     if (is_string($filename_or_fd))
1272     {
1273         $fd    = fopen($filename_or_fd, "rb");
1274         $magic = fread($fd, 4);
1275         fclose($fd);
1276     }
1277     else
1278     {
1279         $fpos  = ftell($filename_or_fd);
1280         $magic = fread($filename_or_fd, 4);
1281         fseek($filename_or_fd, $fpos);
1282     }
1283
1284     return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
1285 }
1286
1287
1288 function LoadAny (&$request, $file_or_dir, $files = false, $exclude = false)
1289 {
1290     // Try urlencoded filename for accented characters.
1291     if (!file_exists($file_or_dir)) {
1292         // Make sure there are slashes first to avoid confusing phps
1293         // with broken dirname or basename functions.
1294         // FIXME: windows uses \ and :
1295         if (is_integer(strpos($file_or_dir, "/"))) {
1296             $file_or_dir = FindFile($file_or_dir);
1297             // Panic
1298             if (!file_exists($file_or_dir))
1299                 $file_or_dir = dirname($file_or_dir) . "/"
1300                     . urlencode(basename($file_or_dir));
1301         } else {
1302             // This is probably just a file.
1303             $file_or_dir = urlencode($file_or_dir);
1304         }
1305     }
1306
1307     $type = filetype($file_or_dir);
1308     if ($type == 'link') {
1309         // For symbolic links, use stat() to determine
1310         // the type of the underlying file.
1311         list(,,$mode) = stat($file_or_dir);
1312         $type = ($mode >> 12) & 017;
1313         if ($type == 010)
1314             $type = 'file';
1315         elseif ($type == 004)
1316             $type = 'dir';
1317     }
1318
1319     if (! $type) {
1320         $request->finish(fmt("Empty or not existing source. Unable to load: %s", $file_or_dir));
1321     }
1322     else if ($type == 'dir') {
1323         LoadDir($request, $file_or_dir, $files, $exclude);
1324     }
1325     else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
1326     {
1327         $request->finish(fmt("Bad file type: %s", $type));
1328     }
1329     else if (IsZipFile($file_or_dir)) {
1330         LoadZip($request, $file_or_dir, $files, $exclude);
1331     }
1332     else /* if (!$files || in_array(basename($file_or_dir), $files)) */
1333     {
1334         LoadFile($request, $file_or_dir);
1335     }
1336 }
1337
1338 function LoadFileOrDir (&$request)
1339 {
1340     $source = $request->getArg('source');
1341     $finder = new FileFinder;
1342     $source = $finder->slashifyPath($source);
1343     $page = rawurldecode(basename($source));
1344     StartLoadDump($request, fmt("Loading '%s'", 
1345         HTML(dirname($source),
1346              dirname($source) ? "/" : "",
1347              WikiLink($page,'auto'))));
1348     echo "<dl>\n";
1349     LoadAny($request, $source);
1350     echo "</dl>\n";
1351     EndLoadDump($request);
1352 }
1353
1354 /**
1355  * HomePage was not found so first-time install is supposed to run.
1356  * - import all pgsrc pages.
1357  * - Todo: installer interface to edit config/config.ini settings
1358  * - Todo: ask for existing old index.php to convert to config/config.ini
1359  * - Todo: theme-specific pages: 
1360  *   blog - HomePage, ADMIN_USER/Blogs
1361  */
1362 function SetupWiki (&$request)
1363 {
1364     global $GenericPages, $LANG;
1365
1366     //FIXME: This is a hack (err, "interim solution")
1367     // This is a bogo-bogo-login:  Login without
1368     // saving login information in session state.
1369     // This avoids logging in the unsuspecting
1370     // visitor as "The PhpWiki programming team".
1371     //
1372     // This really needs to be cleaned up...
1373     // (I'm working on it.)
1374     $real_user = $request->_user;
1375     if (ENABLE_USER_NEW)
1376         $request->_user = new _BogoUser(_("The PhpWiki programming team"));
1377
1378     else
1379         $request->_user = new WikiUser($request, _("The PhpWiki programming team"),
1380                                        WIKIAUTH_BOGO);
1381
1382     StartLoadDump($request, _("Loading up virgin wiki"));
1383     echo "<dl>\n";
1384
1385     $pgsrc = FindLocalizedFile(WIKI_PGSRC);
1386     $default_pgsrc = FindFile(DEFAULT_WIKI_PGSRC);
1387
1388     $request->setArg('overwrite', true);
1389     if ($default_pgsrc != $pgsrc) {
1390         LoadAny($request, $default_pgsrc, $GenericPages);
1391     }
1392     $request->setArg('overwrite', false);
1393     LoadAny($request, $pgsrc);
1394     $dbi =& $request->_dbi;
1395
1396     // Ensure that all mandatory pages are loaded
1397     $finder = new FileFinder;
1398     foreach (array_merge(explode(':','Help/OldTextFormattingRules:Help/TextFormattingRules:PhpWikiAdministration'),
1399                          $GLOBALS['AllActionPages'],
1400                          array(constant('HOME_PAGE'))) as $f) 
1401     {
1402         $page = gettext($f);
1403         $epage = urlencode($page);
1404         if (! $dbi->isWikiPage($page) ) {
1405             // translated version provided?
1406             if ($lf = FindLocalizedFile($pgsrc . $finder->_pathsep . $epage, 1)) {
1407                 LoadAny($request, $lf);
1408             } else { // load english version of required action page
1409                 LoadAny($request, FindFile(DEFAULT_WIKI_PGSRC . $finder->_pathsep . urlencode($f)));
1410                 $page = $f;
1411             }
1412         }
1413         if (! $dbi->isWikiPage($page)) {
1414             trigger_error(sprintf("Mandatory file %s couldn't be loaded!", $page),
1415                           E_USER_WARNING);
1416         }
1417     }
1418
1419     echo "</dl>\n";
1420     EndLoadDump($request);
1421 }
1422
1423 function LoadPostFile (&$request)
1424 {
1425     $upload = $request->getUploadedFile('file');
1426
1427     if (!$upload)
1428         $request->finish(_("No uploaded file to upload?")); // FIXME: more concise message
1429
1430
1431     // Dump http headers.
1432     StartLoadDump($request, sprintf(_("Uploading %s"), $upload->getName()));
1433     echo "<dl>\n";
1434
1435     $fd = $upload->open();
1436     if (IsZipFile($fd))
1437         LoadZip($request, $fd, false, array(_("RecentChanges")));
1438     else
1439         LoadFile($request, $upload->getName(), $upload->getContents());
1440
1441     echo "</dl>\n";
1442     EndLoadDump($request);
1443 }
1444
1445 /**
1446  $Log: not supported by cvs2svn $
1447  Revision 1.149  2007/01/03 21:25:10  rurban
1448  Use convert_charset()
1449
1450  Revision 1.148  2007/01/02 13:21:57  rurban
1451  omit want_content if not necessary. support keep_old and overwrite buttons
1452
1453  Revision 1.147  2006/12/22 17:44:15  rurban
1454  support importing foreign charsets. e.g latin1 => utf8
1455
1456  Revision 1.146  2006/12/17 18:35:23  rurban
1457  Create the right subdirectory name, urlencoded.
1458
1459  Revision 1.145  2006/09/06 06:01:18  rurban
1460  support loadfile multipart archives automatically
1461
1462  Revision 1.144  2006/08/25 22:06:13  rurban
1463  args fix to pass $args to the template
1464
1465  Revision 1.143  2006/08/25 21:48:39  rurban
1466  dumphtml subpages
1467
1468  Revision 1.142  2006/03/19 17:16:32  rurban
1469  remove remaining cruft
1470
1471  Revision 1.141  2006/03/19 17:11:32  rurban
1472  add verify to RevertPage, display reverted page as template
1473
1474  Revision 1.140  2006/03/07 20:45:43  rurban
1475  wikihash for php-5.1
1476
1477  Revision 1.139  2005/08/27 18:02:43  rurban
1478  fix and expand pages
1479
1480  Revision 1.138  2005/08/27 09:39:10  rurban
1481  dumphtml when not at admin page: dump the current or given page
1482
1483  Revision 1.137  2005/01/30 23:14:38  rurban
1484  simplify page names
1485
1486  Revision 1.136  2005/01/25 07:07:24  rurban
1487  remove body tags in html dumps, add css and images to zipdumps, simplify printing
1488
1489  Revision 1.135  2004/12/26 17:17:25  rurban
1490  announce dumps - mult.requests to avoid request::finish, e.g. LinkDatabase, PdfOut, ...
1491
1492  Revision 1.134  2004/12/20 16:05:01  rurban
1493  gettext msg unification
1494
1495  Revision 1.133  2004/12/08 12:57:41  rurban
1496  page-specific timeouts for long multi-page requests
1497
1498  Revision 1.132  2004/12/08 01:18:33  rurban
1499  Disallow loading config*.ini files. Detected by Santtu Jarvi.
1500
1501  Revision 1.131  2004/11/30 17:48:38  rurban
1502  just comments
1503
1504  Revision 1.130  2004/11/25 08:28:12  rurban
1505  dont fatal on missing css or imgfiles and actually print the miss
1506
1507  Revision 1.129  2004/11/25 08:11:40  rurban
1508  pass exclude to the get_all_pages backend
1509
1510  Revision 1.128  2004/11/16 16:16:44  rurban
1511  enable Overwrite All for upgrade
1512
1513  Revision 1.127  2004/11/01 10:43:57  rurban
1514  seperate PassUser methods into seperate dir (memory usage)
1515  fix WikiUser (old) overlarge data session
1516  remove wikidb arg from various page class methods, use global ->_dbi instead
1517  ...
1518
1519  Revision 1.126  2004/10/16 15:13:39  rurban
1520  new [Overwrite All] button
1521
1522  Revision 1.125  2004/10/14 19:19:33  rurban
1523  loadsave: check if the dumped file will be accessible from outside.
1524  and some other minor fixes. (cvsclient native not yet ready)
1525
1526  Revision 1.124  2004/10/04 23:44:28  rurban
1527  for older or CGI phps
1528
1529  Revision 1.123  2004/09/25 16:26:54  rurban
1530  deferr notifies (to be improved)
1531
1532  Revision 1.122  2004/09/17 14:25:45  rurban
1533  update comments
1534
1535  Revision 1.121  2004/09/08 13:38:00  rurban
1536  improve loadfile stability by using markup=2 as default for undefined markup-style.
1537  use more refs for huge objects.
1538  fix debug=static issue in WikiPluginCached
1539
1540  Revision 1.120  2004/07/08 19:04:42  rurban
1541  more unittest fixes (file backend, metadata RatingsDb)
1542
1543  Revision 1.119  2004/07/08 15:23:59  rurban
1544  less verbose for tests
1545
1546  Revision 1.118  2004/07/08 13:50:32  rurban
1547  various unit test fixes: print error backtrace on _DEBUG_TRACE; allusers fix; new PHPWIKI_NOMAIN constant for omitting the mainloop
1548
1549  Revision 1.117  2004/07/02 09:55:58  rurban
1550  more stability fixes: new DISABLE_GETIMAGESIZE if your php crashes when loading LinkIcons: failing getimagesize in old phps; blockparser stabilized
1551
1552  Revision 1.116  2004/07/01 09:05:41  rurban
1553  support pages and exclude arguments for all 4 dump methods
1554
1555  Revision 1.115  2004/07/01 08:51:22  rurban
1556  dumphtml: added exclude, print pagename before processing
1557
1558  Revision 1.114  2004/06/28 12:51:41  rurban
1559  improved dumphtml and virgin setup
1560
1561  Revision 1.113  2004/06/27 10:26:02  rurban
1562  oci8 patch by Philippe Vanhaesendonck + some ADODB notes+fixes
1563
1564  Revision 1.112  2004/06/25 14:29:20  rurban
1565  WikiGroup refactoring:
1566    global group attached to user, code for not_current user.
1567    improved helpers for special groups (avoid double invocations)
1568  new experimental config option ENABLE_XHTML_XML (fails with IE, and document.write())
1569  fixed a XHTML validation error on userprefs.tmpl
1570
1571  Revision 1.111  2004/06/21 16:38:55  rurban
1572  fixed the StartLoadDump html argument hack.
1573
1574  Revision 1.110  2004/06/21 16:22:30  rurban
1575  add DEFAULT_DUMP_DIR and HTML_DUMP_DIR constants, for easier cmdline dumps,
1576  fixed dumping buttons locally (images/buttons/),
1577  support pages arg for dumphtml,
1578  optional directory arg for dumpserial + dumphtml,
1579  fix a AllPages warning,
1580  show dump warnings/errors on DEBUG,
1581  don't warn just ignore on wikilens pagelist columns, if not loaded.
1582  RateIt pagelist column is called "rating", not "ratingwidget" (Dan?)
1583
1584  Revision 1.109  2004/06/17 11:31:05  rurban
1585  jump back to label after dump/upgrade
1586
1587  Revision 1.108  2004/06/16 12:43:01  rurban
1588  4.0.6 cannot use this errorhandler (not found)
1589
1590  Revision 1.107  2004/06/14 11:31:37  rurban
1591  renamed global $Theme to $WikiTheme (gforge nameclash)
1592  inherit PageList default options from PageList
1593    default sortby=pagename
1594  use options in PageList_Selectable (limit, sortby, ...)
1595  added action revert, with button at action=diff
1596  added option regex to WikiAdminSearchReplace
1597
1598  Revision 1.106  2004/06/13 13:54:25  rurban
1599  Catch fatals on the four dump calls (as file and zip, as html and mimified)
1600  FoafViewer: Check against external requirements, instead of fatal.
1601  Change output for xhtmldumps: using file:// urls to the local fs.
1602  Catch SOAP fatal by checking for GOOGLE_LICENSE_KEY
1603  Import GOOGLE_LICENSE_KEY and FORTUNE_DIR from config.ini.
1604
1605  Revision 1.105  2004/06/08 19:48:16  rurban
1606  fixed foreign setup: no ugly skipped msg for the GenericPages, load english actionpages if translated not found
1607
1608  Revision 1.104  2004/06/08 13:51:57  rurban
1609  some comments only
1610
1611  Revision 1.103  2004/06/08 10:54:46  rurban
1612  better acl dump representation, read back acl and owner
1613
1614  Revision 1.102  2004/06/06 16:58:51  rurban
1615  added more required ActionPages for foreign languages
1616  install now english ActionPages if no localized are found. (again)
1617  fixed default anon user level to be 0, instead of -1
1618    (wrong "required administrator to view this page"...)
1619
1620  Revision 1.101  2004/06/04 20:32:53  rurban
1621  Several locale related improvements suggested by Pierrick Meignen
1622  LDAP fix by John Cole
1623  reenable admin check without ENABLE_PAGEPERM in the admin plugins
1624
1625  Revision 1.100  2004/05/02 21:26:38  rurban
1626  limit user session data (HomePageHandle and auth_dbi have to invalidated anyway)
1627    because they will not survive db sessions, if too large.
1628  extended action=upgrade
1629  some WikiTranslation button work
1630  revert WIKIAUTH_UNOBTAINABLE (need it for main.php)
1631  some temp. session debug statements
1632
1633  Revision 1.99  2004/05/02 15:10:07  rurban
1634  new finally reliable way to detect if /index.php is called directly
1635    and if to include lib/main.php
1636  new global AllActionPages
1637  SetupWiki now loads all mandatory pages: HOME_PAGE, action pages, and warns if not.
1638  WikiTranslation what=buttons for Carsten to create the missing MacOSX buttons
1639  PageGroupTestOne => subpages
1640  renamed PhpWikiRss to PhpWikiRecentChanges
1641  more docs, default configs, ...
1642
1643  Revision 1.98  2004/04/29 23:25:12  rurban
1644  re-ordered locale init (as in 1.3.9)
1645  fixed loadfile with subpages, and merge/restore anyway
1646    (sf.net bug #844188)
1647
1648  Revision 1.96  2004/04/19 23:13:03  zorloc
1649  Connect the rest of PhpWiki to the IniConfig system.  Also the keyword regular expression is not a config setting
1650
1651  Revision 1.95  2004/04/18 01:11:52  rurban
1652  more numeric pagename fixes.
1653  fixed action=upload with merge conflict warnings.
1654  charset changed from constant to global (dynamic utf-8 switching)
1655
1656  Revision 1.94  2004/03/14 16:36:37  rurban
1657  dont load backup files
1658
1659  Revision 1.93  2004/02/26 03:22:05  rurban
1660  also copy css and images with XHTML Dump
1661
1662  Revision 1.92  2004/02/26 02:25:54  rurban
1663  fix empty and #-anchored links in XHTML Dumps
1664
1665  Revision 1.91  2004/02/24 17:19:37  rurban
1666  debugging helpers only
1667
1668  Revision 1.90  2004/02/24 17:09:24  rurban
1669  fixed \r\r\n with dumping on windows
1670
1671  Revision 1.88  2004/02/22 23:20:31  rurban
1672  fixed DumpHtmlToDir,
1673  enhanced sortby handling in PageList
1674    new button_heading th style (enabled),
1675  added sortby and limit support to the db backends and plugins
1676    for paging support (<<prev, next>> links on long lists)
1677
1678  Revision 1.87  2004/01/26 09:17:49  rurban
1679  * changed stored pref representation as before.
1680    the array of objects is 1) bigger and 2)
1681    less portable. If we would import packed pref
1682    objects and the object definition was changed, PHP would fail.
1683    This doesn't happen with an simple array of non-default values.
1684  * use $prefs->retrieve and $prefs->store methods, where retrieve
1685    understands the interim format of array of objects also.
1686  * simplified $prefs->get() and fixed $prefs->set()
1687  * added $user->_userid and class '_WikiUser' portability functions
1688  * fixed $user object ->_level upgrading, mostly using sessions.
1689    this fixes yesterdays problems with loosing authorization level.
1690  * fixed WikiUserNew::checkPass to return the _level
1691  * fixed WikiUserNew::isSignedIn
1692  * added explodePageList to class PageList, support sortby arg
1693  * fixed UserPreferences for WikiUserNew
1694  * fixed WikiPlugin for empty defaults array
1695  * UnfoldSubpages: added pagename arg, renamed pages arg,
1696    removed sort arg, support sortby arg
1697
1698  Revision 1.86  2003/12/02 16:18:26  carstenklapp
1699  Minor enhancement: Provide more meaningful filenames for WikiDB zip
1700  dumps & snapshots.
1701
1702  Revision 1.85  2003/11/30 18:18:13  carstenklapp
1703  Minor code optimization: use include_once instead of require_once
1704  inside functions that might not always called.
1705
1706  Revision 1.84  2003/11/26 20:47:47  carstenklapp
1707  Redo bugfix: My last refactoring broke merge-edit & overwrite
1708  functionality again, should be fixed now. Sorry.
1709
1710  Revision 1.83  2003/11/20 22:18:54  carstenklapp
1711  New feature: h1 during merge-edit displays WikiLink to original page.
1712  Internal changes: Replaced some hackish url-generation code in
1713  function SavePage (for pgsrc merge-edit) with appropriate Button()
1714  calls.
1715
1716  Revision 1.82  2003/11/18 19:48:01  carstenklapp
1717  Fixed missing gettext _() for button name.
1718
1719  Revision 1.81  2003/11/18 18:28:35  carstenklapp
1720  Bugfix: In the Load File function of PhpWikiAdministration: When doing
1721  a "Merge Edit" or "Restore Anyway", page names containing accented
1722  letters (such as locale/de/pgsrc/G%E4steBuch) would produce a file not
1723  found error (Use FilenameForPage funtion to urlencode page names).
1724
1725  Revision 1.80  2003/03/07 02:46:57  dairiki
1726  Omit checks for safe_mode before set_time_limit().  Just prefix the
1727  set_time_limit() calls with @ so that they fail silently if not
1728  supported.
1729
1730  Revision 1.79  2003/02/26 01:56:05  dairiki
1731  Only zip pages with legal pagenames.
1732
1733  Revision 1.78  2003/02/24 02:05:43  dairiki
1734  Fix "n bytes written" message when dumping HTML.
1735
1736  Revision 1.77  2003/02/21 04:12:05  dairiki
1737  Minor fixes for new cached markup.
1738
1739  Revision 1.76  2003/02/16 19:47:17  dairiki
1740  Update WikiDB timestamp when editing or deleting pages.
1741
1742  Revision 1.75  2003/02/15 03:04:30  dairiki
1743  Fix for WikiUser constructor API change.
1744
1745  Revision 1.74  2003/02/15 02:18:04  dairiki
1746  When default language was English (at least), pgsrc was being
1747  loaded twice.
1748
1749  LimitedFileSet: Fix typo/bug. ($include was being ignored.)
1750
1751  SetupWiki(): Fix bugs in loading of $GenericPages.
1752
1753  Revision 1.73  2003/01/28 21:09:17  zorloc
1754  The get_cfg_var() function should only be used when one is
1755  interested in the value from php.ini or similar. Use ini_get()
1756  instead to get the effective value of a configuration variable.
1757  -- Martin Geisler
1758
1759  Revision 1.72  2003/01/03 22:25:53  carstenklapp
1760  Cosmetic fix to "Merge Edit" & "Overwrite" buttons. Added "The PhpWiki
1761  programming team" as author when loading from pgsrc. Source
1762  reformatting.
1763
1764  Revision 1.71  2003/01/03 02:48:05  carstenklapp
1765  function SavePage: Added loadfile options for overwriting or merge &
1766  compare a loaded pgsrc file with an existing page.
1767
1768  function LoadAny: Added a general error message when unable to load a
1769  file instead of defaulting to "Bad file type".
1770
1771  */
1772
1773 // For emacs users
1774 // Local Variables:
1775 // mode: php
1776 // tab-width: 8
1777 // c-basic-offset: 4
1778 // c-hanging-comment-ender-p: nil
1779 // indent-tabs-mode: nil
1780 // End:
1781 ?>