Subversion Repositories Applications.projet

Rev

Rev 359 | Go to most recent revision | Details | Compare with Previous | Last modification | View Log | RSS feed

Rev Author Line No. Line
2 ddelon 1
<?php
208 neiluj 2
/*vim: set expandtab tabstop=4 shiftwidth=4: */
3
// +------------------------------------------------------------------------------------------------------+
4
// | PHP version 4.1                                                                                      |
5
// +------------------------------------------------------------------------------------------------------+
6
// | Copyright (C) 2004 Tela Botanica (accueil@tela-botanica.org)                                         |
7
// +------------------------------------------------------------------------------------------------------+
8
// | This library is free software; you can redistribute it and/or                                        |
9
// | modify it under the terms of the GNU General Public                                                  |
10
// | License as published by the Free Software Foundation; either                                         |
11
// | version 2.1 of the License, or (at your option) any later version.                                   |
12
// |                                                                                                      |
13
// | This library is distributed in the hope that it will be useful,                                      |
14
// | but WITHOUT ANY WARRANTY; without even the implied warranty of                                       |
15
// | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU                                    |
16
// | General Public License for more details.                                                             |
17
// |                                                                                                      |
18
// | You should have received a copy of the GNU General Public                                            |
19
// | License along with this library; if not, write to the Free Software                                  |
20
// | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA                            |
21
// +------------------------------------------------------------------------------------------------------+
359 aperonnet 22
// CVS : $Id: ezmlm-parser.php,v 1.5 2008-11-19 09:28:46 aperonnet Exp $
208 neiluj 23
/**
24
* Application projet
25
*
26
* classe ezmlm_parser pour lire les fichiers d index de ezmlm-idx
27
*
28
*@package projet
29
//Auteur original : ?? recupere dans ezmlm-php
30
*@author        Alexandre Granier <alexandre@tela-botanica.org>
31
*@copyright     Tela-Botanica 2000-2004
359 aperonnet 32
*@version       $Revision: 1.5 $
208 neiluj 33
// +------------------------------------------------------------------------------------------------------+
34
*/
35
 
36
 
37
// +------------------------------------------------------------------------------------------------------+
38
// |                                            ENTETE du PROGRAMME                                       |
39
// +------------------------------------------------------------------------------------------------------+
40
 
359 aperonnet 41
// $Id: ezmlm-parser.php,v 1.5 2008-11-19 09:28:46 aperonnet Exp $
2 ddelon 42
//
43
 
44
require_once("ezmlm.php");
45
require_once("Mail/mimeDecode.php") ;
46
// CLASS: ezmlm-parser
47
class ezmlm_parser extends ezmlm_php {
208 neiluj 48
    var $headers;           // the full untouched headers of the message
49
    var $body;              // the full untouched (but decoded) body (this is not $this->parts[0]->body)
2 ddelon 50
	var $parts;		// all the parts, if it is a multipart message. each part is an ezmlm_parser object...
51
 
208 neiluj 52
    // Here's the most accessed headers, everything else can be
53
    // accessed from the $this->headers array.
54
    var $to;                // To:
55
    var $from;              // From:
56
    var $date;              // Date:
57
    var $subject;           // Subject:
58
    var $replyto;           // Reply-To:
59
    var $contenttype;       // Content-Type:
2 ddelon 60
 
61
	var $multipart;		// TRUE if the message is a multipart message
62
 
63
	var $msgfile;		// if parsed from a file, this is the filename...
64
 
65
	// functions
66
 
208 neiluj 67
	/**
68
     * recent_msgs renvoie les derniers messages de la liste de discussion
69
     * ezmlm
70
     *
71
     * (
72
     * [0] => Array
73
     *   (
74
     *       [1] => sujet
75
     *       [2] => date en anglais
76
     *       [3] => le hash de l auteur
77
     *       [4] => l auteur
78
     *   )
79
     * [1] => ...
80
     * )
81
     * @param	int	le nombre de message a renvoye
82
     * @return array	un tableau contenant les messages
83
     * @access public
84
     */
2 ddelon 85
	function recent_msgs($show = 20, $month = "") {
208 neiluj 86
 
87
		$repertoire_archive = opendir($this->listdir . "/archive/");
2 ddelon 88
 
208 neiluj 89
		$repertoire_message = array() ;
90
 
406 raphael 91
		$numArchive = $this->getNumArchive();
92
		$dernier_repertoire = floor($numArchive / 100);
93
 
208 neiluj 94
		$tableau_message = array() ;
95
		$compteur_message = 0 ;
96
		$fichier_index = fopen ($this->listdir.'/archive/'.$dernier_repertoire.'/index', 'r') ;
97
		while (!feof($fichier_index)) {
98
				// Recuperation du numero de message, du hash du sujet et du sujet
99
				$temp = fgets($fichier_index, 4096);
100
				preg_match('/([0-9]+): ([a-z]+) (.*)/', $temp, $match) ;
101
 
102
				// dans la seconde on recupere la date, hash auteur et auteur
103
				$temp = fgets($fichier_index, 4096);
104
				preg_match('/\t([0-9]+) ([a-zA-Z][a-zA-Z][a-zA-Z]) ([0-9][0-9][0-9][0-9]) ([^;]+);([^ ]*) (.*)/', $temp, $match_deuxieme_ligne) ;
105
				if ($match[1] != '') {
106
				$tableau_message[$match[1]] = array ($match[2], $match[3],
107
									$match_deuxieme_ligne[1].' '.$match_deuxieme_ligne[2].' '.$match_deuxieme_ligne[3],
108
									$match_deuxieme_ligne[5],
109
									$match_deuxieme_ligne[6]);
110
				}
111
			}
112
			fclose ($fichier_index);
113
		// on renverse le tableau pour afficher les derniers messages en premier
114
		$tableau_message = array_reverse($tableau_message, true);
2 ddelon 115
 
208 neiluj 116
		// On compte le nombre de message, s il est inferieur $show et que l on est
117
		// pas dans le premier index, on ouvre le fichier precedent et recupere
118
		// le n dernier message
119
 
120
		if (count ($tableau_message) < $show && $dernier_repertoire != '0') {
121
			$avant_dernier_repertoire = $dernier_repertoire - 1 ;
122
			// On utilise file_get_contents pour renverser le fichier
123
			$fichier_index = array_reverse(
124
									explode ("\n",
125
										preg_replace ('/\n$/', '',
126
											file_get_contents ($this->listdir.'/archive/'.$avant_dernier_repertoire.'/index')) ), true) ;
127
			reset ($fichier_index);
128
			//var_dump ($fichier_index);
129
 
130
			for ($i = count ($tableau_message); $i <= $show; $i++) {
131
				// Recuperation du numero de message, du hash du sujet et du sujet
132
				// dans la seconde on recupere la date, hash auteur et auteur
133
 
134
				preg_match('/\t([0-9]+) ([a-zA-Z][a-zA-Z][a-zA-Z]) ([0-9][0-9][0-9][0-9]) ([^;]+);([^ ]*) (.*)/',
135
									current ($fichier_index), $match_deuxieme_ligne) ;
136
				preg_match('/([0-9]+): ([a-z]+) (.*)/', next($fichier_index), $match) ;
137
				next ($fichier_index);
138
 
139
				if ($match[1] != '') {
140
				$tableau_message[$match[1]] = array ($match[2], $match[3],
141
									$match_deuxieme_ligne[1].' '.$match_deuxieme_ligne[2].' '.$match_deuxieme_ligne[3],
142
									$match_deuxieme_ligne[5],
143
									$match_deuxieme_ligne[6]);
144
				}
2 ddelon 145
			}
208 neiluj 146
		} else {
147
			// Si le nombre de message est > $show on limite le tableau de retour
148
			$tableau_message = array_slice($tableau_message, 0, $show, true);
2 ddelon 149
		}
208 neiluj 150
 
151
 
152
		return $tableau_message ;
2 ddelon 153
	}
154
 
155
 
156
	// parse_file - opens a file and feeds the data to parse, file can be relative to the listdir
157
	function parse_file($file,$simple = FALSE) {
158
		if (!is_file($file)) {
159
			if (is_file($this->listdir . "/" . $file)) { $file = $this->listdir . "/" . $file; }
160
			else if (is_file($this->listdir . "/archive/" . $file)) { $file = $this->listdir . "/archive/" . $file; }
161
			else { return FALSE; }
162
		}
163
 
164
		$this->msgfile = $file;
165
        $data = '' ;
166
		$fd = fopen($file, "r");
167
		while (!feof($fd)) { $data .= fgets($fd,4096); }
168
		fclose($fd);
169
		return $this->parse($data,$simple);
170
	}
171
 
208 neiluj 172
    // parse_file_headers - ouvre un fichier et analyse les entête
2 ddelon 173
	function parse_file_headers($file,$simple = FALSE) {
174
		if (!is_file($file)) {
175
			if (is_file($this->listdir . "/" . $file)) { $file = $this->listdir . "/" . $file; }
176
			else if (is_file($this->listdir . "/archive/" . $file)) { $file = $this->listdir . "/archive/" . $file; }
177
			else { return FALSE; }
178
		}
179
 
180
		$this->msgfile = $file;
181
        $data = file_get_contents ($file) ;
182
        $message = file_get_contents($file) ;
183
        $mimeDecode = new Mail_mimeDecode($message) ;
184
        $mailDecode = $mimeDecode->decode() ;
185
        return $mailDecode ;
186
	}
187
 
188
	// this does all of the work (well it calls two functions that do all the work :)
189
	// all the decoding a part breaking follows RFC2045 (http://www.faqs.org/rfcs/rfc2045.html)
190
	function parse($data,$simple = FALSE) {
191
 
192
		if (($this->_get_headers($data,$simple)) && $this->_get_body($data,$simple)) { return TRUE; }
193
		return FALSE;
194
	}
195
 
196
	// all of these are internal functions, you shouldn't call them directly...
197
 
198
	// _ct_parse: parse Content-Type headers -> $ct[0] = Full header, $ct[1] = Content-Type, $ct[2] ... $ct[n] = AP's
199
	function _ct_parse() {
200
		$instr = $this->headers['content-type'];
201
		preg_replace('/\(.*\)/','',$instr); // strip rfc822 comments
202
		if (preg_match('/: /', $instr)) {
203
			$ct = preg_split('/:/',trim($instr),2);
204
			$ct = preg_split('/;/',trim($ct[1]));
205
		} else {
206
			$ct = preg_split('/;/',trim($instr));
207
		}
208
		if (isset($ct[1])) $attrs = preg_split('/[\s\n]/',$ct[1]);
209
		$i = 2;
210
		$ct[1] = $ct[0];
211
		$ct[0] = $this->headers['content-type'];
212
        if (isset($attrs) && is_array($attrs)) {
213
            while (list($key, $val) = each($attrs)) {
214
                if ($val == '') continue;
215
                $ap = preg_split('/=/',$val,2);
216
                if (preg_match('/^"/',$ap[1])) { $ap[1] = substr($ap[1],1,strlen($ap[1])-2); }
217
                $ct[$i] = $ap;
218
                $i++;
219
            }
220
        }
221
		// are we a multipart message?
222
		if (preg_match('/^multipart/i', $ct[1])) { $this->multipart = TRUE; }
223
 
224
		return $ct;
225
	}
226
 
227
	// _get_headers: pulls the headers out of the data and builds the $this->headers array
228
	function _get_headers($data,$simple = FALSE) {
229
		$lines = preg_split('/\n/', $data);
230
		while (list($key, $val) = each($lines)) {
231
			$val = trim($val);
232
			if ($val == "") break;
233
			if (preg_match('/^From[^:].*$/', $val)) continue;	/* strips out any From lines added by the MTA */
234
 
235
			$hdr = preg_split('/: /', $val, 2);
236
			if (count($hdr) == 1) {
237
				// this is a continuation of the last header (like a recieved from line)
238
				$this->headers[$last] .= $val;
239
			} else {
240
				$this->headers[strtolower($hdr[0])] = $hdr[1];
241
                //echo htmlspecialchars($this->headers['from'])."<br />" ;
242
				$last = strtolower($hdr[0]);
243
			}
244
		}
245
        // ajout alex
246
        // pour supprimer le problème des ISO...
247
        // a déplacer ailleur, et appelé avant affichage
248
 
249
        if (preg_match ('/windows-[0-9][0-9][0-9][0-9]/', $this->headers['subject'], $nombre)) {
250
            $reg_exp = $nombre[0] ;
251
        } else {
252
            $reg_exp = 'ISO-8859-15?' ;
253
        }
254
        if (preg_match ('/UTF/i', $this->headers['subject'])) $reg_exp = 'UTF-8' ;
255
        preg_match_all ("/=\?$reg_exp\?(Q|B)\?(.*?)\?=/i", $this->headers['subject'], $match, PREG_PATTERN_ORDER)  ;
256
        for ($i = 0; $i < count ($match[0]); $i++ ) {
257
 
258
                if ($match[1][$i] == 'Q') {
259
                    $decode = quoted_printable_decode ($match[2][$i]) ;
260
                } elseif ($match[1][$i] == 'B') {
261
                    $decode = base64_decode ($match[2][$i]) ;
262
                }
263
                $decode = preg_replace ("/_/", " ", $decode) ;
264
            if ($reg_exp == 'UTF-8') {
265
                $decode = utf8_decode ($decode) ;
266
            }
267
            $this->headers['subject'] = str_replace ($match[0][$i], $decode, $this->headers['subject']) ;
268
        }
269
		// sanity anyone?
270
		if (!$this->headers['content-type']) { $this->headers['content-type'] = "text/plain; charset=us-ascii"; }
271
		if (!$simple) { $this->headers['content-type'] = $this->_ct_parse(); }
272
 
273
 
274
		return TRUE;
275
	}
276
 
277
	// _get_body: pulls the body out of the data and fills $this->body, decoding the data if nessesary.
278
	function _get_body($data,$simple = FALSE) {
279
		$lines = preg_split('/\n/', $data);
280
		$doneheaders = FALSE;
281
 
282
		$data = "";
283
		while (list($key,$val) = each($lines)) {
284
            //echo htmlspecialchars($val)."<br>";
285
			if (($val == '') and (!$doneheaders)) {
286
				$doneheaders = TRUE;
287
				continue;
288
			} else if ($doneheaders) {
289
				$data .= $val . "\n";
290
			}
291
		}
292
 
293
		// now here comes the fun part... decoding.
294
		switch($this->headers['content-transfer-encoding']) {
295
			case 'binary':
296
				$this->body = $this->_cte_8bit($this->_cte_qp($this->_cte_binary($data)),$simple);
297
				break;
298
 
299
			case 'base64':
300
				$this->body = $this->_cte_8bit($this->_cte_qp($this->_cte_base64($data)),$simple);
301
				break;
302
 
303
			case 'quoted-printable':
304
				$this->body = $this->_cte_8bit($this->_cte_qp($data),$simple);
305
				break;
306
 
307
			case '8bit':
308
				$this->body = $this->_cte_8bit($data,$simple);
309
				break;
310
 
311
			case '7bit':		// 7bit doesn't need to be decoded
312
			default:		// And the fall through as well...
313
				$this->body = $data;
314
				break;
315
		}
316
        //echo  $this->headers['content-type'][2][1];
317
        if (isset($this->headers['content-type'][2][1]) && $this->headers['content-type'][2][1] == 'UTF-8') {
318
                //$this->body = utf8_decode ($this->body) ;
319
                //echo quoted_printable_decode(utf8_decode ($this->body)) ;
320
        }
321
		if ($simple) { return TRUE; }
322
 
323
		// if we are a multipart message then break up the parts and decode, set the appropriate variables.
324
		// here comes the best part about making ezmlm-php OOP. since each part is just really a little message
325
		// in itself each part becomes a new parser object and all the wheels turn again... :)
326
		if ($this->multipart) {
327
 
328
			$boundary = '';
329
			for ($i = 2; $i <= count($this->headers['content-type']); $i++) {
330
				if (preg_match('/boundary/i', $this->headers['content-type'][$i][0])) {
331
					$boundary = $this->headers['content-type'][$i][1];
332
 
333
				}
334
			}
335
			if ($boundary != '') {
336
				$this->_get_parts($this->body,$boundary);
337
			} else {
338
				// whoopps... something's not right here. we were told that the message is supposed
339
				// to be a multipart message, yet the boundary wasn't set in the content type.
340
				// mark the message as non multipart and add a message to the top of the body.
341
				$this->multipart = FALSE;
342
				$this->body = "PARSER ERROR:\nWHILE PARSING THIS MESSAGE AS A MULTIPART MESSAGE AS DEFINED IN RFC2045 THE BOUNDARY IDENTIFIER WAS NOT FOUND!\nTHIS MESSAGE WILL NOT DISPLAY CORRECTLY!\n\n" . $this->body;
343
			}
344
		}
345
 
346
		return TRUE;
347
	}
348
 
349
	// _get_parts: breaks up $data into parts based on $boundary following the rfc specs
350
	// detailed in section 5 of RFC2046 (http://www.faqs.org/rfcs/rfc2046.html)
351
	// After the parts are broken up they are then turned into parser objects and the
352
	// resulting array of parts is set to $this->parts;
353
	function _get_parts($data,$boundary) {
354
		$inpart = -1;
355
		$lines = preg_split('/\n/', $data);
356
        // La première partie contient l'avertissement pour les client mail ne supportant pas
357
        // multipart, elle est stocké dans parts[-1]
358
		while(list($key,$val) = each($lines)) {
359
			if ($val == "--" . $boundary) { $inpart++; continue; } // start of a part
360
			else if ($val == "--" . $boundary . "--") { break; } // the end of the last part
361
			else { $parts[$inpart] .= $val . "\n"; }
362
		}
363
 
364
		for ($i = 0; $i < count($parts) - 1; $i++) {    // On saute la première partie
365
			$part[$i] = new ezmlm_parser();
366
			$part[$i]->parse($parts[$i]);
367
			$this->parts[$i] = $part[$i];
368
            //echo $this->parts[$i]."<br>" ;
369
		}
370
 
371
	}
372
 
373
	// _cte_8bit: decode a content transfer encoding of 8bit
374
	// NOTE: this function is a little bit special. Since the end result will be displayed in
375
	// a web browser _cte_8bit decodes ASCII characters > 127 (the US-ASCII table) into the
376
	// html ordinal equivilant, it also ensures that the messages content-type is changed
377
	// to include text/html if it changes anything...
378
	function _cte_8bit($data,$simple = FALSE) {
379
		if ($simple) { return $data; }
380
		$changed = FALSE;
381
		$chars = preg_split('//',$data);
382
		while (list($key,$val) = each($chars)) {
383
			if (ord($val) > 127) { $out .= '&#' . ord($val) . ';'; $changed = TRUE; }
384
			else { $out .= $val; }
385
		}
386
		if ($changed) { $this->headers['content-type'][1] = 'text/html'; }
387
		return $out;
388
	}
389
 
390
	// _cte_binary: decode a content transfer encoding of binary
391
	function _cte_binary($data) { return $data; }
392
 
393
	// _cte_base64: decode a content transfer encoding of base64
394
	function _cte_base64($data) { return base64_decode($data); }
395
 
396
	// _cte_qp: decode a content transfer encoding of quoted_printable
397
	function _cte_qp($data) {
398
		// For the time being we'll use PHP's function, it seems to work well enough.
399
		return quoted_printable_decode($data);
400
	}
401
 
402
}