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