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