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

Revision 4613, 46.4 KB checked in by emersonfaria, 13 years ago (diff)

Ticket #1963 - Foram implementadas correcoes em varias funcoes do backend imap e no mimeDecode.

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