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