source: contrib/z-push/backend/imap.php @ 4904

Revision 4904, 43.1 KB checked in by thiagoaos, 13 years ago (diff)

Ticket #2193 - Corrigido duplicação do atributo From na fonte da mensagem.

  • Property svn:executable set to *
Line 
1<?php
2/***********************************************
3 * File      :   imap.php
4 * Project   :   Z-Push
5 * Descr     :   This backend is based on
6 *               'BackendDiff' and implements an
7 *               IMAP interface
8 *
9 * Created   :   10.10.2007
10 *
11 * Zarafa Deutschland GmbH, www.zarafaserver.de
12 * This file is distributed under GPL v2.
13 * Consult LICENSE file for details
14 ************************************************/
15
16include_once('diffbackend.php');
17
18// The is an improved version of mimeDecode from PEAR that correctly
19// handles charsets and charset conversion
20include_once('mimeDecode.php');
21require_once('z_RFC822.php');
22
23class BackendIMAP extends BackendDiff {
24        /* Called to logon a user. These are the three authentication strings that you must
25         * specify in ActiveSync on the PDA. Normally you would do some kind of password
26         * check here. Alternatively, you could ignore the password here and have Apache
27         * do authentication via mod_auth_*
28         */
29        function Logon($username, $domain, $password) {
30                $this->_wasteID = false;
31                $this->_sentID = false;
32                $this->_server = "{" . IMAP_SERVER . ":" . IMAP_PORT . "/imap" . IMAP_OPTIONS . "}";
33
34                if (!function_exists("imap_open"))
35                debugLog("ERROR BackendIMAP : PHP-IMAP module not installed!!!!!");
36
37                // open the IMAP-mailbox
38                $this->_mbox = @imap_open($this->_server , $username, $password, OP_HALFOPEN);
39                $this->_mboxFolder = "";
40
41                if ($this->_mbox) {
42                        debugLog("IMAP connection opened sucessfully ");
43                        $this->_username = $username;
44                        $this->_domain = $domain;
45                        // set serverdelimiter
46                        $this->_serverdelimiter = $this->getServerDelimiter();
47                        return true;
48                }
49                else {
50                        debugLog("IMAP can't connect: " . imap_last_error());
51                        return false;
52                }
53        }
54
55        /* Called before shutting down the request to close the IMAP connection
56         */
57        function Logoff() {
58                if ($this->_mbox) {
59                        // list all errors
60                        $errors = imap_errors();
61                        if (is_array($errors)) {
62                                foreach ($errors as $e)    debugLog("IMAP-errors: $e");
63                        }
64                        @imap_close($this->_mbox);
65                        debugLog("IMAP connection closed");
66                }
67        }
68
69        /* Called directly after the logon. This specifies the client's protocol version
70         * and device id. The device ID can be used for various things, including saving
71         * per-device state information.
72         * The $user parameter here is normally equal to the $username parameter from the
73         * Logon() call. In theory though, you could log on a 'foo', and then sync the emails
74         * of user 'bar'. The $user here is the username specified in the request URL, while the
75         * $username in the Logon() call is the username which was sent as a part of the HTTP
76         * authentication.
77         */
78        function Setup($user, $devid, $protocolversion) {
79                $this->_user = $user;
80                $this->_devid = $devid;
81                $this->_protocolversion = $protocolversion;
82
83                return true;
84        }
85
86        /* Sends a message which is passed as rfc822. You basically can do two things
87         * 1) Send the message to an SMTP server as-is
88         * 2) Parse the message yourself, and send it some other way
89         * It is up to you whether you want to put the message in the sent items folder. If you
90         * want it in 'sent items', then the next sync on the 'sent items' folder should return
91         * the new message as any other new message in a folder.
92         */
93        function SendMail($rfc822, $forward = false, $reply = false, $parent = false) {
94                debugLog("IMAP-SendMail: for: $forward   reply: $reply   parent: $parent  RFC822:  \n". $rfc822 );
95
96                $mobj = new Mail_mimeDecode($rfc822);
97                $message = $mobj->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
98
99                $Mail_RFC822 = new Mail_RFC822();
100                $toaddr = $ccaddr = $bccaddr = "";
101                if(isset($message->headers["to"]))
102                        $toaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["to"]));
103                if(isset($message->headers["cc"]))
104                        $ccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["cc"]));
105                if(isset($message->headers["bcc"]))
106                        $bccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["bcc"]));
107
108                // save some headers when forwarding mails (content type & transfer-encoding)
109                $headers = "";
110                $forward_h_ct = "";
111                $forward_h_cte = "";
112                $envelopefrom = "";
113
114                $use_orgbody = false;
115
116                // clean up the transmitted headers
117                // remove default headers because we are using imap_mail
118                $changedfrom = false;
119                $returnPathSet = false;
120                $body_base64 = false;
121                $org_charset = "";
122                $from_value = "";
123                $return_path_value = "";
124                $org_boundary = false;
125                $multipartmixed = false;
126               
127                foreach($message->headers as $k => $v) {
128                        if ($k == "subject" || $k == "to" || $k == "cc" || $k == "bcc")
129                                continue;
130
131                        if ($k == "content-type") {
132                                // if the message is a multipart message, then we should use the sent body
133                                if (preg_match("/multipart/i", $v)) {
134                                        $use_orgbody = true;
135                                        $org_boundary = $message->ctype_parameters["boundary"];
136                                }
137
138                                // save the original content-type header for the body part when forwarding
139                                if ($forward && !$use_orgbody) {
140                                        $forward_h_ct = $v;
141                                        continue;
142                                }
143
144                                // set charset always to utf-8
145                                $org_charset = $v;
146                                $v = preg_replace("/charset=([A-Za-z0-9-\"']+)/", "charset=\"utf-8\"", $v);
147                        }
148
149                        if ($k == "content-transfer-encoding") {
150                                // if the content was base64 encoded, encode the body again when sending
151                                if (trim($v) == "base64") $body_base64 = true;
152
153                                // save the original encoding header for the body part when forwarding
154                                if ($forward) {
155                                        $forward_h_cte = $v;
156                                        continue;
157                                }
158                        }
159
160                        if ($k == "from") {
161                                $from_value = $v;
162                                $envelopefrom = "-f$v";
163                        }
164
165                        if ($k == "return-path")
166                                $return_path_value = $v;
167
168                        // all other headers stay
169                        if($k != "from" && $k != "return-path") {
170                                if ($headers) $headers .= "\n";
171                                $headers .= ucfirst($k) . ": ". $v;
172                        }
173                }
174
175                // override set "From" and "return-path" header
176                if(defined("IMAP_DEFAULTFROM")){
177                        if      (IMAP_DEFAULTFROM == 'username') $v = $this->_username;
178                        else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->_domain;
179                        else $v = $this->_username . IMAP_DEFAULTFROM;
180
181                        if(trim($v) != "") {
182                                $from_value = $return_path_value = $v;
183                                $envelopefrom = "-f$v";
184                        }
185                }
186
187                if ($headers) $headers .= "\n";
188                $headers .= "From: ".$from_value."\nReturn-Path: ".$return_path_value;
189
190                // if this is a multipart message with a boundary, we must use the original body
191                if ($use_orgbody) {
192                        list(,$body) = $mobj->_splitBodyHeader($rfc822);
193                        $repl_body = $this->getBody($message);
194                        if ($message->parts[0]->headers["content-transfer-encoding"] == "base64") $multipart_text_cte_base64 = true;
195                        else $multipart_text_cte_base64 = false;
196                }
197                else
198                        $body = $this->getBody($message);
199
200                // reply
201                if ($reply && $parent) {
202                        $this->imap_reopenFolder($parent);
203                        // receive entire mail (header + body) to decode body correctly
204                        $origmail = @imap_fetchheader($this->_mbox, $reply, FT_UID) . @imap_body($this->_mbox, $reply, FT_PEEK | FT_UID);
205
206                        $mobj2 = new Mail_mimeDecode($origmail);
207                        // receive only body
208                        $body .= $this->getBody($mobj2->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8')));
209                        // unset mimedecoder & origmail - free memory
210                        unset($mobj2);
211                        unset($origmail);
212                }
213
214                // encode the body to base64 if it was sent originally in base64 by the pda
215                // contrib - chunk base64 encoded body
216                if ($body_base64 && !$forward) $body = chunk_split(base64_encode($body));
217
218
219                // forward
220                if ($forward && $parent) {
221                        $this->imap_reopenFolder($parent);
222                        // receive entire mail (header + body)
223                        $origmail = @imap_fetchheader($this->_mbox, $forward, FT_UID) . @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID);
224
225                                if (defined('IMAP_INLINE_FORWARD') && IMAP_INLINE_FORWARD === false) {
226                                        // contrib - chunk base64 encoded body
227                                        if ($body_base64) $body = chunk_split(base64_encode($body));
228                                        //use original boundary if it's set
229                                        $boundary = ($org_boundary) ? $org_boundary : false;
230                                        // build a new mime message, forward entire old mail as file
231                                        list($aheader, $body) = $this->mail_attach("forwarded_message.eml",strlen($origmail),$origmail, $body, $forward_h_ct, $forward_h_cte,$boundary);
232                                        // add boundary headers
233                                        $headers .= "\n" . $aheader;
234                                }
235                                else {
236                                        $mobj2 = new Mail_mimeDecode($origmail);
237                                        $mess2 = $mobj2->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
238
239                                        if (!$use_orgbody)
240                                                $nbody = $body;
241                                        else
242                                                $nbody = $repl_body;
243
244                                        $nbody .= "\r\n\r\n";
245                                        $nbody .= "-----Original Message-----\r\n";
246                                        if(isset($mess2->headers['from']))
247                                                $nbody .= "From: " . $mess2->headers['from'] . "\r\n";
248                                        if(isset($mess2->headers['to']) && strlen($mess2->headers['to']) > 0)
249                                                $nbody .= "To: " . $mess2->headers['to'] . "\r\n";
250                                        if(isset($mess2->headers['cc']) && strlen($mess2->headers['cc']) > 0)
251                                                $nbody .= "Cc: " . $mess2->headers['cc'] . "\r\n";
252                                        if(isset($mess2->headers['date']))
253                                                $nbody .= "Sent: " . $mess2->headers['date'] . "\r\n";
254                                        if(isset($mess2->headers['subject']))
255                                                $nbody .= "Subject: " . $mess2->headers['subject'] . "\r\n";
256                                       
257                                        $nbody .= "\r\n";
258                                        $nbody .= $this->getBody($mess2);
259
260                                        if ($body_base64) {
261                                                // contrib - chunk base64 encoded body
262                                                $nbody = chunk_split(base64_encode($nbody));
263                                                if ($use_orgbody)
264                                                        // contrib - chunk base64 encoded body
265                                                        $repl_body = chunk_split(base64_encode($repl_body));
266                                        }
267
268                                        if ($use_orgbody) {
269                                                debugLog("-------------------");
270                                                debugLog("old:\n'$repl_body'\nnew:\n'$nbody'\nund der body:\n'$body'");
271                                                //$body is quoted-printable encoded while $repl_body and $nbody are plain text,
272                                                //so we need to decode $body in order replace to take place
273                                                if (!$multipart_text_cte_base64) {
274                                                        $body = str_replace($repl_body, $nbody, quoted_printable_decode($body));
275                                                } else {
276                                                        $body = str_replace(base64_encode($repl_body), base64_encode($nbody), $body);                   
277                                                }
278                                        }
279                                        else
280                                                $body = $nbody;
281
282
283                                        if(isset($mess2->parts)) {
284                                                $attached = false;
285
286                                                if ($org_boundary) {
287                                                        $att_boundary = $org_boundary;
288                                                        // cut end boundary from body
289                                                        $body = substr($body, 0, strrpos($body, "--$att_boundary--"));
290                                                }
291                                                else {
292                                                        $att_boundary = strtoupper(md5(uniqid(time())));
293                                                        // add boundary headers
294                                                        $headers .= "\n" . "Content-Type: multipart/mixed; boundary=$att_boundary";
295                                                        $multipartmixed = true;
296                                                }
297
298                                                foreach($mess2->parts as $part) {
299                                                        if(isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) {
300
301                                                        if(isset($part->d_parameters['filename']))
302                                                                $attname = $part->d_parameters['filename'];
303                                                        else if(isset($part->ctype_parameters['name']))
304                                                                $attname = $part->ctype_parameters['name'];
305                                                        else if(isset($part->headers['content-description']))
306                                                                $attname = $part->headers['content-description'];
307                                                        else $attname = "unknown attachment";
308
309                                                        // ignore html content
310                                                        if ($part->ctype_primary == "text" && $part->ctype_secondary == "html") {
311                                                                continue;
312                                                        }
313                                                        //
314                                                        if ($use_orgbody || $attached) {
315                                                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
316                                                        }
317                                                        // first attachment
318                                                        else {
319                                                                $encmail = $body;
320                                                                $attached = true;
321                                                                $body = $this->enc_multipart($att_boundary, $body, $forward_h_ct, $forward_h_cte);
322                                                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
323                                                        }
324                                                }
325                                        }
326                                        if ($multipartmixed) {
327                                                //this happens if a multipart/alternative message is forwarded
328                                                //then it's a multipart/mixed message which consists of:
329                                                //1. text/plain part which was written on the mobile
330                                                //2. multipart/alternative part which is the original message
331                                                //$body = "This is a message with multiple parts in MIME format.\n--".
332                                                //        $att_boundary.
333                                                //        "\nContent-Type: $forward_h_ct\nContent-Transfer-Encoding: $forward_h_cte\n\n".
334                                                //        (($body_base64) ? chunk_split(base64_encode($message->body)) : rtrim($message->body)).
335                                                //        "\n--".$att_boundary.
336                                                //        "\nContent-Type: {$mess2->headers['content-type']}\n\n".
337                                                //        @imap_body($this->_mbox, $forward, FT_PEEK | FT_UID)."\n\n";
338                                                $body = "\n--".
339                                                        $att_boundary.
340                                                        "\nContent-Type: $forward_h_ct\nContent-Transfer-Encoding: $forward_h_cte\n\n".
341                                                        $body;
342                                        }
343
344                                        $body .= "--$att_boundary--\n\n";
345                                }
346
347                                unset($mobj2);
348                        }
349
350                        // unset origmail - free memory
351                        unset($origmail);
352
353                }
354
355                // remove carriage-returns from body
356                $body = str_replace("\r\n", "\n", $body);
357
358                if (!$multipartmixed) {
359                        if (!empty($forward_h_ct)) $headers .= "\nContent-Type: $forward_h_ct";
360                        if (!empty($forward_h_cte)) $headers .= "\nContent-Transfer-Encoding: $forward_h_cte";
361                }
362                //advanced debugging
363                debugLog("IMAP-SendMail: parsed message: ". print_r($message,1));
364                debugLog("IMAP-SendMail: headers: $headers");
365                debugLog("IMAP-SendMail: subject: {$message->headers["subject"]}");
366                debugLog("IMAP-SendMail: body: $body");
367
368                if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
369                        $send =  @imap_mail ( $toaddr, $message->headers["subject"], $body, $headers, $ccaddr, $bccaddr);
370                }
371                else {
372                        if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
373                        if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
374                        $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom );
375                }
376
377                // email sent?
378                if (!$send) {
379                        debugLog("The email could not be sent. Last-IMAP-error: ". imap_last_error());
380                }
381
382                // add message to the sent folder
383                // build complete headers
384                $headers .= "\nTo: $toaddr";
385                $headers .= "\nSubject: " . $message->headers["subject"];
386
387                if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
388                        if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
389                        if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
390                }
391                debugLog("IMAP-SendMail: complete headers: $headers");
392
393                $asf = false;
394                if ($this->_sentID) {
395                        $asf = $this->addSentMessage($this->_sentID, $headers, $body);
396                }
397                else if(defined("IMAP_SENTFOLDER")) {
398                        $asf = $this->addSentMessage(IMAP_SENTFOLDER, $headers, $body);
399                        debugLog("IMAP-SendMail: Outgoing mail saved in configured 'Sent' folder '".IMAP_SENTFOLDER."': ". (($asf)?"success":"failed"));
400                }
401                // No Sent folder set, try defaults
402                else {
403                        debugLog("IMAP-SendMail: No Sent mailbox set");
404                        if($this->addSentMessage("INBOX.Sent", $headers, $body)) {
405                                debugLog("IMAP-SendMail: Outgoing mail saved in 'INBOX.Sent'");
406                                $asf = true;
407                        }
408                        else if ($this->addSentMessage("Sent", $headers, $body)) {
409                                debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent'");
410                                $asf = true;
411                        }
412                        else if ($this->addSentMessage("Sent Items", $headers, $body)) {
413                                debugLog("IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
414                                $asf = true;
415                        }
416                }
417
418                // unset mimedecoder - free memory
419                unset($mobj);
420                return ($send && $asf);
421        }
422
423        /* Should return a wastebasket folder if there is one. This is used when deleting
424         * items; if this function returns a valid folder ID, then all deletes are handled
425         * as moves and are sent to your backend as a move. If it returns FALSE, then deletes
426         * are always handled as real deletes and will be sent to your importer as a DELETE
427         */
428        function GetWasteBasket() {
429                return $this->_wasteID;
430        }
431
432        /* Should return a list (array) of messages, each entry being an associative array
433         * with the same entries as StatMessage(). This function should return stable information; ie
434         * if nothing has changed, the items in the array must be exactly the same. The order of
435         * the items within the array is not important though.
436         *
437         * The cutoffdate is a date in the past, representing the date since which items should be shown.
438         * This cutoffdate is determined by the user's setting of getting 'Last 3 days' of e-mail, etc. If
439         * you ignore the cutoffdate, the user will not be able to select their own cutoffdate, but all
440         * will work OK apart from that.
441         */
442
443        function GetMessageList($folderid, $cutoffdate) {
444                debugLog("IMAP-GetMessageList: (fid: '$folderid'  cutdate: '$cutoffdate' )");
445
446                $messages = array();
447                $this->imap_reopenFolder($folderid, true);
448
449                $sequence = "1:*";
450                if ($cutoffdate > 0) {
451                        $search = @imap_search($this->_mbox, "SINCE ". date("d-M-Y", $cutoffdate));
452                        if ($search !== false)
453                        $sequence = implode(",", $search);
454                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> A função @imap_search leu as seguintes SEQUÊNCIAS do servidor IMAP com base no filtro de data: '.$sequence);
455                }
456
457                $overviews = @imap_fetch_overview($this->_mbox, $sequence);
458
459                if (!$overviews) {
460                        debugLog("IMAP-GetMessageList: Failed to retrieve overview");
461                } else {
462                        foreach($overviews as $overview) {
463                                $date = "";
464                                $vars = get_object_vars($overview);
465                                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> A função @imap_fetch_overview leu mais detalhes da mensagem: '. print_r($overview,1));
466                                if (array_key_exists( "date", $vars)) {
467                                        // message is out of range for cutoffdate, ignore it
468                                        if(strtotime(preg_replace("/\(.*\)/", "", $overview->date)) < $cutoffdate) { // emerson-faria.nobre@serpro.gov.br - 07/feb/2011
469                                                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> O overview->date: '.$overview->date.' (overview->date_timestamp: '.strtotime(preg_replace("/\(.*\)/", "", $overview->date)).') é menor que o $cutoffdate: '.date("d/m/Y G:i:s",$cutoffdate).' ($cutoffdate_timestamp: '.$cutoffdate.') ou a função "strtotime" gerou um ERRO porque não conseguiu retornar um valor para o overview->date_timestamp. A mensagem será descartada da sincronização.');
470                                                continue;
471                                        }
472                                        //if(strtotime($overview->date) < $cutoffdate) continue;
473                                        $date = $overview->date;
474                                } else if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> ERRO: O campo date não existe no overview da mensagem.');
475
476                                // cut of deleted messages
477                                if (array_key_exists( "deleted", $vars) && $overview->deleted) {
478                                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> A mensagem está com o flag deleted ativo e será descartada da sincronização');
479                                continue;
480                                }
481
482                                if (array_key_exists( "uid", $vars)) {
483                                        $message = array();
484                                        $message["mod"] = $date;
485                                        $message["id"] = $overview->uid;
486                                        // 'seen' aka 'read' is the only flag we want to know about
487                                        $message["flags"] = 0;
488
489                                        if(array_key_exists( "seen", $vars) && $overview->seen)
490                                        $message["flags"] = 1;
491                                        array_push($messages, $message);
492                                } else if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetMessageList-> ERRO: O campo uid não existe no overview da mensagem.');
493                                }
494                        }
495                return $messages;
496        }
497
498        /* This function is analogous to GetMessageList.
499         *
500         */
501        function GetFolderList() {
502                $folders = array();
503
504                $list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
505                if (is_array($list)) {
506                        // reverse list to obtain folders in right order
507                        $list = array_reverse($list);
508                        foreach ($list as $val) {
509                                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetFolderList-> Pasta lida usando a função @imap_getmailboxes: '.print_r($val,1));
510                                $box = array();
511
512                                // cut off serverstring
513                                $box["id"] = imap_utf7_decode(substr($val->name, strlen($this->_server)));
514
515                                // always use "." as folder delimiter
516                                $box["id"] = imap_utf7_encode(str_replace($val->delimiter, ".", $box["id"]));
517
518                                // explode hierarchies
519                                $fhir = explode(".", $box["id"]);
520                                if (count($fhir) > 1) {
521                                        $box["mod"] = imap_utf7_encode(array_pop($fhir)); // mod is last part of path
522                                        $box["parent"] = imap_utf7_encode(implode(".", $fhir)); // parent is all previous parts of path
523                                }
524                                else {
525                                        $box["mod"] = imap_utf7_encode($box["id"]);
526                                        $box["parent"] = "0";
527                                }
528                                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetFolderList-> Parâmetros da pasta após decodificação: '.print_r($box,1));
529                                $folders[]=$box;
530                        }
531                }
532                else {
533                        debugLog("GetFolderList: imap_list failed: " . imap_last_error());
534                }
535
536                return $folders;
537        }
538
539        /* GetFolder should return an actual SyncFolder object with all the properties set. Folders
540         * are pretty simple really, having only a type, a name, a parent and a server ID.
541         */
542
543        function GetFolder($id) {
544                $folder = new SyncFolder();
545                $folder->serverid = $id;
546
547                // explode hierarchy
548                $fhir = explode(".", $id);
549
550                // compare on lowercase strings
551                $lid = strtolower($id);
552
553                $trash_folder_name = 'inbox.trash';
554
555                if(defined("IMAP_TRASHFOLDER"))
556                        $trash_folder_name = strtolower(str_replace($this->_serverdelimiter, ".", IMAP_TRASHFOLDER));
557
558                $sent_folder_name = 'inbox.sent';
559
560                if(defined("IMAP_SENTFOLDER"))
561                        $sent_folder_name = strtolower(str_replace($this->_serverdelimiter, ".", IMAP_SENTFOLDER));
562
563                $folder->parentid =  (($fhir && count($fhir) > 1) ? $fhir[(count($fhir) - 2)] : "0");
564
565                if($lid == "inbox") {
566                        $folder->parentid = "0"; // Root
567                        $folder->displayname = "Inbox";
568                        $folder->type = SYNC_FOLDER_TYPE_INBOX;
569                }
570                // Zarafa IMAP-Gateway outputs
571                else if($lid == "drafts" || $lid == "inbox.drafts" || $lid == "inbox.rascunhos") {
572                        $folder->displayname = "Drafts";
573                        $folder->type = SYNC_FOLDER_TYPE_DRAFTS;
574                }
575                else if($lid == "trash" || $lid == $trash_folder_name) {
576                        $folder->displayname = (defined("IMAP_DISPLAYNAME_TRASHFOLDER") ? IMAP_DISPLAYNAME_TRASHFOLDER : "Trash");
577                        $folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
578                        $this->_wasteID = $id;
579                }
580                else if($lid == "sent" || $lid == "sent items" || $lid == $sent_folder_name) {
581                        $folder->displayname = (defined("IMAP_DISPLAYNAME_SENTFOLDER") ? IMAP_DISPLAYNAME_SENTFOLDER : "Sent");
582                        $folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
583                        $this->_sentID = $id;
584                }
585                // define the rest as other-folders
586                else {
587                        if (count($fhir) > 1) {
588                                $folder->displayname = windows1252_to_utf8(imap_utf7_decode(array_pop($fhir)));
589                                $folder->parentid = implode(".", $fhir);
590                        }
591                        else {
592                                $folder->displayname = windows1252_to_utf8(imap_utf7_decode($id));
593                                $folder->parentid = "0";
594                        }
595                        $folder->type = SYNC_FOLDER_TYPE_OTHER;
596                }
597
598                //advanced debugging
599                //debugLog("IMAP-GetFolder(id: '$id') -> " . print_r($folder, 1));
600                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::GetFolder(id: '.$id.'): '.print_r($folder,1));
601
602                return $folder;
603        }
604
605        /* Return folder stats. This means you must return an associative array with the
606         * following properties:
607         * "id" => The server ID that will be used to identify the folder. It must be unique, and not too long
608         *         How long exactly is not known, but try keeping it under 20 chars or so. It must be a string.
609         * "parent" => The server ID of the parent of the folder. Same restrictions as 'id' apply.
610         * "mod" => This is the modification signature. It is any arbitrary string which is constant as long as
611         *          the folder has not changed. In practice this means that 'mod' can be equal to the folder name
612         *          as this is the only thing that ever changes in folders. (the type is normally constant)
613         */
614        function StatFolder($id) {
615                $folder = $this->GetFolder($id);
616
617                $stat = array();
618                $stat["id"] = $id;
619                $stat["parent"] = $folder->parentid;
620                $stat["mod"] = $folder->displayname;
621                if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::StatFolder(id: '.$id.'): '.print_r($stat,1));
622                return $stat;
623        }
624
625        /* Creates or modifies a folder
626         * "folderid" => id of the parent folder
627         * "oldid" => if empty -> new folder created, else folder is to be renamed
628         * "displayname" => new folder name (to be created, or to be renamed to)
629         * "type" => folder type, ignored in IMAP
630         *
631         */
632        function ChangeFolder($folderid, $oldid, $displayname, $type){
633                debugLog("ChangeFolder: (parent: '$folderid'  oldid: '$oldid'  displayname: '$displayname'  type: '$type')");
634
635                // go to parent mailbox
636                $this->imap_reopenFolder($folderid);
637
638                // build name for new mailbox
639                $newname = $this->_server . str_replace(".", $this->_serverdelimiter, $folderid) . $this->_serverdelimiter . $displayname;
640
641                $csts = false;
642                // if $id is set => rename mailbox, otherwise create
643                if ($oldid) {
644                        // rename doesn't work properly with IMAP
645                        // the activesync client doesn't support a 'changing ID'
646                        //$csts = imap_renamemailbox($this->_mbox, $this->_server . imap_utf7_encode(str_replace(".", $this->_serverdelimiter, $oldid)), $newname);
647                }
648                else {
649                        $csts = @imap_createmailbox($this->_mbox, $newname);
650                }
651                if ($csts) {
652                        return $this->StatFolder($folderid . "." . $displayname);
653                }
654                else
655                return false;
656        }
657
658        /* Should return attachment data for the specified attachment. The passed attachment identifier is
659         * the exact string that is returned in the 'AttName' property of an SyncAttachment. So, you should
660         * encode any information you need to find the attachment in that 'attname' property.
661         */
662        function GetAttachmentData($attname) {
663                debugLog("getAttachmentDate: (attname: '$attname')");
664
665                list($folderid, $id, $part) = explode(":", $attname);
666
667                $this->imap_reopenFolder($folderid);
668                $mail = @imap_fetchheader($this->_mbox, $id, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $id, FT_PEEK | FT_UID);
669
670                $mobj = new Mail_mimeDecode($mail);
671                $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $mail, 'crlf' => "\n", 'charset' => 'utf-8'));
672
673                if (isset($message->parts[$part]->body))
674                print $message->parts[$part]->body;
675
676                // unset mimedecoder & mail
677                unset($mobj);
678                unset($mail);
679                return true;
680        }
681
682        /* StatMessage should return message stats, analogous to the folder stats (StatFolder). Entries are:
683         * 'id'     => Server unique identifier for the message. Again, try to keep this short (under 20 chars)
684         * 'flags'     => simply '0' for unread, '1' for read
685         * 'mod'    => modification signature. As soon as this signature changes, the item is assumed to be completely
686         *             changed, and will be sent to the PDA as a whole. Normally you can use something like the modification
687         *             time for this field, which will change as soon as the contents have changed.
688         */
689
690        function StatMessage($folderid, $id) {
691                debugLog("IMAP-StatMessage: (fid: '$folderid'  id: '$id' )");
692
693                $this->imap_reopenFolder($folderid);
694                $overview = @imap_fetch_overview( $this->_mbox , $id , FT_UID);
695
696                if (!$overview) {
697                        debugLog("IMAP-StatMessage: Failed to retrieve overview: ". imap_last_error());
698                        return false;
699                }
700
701                else {
702                        // check if variables for this overview object are available
703                        $vars = get_object_vars($overview[0]);
704
705                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL') and (! array_key_exists( "uid", $vars))) debugLog('IMAP::StatMessage-> ERRO: A mensagem será desconsiderada porque não tem o campo "uid"');
706                        // without uid it's not a valid message
707                        if (! array_key_exists( "uid", $vars)) return false;
708
709
710                        $entry = array();
711                        $entry["mod"] = (array_key_exists( "date", $vars)) ? $overview[0]->date : "";
712                        $entry["id"] = $overview[0]->uid;
713                        // 'seen' aka 'read' is the only flag we want to know about
714                        $entry["flags"] = 0;
715
716                        if(array_key_exists( "seen", $vars) && $overview[0]->seen)
717                        $entry["flags"] = 1;
718
719                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog('IMAP::StatMessage: '.print_r($entry,1));
720
721                        //advanced debugging
722                        //debugLog("IMAP-StatMessage-parsed: ". print_r($entry,1));
723
724                        return $entry;
725                }
726        }
727
728        /* GetMessage should return the actual SyncXXX object type. You may or may not use the '$folderid' parent folder
729         * identifier here.
730         * Note that mixing item types is illegal and will be blocked by the engine; ie returning an Email object in a
731         * Tasks folder will not do anything. The SyncXXX objects should be filled with as much information as possible,
732         * but at least the subject, body, to, from, etc.
733         */
734        function GetMessage($folderid, $id, $truncsize, $mimesupport = 0) {
735                debugLog("IMAP-GetMessage: (fid: '$folderid'  id: '$id'  truncsize: $truncsize)");
736
737                // Get flags, etc
738                $stat = $this->StatMessage($folderid, $id);
739
740                if ($stat) {
741                        $this->imap_reopenFolder($folderid);
742                        $mail = @imap_fetchheader($this->_mbox, $id, FT_PREFETCHTEXT | FT_UID) . @imap_body($this->_mbox, $id, FT_PEEK | FT_UID);
743
744                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog("IMAP-GetMessage: Mensagem lida do servidor IMAP através da função @imap_fetchheader: ". print_r($mail,1));
745
746                        $mobj = new Mail_mimeDecode($mail);
747                        $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'input' => $mail, 'crlf' => "\n", 'charset' => 'utf-8'));
748
749                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog("IMAP-GetMessage: Mensagem mime decodificada: ". print_r($message,1));
750
751                        $output = new SyncMail();
752
753                        $body = $this->getBody($message, true); // true - Truncate body due to celular memory limit
754                        // truncate body, if requested
755                        if(strlen($body) > $truncsize) {
756                                $body = utf8_truncate($body, $truncsize);
757                                $output->bodytruncated = 1;
758                        } else {
759                                $body = $body;
760                                $output->bodytruncated = 0;
761                        }
762                        $body = str_replace("\n","\r\n", str_replace("\r","",$body));
763
764                        $output->bodysize = strlen($body);
765                        $output->body = $body;
766                        //$output->datereceived = isset($message->headers["date"]) ? strtotime($message->headers["date"]) : null;
767                        $output->datereceived = isset($message->headers["date"]) ? strtotime(preg_replace("/\(.*\)/", "", $message->headers["date"])) : null; // emerson-faria.nobre@serpro.gov.br
768                        $output->displayto = isset($message->headers["to"]) ? $message->headers["to"] : null;
769                        $output->importance = isset($message->headers["x-priority"]) ? preg_replace("/\D+/", "", $message->headers["x-priority"]) : null;
770                        $output->messageclass = "IPM.Note";
771                        $output->subject = isset($message->headers["subject"]) ? $message->headers["subject"] : "";
772                        $output->read = $stat["flags"];
773                        $output->to = isset($message->headers["to"]) ? $message->headers["to"] : null;
774                        $output->cc = isset($message->headers["cc"]) ? $message->headers["cc"] : null;
775                        $output->from = isset($message->headers["from"]) ? $message->headers["from"] : null;
776                        $output->reply_to = isset($message->headers["reply-to"]) ? $message->headers["reply-to"] : null;
777
778                        // Attachments are only searched in the top-level part
779                        $n = 0;
780                        if(isset($message->parts)) {
781                                foreach($message->parts as $part) {
782                                        if(isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) {
783                                                $attachment = new SyncAttachment();
784
785                                                if (isset($part->body))
786                                                $attachment->attsize = strlen($part->body);
787
788                                                if(isset($part->d_parameters['filename']))
789                                                $attname = $part->d_parameters['filename'];
790                                                else if(isset($part->ctype_parameters['name']))
791                                                $attname = $part->ctype_parameters['name'];
792                                                else if(isset($part->headers['content-description']))
793                                                $attname = $part->headers['content-description'];
794                                                else $attname = "unknown attachment";
795
796                                                $attachment->displayname = $attname;
797                                                $attachment->attname = $folderid . ":" . $id . ":" . $n;
798                                                $attachment->attmethod = 1;
799                                                $attachment->attoid = isset($part->headers['content-id']) ? $part->headers['content-id'] : "";
800                                                array_push($output->attachments, $attachment);
801                                        }
802                                        $n++;
803                                }
804                        }
805                        // unset mimedecoder & mail
806                        unset($mobj);
807                        unset($mail);
808                        if (TRACE_UID !== false and (TRACE_TYPE == 'IMAP' or TRACE_TYPE == 'ALL')) traceLog("IMAP-GetMessage: Mensagem formatada para envio ao celular: ". print_r($output,1));
809                        return $output;
810                }
811                return false;
812        }
813
814        /* This function is called when the user has requested to delete (really delete) a message. Usually
815         * this means just unlinking the file its in or somesuch. After this call has succeeded, a call to
816         * GetMessageList() should no longer list the message. If it does, the message will be re-sent to the PDA
817         * as it will be seen as a 'new' item. This means that if you don't implement this function, you will
818         * be able to delete messages on the PDA, but as soon as you sync, you'll get the item back
819         */
820        function DeleteMessage($folderid, $id) {
821                debugLog("IMAP-DeleteMessage: (fid: '$folderid'  id: '$id' )");
822
823                $this->imap_reopenFolder($folderid);
824                $s1 = @imap_delete ($this->_mbox, $id, FT_UID);
825                $s11 = @imap_setflag_full($this->_mbox, $id, "\\Deleted", FT_UID);
826                $s2 = @imap_expunge($this->_mbox);
827
828                debugLog("IMAP-DeleteMessage: s-delete: $s1   s-expunge: $s2    setflag: $s11");
829
830                return ($s1 && $s2 && $s11);
831        }
832
833        /* This should change the 'read' flag of a message on disk. The $flags
834         * parameter can only be '1' (read) or '0' (unread). After a call to
835         * SetReadFlag(), GetMessageList() should return the message with the
836         * new 'flags' but should not modify the 'mod' parameter. If you do
837         * change 'mod', simply setting the message to 'read' on the PDA will trigger
838         * a full resync of the item from the server
839         */
840        function SetReadFlag($folderid, $id, $flags) {
841                debugLog("IMAP-SetReadFlag: (fid: '$folderid'  id: '$id'  flags: '$flags' )");
842
843                $this->imap_reopenFolder($folderid);
844
845                if ($flags == 0) {
846                        // set as "Unseen" (unread)
847                        $status = @imap_clearflag_full ( $this->_mbox, $id, "\\Seen", ST_UID);
848                } else {
849                        // set as "Seen" (read)
850                        $status = @imap_setflag_full($this->_mbox, $id, "\\Seen",ST_UID);
851                }
852
853                debugLog("IMAP-SetReadFlag -> set as " . (($flags) ? "read" : "unread") . "-->". $status);
854
855                return $status;
856        }
857
858        /* This function is called when a message has been changed on the PDA. You should parse the new
859         * message here and save the changes to disk. The return value must be whatever would be returned
860         * from StatMessage() after the message has been saved. This means that both the 'flags' and the 'mod'
861         * properties of the StatMessage() item may change via ChangeMessage().
862         * Note that this function will never be called on E-mail items as you can't change e-mail items, you
863         * can only set them as 'read'.
864         */
865        function ChangeMessage($folderid, $id, $message) {
866                return false;
867        }
868
869        /* This function is called when the user moves an item on the PDA. You should do whatever is needed
870         * to move the message on disk. After this call, StatMessage() and GetMessageList() should show the items
871         * to have a new parent. This means that it will disappear from GetMessageList() will not return the item
872         * at all on the source folder, and the destination folder will show the new message
873         *
874         */
875        function MoveMessage($folderid, $id, $newfolderid) {
876                debugLog("IMAP-MoveMessage: (sfid: '$folderid'  id: '$id'  dfid: '$newfolderid' )");
877
878                $this->imap_reopenFolder($folderid);
879
880                // read message flags
881                $overview = @imap_fetch_overview ( $this->_mbox , $id, FT_UID);
882
883                if (!$overview) {
884                        debugLog("IMAP-MoveMessage: Failed to retrieve overview");
885                        return false;
886                }
887                else {
888                        // move message
889                        $s1 = imap_mail_move($this->_mbox, $id, str_replace(".", $this->_serverdelimiter, $newfolderid), FT_UID);
890
891                        // delete message in from-folder
892                        $s2 = imap_expunge($this->_mbox);
893
894                        // open new folder
895                        $this->imap_reopenFolder($newfolderid);
896
897                        // remove all flags
898                        $s3 = @imap_clearflag_full ($this->_mbox, $id, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID);
899                        $newflags = "";
900                        if ($overview[0]->seen) $newflags .= "\\Seen";
901                        if ($overview[0]->flagged) $newflags .= " \\Flagged";
902                        if ($overview[0]->answered) $newflags .= " \\Answered";
903                        $s4 = @imap_setflag_full ($this->_mbox, $id, $newflags, FT_UID);
904
905                        debugLog("MoveMessage: (" . $folderid . "->" . $newfolderid . ") s-move: $s1   s-expunge: $s2    unset-Flags: $s3    set-Flags: $s4");
906
907                        return ($s1 && $s2 && $s3 && $s4);
908                }
909        }
910
911        // new ping mechanism for the IMAP-Backend
912        function AlterPing() {
913                return true;
914        }
915
916        // returns a changes array using imap_status
917        // if changes occurr default diff engine computes the actual changes
918        function AlterPingChanges($folderid, &$syncstate) {
919                debugLog("AlterPingChanges on $folderid stat: ". $syncstate);
920                $this->imap_reopenFolder($folderid);
921
922                // courier-imap only cleares the status cache after checking
923                @imap_check($this->_mbox);
924
925                $status = imap_status($this->_mbox, $this->_server . str_replace(".", $this->_serverdelimiter, $folderid), SA_ALL);
926                if (!$status) {
927                        debugLog("AlterPingChanges: could not stat folder $folderid : ". imap_last_error());
928                        return false;
929                }
930                else {
931                        $newstate = "M:". $status->messages ."-R:". $status->recent ."-U:". $status->unseen;
932
933                        // message number is different - change occured
934                        if ($syncstate != $newstate) {
935                                $syncstate = $newstate;
936                                debugLog("AlterPingChanges: Change FOUND!");
937                                // build a dummy change
938                                return array(array("type" => "fakeChange"));
939                        }
940                }
941
942                return array();
943        }
944
945        // ----------------------------------------
946        // imap-specific internals
947
948        /* Parse the message and return only the plaintext body
949         */
950        function getBody($message, $trunc = false) {
951                $body = "";
952                $htmlbody = "";
953
954                $this->getBodyRecursive($message, "plain", $body);
955                if($trunc == true and isset($body) and strlen($body) > 102400) {
956                        $body = substr($body, 0, 102400);
957                        $body .= "\n\n\n A MENSAGEM FOI TRUNCADA NO CELULAR(MENSAGEM MUITO GRANDE).";
958                }
959
960                if(!isset($body) or $body === '') {
961                        $this->getBodyRecursive($message, "html", $body);
962
963                        if($trunc == true and isset($body) and strlen($body) > 209715) {
964                                $body = substr($body, 0, 209715);
965                                $body .= "<BR><BR><BR> A MENSAGEM FOI TRUNCADA NO CELULAR(MENSAGEM MUITO GRANDE).";
966                    }
967                       
968                        // remove css-style tags
969                        $body = preg_replace("/<style.*?<\/style>/is", "a", $body);
970                        // remove all other html
971                        //$body = strip_tags($body);
972
973                        // Remove the HTML tags using the 'html2text' - emerson-faria.nobre@serpro.gov.br
974                        // The 'html2text' (http://www.mbayer.de/html2text) must be installed in Z-Push server.
975                               
976                        // Advanced debug
977                        // debugLog("IMAP-getBody: subject: " . $message->headers["subject"]);
978                        $body = utf8_encode($body);     
979                        libxml_use_internal_errors(true);
980                        try {
981                                $doc = new DOMDocument('1.0', 'UTF-8');
982                                @$doc->loadHTML($body);
983                                $tables = $doc->getElementsByTagName('table');
984                                foreach ($tables as $table)
985                                {
986                                        $tds = $table->getElementsByTagName('td');
987                                        foreach ($tds as $td)
988                                        {
989                                                foreach ($td->childNodes as $td_child) {
990                                                        if ($td_child->nodeName == 'br') $td->removeChild($td_child);
991                                                }
992                                        }
993                                }
994                                $links = $doc->getElementsByTagName('a');
995                                foreach ($links as $link)
996                                {
997                                        if ($link->hasAttributes()){
998                                                $novoNo = $doc->createTextNode(' (' . $link->getAttribute('href') . ')');
999                                                $link->parentNode->insertBefore($novoNo, $link->nextSibling);
1000                                        }
1001                                }
1002                                $body =  $doc->saveHTML();
1003                        } catch (Exception $e) {
1004                                debugLog("IMAP-getBody: Alert - DOMDocument cannot parse HTML.");
1005                        }
1006                        $filename = "./state/" . $this->_user . "-" . $this->_devid . ".html";
1007                        $fp = fopen($filename, 'w') or die("can't open file");
1008                        fwrite($fp, $body);
1009                        $body_aux = shell_exec('html2text -nobs -style compact "' . $filename . '"');
1010                        if (trim($body_aux) != '') $body = $body_aux;
1011                        unset($body_aux);
1012                        fclose($fp);
1013                        unlink($filename);
1014                        $body = utf8_decode($body);
1015                        $body = str_replace('_','',$body);
1016                        // End change block - Remove the HTML tags using the 'html2text' Linux application
1017                }
1018
1019                return $body;
1020        }
1021
1022        // Get all parts in the message with specified type and concatenate them together, unless the
1023        // Content-Disposition is 'attachment', in which case the text is apparently an attachment
1024        function getBodyRecursive($message, $subtype, &$body) {
1025                if(!isset($message->ctype_primary)) return;
1026                if(strcasecmp($message->ctype_primary,"text")==0 && strcasecmp($message->ctype_secondary,$subtype)==0 && isset($message->body))
1027                $body .= $message->body;
1028
1029                if(strcasecmp($message->ctype_primary,"multipart")==0 && isset($message->parts) && is_array($message->parts)) {
1030                        foreach($message->parts as $part) {
1031                                if(!isset($part->disposition) || strcasecmp($part->disposition,"attachment"))  {
1032                                        $this->getBodyRecursive($part, $subtype, $body);
1033                                }
1034                        }
1035                }
1036        }
1037
1038        // save the serverdelimiter for later folder (un)parsing
1039        function getServerDelimiter() {
1040                $list = @imap_getmailboxes($this->_mbox, $this->_server, "*");
1041                if (is_array($list)) {
1042                        $val = $list[0];
1043
1044                        return $val->delimiter;
1045                }
1046                return "."; // default "."
1047        }
1048
1049        // speed things up
1050        // remember what folder is currently open and only change if necessary
1051        function imap_reopenFolder($folderid, $force = false) {
1052                // to see changes, the folder has to be reopened!
1053                if ($this->_mboxFolder != $folderid || $force) {
1054                        $s = @imap_reopen($this->_mbox, $this->_server . str_replace(".", $this->_serverdelimiter, $folderid));
1055                        if (!$s) debugLog("failed to change folder: ". implode(", ", imap_errors()));
1056                        $this->_mboxFolder = $folderid;
1057                }
1058        }
1059
1060
1061        // build a multipart email, embedding body and one file (for attachments)
1062        function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte, $boundary = false) {
1063                if (!$boundary) $boundary = strtoupper(md5(uniqid(time())));
1064
1065                //remove the ending boundary because we will add it at the end
1066                $body = str_replace("--$boundary--", "", $body);
1067
1068                $mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
1069
1070                // build main body with the sumitted type & encoding from the pda
1071                $mail_body  = $this->enc_multipart($boundary, $body, $body_ct, $body_cte);
1072                $mail_body .= $this->enc_attach_file($boundary, $filenm, $filesize, $file_cont);
1073
1074                $mail_body .= "--$boundary--\n\n";
1075               
1076                return array($mail_header, $mail_body);
1077        }
1078
1079        function enc_multipart($boundary, $body, $body_ct, $body_cte) {
1080//        $mail_body = "This is a multi-part message in MIME format\n\n";   
1081//        $mail_body .= "--$boundary\n";
1082//        $mail_body .= "Content-Type: $body_ct\n";
1083//        $mail_body .= "Content-Transfer-Encoding: $body_cte\n\n";
1084        $mail_body = "$body\n\n";
1085
1086        return $mail_body;
1087        }
1088   
1089        function enc_attach_file($boundary, $filenm, $filesize, $file_cont, $content_type = "") {
1090                if (!$content_type) $content_type = "text/plain";
1091                $mail_body = "--$boundary\n";
1092                $mail_body .= "Content-Type: $content_type; name=\"$filenm\"\n";
1093                $mail_body .= "Content-Transfer-Encoding: base64\n";
1094                $mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
1095                $mail_body .= "Content-Description: $filenm\n\n";
1096                //contrib - chunk base64 encoded attachments
1097                $mail_body .= chunk_split(base64_encode($file_cont)) . "\n\n";
1098
1099                return $mail_body;
1100        }
1101
1102        // adds a message as seen to a specified folder (used for saving sent mails)
1103        function addSentMessage($folderid, $header, $body) {
1104                $header_body = str_replace("\n", "\r\n", str_replace("\r", "", $header . "\n\n" . $body));
1105
1106                return @imap_append($this->_mbox, $this->_server . $folderid, $header_body, "\\Seen");
1107        }
1108
1109
1110        // parses address objects back to a simple "," separated string
1111        function parseAddr($ad) {
1112                $addr_string = "";
1113                if (isset($ad) && is_array($ad)) {
1114                        foreach($ad as $addr) {
1115                                if ($addr_string) $addr_string .= ",";
1116                                $addr_string .= $addr->mailbox . "@" . $addr->host;
1117                        }
1118                }
1119                return $addr_string;
1120        }
1121
1122};
1123
1124?>
Note: See TracBrowser for help on using the repository browser.