]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/loadsave.php
Converted presentational markup to semantic markup--element('b' --> element('strong'
[SourceForge/phpwiki.git] / lib / loadsave.php
1 <?php
2 rcs_id('$Id: loadsave.php,v 1.25 2002-01-10 23:55:52 carstenklapp Exp $');
3 require_once("lib/ziplib.php");
4 require_once("lib/Template.php");
5
6 function StartLoadDump($title, $html = '')
7 {
8     // FIXME: This is a hack
9     echo ereg_replace('</body>.*', '',
10                       GeneratePage('MESSAGE', $html, $title, 0));
11 }
12
13 function EndLoadDump()
14 {
15     // FIXME: This is a hack
16     
17     echo Element('p', QElement('strong', _("Complete.")));
18     echo Element('p', sprintf( _("Return to %s"), 
19                                LinkExistingWikiWord($GLOBALS['pagename']) ) );
20     echo "</body></html>\n";
21 }
22
23
24 ////////////////////////////////////////////////////////////////
25 //
26 //  Functions for dumping.
27 //
28 ////////////////////////////////////////////////////////////////
29
30 function MailifyPage ($page, $nversions = 1)
31 {
32     global $SERVER_ADMIN, $pagedump_format;
33     
34     $current = $page->getCurrentRevision();
35     $from = isset($SERVER_ADMIN) ? $SERVER_ADMIN : 'foo@bar';
36     $head = "";
37     if ($pagedump_format == 'quoted-printable') {
38         $head = "From $from  " . CTime(time()) . "\r\n";
39         $head .= "Subject: " . rawurlencode($page->getName()) . "\r\n";
40         $head .= "From: $from (PhpWiki)\r\n";
41         $head .= "Date: " . Rfc2822DateTime($current->get('mtime')) . "\r\n";
42         $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
43                          PHPWIKI_VERSION);
44     } else {
45         $head .= sprintf("Mime-Version: 1.0 (Produced by PhpWiki %s)\r\n",
46                          PHPWIKI_VERSION."+carsten's-binary-hack");
47     }
48     $head .= "X-RCS_ID: $" ."Id" ."$" ."\r\n";
49     
50     $iter = $page->getAllRevisions();
51     $parts = array();
52     while ($revision = $iter->next()) {
53         $parts[] = MimeifyPageRevision($revision);
54         if ($nversions > 0 && count($parts) >= $nversions)
55             break;
56     }
57     if (count($parts) > 1)
58         return $head . MimeMultipart($parts);
59     assert($parts);
60     return $head . $parts[0];
61 }
62
63 /***
64  * Compute filename to used for storing contents of a wiki page.
65  *
66  * Basically we do a rawurlencode() which encodes everything except
67  * ASCII alphanumerics and '.', '-', and '_'.
68  *
69  * But we also want to encode leading dots to avoid filenames like
70  * '.', and '..'. (Also, there's no point in generating "hidden" file
71  * names, like '.foo'.)
72  *
73  * @param $pagename string Pagename.
74  * @return string Filename for page.
75  */
76 function FilenameForPage ($pagename)
77 {
78     $enc = rawurlencode($pagename);
79     return preg_replace('/^\./', '%2e', $enc);
80 }
81
82 /**
83  * The main() function which generates a zip archive of a PhpWiki.
84  *
85  * If $include_archive is false, only the current version of each page
86  * is included in the zip file; otherwise all archived versions are
87  * included as well.
88  */
89 function MakeWikiZip ($dbi, $request)
90 {
91     if ($request->getArg('include') == 'all') {
92         $zipname         = "wikidb.zip";
93         $include_archive = true;
94     }
95     else {
96         $zipname         = "wiki.zip";
97         $include_archive = false;
98     }
99     
100     
101
102     $zip = new ZipWriter("Created by PhpWiki", $zipname);
103
104     $pages = $dbi->getAllPages();
105     while ($page = $pages->next()) {
106         set_time_limit(30);     // Reset watchdog.
107         
108         $current = $page->getCurrentRevision();
109         if ($current->getVersion() == 0)
110             continue;
111         
112         
113         $attrib = array('mtime'    => $current->get('mtime'),
114                         'is_ascii' => 1);
115         if ($page->get('locked'))
116             $attrib['write_protected'] = 1;
117         
118         if ($include_archive)
119             $content = MailifyPage($page, 0);
120         else
121             $content = MailifyPage($page);
122         
123         $zip->addRegularFile( FilenameForPage($page->getName()),
124                               $content, $attrib);
125     }
126     $zip->finish();
127 }
128
129 function DumpToDir ($dbi, $request) 
130 {
131     $directory = $request->getArg('directory');
132     if (empty($directory))
133         ExitWiki(_("You must specify a directory to dump to"));
134     
135     // see if we can access the directory the user wants us to use
136     if (! file_exists($directory)) {
137         if (! mkdir($directory, 0755))
138             ExitWiki( sprintf(_("Cannot create directory '%s'"), 
139                               $directory) . "<br />\n");
140         else
141             $html = sprintf(_("Created directory '%s' for the page dump..."),
142                             $directory) . "<br />\n";
143     } else {
144         $html = sprintf(_("Using directory '%s'"),$directory) . "<br />\n";
145     }
146     
147     StartLoadDump( _("Dumping Pages"), $html);
148     
149     $pages = $dbi->getAllPages();
150     
151     while ($page = $pages->next()) {
152         
153         $enc_name = htmlspecialchars($page->getName());
154         $filename = FilenameForPage($page->getName());
155         
156         echo "<br />$enc_name ... ";
157         if($page->getName() != $filename)
158             echo "<small>" . sprintf(_("saved as %s"),$filename)
159                 . "</small> ... ";
160         
161         $data = MailifyPage($page);
162         
163         if ( !($fd = fopen("$directory/$filename", "w")) )
164             ExitWiki("<strong>" . sprintf(_("couldn't open file '%s' for writing"),
165                                      "$directory/$filename") . "</strong>\n");
166         
167         $num = fwrite($fd, $data, strlen($data));
168         echo "<small>" . sprintf(_("%s bytes written"),$num) . "</small>\n";
169         flush();
170         
171         assert($num == strlen($data));
172         fclose($fd);
173     }
174     
175     EndLoadDump();
176 }
177
178 ////////////////////////////////////////////////////////////////
179 //
180 //  Functions for restoring.
181 //
182 ////////////////////////////////////////////////////////////////
183
184 function SavePage ($dbi, $pageinfo, $source, $filename)
185 {
186     $pagedata    = $pageinfo['pagedata'];    // Page level meta-data.
187     $versiondata = $pageinfo['versiondata']; // Revision level meta-data.
188     
189     if (empty($pageinfo['pagename'])) {
190         echo Element('dd'). Element('dt', QElement('strong',
191                                                    _("Empty pagename!") ));
192         return;
193     }
194     
195     if (empty($versiondata['author_id']))
196         $versiondata['author_id'] = $versiondata['author'];
197     
198     $pagename = $pageinfo['pagename'];
199     $content  = $pageinfo['content'];
200     
201     $page = $dbi->getPage($pagename);
202     
203     foreach ($pagedata as $key => $value) {
204         if (!empty($value))
205             $page->set($key, $value);
206     }
207     
208     $mesg = array();
209     $skip = false;
210     if ($source)
211         $mesg[] = sprintf(_("from %s"), $source);
212
213     $current = $page->getCurrentRevision();
214     if ($current->getVersion() == 0) {
215         $mesg[] = _("new page");
216         $isnew = true;
217     }
218     else {
219         if ($current->getPackedContent() == $content
220             && $current->get('author') == $versiondata['author']) {
221             $mesg[] = sprintf(_("is identical to current version %d"),
222                               $current->getVersion());
223             $mesg[] = _("- skipped");
224             $skip = true;
225         }
226         $isnew = false;
227     }
228     
229     if (! $skip) {
230         $new = $page->createRevision(WIKIDB_FORCE_CREATE, $content,
231                                      $versiondata,
232                                      ExtractWikiPageLinks($content));
233         
234         $mesg[] = sprintf(_("- saved to database as version %d"),
235                           $new->getVersion());
236     }
237     
238     print( Element('dt', LinkExistingWikiWord($pagename))
239            . QElement('dd', join(" ", $mesg))
240            . "\n" );
241     flush();
242 }
243
244 function ParseSerializedPage($text, $default_pagename)
245 {
246     if (!preg_match('/^a:\d+:{[si]:\d+/', $text))
247         return false;
248     
249     $pagehash = unserialize($text);
250     
251     // Split up pagehash into four parts:
252     //   pagename
253     //   content
254     //   page-level meta-data
255     //   revision-level meta-data
256     
257     if (!defined('FLAG_PAGE_LOCKED'))
258         define('FLAG_PAGE_LOCKED', 1);
259     $pageinfo = array('pagedata'    => array(),
260                       'versiondata' => array());
261     
262     $pagedata = &$pageinfo['pagedata'];
263     $versiondata = &$pageinfo['versiondata'];
264     
265     // Fill in defaults.
266     if (empty($pagehash['pagename']))
267         $pagehash['pagename'] = $default_pagename;
268     if (empty($pagehash['author']))
269         $pagehash['author'] = $GLOBALS['user']->id();
270     
271     
272     foreach ($pagehash as $key => $value) {
273         switch($key) {
274         case 'pagename':
275         case 'version':
276             $pageinfo[$key] = $value;
277             break;
278         case 'content':
279             $pageinfo[$key] = join("\n", $value);
280         case 'flags':
281             if (($value & FLAG_PAGE_LOCKED) != 0)
282                 $pagedata['locked'] = 'yes';
283             break;
284         case 'created':
285             $pagedata[$key] = $value;
286             break;
287         case 'lastmodified':
288             $versiondata['mtime'] = $value;
289             break;
290         case 'author':
291             $versiondata[$key] = $value;
292             break;
293         }
294     }
295     return $pageinfo;
296 }
297  
298 function SortByPageVersion ($a, $b) {
299     return $a['version'] - $b['version'];
300 }
301
302 function LoadFile ($dbi, $filename, $text = false, $mtime = false)
303 {
304     if (!is_string($text)) {
305         // Read the file.
306         $stat  = stat($filename);
307         $mtime = $stat[9];
308         $text  = implode("", file($filename));
309     }
310    
311     set_time_limit(30); // Reset watchdog.
312     
313     // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
314     $basename = basename("/dummy/" . $filename);
315    
316     if (!$mtime)
317         $mtime = time();        // Last resort.
318     
319     $defaults = array('author'   => $GLOBALS['user']->id(),
320                       'pagename' => rawurldecode($basename));
321     
322     $default_pagename = rawurldecode($basename);
323     
324     if ( ($parts = ParseMimeifiedPages($text)) ) {
325         usort($parts, 'SortByPageVersion');
326         foreach ($parts as $pageinfo)
327             SavePage($dbi, $pageinfo, sprintf(_("MIME file %s"),$filename),
328                      $basename);
329     }
330     else if ( ($pageinfo = ParseSerializedPage($text, $default_pagename)) ) {
331         SavePage($dbi, $pageinfo, sprintf(_("Serialized file %s"),$filename),
332                  $basename);
333     }
334     else {
335         // Assume plain text file.
336         $pageinfo = array('pagename' => $default_pagename,
337                           'pagedata' => array(),
338                           'versiondata'
339                           => array('author' => $GLOBALS['user']->id()),
340                           'content'  => preg_replace('/[ \t\r]*\n/', "\n",
341                                                      chop($text))
342                           );
343         SavePage($dbi, $pageinfo, sprintf(_("plain file %s"),$filename),
344                  $basename);
345     }
346 }
347
348 function LoadZip ($dbi, $zipfile, $files = false, $exclude = false)
349 {
350    $zip = new ZipReader($zipfile);
351    while (list ($fn, $data, $attrib) = $zip->readFile())
352        {
353            // FIXME: basename("filewithnoslashes") seems to return garbage sometimes.
354            $fn = basename("/dummy/" . $fn);
355            if ( ($files && !in_array($fn, $files))
356                 || ($exclude && in_array($fn, $exclude)) )
357                {
358                    print Element('dt', LinkExistingWikiWord($fn))
359                        . QElement('dd', _("Skipping"));
360                    continue;
361                }
362            
363            LoadFile($dbi, $fn, $data, $attrib['mtime']);
364    }
365 }
366
367 function LoadDir ($dbi, $dirname, $files = false, $exclude = false)
368 {
369     $handle = opendir($dir = $dirname);
370     while ($fn = readdir($handle))
371         {
372             if ($fn[0] == '.' || filetype("$dir/$fn") != 'file')
373                 continue;
374             
375             if ( ($files && !in_array($fn, $files))
376                  || ($exclude && in_array($fn, $exclude)) )
377                 {
378                     print Element('dt', LinkExistingWikiWord($fn))
379                         . QElement('dd', _("Skipping"));
380                     continue;
381                 }
382             
383             LoadFile($dbi, "$dir/$fn");
384         }
385     closedir($handle);
386 }
387
388 function IsZipFile ($filename_or_fd)
389 {
390     // See if it looks like zip file
391     if (is_string($filename_or_fd))
392         {
393             $fd    = fopen($filename_or_fd, "rb");
394             $magic = fread($fd, 4);
395             fclose($fd);
396         }
397     else
398         {
399             $fpos  = ftell($filename_or_fd);
400             $magic = fread($filename_or_fd, 4);
401             fseek($filename_or_fd, $fpos);
402         }
403     
404     return $magic == ZIP_LOCHEAD_MAGIC || $magic == ZIP_CENTHEAD_MAGIC;
405 }
406
407
408 function LoadAny ($dbi, $file_or_dir, $files = false, $exclude = false)
409 {
410     // FIXME: This is a partial workaround for sf bug #501145
411     if (substr_count($file_or_dir,"/") < 1) {
412         $type = filetype(rawurlencode($file_or_dir));
413     } else {
414         $type = filetype($file_or_dir);
415     }
416     
417     if ($type == 'dir') {
418         LoadDir($dbi, $file_or_dir, $files, $exclude);
419     }
420     else if ($type != 'file' && !preg_match('/^(http|ftp):/', $file_or_dir))
421     {
422         ExitWiki( sprintf(_("Bad file type: %s"),$type) );
423     }
424     else if (IsZipFile($file_or_dir)) {
425         LoadZip($dbi, $file_or_dir, $files, $exclude);
426     }
427     else /* if (!$files || in_array(basename($file_or_dir), $files)) */
428     {
429         LoadFile($dbi, $file_or_dir);
430     }
431 }
432
433 function LoadFileOrDir ($dbi, $request)
434 {
435     $source = $request->getArg('source');
436     StartLoadDump( sprintf(_("Loading '%s'"),$source) );
437     echo "<dl>\n";
438     LoadAny($dbi, $source/*, false, array(gettext("RecentChanges"))*/);
439     echo "</dl>\n";
440     EndLoadDump();
441 }
442
443 function SetupWiki ($dbi)
444 {
445     global $GenericPages, $LANG, $user;
446     
447     //FIXME: This is a hack
448     $user->userid = _("The PhpWiki programming team");
449     
450     StartLoadDump(_("Loading up virgin wiki"));
451     echo "<dl>\n";
452     
453     LoadAny($dbi, FindLocalizedFile(WIKI_PGSRC)/*, false, $ignore*/);
454     if ($LANG != "C")
455         LoadAny($dbi, FindFile(DEFAULT_WIKI_PGSRC),
456                 $GenericPages/*, $ignore*/);
457     
458     echo "</dl>\n";
459     EndLoadDump();
460 }
461
462 function LoadPostFile ($dbi, $request)
463 {
464     $upload = $request->getUploadedFile('file');
465     
466     if (!$upload)
467         // FIXME: better message?
468         ExitWiki(_("No uploaded file to upload?"));
469     
470     // Dump http headers.
471     StartLoadDump( sprintf(_("Uploading %s"),$upload->getName()) );
472     echo "<dl>\n";
473     
474     $fd = $upload->open();
475     if (IsZipFile($fd))
476         LoadZip($dbi, $fd, false, array(_("RecentChanges")));
477     else
478         Loadfile($dbi, $upload->getName(), $upload->getContents());
479     
480     echo "</dl>\n";
481     EndLoadDump();
482 }
483
484 // For emacs users
485 // Local Variables:
486 // mode: php
487 // tab-width: 8
488 // c-basic-offset: 4
489 // c-hanging-comment-ender-p: nil
490 // indent-tabs-mode: nil
491 // End:   
492 ?>