]> CyberLeo.Net >> Repos - SourceForge/phpwiki.git/blob - lib/ziplib.php
more numeric pagename fixes.
[SourceForge/phpwiki.git] / lib / ziplib.php
1 <?php rcs_id('$Id: ziplib.php,v 1.34 2004-04-18 01:11:52 rurban Exp $');
2
3 /**
4  * GZIP stuff.
5  *
6  * Note that we use gzopen()/gzwrite() instead of gzcompress() even if
7  * gzcompress() is available.  Gzcompress() puts out data with
8  * different headers --- in particular it includes an "adler-32"
9  * checksum rather than a "CRC32" checksum. Since we need the CRC-32
10  * checksum, and since not all PHP's have gzcompress(), we'll just
11  * stick with gzopen().
12  */
13 function gzip_cleanup () {
14     global $gzip_tmpfile;
15     
16     if ($gzip_tmpfile)
17         @unlink($gzip_tmpfile);
18 }
19
20 function gzip_tempnam () {
21     global $gzip_tmpfile;
22     
23     if (!$gzip_tmpfile) {
24         //FIXME: does this work on non-unix machines?
25         $gzip_tmpfile = tempnam("/tmp", "wkzip");
26         register_shutdown_function("gzip_cleanup");
27     }
28     return $gzip_tmpfile;
29 }
30
31 function gzip_compress ($data) {
32     $filename = gzip_tempnam();
33     if (!($fp = gzopen($filename, "wb")))
34         trigger_error(sprintf("%s failed", 'gzopen'), E_USER_ERROR);
35     gzwrite($fp, $data, strlen($data));
36     if (!gzclose($fp)) {
37         trigger_error(sprintf("%s failed", 'gzclose'), E_USER_ERROR);
38     }
39 /* ---- Original code ----  
40         $size = filesize($filename);
41     if (!($fp = fopen($filename, "rb"))) {
42         trigger_error(sprintf("%s failed", 'fopen'), E_USER_ERROR);
43         }
44     if (!($z = fread($fp, $size)) || strlen($z) != $size)
45         trigger_error(sprintf("%s failed", 'fread'), E_USER_ERROR);
46     if (!fclose($fp))
47         trigger_error(sprintf("%s failed", 'fclose'), E_USER_ERROR);
48 */
49 // -- FIX -------------
50     $z = NULL;
51     if (!($fp = fopen($filename,"rb"))) {
52         trigger_error(sprintf("%s failed", 'fopen'), E_USER_ERROR);
53     }
54     while(!feof($fp)) {
55         $z .= fread($fp,1024);
56     }
57     if (!fclose($fp))
58         trigger_error(sprintf("%s failed", 'fclose'), E_USER_ERROR);
59 // -- End FIX ----------
60     unlink($filename);
61     return $z;
62 }
63
64 function gzip_uncompress ($data) {
65     $filename = gzip_tempnam();
66     if (!($fp = fopen($filename, "wb")))
67         trigger_error(sprintf("%s failed", 'fopen'), E_USER_ERROR);
68     fwrite($fp, $data, strlen($data));
69     if (!fclose($fp))
70         trigger_error(sprintf("%s failed", 'fclose'), E_USER_ERROR);
71     
72     if (!($fp = gzopen($filename, "rb")))
73         trigger_error(sprintf("%s failed", 'gzopen'), E_USER_ERROR);
74     $unz = '';
75     while ($buf = gzread($fp, 4096))
76         $unz .= $buf;
77     if (!gzclose($fp))
78         trigger_error(sprintf("%s failed", 'gzclose'), E_USER_ERROR);
79     
80     unlink($filename);
81     return $unz;
82 }
83
84 /**
85  * CRC32 computation.  Hacked from Info-zip's zip-2.3 source code.
86  */
87
88 function zip_crc32 ($str, $crc = 0)
89 {
90     static $zip_crc_table;
91     
92     if (empty($zip_crc_table)) {
93         /* NOTE: The range of PHP ints seems to be -0x80000000 to 0x7fffffff.
94          * So, had to munge these constants.
95          */
96         $zip_crc_table
97             = array (0x00000000,  0x77073096, -0x11f19ed4, -0x66f6ae46,  0x076dc419,
98                      0x706af48f, -0x169c5acb, -0x619b6a5d,  0x0edb8832,  0x79dcb8a4,
99                     -0x1f2a16e2, -0x682d2678,  0x09b64c2b,  0x7eb17cbd, -0x1847d2f9,
100                     -0x6f40e26f,  0x1db71064,  0x6ab020f2, -0x0c468eb8, -0x7b41be22,
101                      0x1adad47d,  0x6ddde4eb, -0x0b2b4aaf, -0x7c2c7a39,  0x136c9856,
102                      0x646ba8c0, -0x029d0686, -0x759a3614,  0x14015c4f,  0x63066cd9,
103                     -0x05f0c29d, -0x72f7f20b,  0x3b6e20c8,  0x4c69105e, -0x2a9fbe1c,
104                     -0x5d988e8e,  0x3c03e4d1,  0x4b04d447, -0x2df27a03, -0x5af54a95,
105                      0x35b5a8fa,  0x42b2986c, -0x2444362a, -0x534306c0,  0x32d86ce3,
106                      0x45df5c75, -0x2329f231, -0x542ec2a7,  0x26d930ac,  0x51de003a,
107                     -0x3728ae80, -0x402f9eea,  0x21b4f4b5,  0x56b3c423, -0x30456a67,
108                     -0x47425af1,  0x2802b89e,  0x5f058808, -0x39f3264e, -0x4ef416dc,
109                      0x2f6f7c87,  0x58684c11, -0x3e9ee255, -0x4999d2c3,  0x76dc4190,
110                      0x01db7106, -0x672ddf44, -0x102aefd6,  0x71b18589,  0x06b6b51f,
111                     -0x60401b5b, -0x17472bcd,  0x7807c9a2,  0x0f00f934, -0x69f65772,
112                     -0x1ef167e8,  0x7f6a0dbb,  0x086d3d2d, -0x6e9b9369, -0x199ca3ff,
113                      0x6b6b51f4,  0x1c6c6162, -0x7a9acf28, -0x0d9dffb2,  0x6c0695ed,
114                      0x1b01a57b, -0x7df70b3f, -0x0af03ba9,  0x65b0d9c6,  0x12b7e950,
115                     -0x74414716, -0x03467784,  0x62dd1ddf,  0x15da2d49, -0x732c830d,
116                     -0x042bb39b,  0x4db26158,  0x3ab551ce, -0x5c43ff8c, -0x2b44cf1e,
117                      0x4adfa541,  0x3dd895d7, -0x5b2e3b93, -0x2c290b05,  0x4369e96a,
118                      0x346ed9fc, -0x529877ba, -0x259f4730,  0x44042d73,  0x33031de5,
119                     -0x55f5b3a1, -0x22f28337,  0x5005713c,  0x270241aa, -0x41f4eff0,
120                     -0x36f3df7a,  0x5768b525,  0x206f85b3, -0x46992bf7, -0x319e1b61,
121                      0x5edef90e,  0x29d9c998, -0x4f2f67de, -0x3828574c,  0x59b33d17,
122                      0x2eb40d81, -0x4842a3c5, -0x3f459353, -0x12477ce0, -0x65404c4a,
123                      0x03b6e20c,  0x74b1d29a, -0x152ab8c7, -0x622d8851,  0x04db2615,
124                      0x73dc1683, -0x1c9cf4ee, -0x6b9bc47c,  0x0d6d6a3e,  0x7a6a5aa8,
125                     -0x1bf130f5, -0x6cf60063,  0x0a00ae27,  0x7d079eb1, -0x0ff06cbc,
126                     -0x78f75c2e,  0x1e01f268,  0x6906c2fe, -0x089da8a3, -0x7f9a9835,
127                      0x196c3671,  0x6e6b06e7, -0x012be48a, -0x762cd420,  0x10da7a5a,
128                      0x67dd4acc, -0x06462091, -0x71411007,  0x17b7be43,  0x60b08ed5,
129                     -0x29295c18, -0x5e2e6c82,  0x38d8c2c4,  0x4fdff252, -0x2e44980f,
130                     -0x5943a899,  0x3fb506dd,  0x48b2364b, -0x27f2d426, -0x50f5e4b4,
131                      0x36034af6,  0x41047a60, -0x209f103d, -0x579820ab,  0x316e8eef,
132                      0x4669be79, -0x349e4c74, -0x43997ce6,  0x256fd2a0,  0x5268e236,
133                     -0x33f3886b, -0x44f4b8fd,  0x220216b9,  0x5505262f, -0x3a45c442,
134                     -0x4d42f4d8,  0x2bb45a92,  0x5cb36a04, -0x3d280059, -0x4a2f30cf,
135                      0x2cd99e8b,  0x5bdeae1d, -0x649b3d50, -0x139c0dda,  0x756aa39c,
136                      0x026d930a, -0x63f6f957, -0x14f1c9c1,  0x72076785,  0x05005713,
137                     -0x6a40b57e, -0x1d4785ec,  0x7bb12bae,  0x0cb61b38, -0x6d2d7165,
138                     -0x1a2a41f3,  0x7cdcefb7,  0x0bdbdf21, -0x792c2d2c, -0x0e2b1dbe,
139                      0x68ddb3f8,  0x1fda836e, -0x7e41e933, -0x0946d9a5,  0x6fb077e1,
140                      0x18b74777, -0x77f7a51a, -0x00f09590,  0x66063bca,  0x11010b5c,
141                     -0x709a6101, -0x079d5197,  0x616bffd3,  0x166ccf45, -0x5ff51d88,
142                     -0x28f22d12,  0x4e048354,  0x3903b3c2, -0x5898d99f, -0x2f9fe909,
143                      0x4969474d,  0x3e6e77db, -0x512e95b6, -0x2629a524,  0x40df0b66,
144                      0x37d83bf0, -0x564351ad, -0x2144613b,  0x47b2cf7f,  0x30b5ffe9,
145                     -0x42420de4, -0x35453d76,  0x53b39330,  0x24b4a3a6, -0x452fc9fb,
146                     -0x3228f96d,  0x54de5729,  0x23d967bf, -0x4c9985d2, -0x3b9eb548,
147                      0x5d681b02,  0x2a6f2b94, -0x4bf441c9, -0x3cf3715f,  0x5a05df1b,
148                      0x2d02ef8d);
149     }
150     
151     $crc = ~$crc;
152     for ($i = 0; $i < strlen($str); $i++) {
153         $crc = ( $zip_crc_table[($crc ^ ord($str[$i])) & 0xff]
154                  ^ (($crc >> 8) & 0xffffff) );
155     }
156     return ~$crc;
157 }
158
159 define('GZIP_MAGIC', "\037\213");
160 define('GZIP_DEFLATE', 010);
161
162 function zip_deflate ($content)
163 {
164     // Compress content, and suck information from gzip header.
165     if (function_exists('gzencode'))
166         $z = gzencode($content);
167     else
168     $z = gzip_compress($content);
169     
170     // Suck OS type byte from gzip header. FIXME: this smells bad.
171     
172     extract(unpack("a2magic/Ccomp_type/Cflags/@9/Cos_type", $z));
173     
174     if ($magic != GZIP_MAGIC)
175         trigger_error(sprintf("Bad %s", "gzip magic"), E_USER_ERROR);
176     if ($comp_type != GZIP_DEFLATE)
177         trigger_error(sprintf("Bad %s", "gzip comp type"), E_USER_ERROR);
178     if (($flags & 0x3e) != 0)
179         trigger_error(sprintf("Bad %s", sprintf("flags (0x%02x)", $flags)),
180                       E_USER_ERROR);
181     
182     $gz_header_len = 10;
183     $gz_data_len = strlen($z) - $gz_header_len - 8;
184     if ($gz_data_len < 0)
185         trigger_error("not enough gzip output?", E_USER_ERROR);
186     
187     extract(unpack("Vcrc32", substr($z, $gz_header_len + $gz_data_len)));
188     
189     return array(substr($z, $gz_header_len, $gz_data_len), // gzipped data
190                  $crc32,                // crc
191                  $os_type               // OS type
192                  );
193 }
194
195 function zip_inflate ($data, $crc32, $uncomp_size)
196 {
197     if (function_exists('gzinflate')) {
198         $data = gzinflate($data);
199         if (strlen($data) != $uncomp_size)
200             trigger_error("not enough output from gzinflate", E_USER_ERROR);
201         if (zip_crc32($data) != $crc32)
202             trigger_error("CRC32 mismatch", E_USER_ERROR);
203         return $data;
204     }
205     
206     if (!function_exists('gzopen')) {
207         global $request;
208         $request->finish(_("Can't inflate data: zlib support not enabled in this PHP"));
209     }
210     
211     // Reconstruct gzip header and ungzip the data.
212     $mtime = time();            //(Bogus mtime)
213     
214     return gzip_uncompress( pack("a2CxV@10", GZIP_MAGIC, GZIP_DEFLATE, $mtime)
215                             . $data
216                             . pack("VV", $crc32, $uncomp_size) );
217 }
218
219 function unixtime2dostime ($unix_time) {
220     if ($unix_time % 1)
221         $unix_time++;           // Round up to even seconds.
222
223     list ($year,$month,$mday,$hour,$min,$sec)
224         = explode(" ", date("Y n j G i s", $unix_time));
225     
226     if ($year < 1980)
227         list ($year,$month,$mday,$hour,$min,$sec) = array(1980, 1, 1, 0, 0, 0);
228     
229     $dosdate = (($year - 1980) << 9) | ($month << 5) | $mday;
230     $dostime = ($hour << 11) | ($min << 5) | ($sec >> 1);
231     
232     return array($dosdate, $dostime);
233 }
234
235 function dostime2unixtime ($dosdate, $dostime) {
236     $mday  = $dosdate & 0x1f;
237     $month = ($dosdate >> 5) & 0x0f;
238     $year  = 1980 + (($dosdate >> 9) & 0x7f);
239     
240     $sec  = ($dostime & 0x1f) * 2;
241     $min  = ($dostime >> 5) & 0x3f;
242     $hour = ($dostime >> 11) & 0x1f;
243     
244     return mktime($hour, $min, $sec, $month, $mday, $year);
245 }
246
247
248 /**
249  * Class for zipfile creation.
250  */
251 define('ZIP_DEFLATE', GZIP_DEFLATE);
252 define('ZIP_STORE',   0);
253 define('ZIP_CENTHEAD_MAGIC', "PK\001\002");
254 define('ZIP_LOCHEAD_MAGIC',  "PK\003\004");
255 define('ZIP_ENDDIR_MAGIC',   "PK\005\006");
256
257 class ZipWriter
258 {
259     function ZipWriter ($comment = "", $zipname = "archive.zip") {
260         $this->comment = $comment;
261         $this->nfiles = 0;
262         $this->dir = "";                // "Central directory block"
263         $this->offset = 0;              // Current file position.
264         
265         $zipname = addslashes($zipname);
266         header("Content-Type: application/zip; name=\"$zipname\"");
267         header("Content-Disposition: attachment; filename=\"$zipname\"");
268     }
269     
270   function addRegularFile ($filename, $content, $attrib = false) {
271       if (!$attrib)
272           $attrib = array();
273       
274       $size = strlen($content);
275       if (function_exists('gzopen')) {
276           list ($data, $crc32, $os_type) = zip_deflate($content);
277           if (strlen($data) < $size) {
278               $content = $data; // Use compressed data.
279               $comp_type = ZIP_DEFLATE;
280           }
281           else
282               unset($crc32);    // force plain store.
283       }
284       else  {
285           // Punt:
286           $os_type = 0;     // 0 = FAT --- hopefully this is good enough.
287           /* (Another choice might be 3 = Unix) */
288       }
289
290       if (!isset($crc32)) {
291           $comp_type = ZIP_STORE;
292           $crc32 = zip_crc32($content);
293       }
294       
295       if (!empty($attrib['write_protected']))
296           $atx = (0100444 << 16) | 1; // S_IFREG + read permissions to
297                                       // everybody.
298       else
299           $atx = (0100644 << 16); // Add owner write perms.
300       
301       $ati = $attrib['is_ascii'] ? 1 : 0;
302       
303       if (empty($attrib['mtime']))
304           $attrib['mtime'] = time();
305       list ($mod_date, $mod_time) = unixtime2dostime($attrib['mtime']);
306       
307       // Construct parts common to "Local file header" and "Central
308       // directory file header."
309       if (!isset($attrib['extra_field']))
310           $attrib['extra_field'] = '';
311       if (!isset($attrib['file_comment']))
312           $attrib['file_comment'] = '';
313       
314       $head = pack("vvvvvVVVvv",
315                    20,  // Version needed to extract (FIXME: is this right?)
316                    0,   // Gen purp bit flag
317                    $comp_type,
318                    $mod_time,
319                    $mod_date,
320                    $crc32,
321                    strlen($content),
322                    $size,
323                    strlen($filename),
324                    strlen($attrib['extra_field']));
325       
326       // Construct the "Local file header"
327       $lheader = ZIP_LOCHEAD_MAGIC . $head . $filename
328           . $attrib['extra_field'];
329       
330       // Construct the "central directory file header"
331       $this->dir .= pack("a4CC",
332                          ZIP_CENTHEAD_MAGIC,
333                          23,    // Version made by (FIXME: is this right?)
334                          $os_type);
335       $this->dir .= $head;
336       $this->dir .= pack("vvvVV",
337                          strlen($attrib['file_comment']),
338                          0,              // Disk number start
339                          $ati,           // Internal file attributes
340                          $atx,           // External file attributes
341                          $this->offset); // Relative offset of local header
342       $this->dir .= $filename . $attrib['extra_field']
343           . $attrib['file_comment'];
344       
345       // Output the "Local file header" and file contents.
346       echo $lheader;
347       echo $content;
348       
349       $this->offset += strlen($lheader) + strlen($content);
350       $this->nfiles++;
351   }
352   
353   function finish () {
354       // Output the central directory
355       echo $this->dir;
356       
357       // Construct the "End of central directory record"
358       echo ZIP_ENDDIR_MAGIC;
359       echo pack("vvvvVVv",
360                 0,                  // Number of this disk.
361                 0,                  // Number of disk with start of c dir
362                 $this->nfiles,      // Number entries on this disk
363                 $this->nfiles,      // Number entries
364                 strlen($this->dir), // Size of central directory
365                 $this->offset,      // Offset of central directory
366                 strlen($this->comment));
367       echo $this->comment;
368   }
369 }
370
371
372 /**
373  * Class for reading zip files.
374  *
375  * BUGS:
376  *
377  * Many of the ExitWiki()'s should probably be warn()'s (eg. CRC mismatch).
378  *
379  * Only a subset of zip formats is recognized. (I think that
380  * unsupported formats will be recognized as such rather than silently
381  * munged.)
382  *
383  * We don't read the central directory. This means we don't see the
384  * file attributes (text? read-only?), or file comments.
385  *
386  * Right now we ignore the file mod date and time, since we don't need it.
387  */
388 class ZipReader
389 {
390     function ZipReader ($zipfile) {
391         if (!is_string($zipfile))
392             $this->fp = $zipfile;       // File already open
393         else if (!($this->fp = fopen($zipfile, "rb")))
394             trigger_error(sprintf(_("Can't open zip file '%s' for reading"),
395                                   $zipfile), E_USER_ERROR);
396     }
397     
398     function _read ($nbytes) {
399         $chunk = fread($this->fp, $nbytes);
400         if (strlen($chunk) != $nbytes)
401             trigger_error(_("Unexpected EOF in zip file"), E_USER_ERROR);
402         return $chunk;
403     }
404     
405     function done () {
406         fclose($this->fp);
407         return false;
408     }
409     
410   function readFile () {
411       $head = $this->_read(30);
412       
413       extract(unpack("a4magic/vreq_version/vflags/vcomp_type"
414                      . "/vmod_time/vmod_date"
415                      . "/Vcrc32/Vcomp_size/Vuncomp_size"
416                      . "/vfilename_len/vextrafld_len",
417                      $head));
418       
419       //FIXME: we should probably check $req_version.
420       $attrib['mtime'] = dostime2unixtime($mod_date, $mod_time);
421       
422       if ($magic != ZIP_LOCHEAD_MAGIC) {
423           if ($magic != ZIP_CENTHEAD_MAGIC)
424               // FIXME: better message?
425               ExitWiki(sprintf("Bad header type: %s", $magic));
426           return $this->done();
427       }
428       if (($flags & 0x21) != 0)
429           ExitWiki("Encryption and/or zip patches not supported.");
430       if (($flags & 0x08) != 0)
431           // FIXME: better message?
432           ExitWiki("Postponed CRC not yet supported.");
433       
434       $filename = $this->_read($filename_len);
435       if ($extrafld_len != 0)
436           $attrib['extra_field'] = $this->_read($extrafld_len);
437       
438       $data = $this->_read($comp_size);
439       
440       if ($comp_type == ZIP_DEFLATE) {
441           $data = zip_inflate($data, $crc32, $uncomp_size);
442       }
443       else if ($comp_type == ZIP_STORE) {
444           $crc = zip_crc32($data);
445           if ($crc32 != $crc)
446               ExitWiki(sprintf("CRC mismatch %x != %x", $crc, $crc32));
447       }
448       else
449           ExitWiki(sprintf("Compression method %s unsupported",
450                            $comp_method));
451       
452       if (strlen($data) != $uncomp_size)
453           ExitWiki(sprintf("Uncompressed size mismatch %d != %d",
454                            strlen($data), $uncomp_size));
455       
456       return array($filename, $data, $attrib);
457   }
458 }
459
460 /**
461  * Routines for Mime mailification of pages.
462  */
463 //FIXME: these should go elsewhere (libmime?).
464
465 /**
466  * Routines for quoted-printable en/decoding.
467  */
468 function QuotedPrintableEncode ($string)
469 {
470     // Quote special characters in line.
471     $quoted = "";
472     while ($string) {
473         // The complicated regexp is to force quoting of trailing spaces.
474         preg_match('/^([ !-<>-~]*)(?:([!-<>-~]$)|(.))/s', $string, $match);
475         $quoted .= $match[1] . $match[2];
476         if (!empty($match[3]))
477             $quoted .= sprintf("=%02X", ord($match[3]));
478         $string = substr($string, strlen($match[0]));
479     }
480     // Split line.
481     // This splits the line (preferably after white-space) into lines
482     // which are no longer than 76 chars (after adding trailing '=' for
483     // soft line break, but before adding \r\n.)
484     return preg_replace('/(?=.{77})(.{10,74}[ \t]|.{71,73}[^=][^=])/s',
485                         "\\1=\r\n", $quoted);
486 }
487
488 function QuotedPrintableDecode ($string)
489 {
490     // Eliminate soft line-breaks.
491     $string = preg_replace('/=[ \t\r]*\n/', '', $string);
492     return quoted_printable_decode($string);
493 }
494
495 define('MIME_TOKEN_REGEXP', "[-!#-'*+.0-9A-Z^-~]+");
496
497 function MimeContentTypeHeader ($type, $subtype, $params)
498 {
499     $header = "Content-Type: $type/$subtype";
500     reset($params);
501     while (list($key, $val) = each($params)) {
502         //FIXME:  what about non-ascii printables in $val?
503         if (!preg_match('/^' . MIME_TOKEN_REGEXP . '$/', $val))
504             $val = '"' . addslashes($val) . '"';
505         $header .= ";\r\n  $key=$val";
506     }
507     return "$header\r\n";
508 }
509
510 function MimeMultipart ($parts) 
511 {
512     global $mime_multipart_count;
513     
514     // The string "=_" can not occur in quoted-printable encoded data.
515     $boundary = "=_multipart_boundary_" . ++$mime_multipart_count;
516     
517     $head = MimeContentTypeHeader('multipart', 'mixed',
518                                   array('boundary' => $boundary));
519     
520     $sep = "\r\n--$boundary\r\n";
521     
522     return $head . $sep . implode($sep, $parts) . "\r\n--${boundary}--\r\n";
523 }
524
525 /**
526  * For reference see:
527  * http://www.nacs.uci.edu/indiv/ehood/MIME/2045/rfc2045.html
528  * http://www.faqs.org/rfcs/rfc2045.html
529  * (RFC 1521 has been superceeded by RFC 2045 & others).
530  *
531  * Also see http://www.faqs.org/rfcs/rfc2822.html
532  *
533  *
534  * Notes on content-transfer-encoding.
535  *
536  * "7bit" means short lines of US-ASCII.
537  * "8bit" means short lines of octets with (possibly) the high-order bit set.
538  * "binary" means lines are not necessarily short enough for SMTP
539  * transport, and non-ASCII characters may be present.
540  *
541  * Only "7bit", "quoted-printable", and "base64" are universally safe
542  * for transport via e-mail.  (Though many MTAs can/will be configured to
543  * automatically convert encodings to a safe type if they receive
544  * mail encoded in '8bit' and/or 'binary' encodings.
545  */
546 function MimeifyPageRevision ($revision) {
547     $page = $revision->getPage();
548     // FIXME: add 'hits' to $params 
549     $params = array('pagename'     => $page->getName(),
550                     'flags'        => "",
551                     'author'       => $revision->get('author'),
552                     'version'      => $revision->getVersion(),
553                     'lastmodified' => $revision->get('mtime'));
554     
555     if ($page->get('mtime'))
556         $params['created'] = $page->get('mtime');
557     if ($page->get('locked'))
558         $params['flags'] = 'PAGE_LOCKED';
559     if ($revision->get('author_id'))
560         $params['author_id'] = $revision->get('author_id');
561     if ($revision->get('markup'))
562         $params['markup'] = $revision->get('markup');
563     if ($revision->get('summary'))
564         $params['summary'] = $revision->get('summary');
565     if ($page->get('hits'))
566         $params['hits'] = $page->get('hits');
567
568     $params['charset'] = $GLOBALS['charset'];
569
570     // Non-US-ASCII is not allowed in Mime headers (at least not without
571     // special handling) --- so we urlencode all parameter values.
572     foreach ($params as $key => $val)
573         $params[$key] = rawurlencode($val);
574     
575     $out = MimeContentTypeHeader('application', 'x-phpwiki', $params);
576     $out .= sprintf("Content-Transfer-Encoding: %s\r\n",
577                     STRICT_MAILABLE_PAGEDUMPS ? 'quoted-printable' : 'binary');
578
579     $out .= "\r\n";
580     
581     foreach ($revision->getContent() as $line) {
582         // This is a dirty hack to allow saving binary text files. See above.
583         $line = rtrim($line);
584         if (STRICT_MAILABLE_PAGEDUMPS)
585             $line = QuotedPrintableEncode(rtrim($line));
586         $out .= "$line\r\n";
587     }
588     return $out;
589 }
590
591 /**
592  * Routines for parsing Mime-ified phpwiki pages.
593  */
594 function ParseRFC822Headers (&$string)
595 {
596     if (preg_match("/^From (.*)\r?\n/", $string, $match)) {
597         $headers['from '] = preg_replace('/^\s+|\s+$/', '', $match[1]);
598         $string = substr($string, strlen($match[0]));
599     }
600     
601     while (preg_match('/^([!-9;-~]+) [ \t]* : [ \t]* '
602                       . '( .* \r?\n (?: [ \t] .* \r?\n)* )/x',
603                       $string, $match))
604     {
605         $headers[strtolower($match[1])]
606             = preg_replace('/^\s+|\s+$/', '', $match[2]);
607         $string = substr($string, strlen($match[0]));
608     }
609     
610     if (empty($headers))
611         return false;
612     
613     if (! preg_match("/^\r?\n/", $string, $match))  {
614         // No blank line after headers.
615         return false;
616     }
617     
618     $string = substr($string, strlen($match[0]));
619     
620     return $headers;
621 }
622
623
624 function ParseMimeContentType ($string)
625 {
626     // FIXME: Remove (RFC822 style comments).
627     
628     // Get type/subtype
629     if (!preg_match(':^\s*(' . MIME_TOKEN_REGEXP . ')\s*'
630                     . '/'
631                     . '\s*(' . MIME_TOKEN_REGEXP . ')\s*:x',
632                     $string, $match))
633         ExitWiki(sprintf("Bad %s",'MIME content-type'));
634     
635     $type    = strtolower($match[1]);
636     $subtype = strtolower($match[2]);
637     $string  = substr($string, strlen($match[0]));
638     
639     $param = array();
640     while (preg_match('/^;\s*(' . MIME_TOKEN_REGEXP . ')\s*=\s*'
641                       . '(?:(' . MIME_TOKEN_REGEXP . ')|"((?:[^"\\\\]|\\.)*)") \s*/sx',
642                       $string, $match)) {
643         //" <--kludge for brain-dead syntax coloring
644         if (strlen($match[2]))
645             $val = $match[2];
646         else
647             $val = preg_replace('/[\\\\](.)/s', '\\1', $match[3]);
648         
649         $param[strtolower($match[1])] = $val;
650         
651         $string = substr($string, strlen($match[0]));
652     }
653     
654     return array($type, $subtype, $param);
655 }
656
657 function ParseMimeMultipart($data, $boundary)
658 {
659     if (!$boundary)
660         ExitWiki("No boundary?");
661     
662     $boundary = preg_quote($boundary);
663     
664     while (preg_match("/^(|.*?\n)--$boundary((?:--)?)[^\n]*\n/s",
665                       $data, $match))
666     {
667         $data = substr($data, strlen($match[0]));
668         if ( ! isset($parts) )
669             $parts = array();  // First time through: discard leading chaff
670         else {
671             if ($content = ParseMimeifiedPages($match[1]))
672                 for (reset($content); $p = current($content); next($content))
673                     $parts[] = $p;
674         }
675             
676         if ($match[2])
677             return $parts;      // End boundary found.
678     }
679     ExitWiki("No end boundary?");
680 }
681
682 function GenerateFootnotesFromRefs($params)
683 {
684     $footnotes = array();
685     reset($params);
686     while (list($p, $reference) = each($params)) {
687             if (preg_match('/^ref([1-9][0-9]*)$/', $p, $m))
688                 $footnotes[$m[1]] = sprintf(_("[%d] See [%s]"),
689                                             $m[1], rawurldecode($reference));
690     }
691     
692     if (sizeof($footnotes) > 0) {
693         ksort($footnotes);
694         return "-----\n"
695             . "!" ._("References") . "\n"
696             . join("\n%%%\n", $footnotes) . "\n";
697     } else
698         return "";
699 }
700
701
702 // Convert references in meta-data to footnotes.
703 // Only zip archives generated by phpwiki 1.2.x or earlier should have
704 // references.
705 function ParseMimeifiedPages ($data)
706 {
707     if (!($headers = ParseRFC822Headers($data))
708         || empty($headers['content-type'])) {
709         //trigger_error( sprintf(_("Can't find %s"),'content-type header'),
710         //               E_USER_WARNING );
711         return false;
712     }
713     $typeheader = $headers['content-type'];
714     
715     if (!(list ($type, $subtype, $params) = ParseMimeContentType($typeheader))) {
716         trigger_error( sprintf("Can't parse %s: (%s)",
717                                'content-type', $typeheader),
718                        E_USER_WARNING );
719         return false;
720     }
721     if ("$type/$subtype" == 'multipart/mixed') {
722         return ParseMimeMultipart($data, $params['boundary']);
723     }
724     else if ("$type/$subtype" != 'application/x-phpwiki') {
725         trigger_error( sprintf("Bad %s","content-type: $type/$subtype"),
726                        E_USER_WARNING );
727         return false;
728     }
729     
730     // FIXME: more sanity checking?
731     $page        = array();
732     $pagedata    = array();
733     $versiondata = array();
734     
735     foreach ($params as $key => $value) {
736         if (empty($value))
737             continue;
738         $value = rawurldecode($value);
739         switch ($key) {
740         case 'pagename':
741         case 'version':
742             $page[$key] = $value;
743             break;
744         case 'flags':
745             if (preg_match('/PAGE_LOCKED/', $value))
746                 $pagedata['locked'] = 'yes';
747             break;
748         case 'created':
749         case 'hits':
750             $pagedata[$key] = $value;
751             break;
752         case 'lastmodified':
753             $versiondata['mtime'] = $value;
754             break;
755         case 'author':
756         case 'author_id':
757         case 'summary':
758         case 'markup':
759         case 'pagetype':
760             $versiondata[$key] = $value;
761             break;
762         }
763     }
764     
765     // FIXME: do we need to try harder to find a pagename if we
766     //        haven't got one yet?
767     if (!isset($versiondata['author'])) {
768         global $request;
769         $user = $request->getUser();
770         $versiondata['author'] = $user->getId(); //FIXME:?
771     }
772     
773     $encoding = strtolower($headers['content-transfer-encoding']);
774     if ($encoding == 'quoted-printable')
775         $data = QuotedPrintableDecode($data);
776     else if ($encoding && $encoding != 'binary')
777         ExitWiki( sprintf("Unknown %s", 'encoding type: $encoding') );
778     
779     $data .= GenerateFootnotesFromRefs($params);
780     
781     $page['content'] = preg_replace('/[ \t\r]*\n/', "\n", chop($data));
782     $page['pagedata'] = $pagedata;
783     $page['versiondata'] = $versiondata;
784     
785     return array($page);
786 }
787
788 // $Log: not supported by cvs2svn $
789 // Revision 1.33  2004/04/12 13:04:50  rurban
790 // added auth_create: self-registering Db users
791 // fixed IMAP auth
792 // removed rating recommendations
793 // ziplib reformatting
794 //
795
796 // Local Variables:
797 // mode: php
798 // tab-width: 8
799 // c-basic-offset: 4
800 // c-hanging-comment-ender-p: nil
801 // indent-tabs-mode: nil
802 // End:   
803 ?>