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