source: branches/2.5/zpush/backend/expresso/providers/imapProvider.php @ 8232

Revision 8232, 77.6 KB checked in by douglas, 11 years ago (diff)

Ticket #0000 - Copiadas as alterações do Trunk. Versão final 2.5.1.

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* Copyright 2007 - 2012 Zarafa Deutschland GmbH
12*
13* This program is free software: you can redistribute it and/or modify
14* it under the terms of the GNU Affero General Public License, version 3,
15* as published by the Free Software Foundation with the following additional
16* term according to sec. 7:
17*
18* According to sec. 7 of the GNU Affero General Public License, version 3,
19* the terms of the AGPL are supplemented with the following terms:
20*
21* "Zarafa" is a registered trademark of Zarafa B.V.
22* "Z-Push" is a registered trademark of Zarafa Deutschland GmbH
23* The licensing of the Program under the AGPL does not imply a trademark license.
24* Therefore any rights, title and interest in our trademarks remain entirely with us.
25*
26* However, if you propagate an unmodified version of the Program you are
27* allowed to use the term "Z-Push" to indicate that you distribute the Program.
28* Furthermore you may use our trademarks where it is necessary to indicate
29* the intended purpose of a product or service provided you use it in accordance
30* with honest practices in industrial or commercial matters.
31* If you want to propagate modified versions of the Program under the name "Z-Push",
32* you may only do so if you have a written permission by Zarafa Deutschland GmbH
33* (to acquire a permission please contact Zarafa at trademark@zarafa.com).
34*
35* This program is distributed in the hope that it will be useful,
36* but WITHOUT ANY WARRANTY; without even the implied warranty of
37* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
38* GNU Affero General Public License for more details.
39*
40* You should have received a copy of the GNU Affero General Public License
41* along with this program.  If not, see <http://www.gnu.org/licenses/>.
42*
43* Consult LICENSE file for details
44************************************************/
45
46include_once(__DIR__.'/../../../lib/default/diffbackend/diffbackend.php');
47include_once(__DIR__.'/../../../include/mimeDecode.php');
48require_once(__DIR__.'/../../../include/z_RFC822.php');
49
50
51class ExpressoImapProvider extends BackendDiff {
52    protected $wasteID;
53    protected $sentID;
54    protected $server;
55    protected $mbox;
56    protected $mboxFolder;
57    protected $username;
58    protected $domain;
59    protected $serverdelimiter;
60    protected $sinkfolders;
61    protected $sinkstates;
62    protected $excludedFolders; /* fmbiete's contribution r1527, ZP-319 */
63
64    /**----------------------------------------------------------------------------------------------------------
65     * default backend methods
66     */
67
68    /**
69     * Authenticates the user
70     *
71     * @param string        $username
72     * @param string        $domain
73     * @param string        $password
74     *
75     * @access public
76     * @return boolean
77     * @throws FatalException   if php-imap module can not be found
78     */
79    public function Logon($username, $domain, $password) {
80        $this->wasteID = false;
81        $this->sentID = false;
82        $this->server = "{" . IMAP_SERVER . ":" . IMAP_PORT . "/imap" . IMAP_OPTIONS . "}";
83
84        if (!function_exists("imap_open"))
85            throw new FatalException("BackendIMAP(): php-imap module is not installed", 0, null, LOGLEVEL_FATAL);
86
87        /* BEGIN fmbiete's contribution r1527, ZP-319 */
88        $this->excludedFolders = array();
89        if (defined('IMAP_EXCLUDED_FOLDERS')) {
90            $this->excludedFolders = explode("|", IMAP_EXCLUDED_FOLDERS);
91            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->Logon(): Excluding Folders (%s)", IMAP_EXCLUDED_FOLDERS));
92        }
93        /* END fmbiete's contribution r1527, ZP-319 */
94
95        // open the IMAP-mailbox
96        $this->mbox = @imap_open($this->server , $username, $password, OP_HALFOPEN);
97        $this->mboxFolder = "";
98
99
100        $ldapConfig = parse_ini_file(EXPRESSO_PATH . '/prototype/config/OpenLDAP.srv' , true );
101        $ldapConfig =  $ldapConfig['config'];
102        $sr = ldap_search( $GLOBALS['connections']['ldap'] , $ldapConfig['context'] , "(uid=$username)" , array('uidNumber'), 0 , 1 );
103        if(!$sr) return false;
104
105        $entries = ldap_get_entries( $GLOBALS['connections']['ldap'] , $sr );
106        $uidNumber = $entries[0]['uidnumber'][0];
107
108
109        $rs = pg_query( $GLOBALS['connections']['db'], 'Select * FROM phpgw_preferences WHERE preference_owner IN (\'-2\',\'-1\',\''.$uidNumber.'\') AND preference_app = \'expressoMail\' ORDER BY preference_owner' );
110
111        $results = array();
112        while( $row = pg_fetch_assoc( $rs ) )
113            $results[] = $row;
114
115        foreach($results as $result)
116        {
117            $ra = unserialize($result['preference_value']);
118            if(isset($ra['save_in_folder']))
119            {
120                $this->sentID = $ra['save_in_folder'];
121                break;
122            }
123        }
124
125        if ($this->mbox) {
126            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->Logon(): User '%s' is authenticated on IMAP",$username));
127            $this->username = $username;
128            $this->domain = $domain;
129            // set serverdelimiter
130            $this->serverdelimiter = $this->getServerDelimiter();
131            return true;
132        }
133        else {
134            ZLog::Write(LOGLEVEL_ERROR, "BackendIMAP->Logon(): can't connect: " . imap_last_error());
135            return false;
136        }
137    }
138
139    /**
140     * Logs off
141     * Called before shutting down the request to close the IMAP connection
142     * writes errors to the log
143     *
144     * @access public
145     * @return boolean
146     */
147    public function Logoff() {
148        if ($this->mbox) {
149            // list all errors
150            $errors = imap_errors();
151            if (is_array($errors)) {
152                foreach ($errors as $e) {
153                    if (stripos($e, "fail") !== false) {
154                        $level = LOGLEVEL_WARN;
155                    }
156                    else {
157                        $level = LOGLEVEL_DEBUG;
158                    }
159                    ZLog::Write($level, "BackendIMAP->Logoff(): IMAP said: " . $e);
160                }
161            }
162            @imap_close($this->mbox);
163            ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->Logoff(): IMAP connection closed");
164        }
165        $this->SaveStorages();
166    }
167
168    /**
169     * Sends an e-mail
170     * This messages needs to be saved into the 'sent items' folder
171     *
172     * @param SyncSendMail  $sm     SyncSendMail object
173     *
174     * @access public
175     * @return boolean
176     * @throws StatusException
177     */
178    // TODO implement , $saveInSent = true
179    public function SendMail($sm) {
180        $forward = $reply = (isset($sm->source->itemid) && $sm->source->itemid) ? $sm->source->itemid : false;
181        $parent = false;
182
183        ZLog::Write(LOGLEVEL_DEBUG, sprintf("IMAPBackend->SendMail(): RFC822: %d bytes  forward-id: '%s' reply-id: '%s' parent-id: '%s' SaveInSent: '%s' ReplaceMIME: '%s'",
184                                            strlen($sm->mime), Utils::PrintAsString($sm->forwardflag), Utils::PrintAsString($sm->replyflag),
185                                            Utils::PrintAsString((isset($sm->source->folderid) ? $sm->source->folderid : false)),
186                                            Utils::PrintAsString(($sm->saveinsent)), Utils::PrintAsString(isset($sm->replacemime)) ));
187
188        if (isset($sm->source->folderid) && $sm->source->folderid)
189            // convert parent folder id back to work on an imap-id
190            $parent = $this->getImapIdFromFolderId($sm->source->folderid);
191
192
193        // by splitting the message in several lines we can easily grep later
194        foreach(preg_split("/((\r)?\n)/", $sm->mime) as $rfc822line)
195            ZLog::Write(LOGLEVEL_WBXML, "RFC822: ". $rfc822line);
196
197        $mobj = new Mail_mimeDecode($sm->mime);
198        $message = $mobj->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
199
200        $Mail_RFC822 = new Mail_RFC822();
201        $toaddr = $ccaddr = $bccaddr = "";
202        if(isset($message->headers["to"]))
203            $toaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["to"]));
204        if(isset($message->headers["cc"]))
205            $ccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["cc"]));
206        if(isset($message->headers["bcc"]))
207            $bccaddr = $this->parseAddr($Mail_RFC822->parseAddressList($message->headers["bcc"]));
208
209        // save some headers when forwarding mails (content type & transfer-encoding)
210        $headers = "";
211        $forward_h_ct = "";
212        $forward_h_cte = "";
213        $envelopefrom = "";
214
215        $use_orgbody = false;
216
217        // clean up the transmitted headers
218        // remove default headers because we are using imap_mail
219        $changedfrom = false;
220        $returnPathSet = false;
221        $body_base64 = false;
222        $org_charset = "";
223        $org_boundary = false;
224        $multipartmixed = false;
225        foreach($message->headers as $k => $v) {
226            if ($k == "subject" || $k == "to" || $k == "cc" || $k == "bcc")
227                continue;
228
229            if ($k == "content-type") {
230                // if the message is a multipart message, then we should use the sent body
231                if (preg_match("/multipart/i", $v)) {
232                    $use_orgbody = true;
233                    $org_boundary = $message->ctype_parameters["boundary"];
234                }
235
236                // save the original content-type header for the body part when forwarding
237                if ($sm->forwardflag && !$use_orgbody) {
238                    $forward_h_ct = $v;
239                    continue;
240                }
241
242                // set charset always to utf-8
243                $org_charset = $v;
244                $v = preg_replace("/charset=([A-Za-z0-9-\"']+)/", "charset=\"utf-8\"", $v);
245            }
246
247            if ($k == "content-transfer-encoding") {
248                // if the content was base64 encoded, encode the body again when sending
249                if (trim($v) == "base64") $body_base64 = true;
250
251                // save the original encoding header for the body part when forwarding
252                if ($sm->forwardflag) {
253                    $forward_h_cte = $v;
254                    continue;
255                }
256            }
257
258            // check if "from"-header is set, do nothing if it's set
259            // else set it to IMAP_DEFAULTFROM
260            if ($k == "from") {
261                if (trim($v)) {
262                    $changedfrom = true;
263                } elseif (! trim($v) && IMAP_DEFAULTFROM) {
264                    $changedfrom = true;
265                    if      (IMAP_DEFAULTFROM == 'username') $v = $this->username;
266                    else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->domain;
267                    else $v = $this->username . IMAP_DEFAULTFROM;
268                    $envelopefrom = "-f$v";
269                }
270            }
271
272            // check if "Return-Path"-header is set
273            if ($k == "return-path") {
274                $returnPathSet = true;
275                if (! trim($v) && IMAP_DEFAULTFROM) {
276                    if      (IMAP_DEFAULTFROM == 'username') $v = $this->username;
277                    else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->domain;
278                    else $v = $this->username . IMAP_DEFAULTFROM;
279                }
280            }
281
282            // all other headers stay
283            if ($headers) $headers .= "\n";
284            $headers .= ucfirst($k) . ": ". $v;
285        }
286
287        // set "From" header if not set on the device
288        if(IMAP_DEFAULTFROM && !$changedfrom){
289            if      (IMAP_DEFAULTFROM == 'username') $v = $this->username;
290            else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->domain;
291            else $v = $this->username . IMAP_DEFAULTFROM;
292            if ($headers) $headers .= "\n";
293            $headers .= 'From: '.$v;
294            $envelopefrom = "-f$v";
295        }
296
297        // set "Return-Path" header if not set on the device
298        if(IMAP_DEFAULTFROM && !$returnPathSet){
299            if      (IMAP_DEFAULTFROM == 'username') $v = $this->username;
300            else if (IMAP_DEFAULTFROM == 'domain')   $v = $this->domain;
301            else $v = $this->username . IMAP_DEFAULTFROM;
302            if ($headers) $headers .= "\n";
303            $headers .= 'Return-Path: '.$v;
304        }
305
306        // if this is a multipart message with a boundary, we must use the original body
307        if ($use_orgbody) {
308            list(,$body) = $mobj->_splitBodyHeader($sm->mime);
309            $repl_body = $this->getBody($message);
310        }
311        else
312            $body = $this->getBody($message);
313
314        // reply
315        if ($sm->replyflag && $parent) {
316            $this->imap_reopenFolder($parent);
317            // receive entire mail (header + body) to decode body correctly
318            $origmail = @imap_fetchheader($this->mbox, $reply, FT_UID) . @imap_body($this->mbox, $reply, FT_PEEK | FT_UID);
319            if (!$origmail)
320                throw new StatusException(sprintf("BackendIMAP->SendMail(): Could not open message id '%s' in folder id '%s' to be replied: %s", $reply, $parent, imap_last_error()), SYNC_COMMONSTATUS_ITEMNOTFOUND);
321
322            $mobj2 = new Mail_mimeDecode($origmail);
323            // receive only body
324            $body .= $this->getBody($mobj2->decode(array('decode_headers' => false, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8')));
325            // unset mimedecoder & origmail - free memory
326            unset($mobj2);
327            unset($origmail);
328        }
329
330        // encode the body to base64 if it was sent originally in base64 by the pda
331        // contrib - chunk base64 encoded body
332        if ($body_base64 && !$sm->forwardflag) $body = chunk_split(base64_encode($body));
333
334
335        // forward
336        if ($sm->forwardflag && $parent) {
337            $this->imap_reopenFolder($parent);
338            // receive entire mail (header + body)
339            $origmail = @imap_fetchheader($this->mbox, $forward, FT_UID) . @imap_body($this->mbox, $forward, FT_PEEK | FT_UID);
340
341            if (!$origmail)
342                throw new StatusException(sprintf("BackendIMAP->SendMail(): Could not open message id '%s' in folder id '%s' to be forwarded: %s", $forward, $parent, imap_last_error()), SYNC_COMMONSTATUS_ITEMNOTFOUND);
343
344            if (!defined('IMAP_INLINE_FORWARD') || IMAP_INLINE_FORWARD === false) {
345                // contrib - chunk base64 encoded body
346                if ($body_base64) $body = chunk_split(base64_encode($body));
347                //use original boundary if it's set
348                $boundary = ($org_boundary) ? $org_boundary : false;
349                // build a new mime message, forward entire old mail as file
350                list($aheader, $body) = $this->mail_attach("forwarded_message.eml",strlen($origmail),$origmail, $body, $forward_h_ct, $forward_h_cte,$boundary);
351                // add boundary headers
352                $headers .= "\n" . $aheader;
353
354            }
355            else {
356                $mobj2 = new Mail_mimeDecode($origmail);
357                $mess2 = $mobj2->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
358
359                if (!$use_orgbody)
360                    $nbody = $body;
361                else
362                    $nbody = $repl_body;
363
364                $nbody .= "\r\n\r\n";
365                $nbody .= "-----Original Message-----\r\n";
366                if(isset($mess2->headers['from']))
367                    $nbody .= "From: " . $mess2->headers['from'] . "\r\n";
368                if(isset($mess2->headers['to']) && strlen($mess2->headers['to']) > 0)
369                    $nbody .= "To: " . $mess2->headers['to'] . "\r\n";
370                if(isset($mess2->headers['cc']) && strlen($mess2->headers['cc']) > 0)
371                    $nbody .= "Cc: " . $mess2->headers['cc'] . "\r\n";
372                if(isset($mess2->headers['date']))
373                    $nbody .= "Sent: " . $mess2->headers['date'] . "\r\n";
374                if(isset($mess2->headers['subject']))
375                    $nbody .= "Subject: " . $mess2->headers['subject'] . "\r\n";
376                $nbody .= "\r\n";
377                $nbody .= $this->getBody($mess2);
378
379                if ($body_base64) {
380                    // contrib - chunk base64 encoded body
381                    $nbody = chunk_split(base64_encode($nbody));
382                    if ($use_orgbody)
383                    // contrib - chunk base64 encoded body
384                        $repl_body = chunk_split(base64_encode($repl_body));
385                }
386
387                if ($use_orgbody) {
388                    ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): -------------------");
389                    ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): old:\n'$repl_body'\nnew:\n'$nbody'\nund der body:\n'$body'");
390                    //$body is quoted-printable encoded while $repl_body and $nbody are plain text,
391                    //so we need to decode $body in order replace to take place
392                    $body = str_replace($repl_body, $nbody, quoted_printable_decode($body));
393                }
394                else
395                    $body = $nbody;
396
397
398                if(isset($mess2->parts)) {
399                    $attached = false;
400
401                    if ($org_boundary) {
402                        $att_boundary = $org_boundary;
403                        // cut end boundary from body
404                        $body = substr($body, 0, strrpos($body, "--$att_boundary--"));
405                    }
406                    else {
407                        $att_boundary = strtoupper(md5(uniqid(time())));
408                        // add boundary headers
409                        $headers .= "\n" . "Content-Type: multipart/mixed; boundary=$att_boundary";
410                        $multipartmixed = true;
411                    }
412
413                    foreach($mess2->parts as $part) {
414                        if(isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) {
415
416                            if(isset($part->d_parameters['filename']))
417                                $attname = $part->d_parameters['filename'];
418                            else if(isset($part->ctype_parameters['name']))
419                                $attname = $part->ctype_parameters['name'];
420                            else if(isset($part->headers['content-description']))
421                                $attname = $part->headers['content-description'];
422                            else $attname = "unknown attachment";
423
424                            // ignore html content
425                            if ($part->ctype_primary == "text" && $part->ctype_secondary == "html") {
426                                continue;
427                            }
428                            //
429                            if ($use_orgbody || $attached) {
430                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
431                            }
432                            // first attachment
433                            else {
434                                $encmail = $body;
435                                $attached = true;
436                                $body = $this->enc_multipart($att_boundary, $body, $forward_h_ct, $forward_h_cte);
437                                $body .= $this->enc_attach_file($att_boundary, $attname, strlen($part->body),$part->body, $part->ctype_primary ."/". $part->ctype_secondary);
438                            }
439                        }
440                    }
441                    if ($multipartmixed && strpos(strtolower($mess2->headers['content-type']), "alternative") !== false) {
442                        //this happens if a multipart/alternative message is forwarded
443                        //then it's a multipart/mixed message which consists of:
444                        //1. text/plain part which was written on the mobile
445                        //2. multipart/alternative part which is the original message
446                        $body = "This is a message with multiple parts in MIME format.\n--".
447                                $att_boundary.
448                                "\nContent-Type: $forward_h_ct\nContent-Transfer-Encoding: $forward_h_cte\n\n".
449                                (($body_base64) ? chunk_split(base64_encode($message->body)) : rtrim($message->body)).
450                                "\n--".$att_boundary.
451                                "\nContent-Type: {$mess2->headers['content-type']}\n\n".
452                                @imap_body($this->mbox, $forward, FT_PEEK | FT_UID)."\n\n";
453                    }
454                    $body .= "--$att_boundary--\n\n";
455                }
456
457                unset($mobj2);
458            }
459
460            // unset origmail - free memory
461            unset($origmail);
462
463        }
464
465        // remove carriage-returns from body
466        $body = str_replace("\r\n", "\n", $body);
467
468        if (!$multipartmixed) {
469            if (!empty($forward_h_ct)) $headers .= "\nContent-Type: $forward_h_ct";
470            if (!empty($forward_h_cte)) $headers .= "\nContent-Transfer-Encoding: $forward_h_cte";
471        //  if body was quoted-printable, convert it again
472            if (isset($message->headers["content-transfer-encoding"]) && strtolower($message->headers["content-transfer-encoding"]) == "quoted-printable") {
473                $body = quoted_printable_encode($body);
474            }
475        }
476
477        // more debugging
478        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): parsed message: ". print_r($message,1));
479        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): headers: $headers");
480        /* BEGIN fmbiete's contribution r1528, ZP-320 */
481        if (isset($message->headers["subject"])) {
482            ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): subject: {$message->headers["subject"]}");
483        }
484        else {
485            ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): subject: no subject set. Set to empty.");
486            $message->headers["subject"] = ""; // added by mku ZP-330
487        }
488        /* END fmbiete's contribution r1528, ZP-320 */
489        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): body: $body");
490
491        if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
492            // changed by mku ZP-330
493            $send =  @imap_mail ( $toaddr, $message->headers["subject"], $body, $headers, $ccaddr, $bccaddr);
494        }
495        else {
496            if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
497            if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
498            // changed by mku ZP-330
499
500            require_once(__DIR__."/../../../../library/Mail/Mail.php");
501            $mail_object =& Mail::factory("smtp", $GLOBALS['config']['SMTP']);
502            $send = $mail_object->send($toaddr, $message->headers , $body);
503          //  $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom );
504        }
505
506        // email sent?
507        if (!$send)
508            throw new StatusException(sprintf("BackendIMAP->SendMail(): The email could not be sent. Last IMAP-error: %s", imap_last_error()), SYNC_COMMONSTATUS_MAILSUBMISSIONFAILED);
509
510        // add message to the sent folder
511        // build complete headers
512        $headers .= "\nTo: $toaddr";
513        $headers .= "\nSubject: " . $message->headers["subject"]; // changed by mku ZP-330
514
515        if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
516            if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
517            if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
518        }
519        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): complete headers: $headers");
520
521        $asf = false;
522        if ($this->sentID) {
523            $asf = $this->addSentMessage($this->sentID, $headers, $body);
524        }
525        else if (IMAP_SENTFOLDER) {
526            $asf = $this->addSentMessage(IMAP_SENTFOLDER, $headers, $body);
527            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->SendMail(): Outgoing mail saved in configured 'Sent' folder '%s': %s", IMAP_SENTFOLDER, Utils::PrintAsString($asf)));
528        }
529        // No Sent folder set, try defaults
530        else {
531            ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): No Sent mailbox set");
532            if($this->addSentMessage("INBOX.Sent", $headers, $body)) {
533                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): Outgoing mail saved in 'INBOX.Sent'");
534                $asf = true;
535            }
536            else if ($this->addSentMessage("Sent", $headers, $body)) {
537                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): Outgoing mail saved in 'Sent'");
538                $asf = true;
539            }
540            else if ($this->addSentMessage("Sent Items", $headers, $body)) {
541                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail():IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
542                $asf = true;
543            }
544        }
545
546        if (!$asf) {
547            ZLog::Write(LOGLEVEL_ERROR, "BackendIMAP->SendMail(): The email could not be saved to Sent Items folder. Check your configuration.");
548        }
549
550        return $send;
551    }
552
553    /**
554     * Returns the waste basket
555     *
556     * @access public
557     * @return string
558     */
559    public function GetWasteBasket() {
560        // TODO this could be retrieved from the DeviceFolderCache
561        if ($this->wasteID == false) {
562            //try to get the waste basket without doing complete hierarchy sync
563            $wastebaskt = @imap_getmailboxes($this->mbox, $this->server, IMAP_TRASHFOLDER);
564            if (isset($wastebaskt[0])) {
565                $this->wasteID = $this->convertImapId(substr($wastebaskt[0]->name, strlen($this->server)));
566                return $this->wasteID;
567            }
568            //try get waste id from hierarchy if it wasn't possible with above for some reason
569            $this->GetHierarchy();
570        }
571        return $this->wasteID;
572    }
573
574    /**
575     * Returns the content of the named attachment as stream. The passed attachment identifier is
576     * the exact string that is returned in the 'AttName' property of an SyncAttachment.
577     * Any information necessary to find the attachment must be encoded in that 'attname' property.
578     * Data is written directly (with print $data;)
579     *
580     * @param string        $attname
581     *
582     * @access public
583     * @return SyncItemOperationsAttachment
584     * @throws StatusException
585     */
586    public function GetAttachmentData($attname) {
587        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetAttachmentData('%s')", $attname));
588
589        list($folderid, $id, $part) = explode(":", $attname);
590
591        if (!$folderid || !$id || !$part)
592            throw new StatusException(sprintf("BackendIMAP->GetAttachmentData('%s'): Error, attachment name key can not be parsed", $attname), SYNC_ITEMOPERATIONSSTATUS_INVALIDATT);
593
594        // convert back to work on an imap-id
595        $folderImapid = $this->getImapIdFromFolderId($folderid);
596
597        $this->imap_reopenFolder($folderImapid);
598        $mail = @imap_fetchheader($this->mbox, $id, FT_UID) . @imap_body($this->mbox, $id, FT_PEEK | FT_UID);
599
600        $mobj = new Mail_mimeDecode($mail);
601        $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
602
603        /* BEGIN fmbiete's contribution r1528, ZP-320 */
604        //trying parts
605        $mparts = $message->parts;
606        for ($i = 0; $i < count($mparts); $i++) {
607            $auxpart = $mparts[$i];
608            //recursively add parts
609            if($auxpart->ctype_primary == "multipart" && ($auxpart->ctype_secondary == "mixed" || $auxpart->ctype_secondary == "alternative"  || $auxpart->ctype_secondary == "related")) {
610                foreach($auxpart->parts as $spart)
611                    $mparts[] = $spart;
612            }
613        }
614        /* END fmbiete's contribution r1528, ZP-320 */
615
616        if (!isset($mparts[$part]->body))
617            throw new StatusException(sprintf("BackendIMAP->GetAttachmentData('%s'): Error, requested part key can not be found: '%d'", $attname, $part), SYNC_ITEMOPERATIONSSTATUS_INVALIDATT);
618
619        // unset mimedecoder & mail
620        unset($mobj);
621        unset($mail);
622
623        include_once('include/stringstreamwrapper.php');
624        $attachment = new SyncItemOperationsAttachment();
625        /* BEGIN fmbiete's contribution r1528, ZP-320 */
626        $attachment->data = StringStreamWrapper::Open($mparts[$part]->body);
627        if (isset($mparts[$part]->ctype_primary) && isset($mparts[$part]->ctype_secondary))
628            $attachment->contenttype = $mparts[$part]->ctype_primary .'/'.$mparts[$part]->ctype_secondary;
629
630        unset($mparts);
631        unset($message);
632
633        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetAttachmentData contenttype %s", $attachment->contenttype));
634        /* END fmbiete's contribution r1528, ZP-320 */
635
636        return $attachment;
637    }
638
639    /**
640     * Indicates if the backend has a ChangesSink.
641     * A sink is an active notification mechanism which does not need polling.
642     * The IMAP backend simulates a sink by polling status information of the folder
643     *
644     * @access public
645     * @return boolean
646     */
647    public function HasChangesSink() {
648        $this->sinkfolders = array();
649        $this->sinkstates = array();
650        return true;
651    }
652
653    /**
654     * The folder should be considered by the sink.
655     * Folders which were not initialized should not result in a notification
656     * of IBacken->ChangesSink().
657     *
658     * @param string        $folderid
659     *
660     * @access public
661     * @return boolean      false if found can not be found
662     */
663    public function ChangesSinkInitialize($folderid) {
664        ZLog::Write(LOGLEVEL_DEBUG, sprintf("IMAPBackend->ChangesSinkInitialize(): folderid '%s'", $folderid));
665
666        $imapid = $this->getImapIdFromFolderId($folderid);
667
668        if ($imapid) {
669            $this->sinkfolders[] = $imapid;
670            return true;
671        }
672
673        return false;
674    }
675
676    /**
677     * The actual ChangesSink.
678     * For max. the $timeout value this method should block and if no changes
679     * are available return an empty array.
680     * If changes are available a list of folderids is expected.
681     *
682     * @param int           $timeout        max. amount of seconds to block
683     *
684     * @access public
685     * @return array
686     */
687    public function ChangesSink($timeout = 30) {
688        $notifications = array();
689        $stopat = time() + $timeout - 1;
690
691        while($stopat > time() && empty($notifications)) {
692            foreach ($this->sinkfolders as $imapid) {
693                $this->imap_reopenFolder($imapid);
694
695                // courier-imap only cleares the status cache after checking
696                @imap_check($this->mbox);
697
698                $status = @imap_status($this->mbox, $this->server . $imapid, SA_ALL);
699                if (!$status) {
700                    ZLog::Write(LOGLEVEL_WARN, sprintf("ChangesSink: could not stat folder '%s': %s ", $this->getFolderIdFromImapId($imapid), imap_last_error()));
701                }
702                else {
703                    $newstate = "M:". $status->messages ."-R:". $status->recent ."-U:". $status->unseen;
704
705                    if (! isset($this->sinkstates[$imapid]) )
706                        $this->sinkstates[$imapid] = $newstate;
707
708                    if ($this->sinkstates[$imapid] != $newstate) {
709                        $notifications[] = $this->getFolderIdFromImapId($imapid);
710                        $this->sinkstates[$imapid] = $newstate;
711                    }
712                }
713            }
714
715            if (empty($notifications))
716                sleep(5);
717        }
718
719        return $notifications;
720    }
721
722
723    /**----------------------------------------------------------------------------------------------------------
724     * implemented DiffBackend methods
725     */
726
727
728    /**
729     * Returns a list (array) of folders.
730     *
731     * @access public
732     * @return array/boolean        false if the list could not be retrieved
733     */
734    public function GetFolderList() {
735        $folders = array();
736
737        $list = @imap_getmailboxes($this->mbox, $this->server, "*");
738        if (is_array($list)) {
739            // reverse list to obtain folders in right order
740            $list = array_reverse($list);
741
742            foreach ($list as $val) {
743                /* BEGIN fmbiete's contribution r1527, ZP-319 */
744                // don't return the excluded folders
745                $notExcluded = true;
746                for ($i = 0, $cnt = count($this->excludedFolders); $notExcluded && $i < $cnt; $i++) { // expr1, expr2 modified by mku ZP-329
747                    // fix exclude folders with special chars by mku ZP-329
748                    if (strpos(strtolower($val->name), strtolower(Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($this->excludedFolders[$i])))) !== false) {
749                        $notExcluded = false;
750                        ZLog::Write(LOGLEVEL_DEBUG, sprintf("Pattern: <%s> found, excluding folder: '%s'", $this->excludedFolders[$i], $val->name)); // sprintf added by mku ZP-329
751                    }
752                }
753
754                if ($notExcluded) {
755                    $box = array();
756                    // cut off serverstring
757                    $imapid = substr($val->name, strlen($this->server));
758                    $box["id"] = $this->convertImapId($imapid);
759
760                    $fhir = explode($val->delimiter, $imapid);
761                    if (count($fhir) > 1) {
762                        $this->getModAndParentNames($fhir, $box["mod"], $imapparent);
763                        $box["parent"] = $this->convertImapId($imapparent);
764                    }
765                    else {
766                        $box["mod"] = $imapid;
767                        $box["parent"] = "0";
768                    }
769                    $folders[]=$box;
770                    /* END fmbiete's contribution r1527, ZP-319 */
771                }
772            }
773        }
774        else {
775            ZLog::Write(LOGLEVEL_WARN, "BackendIMAP->GetFolderList(): imap_list failed: " . imap_last_error());
776            return false;
777        }
778
779        return $folders;
780    }
781
782    /**
783     * Returns an actual SyncFolder object
784     *
785     * @param string        $id           id of the folder
786     *
787     * @access public
788     * @return object       SyncFolder with information
789     */
790    public function GetFolder($id) {
791        $folder = new SyncFolder();
792        $folder->serverid = $id;
793
794        // convert back to work on an imap-id
795        $imapid = $this->getImapIdFromFolderId($id);
796
797        // explode hierarchy
798        $fhir = explode($this->serverdelimiter, $imapid);
799
800        // compare on lowercase strings
801        $lid = strtolower($imapid);
802// TODO WasteID or SentID could be saved for later ussage
803        if($lid == "inbox") {
804            $folder->parentid = "0"; // Root
805            $folder->displayname = "Inbox";
806            $folder->type = SYNC_FOLDER_TYPE_INBOX;
807        }
808//        // Zarafa IMAP-Gateway outputs
809//        else if($lid == "drafts") {
810//            $folder->parentid = "0";
811//            $folder->displayname = "Drafts";
812//            $folder->type = SYNC_FOLDER_TYPE_DRAFTS;
813//        }
814//        else if($lid == "trash") {
815//            $folder->parentid = "0";
816//            $folder->displayname = "Trash";
817//            $folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
818//            $this->wasteID = $id;
819//        }
820//        else if($lid == "sent" || $lid == "sent items" || $lid == IMAP_SENTFOLDER) {
821//            $folder->parentid = "0";
822//            $folder->displayname = "Sent";
823//            $folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
824//            //$this->sentID = $id;
825//        }
826        // courier-imap outputs and cyrus-imapd outputs
827        //else if(  $lid == "inbox.drafts" || $lid == "inbox/drafts") {
828        else if(  $lid == strtolower(IMAP_DRAFTFOLDER) ) {
829            $folder->parentid = $this->convertImapId($fhir[0]);
830            $folder->displayname = "Drafts";
831            $folder->type = SYNC_FOLDER_TYPE_DRAFTS;
832        }
833        else if($lid == strtolower(IMAP_TRASHFOLDER) ) {
834            $folder->parentid = $this->convertImapId($fhir[0]);
835            $folder->displayname = "Trash";
836            $folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
837            $this->wasteID = $id;
838        }
839        else if($lid == strtolower(IMAP_SENTFOLDER) ) {
840            $folder->parentid = $this->convertImapId($fhir[0]);
841            $folder->displayname = "Sent";
842            $folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
843            //$this->sentID = $id;
844        }
845
846        // define the rest as other-folders
847        else {
848            if (count($fhir) > 1) {
849                $this->getModAndParentNames($fhir, $folder->displayname, $imapparent);
850                $folder->parentid = $this->convertImapId($imapparent);
851                $folder->displayname = Utils::Utf7_to_utf8(Utils::Utf7_iconv_decode($folder->displayname));
852            }
853            else {
854                $folder->displayname = Utils::Utf7_to_utf8(Utils::Utf7_iconv_decode($imapid));
855                $folder->parentid = "0";
856            }
857            $folder->type = SYNC_FOLDER_TYPE_USER_MAIL;
858        }
859
860        //advanced debugging
861        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetFolder('%s'): '%s'", $id, $folder));
862
863        return $folder;
864    }
865
866    /**
867     * Returns folder stats. An associative array with properties is expected.
868     *
869     * @param string        $id             id of the folder
870     *
871     * @access public
872     * @return array
873     */
874    public function StatFolder($id) {
875        $folder = $this->GetFolder($id);
876
877        $stat = array();
878        $stat["id"] = $id;
879        $stat["parent"] = $folder->parentid;
880        $stat["mod"] = $folder->displayname;
881
882        return $stat;
883    }
884
885    /**
886     * Creates or modifies a folder
887     * The folder type is ignored in IMAP, as all folders are Email folders
888     *
889     * @param string        $folderid       id of the parent folder
890     * @param string        $oldid          if empty -> new folder created, else folder is to be renamed
891     * @param string        $displayname    new folder name (to be created, or to be renamed to)
892     * @param int           $type           folder type
893     *
894     * @access public
895     * @return boolean                      status
896     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
897     *
898     */
899    public function ChangeFolder($folderid, $oldid, $displayname, $type){
900        ZLog::Write(LOGLEVEL_INFO, sprintf("BackendIMAP->ChangeFolder('%s','%s','%s','%s')", $folderid, $oldid, $displayname, $type));
901
902        // go to parent mailbox
903        $this->imap_reopenFolder($folderid);
904
905        // build name for new mailboxBackendMaildir
906        $displayname = Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($displayname));;
907        $new = $this->server . $this->getImapIdFromFolderId($folderid) . $this->serverdelimiter.  $displayname;
908        $csts = false;
909
910        $csts = ($oldid) ? imap_renamemailbox($this->mbox,  $this->server .$this->getImapIdFromFolderId($oldid) , $new) : imap_createmailbox($this->mbox, $new);
911
912        if ($csts) {
913           $newId =  $this->convertImapId($new);
914           return $this->StatFolder($newId);
915        }
916        else
917            return false;
918    }
919
920    /**
921     * Deletes a folder
922     *
923     * @param string        $id
924     * @param string        $parent         is normally false
925     *
926     * @access public
927     * @return boolean                      status - false if e.g. does not exist
928     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
929     *
930     */
931    public function DeleteFolder($id, $parentid)
932    {
933        $ret = imap_deletemailbox($this->mbox , $this->server .$this->getImapIdFromFolderId($id) );
934        imap_expunge( $this->mbox );
935        return $ret;
936    }
937
938    /**
939     * Returns a list (array) of messages
940     *
941     * @param string        $folderid       id of the parent folder
942     * @param long          $cutoffdate     timestamp in the past from which on messages should be returned
943     *
944     * @access public
945     * @return array/false  array with messages or false if folder is not available
946     */
947    public function GetMessageList($folderid, $cutoffdate) {
948        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetMessageList('%s','%s')", $folderid, $cutoffdate));
949
950        $folderid = $this->getImapIdFromFolderId($folderid);
951
952        if ($folderid == false)
953            throw new StatusException("Folderid not found in cache", SYNC_STATUS_FOLDERHIERARCHYCHANGED);
954
955        $messages = array();
956        $this->imap_reopenFolder($folderid, true);
957
958        $sequence = "1:*";
959        if ($cutoffdate > 0) {
960            $search = @imap_search($this->mbox, "SINCE ". date("d-M-Y", $cutoffdate));
961            if ($search !== false)
962                $sequence = implode(",", $search);
963        }
964        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetMessageList(): searching with sequence '%s'", $sequence));
965        $overviews = @imap_fetch_overview($this->mbox, $sequence);
966
967        if (!$overviews || !is_array($overviews)) {
968            ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->GetMessageList('%s','%s'): Failed to retrieve overview: %s",$folderid, $cutoffdate, imap_last_error()));
969            return $messages;
970        }
971
972        foreach($overviews as $overview) {
973            $date = "";
974            $vars = get_object_vars($overview);
975            if (array_key_exists( "date", $vars)) {
976                // message is out of range for cutoffdate, ignore it
977                if ($this->cleanupDate($overview->date) < $cutoffdate) continue;
978                $date = $overview->date;
979            }
980
981            // cut of deleted messages
982            if (array_key_exists("deleted", $vars) && $overview->deleted)
983                continue;
984
985            if (array_key_exists("uid", $vars)) {
986                $message = array();
987                $message["mod"] = $date;
988                $message["id"] = $overview->uid;
989                // 'seen' aka 'read' is the only flag we want to know about
990                $message["flags"] = 0;
991
992                if(array_key_exists( "seen", $vars) && $overview->seen)
993                    $message["flags"] = 1;
994
995                array_push($messages, $message);
996            }
997        }
998        return $messages;
999    }
1000
1001    /**
1002     * Returns the actual SyncXXX object type.
1003     *
1004     * @param string            $folderid           id of the parent folder
1005     * @param string            $id                 id of the message
1006     * @param ContentParameters $contentparameters  parameters of the requested message (truncation, mimesupport etc)
1007     *
1008     * @access public
1009     * @return object/false     false if the message could not be retrieved
1010     */
1011    public function GetMessage($folderid, $id, $contentparameters) {
1012        $truncsize = Utils::GetTruncSize($contentparameters->GetTruncation());
1013        $mimesupport = $contentparameters->GetMimeSupport();
1014        $bodypreference = $contentparameters->GetBodyPreference(); /* fmbiete's contribution r1528, ZP-320 */
1015        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetMessage('%s','%s')", $folderid,  $id));
1016
1017        $folderImapid = $this->getImapIdFromFolderId($folderid);
1018
1019        // Get flags, etc
1020        $stat = $this->StatMessage($folderid, $id);
1021
1022        if ($stat) {
1023            $this->imap_reopenFolder($folderImapid);
1024            $mail = @imap_fetchheader($this->mbox, $id, FT_UID) . @imap_body($this->mbox, $id, FT_PEEK | FT_UID);
1025
1026            $mobj = new Mail_mimeDecode($mail);
1027            $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
1028
1029
1030
1031
1032            /* BEGIN fmbiete's contribution r1528, ZP-320 */
1033            $output = new SyncMail();
1034
1035            //Select body type preference
1036            $bpReturnType = SYNC_BODYPREFERENCE_PLAIN;
1037            if ($bodypreference !== false) {
1038                $bpReturnType = Utils::GetBodyPreferenceBestMatch($bodypreference); // changed by mku ZP-330
1039            }
1040            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetMessage - getBodyPreferenceBestMatch: %d", $bpReturnType));
1041
1042            //Get body data
1043            $this->getBodyRecursive($message, "plain", $plainBody);
1044            $this->getBodyRecursive($message, "html", $htmlBody);
1045            if ($plainBody == "") {
1046                $plainBody = Utils::ConvertHtmlToText($htmlBody);
1047            }
1048            $htmlBody = str_replace("\n","\r\n", str_replace("\r","",$htmlBody));
1049            $plainBody = str_replace("\n","\r\n", str_replace("\r","",$plainBody));
1050            $plainBody = html_entity_decode($plainBody);
1051            if (Request::GetProtocolVersion() >= 12.0) {
1052                $output->asbody = new SyncBaseBody();
1053
1054                switch($bpReturnType) {
1055                    case SYNC_BODYPREFERENCE_PLAIN:
1056                        $output->asbody->data = $plainBody;
1057                        break;
1058                    case SYNC_BODYPREFERENCE_HTML:
1059                        if ($htmlBody == "") {
1060                            $output->asbody->data = $plainBody;
1061                            $bpReturnType = SYNC_BODYPREFERENCE_PLAIN;
1062                        }
1063                        else {
1064                            $output->asbody->data = $htmlBody;
1065                        }
1066                        break;
1067                    case SYNC_BODYPREFERENCE_MIME:
1068                        //We don't need to create a new MIME mail, we already have one!!
1069                        $output->asbody->data = $mail;
1070                        break;
1071                    case SYNC_BODYPREFERENCE_RTF:
1072                        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->GetMessage RTF Format NOT CHECKED");
1073                        $output->asbody->data = base64_encode($plainBody);
1074                        break;
1075                }
1076                // truncate body, if requested
1077                if(strlen($output->asbody->data) > $truncsize) {
1078                    $output->asbody->data = Utils::Utf8_truncate($output->asbody->data, $truncsize);
1079                    $output->asbody->truncated = 1;
1080                }
1081
1082                $output->asbody->type = $bpReturnType;
1083                $output->nativebodytype = $bpReturnType;
1084                $output->asbody->estimatedDataSize = strlen($output->asbody->data);
1085
1086                $bpo = $contentparameters->BodyPreference($output->asbody->type);
1087                if (Request::GetProtocolVersion() >= 14.0 && $bpo->GetPreview()) {
1088                    $output->asbody->preview = Utils::Utf8_truncate(Utils::ConvertHtmlToText($plainBody), $bpo->GetPreview());
1089                }
1090                else {
1091                    $output->asbody->truncated = 0;
1092                }
1093            }
1094            /* END fmbiete's contribution r1528, ZP-320 */
1095            else { // ASV_2.5
1096                $output->bodytruncated = 0;
1097                /* BEGIN fmbiete's contribution r1528, ZP-320 */
1098                if ($bpReturnType == SYNC_BODYPREFERENCE_MIME) {
1099                    if (strlen($mail) > $truncsize) {
1100                        $output->mimedata = Utils::Utf8_truncate($mail, $truncsize);
1101                        $output->mimetruncated = 1;
1102                    }
1103                    else {
1104                        $output->mimetruncated = 0;
1105                        $output->mimedata = $mail;
1106                    }
1107                    $output->mimesize = strlen($output->mimedata);
1108                }
1109                else {
1110                    // truncate body, if requested
1111                    if (strlen($plainBody) > $truncsize) {
1112                        $output->body = Utils::Utf8_truncate($plainBody, $truncsize);
1113                        $output->bodytruncated = 1;
1114                    }
1115                    else {
1116                        $output->body = $plainBody;
1117                        $output->bodytruncated = 0;
1118                    }
1119                    $output->bodysize = strlen($output->body);
1120                }
1121                /* END fmbiete's contribution r1528, ZP-320 */
1122            }
1123
1124            $output->datereceived = isset($message->headers["date"]) ? $this->cleanupDate($message->headers["date"]) : null;
1125            $output->messageclass = "IPM.Note";
1126            $output->subject = isset($message->headers["subject"]) ? $message->headers["subject"] : "";
1127            $output->read = $stat["flags"];
1128            $output->from = isset($message->headers["from"]) ? $message->headers["from"] : null;
1129
1130            /* BEGIN fmbiete's contribution r1528, ZP-320 */
1131            if (isset($message->headers["thread-topic"])) {
1132                $output->threadtopic = $message->headers["thread-topic"];
1133            }
1134
1135            // Language Code Page ID: http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx
1136            $output->internetcpid = INTERNET_CPID_UTF8;
1137            if (Request::GetProtocolVersion() >= 12.0) {
1138                $output->contentclass = "urn:content-classes:message";
1139            }
1140            /* END fmbiete's contribution r1528, ZP-320 */
1141
1142            $Mail_RFC822 = new Mail_RFC822();
1143            $toaddr = $ccaddr = $replytoaddr = array();
1144            if(isset($message->headers["to"]))
1145                $toaddr = $Mail_RFC822->parseAddressList($message->headers["to"]);
1146            if(isset($message->headers["cc"]))
1147                $ccaddr = $Mail_RFC822->parseAddressList($message->headers["cc"]);
1148            if(isset($message->headers["reply_to"]))
1149                $replytoaddr = $Mail_RFC822->parseAddressList($message->headers["reply_to"]);
1150
1151            $output->to = array();
1152            $output->cc = array();
1153            $output->reply_to = array();
1154            foreach(array("to" => $toaddr, "cc" => $ccaddr, "reply_to" => $replytoaddr) as $type => $addrlist) {
1155                foreach($addrlist as $addr) {
1156                    $address = $addr->mailbox . "@" . $addr->host;
1157                    $name = $addr->personal;
1158
1159                    if (!isset($output->displayto) && $name != "")
1160                        $output->displayto = $name;
1161
1162                    if($name == "" || $name == $address)
1163                        $fulladdr = w2u($address);
1164                    else {
1165                        if (substr($name, 0, 1) != '"' && substr($name, -1) != '"') {
1166                            $fulladdr = "\"" . w2u($name) ."\" <" . w2u($address) . ">";
1167                        }
1168                        else {
1169                            $fulladdr = w2u($name) ." <" . w2u($address) . ">";
1170                        }
1171                    }
1172
1173                    array_push($output->$type, $fulladdr);
1174                }
1175            }
1176
1177            // convert mime-importance to AS-importance
1178            if (isset($message->headers["x-priority"])) {
1179                $mimeImportance =  preg_replace("/\D+/", "", $message->headers["x-priority"]);
1180                //MAIL 1 - most important, 3 - normal, 5 - lowest
1181                //AS 0 - low, 1 - normal, 2 - important
1182                if ($mimeImportance > 3)
1183                    $output->importance = 0;
1184                if ($mimeImportance == 3)
1185                    $output->importance = 1;
1186                if ($mimeImportance < 3)
1187                    $output->importance = 2;
1188            } else { /* fmbiete's contribution r1528, ZP-320 */
1189                $output->importance = 1;
1190            }
1191
1192            // Attachments are not needed for MIME messages
1193            if($bpReturnType != SYNC_BODYPREFERENCE_MIME && isset($message->parts)) {
1194                $mparts = $message->parts;
1195                for ($i=0; $i<count($mparts); $i++) {
1196                    $part = $mparts[$i];
1197                    //recursively add parts
1198                    if($part->ctype_primary == "multipart" && ($part->ctype_secondary == "mixed" || $part->ctype_secondary == "alternative"  || $part->ctype_secondary == "related")) {
1199                        foreach($part->parts as $spart)
1200                            $mparts[] = $spart;
1201                        continue;
1202                    }
1203                    //add part as attachment if it's disposition indicates so or if it is not a text part
1204                    if ((isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) ||
1205                        (isset($part->ctype_primary) && $part->ctype_primary != "text")) {
1206
1207                        if(isset($part->d_parameters['filename']))
1208                            $attname = $part->d_parameters['filename'];
1209                        else if(isset($part->ctype_parameters['name']))
1210                            $attname = $part->ctype_parameters['name'];
1211                        else if(isset($part->headers['content-description']))
1212                            $attname = $part->headers['content-description'];
1213                        else $attname = "unknown attachment";
1214
1215                        /* BEGIN fmbiete's contribution r1528, ZP-320 */
1216                        if (Request::GetProtocolVersion() >= 12.0) {
1217                            if (!isset($output->asattachments) || !is_array($output->asattachments))
1218                                $output->asattachments = array();
1219
1220                            $attachment = new SyncBaseAttachment();
1221
1222                            $attachment->estimatedDataSize = isset($part->d_parameters['size']) ? $part->d_parameters['size'] : isset($part->body) ? strlen($part->body) : 0;
1223
1224                            $attachment->displayname = $attname;
1225                            $attachment->filereference = $folderid . ":" . $id . ":" . $i;
1226                            $attachment->method = 1; //Normal attachment
1227                            $attachment->contentid = isset($part->headers['content-id']) ? str_replace("<", "", str_replace(">", "", $part->headers['content-id'])) : "";
1228                            if (isset($part->disposition) && $part->disposition == "inline") {
1229                                $attachment->isinline = 1;
1230                            }
1231                            else {
1232                                $attachment->isinline = 0;
1233                            }
1234
1235                            array_push($output->asattachments, $attachment);
1236                        }
1237                        else { //ASV_2.5
1238                            if (!isset($output->attachments) || !is_array($output->attachments))
1239                                $output->attachments = array();
1240
1241                            $attachment = new SyncAttachment();
1242
1243                            $attachment->attsize = isset($part->d_parameters['size']) ? $part->d_parameters['size'] : isset($part->body) ? strlen($part->body) : 0;
1244
1245                            $attachment->displayname = $attname;
1246                            $attachment->attname = $folderid . ":" . $id . ":" . $i;
1247                            $attachment->attmethod = 1;
1248                            $attachment->attoid = isset($part->headers['content-id']) ? str_replace("<", "", str_replace(">", "", $part->headers['content-id'])) : "";
1249
1250                            array_push($output->attachments, $attachment);
1251                        }
1252                        /* END fmbiete's contribution r1528, ZP-320 */
1253                    }
1254                }
1255            }
1256            // unset mimedecoder & mail
1257            unset($mobj);
1258            unset($mail);
1259            return $output;
1260        }
1261
1262        return false;
1263    }
1264
1265    /**
1266     * Returns message stats, analogous to the folder stats from StatFolder().
1267     *
1268     * @param string        $folderid       id of the folder
1269     * @param string        $id             id of the message
1270     *
1271     * @access public
1272     * @return array/boolean
1273     */
1274    public function StatMessage($folderid, $id) {
1275        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->StatMessage('%s','%s')", $folderid,  $id));
1276        $folderImapid = $this->getImapIdFromFolderId($folderid);
1277
1278        $this->imap_reopenFolder($folderImapid);
1279        $overview = @imap_fetch_overview( $this->mbox , $id , FT_UID);
1280
1281        if (!$overview) {
1282            ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->StatMessage('%s','%s'): Failed to retrieve overview: %s", $folderid,  $id, imap_last_error()));
1283            return false;
1284        }
1285
1286        // check if variables for this overview object are available
1287        $vars = get_object_vars($overview[0]);
1288
1289        // without uid it's not a valid message
1290        if (! array_key_exists( "uid", $vars)) return false;
1291
1292        $entry = array();
1293        $entry["mod"] = (array_key_exists( "date", $vars)) ? $overview[0]->date : "";
1294        $entry["id"] = $overview[0]->uid;
1295        // 'seen' aka 'read' is the only flag we want to know about
1296        $entry["flags"] = 0;
1297
1298        if(array_key_exists( "seen", $vars) && $overview[0]->seen)
1299            $entry["flags"] = 1;
1300
1301        return $entry;
1302    }
1303
1304    /**
1305     * Called when a message has been changed on the mobile.
1306     * Added support for FollowUp flag
1307     *
1308     * @param string        $folderid       id of the folder
1309     * @param string        $id             id of the message
1310     * @param SyncXXX       $message        the SyncObject containing a message
1311     *
1312     * @access public
1313     * @return array                        same return value as StatMessage()
1314     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1315     */
1316    public function ChangeMessage($folderid, $id, $message) {
1317        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->ChangeMessage('%s','%s','%s')", $folderid, $id, get_class($message)));
1318
1319        /* BEGIN fmbiete's contribution r1529, ZP-321 */
1320        if (isset($message->flag)) {
1321            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->ChangeMessage('Setting flag')"));
1322
1323            $folderImapid = $this->getImapIdFromFolderId($folderid);
1324
1325            $this->imap_reopenFolder($folderImapid);
1326
1327            if (isset($message->flag->flagstatus) && $message->flag->flagstatus == 2) {
1328                ZLog::Write(LOGLEVEL_DEBUG, "Set On FollowUp -> IMAP Flagged");
1329                $status = @imap_setflag_full($this->mbox, $id, "\\Flagged",ST_UID);
1330            }
1331            else {
1332                ZLog::Write(LOGLEVEL_DEBUG, "Clearing Flagged");
1333                $status = @imap_clearflag_full ( $this->mbox, $id, "\\Flagged", ST_UID);
1334            }
1335
1336            if ($status) {
1337                ZLog::Write(LOGLEVEL_DEBUG, "Flagged changed");
1338            }
1339            else {
1340                ZLog::Write(LOGLEVEL_DEBUG, "Flagged failed");
1341            }
1342        }
1343
1344        return $this->StatMessage($folderid, $id);
1345        /* END fmbiete's contribution r1529, ZP-321 */
1346    }
1347
1348    /**
1349     * Changes the 'read' flag of a message on disk
1350     *
1351     * @param string        $folderid       id of the folder
1352     * @param string        $id             id of the message
1353     * @param int           $flags          read flag of the message
1354     *
1355     * @access public
1356     * @return boolean                      status of the operation
1357     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1358     */
1359    public function SetReadFlag($folderid, $id, $flags) {
1360        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->SetReadFlag('%s','%s','%s')", $folderid, $id, $flags));
1361        $folderImapid = $this->getImapIdFromFolderId($folderid);
1362
1363        $this->imap_reopenFolder($folderImapid);
1364
1365        if ($flags == 0) {
1366            // set as "Unseen" (unread)
1367            $status = @imap_clearflag_full ( $this->mbox, $id, "\\Seen", ST_UID);
1368        } else {
1369            // set as "Seen" (read)
1370            $status = @imap_setflag_full($this->mbox, $id, "\\Seen",ST_UID);
1371        }
1372
1373        return $status;
1374    }
1375
1376    /**
1377     * Called when the user has requested to delete (really delete) a message
1378     *
1379     * @param string        $folderid       id of the folder
1380     * @param string        $id             id of the message
1381     *
1382     * @access public
1383     * @return boolean                      status of the operation
1384     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1385     */
1386    public function DeleteMessage($folderid, $id) {
1387        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->DeleteMessage('%s','%s')", $folderid, $id));
1388        $folderImapid = $this->getImapIdFromFolderId($folderid);
1389
1390        $this->imap_reopenFolder($folderImapid);
1391        $s1 = @imap_delete ($this->mbox, $id, FT_UID);
1392        $s11 = @imap_setflag_full($this->mbox, $id, "\\Deleted", FT_UID);
1393        $s2 = @imap_expunge($this->mbox);
1394
1395        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->DeleteMessage('%s','%s'): result: s-delete: '%s' s-expunge: '%s' setflag: '%s'", $folderid, $id, $s1, $s2, $s11));
1396
1397        return ($s1 && $s2 && $s11);
1398    }
1399
1400    /**
1401     * Called when the user moves an item on the PDA from one folder to another
1402     *
1403     * @param string        $folderid       id of the source folder
1404     * @param string        $id             id of the message
1405     * @param string        $newfolderid    id of the destination folder
1406     *
1407     * @access public
1408     * @return boolean                      status of the operation
1409     * @throws StatusException              could throw specific SYNC_MOVEITEMSSTATUS_* exceptions
1410     */
1411    public function MoveMessage($folderid, $id, $newfolderid) {
1412        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s')", $folderid, $id, $newfolderid));
1413        $folderImapid = $this->getImapIdFromFolderId($folderid);
1414        $newfolderImapid = $this->getImapIdFromFolderId($newfolderid);
1415
1416
1417        $this->imap_reopenFolder($folderImapid);
1418
1419        // TODO this should throw a StatusExceptions on errors like SYNC_MOVEITEMSSTATUS_SAMESOURCEANDDEST,SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID,SYNC_MOVEITEMSSTATUS_CANNOTMOVE
1420
1421        // read message flags
1422        $overview = @imap_fetch_overview ( $this->mbox , $id, FT_UID);
1423
1424        if (!$overview)
1425            throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to retrieve overview of source message: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID);
1426        else {
1427            // get next UID for destination folder
1428            // when moving a message we have to announce through ActiveSync the new messageID in the
1429            // destination folder. This is a "guessing" mechanism as IMAP does not inform that value.
1430            // when lots of simultaneous operations happen in the destination folder this could fail.
1431            // in the worst case the moved message is displayed twice on the mobile.
1432            $destStatus = imap_status($this->mbox, $this->server . $newfolderImapid, SA_ALL);
1433            if (!$destStatus)
1434                throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, unable to open destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_INVALIDDESTID);
1435
1436            $newid = $destStatus->uidnext;
1437
1438            // move message
1439            $s1 = imap_mail_move($this->mbox, $id, $newfolderImapid, CP_UID);
1440            if (! $s1)
1441                throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, copy to destination folder failed: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE);
1442
1443
1444            // delete message in from-folder
1445            $s2 = imap_expunge($this->mbox);
1446
1447            // open new folder
1448            $stat = $this->imap_reopenFolder($newfolderImapid);
1449            if (! $s1)
1450                throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, openeing the destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE);
1451
1452
1453            // remove all flags
1454            $s3 = @imap_clearflag_full ($this->mbox, $newid, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID);
1455            $newflags = "";
1456            if ($overview[0]->seen) $newflags .= "\\Seen";
1457            if ($overview[0]->flagged) $newflags .= " \\Flagged";
1458            if ($overview[0]->answered) $newflags .= " \\Answered";
1459            $s4 = @imap_setflag_full ($this->mbox, $newid, $newflags, FT_UID);
1460
1461            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): result s-move: '%s' s-expunge: '%s' unset-Flags: '%s' set-Flags: '%s'", $folderid, $id, $newfolderid, Utils::PrintAsString($s1), Utils::PrintAsString($s2), Utils::PrintAsString($s3), Utils::PrintAsString($s4)));
1462
1463            // return the new id "as string""
1464            return $newid . "";
1465        }
1466    }
1467
1468
1469    /**----------------------------------------------------------------------------------------------------------
1470     * protected IMAP methods
1471     */
1472
1473    /**
1474     * Unmasks a hex folderid and returns the imap folder id
1475     *
1476     * @param string        $folderid       hex folderid generated by convertImapId()
1477     *
1478     * @access protected
1479     * @return string       imap folder id
1480     */
1481    protected function getImapIdFromFolderId($folderid) {
1482        $this->InitializePermanentStorage();
1483
1484        if (isset($this->permanentStorage->fmFidFimap)) {
1485            if (isset($this->permanentStorage->fmFidFimap[$folderid])) {
1486                $imapId = $this->permanentStorage->fmFidFimap[$folderid];
1487                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, $imapId));
1488                return $imapId;
1489            }
1490            else {
1491                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, 'not found'));
1492                return false;
1493            }
1494        }
1495        ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, 'not initialized!'));
1496        return false;
1497    }
1498
1499    /**
1500     * Retrieves a hex folderid previousily masked imap
1501     *
1502     * @param string        $imapid         Imap folder id
1503     *
1504     * @access protected
1505     * @return string       hex folder id
1506     */
1507    protected function getFolderIdFromImapId($imapid) {
1508        $this->InitializePermanentStorage();
1509
1510        if (isset($this->permanentStorage->fmFimapFid)) {
1511            if (isset($this->permanentStorage->fmFimapFid[$imapid])) {
1512                $folderid = $this->permanentStorage->fmFimapFid[$imapid];
1513                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, $folderid));
1514                return $folderid;
1515            }
1516            else {
1517                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, 'not found'));
1518                return false;
1519            }
1520        }
1521        ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, 'not initialized!'));
1522        return false;
1523    }
1524
1525    /**
1526     * Masks a imap folder id into a generated hex folderid
1527     * The method getFolderIdFromImapId() is consulted so that an
1528     * imapid always returns the same hex folder id
1529     *
1530     * @param string        $imapid         Imap folder id
1531     *
1532     * @access protected
1533     * @return string       hex folder id
1534     */
1535    protected function convertImapId($imapid) {
1536        $this->InitializePermanentStorage();
1537
1538        // check if this imap id was converted before
1539        $folderid = $this->getFolderIdFromImapId($imapid);
1540
1541        // nothing found, so generate a new id and put it in the cache
1542        if (!$folderid) {
1543            // generate folderid and add it to the mapping
1544            $folderid = sprintf('%04x%04x', mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ));
1545
1546            // folderId to folderImap mapping
1547            if (!isset($this->permanentStorage->fmFidFimap))
1548                $this->permanentStorage->fmFidFimap = array();
1549
1550            $a = $this->permanentStorage->fmFidFimap;
1551            $a[$folderid] = $imapid;
1552            $this->permanentStorage->fmFidFimap = $a;
1553
1554            // folderImap to folderid mapping
1555            if (!isset($this->permanentStorage->fmFimapFid))
1556                $this->permanentStorage->fmFimapFid = array();
1557
1558            $b = $this->permanentStorage->fmFimapFid;
1559            $b[$imapid] = $folderid;
1560            $this->permanentStorage->fmFimapFid = $b;
1561        }
1562
1563        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->convertImapId('%s') = %s", $imapid, $folderid));
1564
1565        return $folderid;
1566    }
1567
1568
1569    /**
1570     * Parses the message and return only the plaintext body
1571     *
1572     * @param string        $message        html message
1573     *
1574     * @access protected
1575     * @return string       plaintext message
1576     */
1577    protected function getBody($message) {
1578        $body = "";
1579        $htmlbody = "";
1580
1581        $this->getBodyRecursive($message, "plain", $body);
1582
1583        if($body === "") {
1584            $this->getBodyRecursive($message, "html", $body);
1585        }
1586
1587        return $body;
1588    }
1589
1590    /**
1591     * Get all parts in the message with specified type and concatenate them together, unless the
1592     * Content-Disposition is 'attachment', in which case the text is apparently an attachment
1593     *
1594     * @param string        $message        mimedecode message(part)
1595     * @param string        $message        message subtype
1596     * @param string        &$body          body reference
1597     *
1598     * @access protected
1599     * @return
1600     */
1601    protected function getBodyRecursive($message, $subtype, &$body) {
1602        if(!isset($message->ctype_primary)) return;
1603        if(strcasecmp($message->ctype_primary,"text")==0 && strcasecmp($message->ctype_secondary,$subtype)==0 && isset($message->body)){
1604
1605            if(strtolower($message->ctype_parameters['charset']) == 'iso-8859-1')
1606            {
1607                $body .=  mb_detect_encoding($message->body) == 'UTF-8' ? $message->body : mb_convert_encoding($message->body , 'ISO-8859-1');
1608            }
1609            else
1610            {
1611                $body .= $message->body;
1612            }
1613         }
1614
1615        if(strcasecmp($message->ctype_primary,"multipart")==0 && isset($message->parts) && is_array($message->parts)) {
1616            foreach($message->parts as $part) {
1617                if(!isset($part->disposition) || strcasecmp($part->disposition,"attachment"))  {
1618                    $this->getBodyRecursive($part, $subtype, $body);
1619                }
1620            }
1621        }
1622    }
1623
1624    /**
1625     * Returns the serverdelimiter for folder parsing
1626     *
1627     * @access protected
1628     * @return string       delimiter
1629     */
1630    protected function getServerDelimiter() {
1631        $list = @imap_getmailboxes($this->mbox, $this->server, "INBOX*");
1632        if (is_array($list)) {
1633            $val = $list[0];
1634
1635            return $val->delimiter;
1636        }
1637        return "."; // default "."
1638    }
1639
1640    /**
1641     * Helper to re-initialize the folder to speed things up
1642     * Remember what folder is currently open and only change if necessary
1643     *
1644     * @param string        $folderid       id of the folder
1645     * @param boolean       $force          re-open the folder even if currently opened
1646     *
1647     * @access protected
1648     * @return
1649     */
1650    protected function imap_reopenFolder($folderid, $force = false) {
1651        // to see changes, the folder has to be reopened!
1652           if ($this->mboxFolder != $folderid || $force) {
1653               $s = @imap_reopen($this->mbox, $this->server . $folderid);
1654               // TODO throw status exception
1655               if (!$s) {
1656                ZLog::Write(LOGLEVEL_WARN, "BackendIMAP->imap_reopenFolder('%s'): failed to change folder: ",$folderid, implode(", ", imap_errors()));
1657                return false;
1658               }
1659            $this->mboxFolder = $folderid;
1660        }
1661    }
1662
1663
1664    /**
1665     * Build a multipart RFC822, embedding body and one file (for attachments)
1666     *
1667     * @param string        $filenm         name of the file to be attached
1668     * @param long          $filesize       size of the file to be attached
1669     * @param string        $file_cont      content of the file
1670     * @param string        $body           current body
1671     * @param string        $body_ct        content-type
1672     * @param string        $body_cte       content-transfer-encoding
1673     * @param string        $boundary       optional existing boundary
1674     *
1675     * @access protected
1676     * @return array        with [0] => $mail_header and [1] => $mail_body
1677     */
1678    protected function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte, $boundary = false) {
1679        if (!$boundary) $boundary = strtoupper(md5(uniqid(time())));
1680
1681        //remove the ending boundary because we will add it at the end
1682        $body = str_replace("--$boundary--", "", $body);
1683
1684        $mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
1685
1686        // build main body with the sumitted type & encoding from the pda
1687        $mail_body  = $this->enc_multipart($boundary, $body, $body_ct, $body_cte);
1688        $mail_body .= $this->enc_attach_file($boundary, $filenm, $filesize, $file_cont);
1689
1690        $mail_body .= "--$boundary--\n\n";
1691        return array($mail_header, $mail_body);
1692    }
1693
1694    /**
1695     * Helper for mail_attach()
1696     *
1697     * @param string        $boundary       boundary
1698     * @param string        $body           current body
1699     * @param string        $body_ct        content-type
1700     * @param string        $body_cte       content-transfer-encoding
1701     *
1702     * @access protected
1703     * @return string       message body
1704     */
1705    protected function enc_multipart($boundary, $body, $body_ct, $body_cte) {
1706        $mail_body = "This is a multi-part message in MIME format\n\n";
1707        $mail_body .= "--$boundary\n";
1708        $mail_body .= "Content-Type: $body_ct\n";
1709        $mail_body .= "Content-Transfer-Encoding: $body_cte\n\n";
1710        $mail_body .= "$body\n\n";
1711
1712        return $mail_body;
1713    }
1714
1715    /**
1716     * Helper for mail_attach()
1717     *
1718     * @param string        $boundary       boundary
1719     * @param string        $filenm         name of the file to be attached
1720     * @param long          $filesize       size of the file to be attached
1721     * @param string        $file_cont      content of the file
1722     * @param string        $content_type   optional content-type
1723     *
1724     * @access protected
1725     * @return string       message body
1726     */
1727    protected function enc_attach_file($boundary, $filenm, $filesize, $file_cont, $content_type = "") {
1728        if (!$content_type) $content_type = "text/plain";
1729        $mail_body = "--$boundary\n";
1730        $mail_body .= "Content-Type: $content_type; name=\"$filenm\"\n";
1731        $mail_body .= "Content-Transfer-Encoding: base64\n";
1732        $mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
1733        $mail_body .= "Content-Description: $filenm\n\n";
1734        //contrib - chunk base64 encoded attachments
1735        $mail_body .= chunk_split(base64_encode($file_cont)) . "\n\n";
1736
1737        return $mail_body;
1738    }
1739
1740    /**
1741     * Adds a message with seen flag to a specified folder (used for saving sent items)
1742     *
1743     * @param string        $folderid       id of the folder
1744     * @param string        $header         header of the message
1745     * @param long          $body           body of the message
1746     *
1747     * @access protected
1748     * @return boolean      status
1749     */
1750    protected function addSentMessage($folderid, $header, $body) {
1751        $header_body = str_replace("\n", "\r\n", str_replace("\r", "", $header . "\n\n" . $body));
1752
1753        return @imap_append($this->mbox, $this->server . $folderid, $header_body, "\\Seen");
1754    }
1755
1756    /**
1757     * Parses an mimedecode address array back to a simple "," separated string
1758     *
1759     * @param array         $ad             addresses array
1760     *
1761     * @access protected
1762     * @return string       mail address(es) string
1763     */
1764    protected function parseAddr($ad) {
1765        $addr_string = "";
1766        if (isset($ad) && is_array($ad)) {
1767            foreach($ad as $addr) {
1768                if ($addr_string) $addr_string .= ",";
1769                    $addr_string .= $addr->mailbox . "@" . $addr->host;
1770            }
1771        }
1772        return $addr_string;
1773    }
1774
1775    /**
1776     * Recursive way to get mod and parent - repeat until only one part is left
1777     * or the folder is identified as an IMAP folder
1778     *
1779     * @param string        $fhir           folder hierarchy string
1780     * @param string        &$displayname   reference of the displayname
1781     * @param long          &$parent        reference of the parent folder
1782     *
1783     * @access protected
1784     * @return
1785     */
1786    protected function getModAndParentNames($fhir, &$displayname, &$parent) {
1787        // if mod is already set add the previous part to it as it might be a folder which has
1788        // delimiter in its name
1789        $displayname = (isset($displayname) && strlen($displayname) > 0) ? $displayname = array_pop($fhir).$this->serverdelimiter.$displayname : array_pop($fhir);
1790        $parent = implode($this->serverdelimiter, $fhir);
1791
1792        if (count($fhir) == 1 || $this->checkIfIMAPFolder($parent)) {
1793            return;
1794        }
1795        //recursion magic
1796        $this->getModAndParentNames($fhir, $displayname, $parent);
1797    }
1798
1799    /**
1800     * Checks if a specified name is a folder in the IMAP store
1801     *
1802     * @param string        $foldername     a foldername
1803     *
1804     * @access protected
1805     * @return boolean
1806     */
1807    protected function checkIfIMAPFolder($folderName) {
1808        $parent = imap_list($this->mbox, $this->server, $folderName);
1809        if ($parent === false) return false;
1810        return true;
1811    }
1812
1813    /**
1814     * Removes parenthesis (comments) from the date string because
1815     * strtotime returns false if received date has them
1816     *
1817     * @param string        $receiveddate   a date as a string
1818     *
1819     * @access protected
1820     * @return string
1821     */
1822    protected function cleanupDate($receiveddate) {
1823        $receiveddate = strtotime(preg_replace("/\(.*\)/", "", $receiveddate));
1824        if ($receiveddate == false || $receiveddate == -1) {
1825            debugLog("Received date is false. Message might be broken.");
1826            return null;
1827        }
1828
1829        return $receiveddate;
1830    }
1831
1832    /* BEGIN fmbiete's contribution r1528, ZP-320 */
1833    /**
1834     * Indicates which AS version is supported by the backend.
1835     *
1836     * @access public
1837     * @return string       AS version constant
1838     */
1839    public function GetSupportedASVersion() {
1840        return ZPush::ASV_14;
1841    }
1842    /* END fmbiete's contribution r1528, ZP-320 */
1843};
1844
1845?>
Note: See TracBrowser for help on using the repository browser.