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