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