2 rcs_id('$Id: loadsave.php,v 1.30 2002-01-22 17:01:39 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 $pagelink = LinkExistingWikiWord($request->getArg('pagename'));
19 PrintXML(array(HTML::p(HTML::strong(_("Complete."))),
20 HTML::p(fmt("Return to %s", $pagelink))));
21 echo "</body></html>\n";
25 ////////////////////////////////////////////////////////////////
27 // Functions for dumping.
29 ////////////////////////////////////////////////////////////////
31 function MailifyPage ($page, $nversions = 1)
33 global $SERVER_ADMIN, $pagedump_format;
35 $current = $page->getCurrentRevision();
36 $from = isset($SERVER_ADMIN) ? $SERVER_ADMIN : 'foo@bar';
38 if ($pagedump_format == 'quoted-printable') {
39 $head = "From $from " . CTime(time()) . "\r\n";
40 $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
41 $head .= "From: $from (PhpWiki)\r\n";
42 $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
43 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
46 $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
47 PHPWIKI_VERSION."+carsten's-binary-hack");
49 $head .= "X-RCS_ID: $" ."Id" ."$" ."\r\n";
51 $iter = $page->getAllRevisions();
53 while ($revision = $iter->next()) {
54 $parts[] = MimeifyPageRevision($revision);
55 if ($nversions > 0 && count($parts) >= $nversions)
58 if (count($parts) > 1)
59 return $head . MimeMultipart($parts);
61 return $head . $parts[0];
65 * Compute filename to used for storing contents of a wiki page.
67 * Basically we do a rawurlencode() which encodes everything except
68 * ASCII alphanumerics and '.', '-', and '_'.
70 * But we also want to encode leading dots to avoid filenames like
71 * '.', and '..'. (Also, there's no point in generating "hidden" file
72 * names, like '.foo'.)
74 * @param $pagename string Pagename.
75 * @return string Filename for page.
77 function FilenameForPage ($pagename)
79 $enc = rawurlencode($pagename);
80 return preg_replace('/^\./', '%2e', $enc);
84 * The main() function which generates a zip archive of a PhpWiki.
86 * If $include_archive is false, only the current version of each page
87 * is included in the zip file; otherwise all archived versions are
90 function MakeWikiZip ($dbi, $request)
92 if ($request->getArg('include') == 'all') {
93 $zipname = "wikidb.zip";
94 $include_archive = true;
97 $zipname = "wiki.zip";
98 $include_archive = false;
103 $zip = new ZipWriter("Created by PhpWiki", $zipname);
105 $pages = $dbi->getAllPages();
106 while ($page = $pages->next()) {
107 set_time_limit(30); // Reset watchdog.
109 $current = $page->getCurrentRevision();
110 if ($current->getVersion() == 0)
114 $attrib = array('mtime' => $current->get('mtime'),
116 if ($page->get('locked'))
117 $attrib['write_protected'] = 1;
119 if ($include_archive)
120 $content = MailifyPage($page, 0);
122 $content = MailifyPage($page);
124 $zip->addRegularFile( FilenameForPage($page->getName()),
130 function DumpToDir ($dbi, $request)
132 global $pagedump_format;
133 $directory = $request->getArg('directory');
134 if (empty($directory))
135 ExitWiki(_("You must specify a directory to dump to"));
137 // see if we can access the directory the user wants us to use
138 if (! file_exists($directory)) {
139 if (! mkdir($directory, 0755))
140 ExitWiki( sprintf(_("Cannot create directory '%s'"),
141 $directory) . "<br />\n");
143 $html = sprintf(_("Created directory '%s' for the page dump..."),
144 $directory) . "<br />\n";
146 $html = sprintf(_("Using directory '%s'"),$directory) . "<br />\n";
149 $html .= "MIME " . $pagedump_format . "<br />\n";
150 StartLoadDump( _("Dumping Pages"), $html);
152 $pages = $dbi->getAllPages();
154 while ($page = $pages->next()) {
156 $filename = FilenameForPage($page->getName());
158 $msg = array(HTML::br(), $page->getName(), ' ... ');
160 if($page->getName() != $filename) {
161 $msg[] = HTTP::small(fmt("saved as %s", $filename));
165 $data = MailifyPage($page);
167 if ( !($fd = fopen("$directory/$filename", "w")) ) {
168 $msg[] = HTML::strong(fmt("couldn't open file '%s' for writing",
169 "$directory/$filename"));
173 $num = fwrite($fd, $data, strlen($data));
174 $msg[] = HTML::small(fmt("%s bytes written", $num));
178 assert($num == strlen($data));
185 ////////////////////////////////////////////////////////////////
187 // Functions for restoring.
189 ////////////////////////////////////////////////////////////////
191 function SavePage ($dbi, $pageinfo, $source, $filename)
193 $pagedata = $pageinfo['pagedata']; // Page level meta-data.
194 $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
196 if (empty($pageinfo['pagename'])) {
197 PrintXML(HTML::dt(HTML::strong(_("Empty pagename!"))));
201 if (empty($versiondata['author_id']))
202 $versiondata['author_id'] = $versiondata['author'];
204 $pagename = $pageinfo['pagename'];
205 $content = $pageinfo['content'];
207 $page = $dbi->getPage($pagename);
209 foreach ($pagedata as $key => $value) {
211 $page->set($key, $value);
217 $mesg->pushContent(' ', fmt("from %s", $source));
220 $current = $page->getCurrentRevision();
221 if ($current->getVersion() == 0) {
222 $mesg->pushContent(' ', _("new page"));
226 if ($current->getPackedContent() == $content
227 && $current->get('author') == $versiondata['author']) {
228 $mesg->pushContent(' ',
229 fmt("is identical to current version %d - skipped",
230 $current->getVersion()));
237 $new = $page->createRevision(WIKIDB_FORCE_CREATE, $content,
239 ExtractWikiPageLinks($content));
241 $mesg->pushContent(' ', fmt("- saved to database as version %d",
242 $new->getVersion()));
245 $pagelink = LinkExistingWikiWord($pagename);
247 PrintXML(array(HTML::dt($pagelink), $mesg));
251 function ParseSerializedPage($text, $default_pagename)
253 if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
256 $pagehash = unserialize($text);
258 // Split up pagehash into four parts:
261 // page-level meta-data
262 // revision-level meta-data
264 if (!defined('FLAG_PAGE_LOCKED'))
265 define('FLAG_PAGE_LOCKED', 1);
266 $pageinfo = array('pagedata' => array(),
267 'versiondata' => array());
269 $pagedata = &$pageinfo['pagedata'];
270 $versiondata = &$pageinfo['versiondata'];
273 if (empty($pagehash['pagename']))
274 $pagehash['pagename'] = $default_pagename;
275 if (empty($pagehash['author']))
276 $pagehash['author'] = $GLOBALS['user']->getId(); // FIXME:?
279 foreach ($pagehash as $key => $value) {
283 $pageinfo[$key] = $value;
286 $pageinfo[$key] = join("\n", $value);
288 if (($value & FLAG_PAGE_LOCKED) != 0)
289 $pagedata['locked'] = 'yes';
292 $pagedata[$key] = $value;
295 $versiondata['mtime'] = $value;
298 $versiondata[$key] = $value;
305 function SortByPageVersion ($a, $b) {
306 return $a['version'] - $b['version'];
309 function LoadFile ($dbi, $filename, $text = false, $mtime = false)
311 if (!is_string($text)) {
313 $stat = stat($filename);
315 $text = implode("", file($filename));
318 set_time_limit(30); // Reset watchdog.
320 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
321 $basename = basename("/dummy/" . $filename);
324 $mtime = time(); // Last resort.
326 $default_pagename = rawurldecode($basename);
328 if ( ($parts = ParseMimeifiedPages($text)) ) {
329 usort($parts, 'SortByPageVersion');
330 foreach ($parts as $pageinfo)
331 SavePage($dbi, $pageinfo, sprintf(_("MIME file %s"),$filename),
334 else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename)) ) {
335 SavePage($dbi, $pageinfo, sprintf(_("Serialized file %s"),$filename),
339 // Assume plain text file.
340 $pageinfo = array('pagename' => $default_pagename,
341 'pagedata' => array(),
343 => array('author' => $GLOBALS['user']->getId()), //FIXME:?
344 'content' => preg_replace('/[ \t\r]*\n/', "\n",
347 SavePage($dbi, $pageinfo, sprintf(_("plain file %s"),$filename),
352 function LoadZip ($dbi, $zipfile, $files = false, $exclude = false) {
353 $zip = new ZipReader($zipfile);
354 while (list ($fn, $data, $attrib) = $zip->readFile()) {
355 // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
356 $fn = basename("/dummy/" . $fn);
357 if ( ($files && !in_array($fn, $files)) || ($exclude && in_array($fn, $exclude)) ) {
359 PrintXML(array(HTML::dt(LinkExistingWikiWord($fn)),
360 HTML::dd(_("Skipping"))));
365 LoadFile($dbi, $fn, $data, $attrib['mtime']);
369 function LoadDir ($dbi, $dirname, $files = false, $exclude = false)
371 $handle = opendir($dir = $dirname);
372 while ($fn = readdir($handle)) {
373 if ($fn[0] == '.' || filetype("$dir/$fn") != 'file')
376 if ( ($files && !in_array($fn, $files)) || ($exclude && in_array($fn, $exclude)) ) {
378 PrintXML(array(HTML::dt(LinkExistingWikiWord($fn)),
379 HTML::dd(_("Skipping"))));
383 LoadFile($dbi, "$dir/$fn");
388 function IsZipFile ($filename_or_fd)
390 // See if it looks like zip file
391 if (is_string($filename_or_fd))
393 $fd = fopen($filename_or_fd, "rb");
394 $magic = fread($fd, 4);
399 $fpos = ftell($filename_or_fd);
400 $magic = fread($filename_or_fd, 4);
401 fseek($filename_or_fd, $fpos);
404 return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
408 function LoadAny ($dbi, $file_or_dir, $files = false, $exclude = false)
410 $type = filetype($file_or_dir);
411 if ($type == 'link') {
412 // For symbolic links, use stat() to determine
413 // the type of the underlying file.
414 list(,,$mode) = stat($file_or_dir);
415 $type = ($mode >> 12) & 017;
418 elseif ($type == 004)
422 if ($type == 'dir') {
423 LoadDir($dbi, $file_or_dir, $files, $exclude);
425 else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
427 ExitWiki( sprintf(_("Bad file type: %s"),$type) );
429 else if (IsZipFile($file_or_dir)) {
430 LoadZip($dbi, $file_or_dir, $files, $exclude);
432 else /* if (!$files || in_array(basename($file_or_dir), $files)) */
434 LoadFile($dbi, $file_or_dir);
438 function LoadFileOrDir ($dbi, $request)
440 $source = $request->getArg('source');
441 StartLoadDump( sprintf(_("Loading '%s'"),$source) );
443 LoadAny($dbi, $source/*, false, array(gettext("RecentChanges"))*/);
448 function SetupWiki ($dbi)
450 global $GenericPages, $LANG, $user;
452 //FIXME: This is a hack (err, "interim solution")
453 // This is a bogo-bogo-login: Login without
454 // saving login information in session state.
455 // This avoids logging in the unsuspecting
456 // visitor as "The PhpWiki programming team".
458 // This really needs to be cleaned up...
459 // (I'm working on it.)
460 $user->_userid = _("The PhpWiki programming team");
461 $user->_level = WIKIAUTH_BOGO;
463 StartLoadDump(_("Loading up virgin wiki"));
466 LoadAny($dbi, FindLocalizedFile(WIKI_PGSRC)/*, false, $ignore*/);
468 LoadAny($dbi, FindFile(DEFAULT_WIKI_PGSRC),
469 $GenericPages/*, $ignore*/);
475 function LoadPostFile ($dbi, $request)
477 $upload = $request->getUploadedFile('file');
480 // FIXME: better message?
481 ExitWiki(_("No uploaded file to upload?"));
483 // Dump http headers.
484 StartLoadDump( sprintf(_("Uploading %s"),$upload->getName()) );
487 $fd = $upload->open();
489 LoadZip($dbi, $fd, false, array(_("RecentChanges")));
491 Loadfile($dbi, $upload->getName(), $upload->getContents());
502 // c-hanging-comment-ender-p: nil
503 // indent-tabs-mode: nil