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