2 rcs_id('$Id: loadsave.php,v 1.14 2001-12-11 18:21:38 dairiki Exp $');
3 require_once("lib/ziplib.php");
4 require_once("lib/Template.php");
6 function StartLoadDump($title, $html = '')
8 // FIXME: This is a hack
9 echo ereg_replace('</body>.*', '',
10 GeneratePage('MESSAGE', $html, $title, 0));
13 function EndLoadDump()
15 // FIXME: This is a hack
17 echo Element('p', QElement('b', gettext("Complete.")));
18 echo Element('p', "Return to " . LinkExistingWikiWord($GLOBALS['pagename']));
19 echo "</body></html>\n";
23 ////////////////////////////////////////////////////////////////
25 // Functions for dumping.
27 ////////////////////////////////////////////////////////////////
29 function MailifyPage ($page, $nversions = 1)
33 $current = $page->getCurrentRevision();
34 $from = isset($SERVER_ADMIN) ? $SERVER_ADMIN : 'foo@bar';
36 $head = "From $from " . CTime(time()) . "\r\n";
37 $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
38 $head .= "From: $from (PhpWiki)\r\n";
39 $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
40 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n", PHPWIKI_VERSION);
42 $iter = $page->getAllRevisions();
44 while ($revision = $iter->next()) {
45 $parts[] = MimeifyPageRevision($revision);
46 if ($nversions > 0 && count($parts) >= $nversions)
49 if (count($parts) > 1)
50 return $head . MimeMultipart($parts);
52 return $head . $parts[0];
56 * Compute filename to used for storing contents of a wiki page.
58 * Basically we do a rawurlencode() which encodes everything
59 * except ASCII alphanumerics and '.', '-', and '_'.
61 * But we also want to encode leading dots to avoid filenames
62 * like '.', and '..'. (Also, there's no point in generating
63 * "hidden" file names, like '.foo'.)
65 * @param $pagename string Pagename.
66 * @return string Filename for page.
68 function FilenameForPage ($pagename)
70 $enc = rawurlencode($pagename);
71 return preg_replace('/^\./', '%2e', $enc);
75 * The main() function which generates a zip archive of a PhpWiki.
77 * If $include_archive is false, only the current version of each page
78 * is included in the zip file; otherwise all archived versions are
81 function MakeWikiZip ($dbi, $request)
83 if ($request->getArg('include') == 'all') {
84 $zipname = "wikidb.zip";
85 $include_archive = true;
88 $zipname = "wiki.zip";
89 $include_archive = false;
94 $zip = new ZipWriter("Created by PhpWiki", $zipname);
96 $pages = $dbi->getAllPages();
97 while ($page = $pages->next()) {
98 set_time_limit(30); // Reset watchdog.
100 $current = $page->getCurrentRevision();
101 if ($current->getVersion() == 0)
105 $attrib = array('mtime' => $current->get('mtime'),
107 if ($page->get('locked'))
108 $attrib['write_protected'] = 1;
110 if ($include_archive)
111 $content = MailifyPage($page, 0);
113 $content = MailifyPage($page);
115 $zip->addRegularFile( FilenameForPage($page->getName()),
121 function DumpToDir ($dbi, $request)
123 $directory = $request->getArg('directory');
124 if (empty($directory))
125 ExitWiki(gettext("You must specify a directory to dump to"));
127 // see if we can access the directory the user wants us to use
128 if (! file_exists($directory)) {
129 if (! mkdir($directory, 0755))
130 ExitWiki("Cannot create directory '$directory'<br>\n");
132 $html = "Created directory '$directory' for the page dump...<br>\n";
134 $html = "Using directory '$directory'<br>\n";
137 StartLoadDump("Dumping Pages", $html);
139 $pages = $dbi->getAllPages();
141 while ($page = $pages->next()) {
143 $enc_name = htmlspecialchars($page->getName());
144 $filename = FilenameForPage($page->getName());
146 echo "<br>$enc_name ... ";
147 if($pagename != $filename)
148 echo "<small>saved as $filename</small> ... ";
150 $data = MailifyPage($page);
152 if ( !($fd = fopen("$directory/$filename", "w")) )
153 ExitWiki("<b>couldn't open file '$directory/$filename' for writing</b>\n");
155 $num = fwrite($fd, $data, strlen($data));
156 echo "<small>$num bytes written</small>\n";
159 assert($num == strlen($data));
166 ////////////////////////////////////////////////////////////////
168 // Functions for restoring.
170 ////////////////////////////////////////////////////////////////
172 function SavePage ($dbi, $pageinfo, $source, $filename)
174 $pagedata = $pageinfo['pagedata']; // Page level meta-data.
175 $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
177 if (empty($pageinfo['pagename'])) {
178 echo Element('dd'). Element('dt', QElement('b', "Empty pagename!"));
182 if (empty($versiondata['author_id']))
183 $versiondata['author_id'] = $versiondata['author'];
185 $pagename = $pageinfo['pagename'];
186 $content = $pageinfo['content'];
188 $page = $dbi->getPage($pagename);
190 foreach ($pagedata as $key => $value) {
192 $page->set($key, $value);
198 $mesg[] = sprintf(gettext("from %s"), $source);
200 $current = $page->getCurrentRevision();
201 if ($current->getVersion() == 0) {
202 $mesg[] = gettext("new page");
206 if ($current->getPackedContent() == $content
207 && $current->get('author') == $versiondata['author']) {
208 $mesg[] = sprintf(gettext("is identical to current version %d"),
209 $current->getVersion());
210 $mesg[] = gettext("- skipped");
217 $new = $page->createRevision(WIKIDB_FORCE_CREATE, $content,
219 ExtractWikiPageLinks($content));
221 $mesg[] = sprintf(gettext("- saved as version %d"), $new->getVersion());
224 print( Element('dt', LinkExistingWikiWord($pagename))
225 . QElement('dd', join(" ", $mesg))
230 function ParseSerializedPage($text, $default_pagename)
232 if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
235 $pagehash = unserialize($text);
237 // Split up pagehash into four parts:
240 // page-level meta-data
241 // revision-level meta-data
243 if (!defined('FLAG_PAGE_LOCKED'))
244 define('FLAG_PAGE_LOCKED', 1);
245 $pageinfo = array('pagedata' => array(),
246 'versiondata' => array());
248 $pagedata = &$pageinfo['pagedata'];
249 $versiondata = &$pageinfo['versiondata'];
252 if (empty($pagehash['pagename']))
253 $pagehash['pagename'] = $default_pagename;
254 if (empty($pagehash['author']))
255 $pagehash['author'] = $GLOBALS['user']->id();
258 foreach ($pagehash as $key => $value) {
262 $pageinfo[$key] = $value;
265 $pageinfo[$key] = join("\n", $value);
267 if (($value & FLAG_PAGE_LOCKED) != 0)
268 $pagedata['locked'] = 'yes';
271 $pagedata[$key] = $value;
274 $versiondata['mtime'] = $value;
277 $versiondata[$key] = $value;
284 function SortByPageVersion ($a, $b) {
285 return $a['version'] - $b['version'];
288 function LoadFile ($dbi, $filename, $text = false, $mtime = false)
290 if (!is_string($text)) {
292 $stat = stat($filename);
294 $text = implode("", file($filename));
297 set_time_limit(30); // Reset watchdog.
299 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
300 $basename = basename("/dummy/" . $filename);
303 $mtime = time(); // Last resort.
305 $defaults = array('author' => $GLOBALS['user']->id(),
306 'pagename' => rawurldecode($basename));
308 $default_pagename = rawurldecode($basename);
310 if ( ($parts = ParseMimeifiedPages($text)) ) {
311 usort($parts, 'SortByPageVersion');
312 foreach ($parts as $pageinfo)
313 SavePage($dbi, $pageinfo, "MIME file $filename", $basename);
315 else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename)) ) {
316 SavePage($dbi, $pageinfo, "Serialized file $filename", $basename);
319 // Assume plain text file.
320 $pageinfo = array('pagename' => $default_pagename,
321 'pagedata' => array(),
323 => array('author' => $GLOBALS['user']->id()),
325 => preg_replace('/[ \t\r]*\n/', "\n", chop($text))
327 SavePage($dbi, $pageinfo, "plain file $filename", $basename);
331 function LoadZip ($dbi, $zipfile, $files = false, $exclude = false)
333 $zip = new ZipReader($zipfile);
334 while (list ($fn, $data, $attrib) = $zip->readFile())
336 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
337 $fn = basename("/dummy/" . $fn);
338 if ( ($files && !in_array($fn, $files))
339 || ($exclude && in_array($fn, $exclude)) )
341 print Element('dt', LinkExistingWikiWord($fn)) . QElement('dd', 'Skipping');
345 LoadFile($dbi, $fn, $data, $attrib['mtime']);
349 function LoadDir ($dbi, $dirname, $files = false, $exclude = false)
351 $handle = opendir($dir = $dirname);
352 while ($fn = readdir($handle))
354 if ($fn[0] == '.' || filetype("$dir/$fn") != 'file')
357 if ( ($files && !in_array($fn, $files))
358 || ($exclude && in_array($fn, $exclude)) )
360 print Element('dt', LinkExistingWikiWord($fn)) . QElement('dd', 'Skipping');
364 LoadFile($dbi, "$dir/$fn");
369 function IsZipFile ($filename_or_fd)
371 // See if it looks like zip file
372 if (is_string($filename_or_fd))
374 $fd = fopen($filename_or_fd, "rb");
375 $magic = fread($fd, 4);
380 $fpos = ftell($filename_or_fd);
381 $magic = fread($filename_or_fd, 4);
382 fseek($filename_or_fd, $fpos);
385 return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
389 function LoadAny ($dbi, $file_or_dir, $files = false, $exclude = false)
391 $type = filetype($file_or_dir);
395 LoadDir($dbi, $file_or_dir, $files, $exclude);
397 else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
399 ExitWiki("Bad file type: $type");
401 else if (IsZipFile($file_or_dir))
403 LoadZip($dbi, $file_or_dir, $files, $exclude);
405 else /* if (!$files || in_array(basename($file_or_dir), $files)) */
407 LoadFile($dbi, $file_or_dir);
411 function LoadFileOrDir ($dbi, $request)
413 $source = $request->getArg('source');
414 StartLoadDump("Loading '$source'");
416 LoadAny($dbi, $source/*, false, array(gettext('RecentChanges'))*/);
421 function SetupWiki ($dbi)
423 global $GenericPages, $LANG, $user;
425 //FIXME: This is a hack
426 $user->userid = 'The PhpWiki programming team';
428 StartLoadDump('Loading up virgin wiki');
431 LoadAny($dbi, FindLocalizedFile(WIKI_PGSRC)/*, false, $ignore*/);
433 LoadAny($dbi, FindFile(DEFAULT_WIKI_PGSRC), $GenericPages/*, $ignore*/);
439 function LoadPostFile ($dbi, $request)
441 $upload = $request->getUploadedFile('file');
444 ExitWiki('No uploaded file to upload?');
446 // Dump http headers.
447 StartLoadDump("Uploading " . $upload->getName());
450 $fd = $upload->open();
452 LoadZip($dbi, $fd, false, array(gettext('RecentChanges')));
454 Loadfile($dbi, $upload->getName(), $upload->getContents());
465 // c-hanging-comment-ender-p: nil
466 // indent-tabs-mode: nil