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