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

Revision 3754, 33.9 KB checked in by emersonfaria, 13 years ago (diff)

Ticket #1551 - Correcoes de bugs e Melhorias de formatacao de email no Z-Push.

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