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