source: trunk/zpush/backend/expresso/providers/imapProvider.php @ 7671

Revision 7671, 77.1 KB checked in by cristiano, 11 years ago (diff)

Ticket #3209 - Atualizações de lib e correções de config

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            $send =  @mail ( $toaddr, $message->headers["subject"], $body, $headers, $envelopefrom );
500        }
501
502        // email sent?
503        if (!$send)
504            throw new StatusException(sprintf("BackendIMAP->SendMail(): The email could not be sent. Last IMAP-error: %s", imap_last_error()), SYNC_COMMONSTATUS_MAILSUBMISSIONFAILED);
505
506        // add message to the sent folder
507        // build complete headers
508        $headers .= "\nTo: $toaddr";
509        $headers .= "\nSubject: " . $message->headers["subject"]; // changed by mku ZP-330
510
511        if (!defined('IMAP_USE_IMAPMAIL') || IMAP_USE_IMAPMAIL == true) {
512            if (!empty($ccaddr))  $headers .= "\nCc: $ccaddr";
513            if (!empty($bccaddr)) $headers .= "\nBcc: $bccaddr";
514        }
515        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): complete headers: $headers");
516
517        $asf = false;
518        if ($this->sentID) {
519            $asf = $this->addSentMessage($this->sentID, $headers, $body);
520        }
521        else if (IMAP_SENTFOLDER) {
522            $asf = $this->addSentMessage(IMAP_SENTFOLDER, $headers, $body);
523            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->SendMail(): Outgoing mail saved in configured 'Sent' folder '%s': %s", IMAP_SENTFOLDER, Utils::PrintAsString($asf)));
524        }
525        // No Sent folder set, try defaults
526        else {
527            ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): No Sent mailbox set");
528            if($this->addSentMessage("INBOX.Sent", $headers, $body)) {
529                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): Outgoing mail saved in 'INBOX.Sent'");
530                $asf = true;
531            }
532            else if ($this->addSentMessage("Sent", $headers, $body)) {
533                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail(): Outgoing mail saved in 'Sent'");
534                $asf = true;
535            }
536            else if ($this->addSentMessage("Sent Items", $headers, $body)) {
537                ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->SendMail():IMAP-SendMail: Outgoing mail saved in 'Sent Items'");
538                $asf = true;
539            }
540        }
541
542        if (!$asf) {
543            ZLog::Write(LOGLEVEL_ERROR, "BackendIMAP->SendMail(): The email could not be saved to Sent Items folder. Check your configuration.");
544        }
545
546        return $send;
547    }
548
549    /**
550     * Returns the waste basket
551     *
552     * @access public
553     * @return string
554     */
555    public function GetWasteBasket() {
556        // TODO this could be retrieved from the DeviceFolderCache
557        if ($this->wasteID == false) {
558            //try to get the waste basket without doing complete hierarchy sync
559            $wastebaskt = @imap_getmailboxes($this->mbox, $this->server, "Trash");
560            if (isset($wastebaskt[0])) {
561                $this->wasteID = $this->convertImapId(substr($wastebaskt[0]->name, strlen($this->server)));
562                return $this->wasteID;
563            }
564            //try get waste id from hierarchy if it wasn't possible with above for some reason
565            $this->GetHierarchy();
566        }
567        return $this->wasteID;
568    }
569
570    /**
571     * Returns the content of the named attachment as stream. The passed attachment identifier is
572     * the exact string that is returned in the 'AttName' property of an SyncAttachment.
573     * Any information necessary to find the attachment must be encoded in that 'attname' property.
574     * Data is written directly (with print $data;)
575     *
576     * @param string        $attname
577     *
578     * @access public
579     * @return SyncItemOperationsAttachment
580     * @throws StatusException
581     */
582    public function GetAttachmentData($attname) {
583        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetAttachmentData('%s')", $attname));
584
585        list($folderid, $id, $part) = explode(":", $attname);
586
587        if (!$folderid || !$id || !$part)
588            throw new StatusException(sprintf("BackendIMAP->GetAttachmentData('%s'): Error, attachment name key can not be parsed", $attname), SYNC_ITEMOPERATIONSSTATUS_INVALIDATT);
589
590        // convert back to work on an imap-id
591        $folderImapid = $this->getImapIdFromFolderId($folderid);
592
593        $this->imap_reopenFolder($folderImapid);
594        $mail = @imap_fetchheader($this->mbox, $id, FT_UID) . @imap_body($this->mbox, $id, FT_PEEK | FT_UID);
595
596        $mobj = new Mail_mimeDecode($mail);
597        $message = $mobj->decode(array('decode_headers' => true, 'decode_bodies' => true, 'include_bodies' => true, 'charset' => 'utf-8'));
598
599        /* BEGIN fmbiete's contribution r1528, ZP-320 */
600        //trying parts
601        $mparts = $message->parts;
602        for ($i = 0; $i < count($mparts); $i++) {
603            $auxpart = $mparts[$i];
604            //recursively add parts
605            if($auxpart->ctype_primary == "multipart" && ($auxpart->ctype_secondary == "mixed" || $auxpart->ctype_secondary == "alternative"  || $auxpart->ctype_secondary == "related")) {
606                foreach($auxpart->parts as $spart)
607                    $mparts[] = $spart;
608            }
609        }
610        /* END fmbiete's contribution r1528, ZP-320 */
611
612        if (!isset($mparts[$part]->body))
613            throw new StatusException(sprintf("BackendIMAP->GetAttachmentData('%s'): Error, requested part key can not be found: '%d'", $attname, $part), SYNC_ITEMOPERATIONSSTATUS_INVALIDATT);
614
615        // unset mimedecoder & mail
616        unset($mobj);
617        unset($mail);
618
619        include_once('include/stringstreamwrapper.php');
620        $attachment = new SyncItemOperationsAttachment();
621        /* BEGIN fmbiete's contribution r1528, ZP-320 */
622        $attachment->data = StringStreamWrapper::Open($mparts[$part]->body);
623        if (isset($mparts[$part]->ctype_primary) && isset($mparts[$part]->ctype_secondary))
624            $attachment->contenttype = $mparts[$part]->ctype_primary .'/'.$mparts[$part]->ctype_secondary;
625
626        unset($mparts);
627        unset($message);
628
629        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetAttachmentData contenttype %s", $attachment->contenttype));
630        /* END fmbiete's contribution r1528, ZP-320 */
631
632        return $attachment;
633    }
634
635    /**
636     * Indicates if the backend has a ChangesSink.
637     * A sink is an active notification mechanism which does not need polling.
638     * The IMAP backend simulates a sink by polling status information of the folder
639     *
640     * @access public
641     * @return boolean
642     */
643    public function HasChangesSink() {
644        $this->sinkfolders = array();
645        $this->sinkstates = array();
646        return true;
647    }
648
649    /**
650     * The folder should be considered by the sink.
651     * Folders which were not initialized should not result in a notification
652     * of IBacken->ChangesSink().
653     *
654     * @param string        $folderid
655     *
656     * @access public
657     * @return boolean      false if found can not be found
658     */
659    public function ChangesSinkInitialize($folderid) {
660        ZLog::Write(LOGLEVEL_DEBUG, sprintf("IMAPBackend->ChangesSinkInitialize(): folderid '%s'", $folderid));
661
662        $imapid = $this->getImapIdFromFolderId($folderid);
663
664        if ($imapid) {
665            $this->sinkfolders[] = $imapid;
666            return true;
667        }
668
669        return false;
670    }
671
672    /**
673     * The actual ChangesSink.
674     * For max. the $timeout value this method should block and if no changes
675     * are available return an empty array.
676     * If changes are available a list of folderids is expected.
677     *
678     * @param int           $timeout        max. amount of seconds to block
679     *
680     * @access public
681     * @return array
682     */
683    public function ChangesSink($timeout = 30) {
684        $notifications = array();
685        $stopat = time() + $timeout - 1;
686
687        while($stopat > time() && empty($notifications)) {
688            foreach ($this->sinkfolders as $imapid) {
689                $this->imap_reopenFolder($imapid);
690
691                // courier-imap only cleares the status cache after checking
692                @imap_check($this->mbox);
693
694                $status = @imap_status($this->mbox, $this->server . $imapid, SA_ALL);
695                if (!$status) {
696                    ZLog::Write(LOGLEVEL_WARN, sprintf("ChangesSink: could not stat folder '%s': %s ", $this->getFolderIdFromImapId($imapid), imap_last_error()));
697                }
698                else {
699                    $newstate = "M:". $status->messages ."-R:". $status->recent ."-U:". $status->unseen;
700
701                    if (! isset($this->sinkstates[$imapid]) )
702                        $this->sinkstates[$imapid] = $newstate;
703
704                    if ($this->sinkstates[$imapid] != $newstate) {
705                        $notifications[] = $this->getFolderIdFromImapId($imapid);
706                        $this->sinkstates[$imapid] = $newstate;
707                    }
708                }
709            }
710
711            if (empty($notifications))
712                sleep(5);
713        }
714
715        return $notifications;
716    }
717
718
719    /**----------------------------------------------------------------------------------------------------------
720     * implemented DiffBackend methods
721     */
722
723
724    /**
725     * Returns a list (array) of folders.
726     *
727     * @access public
728     * @return array/boolean        false if the list could not be retrieved
729     */
730    public function GetFolderList() {
731        $folders = array();
732
733        $list = @imap_getmailboxes($this->mbox, $this->server, "*");
734        if (is_array($list)) {
735            // reverse list to obtain folders in right order
736            $list = array_reverse($list);
737
738            foreach ($list as $val) {
739                /* BEGIN fmbiete's contribution r1527, ZP-319 */
740                // don't return the excluded folders
741                $notExcluded = true;
742                for ($i = 0, $cnt = count($this->excludedFolders); $notExcluded && $i < $cnt; $i++) { // expr1, expr2 modified by mku ZP-329
743                    // fix exclude folders with special chars by mku ZP-329
744                    if (strpos(strtolower($val->name), strtolower(Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($this->excludedFolders[$i])))) !== false) {
745                        $notExcluded = false;
746                        ZLog::Write(LOGLEVEL_DEBUG, sprintf("Pattern: <%s> found, excluding folder: '%s'", $this->excludedFolders[$i], $val->name)); // sprintf added by mku ZP-329
747                    }
748                }
749
750                if ($notExcluded) {
751                    $box = array();
752                    // cut off serverstring
753                    $imapid = substr($val->name, strlen($this->server));
754                    $box["id"] = $this->convertImapId($imapid);
755
756                    $fhir = explode($val->delimiter, $imapid);
757                    if (count($fhir) > 1) {
758                        $this->getModAndParentNames($fhir, $box["mod"], $imapparent);
759                        $box["parent"] = $this->convertImapId($imapparent);
760                    }
761                    else {
762                        $box["mod"] = $imapid;
763                        $box["parent"] = "0";
764                    }
765                    $folders[]=$box;
766                    /* END fmbiete's contribution r1527, ZP-319 */
767                }
768            }
769        }
770        else {
771            ZLog::Write(LOGLEVEL_WARN, "BackendIMAP->GetFolderList(): imap_list failed: " . imap_last_error());
772            return false;
773        }
774
775        return $folders;
776    }
777
778    /**
779     * Returns an actual SyncFolder object
780     *
781     * @param string        $id           id of the folder
782     *
783     * @access public
784     * @return object       SyncFolder with information
785     */
786    public function GetFolder($id) {
787        $folder = new SyncFolder();
788        $folder->serverid = $id;
789
790        // convert back to work on an imap-id
791        $imapid = $this->getImapIdFromFolderId($id);
792
793        // explode hierarchy
794        $fhir = explode($this->serverdelimiter, $imapid);
795
796        // compare on lowercase strings
797        $lid = strtolower($imapid);
798// TODO WasteID or SentID could be saved for later ussage
799        if($lid == "inbox") {
800            $folder->parentid = "0"; // Root
801            $folder->displayname = "Inbox";
802            $folder->type = SYNC_FOLDER_TYPE_INBOX;
803        }
804        // Zarafa IMAP-Gateway outputs
805        else if($lid == "drafts") {
806            $folder->parentid = "0";
807            $folder->displayname = "Drafts";
808            $folder->type = SYNC_FOLDER_TYPE_DRAFTS;
809        }
810        else if($lid == "trash") {
811            $folder->parentid = "0";
812            $folder->displayname = "Trash";
813            $folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
814            $this->wasteID = $id;
815        }
816        else if($lid == "sent" || $lid == "sent items" || $lid == IMAP_SENTFOLDER) {
817            $folder->parentid = "0";
818            $folder->displayname = "Sent";
819            $folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
820            //$this->sentID = $id;
821        }
822        // courier-imap outputs and cyrus-imapd outputs
823        else if($lid == "inbox.drafts" || $lid == "inbox/drafts") {
824            $folder->parentid = $this->convertImapId($fhir[0]);
825            $folder->displayname = "Drafts";
826            $folder->type = SYNC_FOLDER_TYPE_DRAFTS;
827        }
828        else if($lid == "inbox.trash" || $lid == "inbox/trash") {
829            $folder->parentid = $this->convertImapId($fhir[0]);
830            $folder->displayname = "Trash";
831            $folder->type = SYNC_FOLDER_TYPE_WASTEBASKET;
832            $this->wasteID = $id;
833        }
834        else if($lid == "inbox.sent" || $lid == "inbox/sent") {
835            $folder->parentid = $this->convertImapId($fhir[0]);
836            $folder->displayname = "Sent";
837            $folder->type = SYNC_FOLDER_TYPE_SENTMAIL;
838            //$this->sentID = $id;
839        }
840
841        // define the rest as other-folders
842        else {
843            if (count($fhir) > 1) {
844                $this->getModAndParentNames($fhir, $folder->displayname, $imapparent);
845                $folder->parentid = $this->convertImapId($imapparent);
846                $folder->displayname = Utils::Utf7_to_utf8(Utils::Utf7_iconv_decode($folder->displayname));
847            }
848            else {
849                $folder->displayname = Utils::Utf7_to_utf8(Utils::Utf7_iconv_decode($imapid));
850                $folder->parentid = "0";
851            }
852            $folder->type = SYNC_FOLDER_TYPE_USER_MAIL;
853        }
854
855        //advanced debugging
856        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetFolder('%s'): '%s'", $id, $folder));
857
858        return $folder;
859    }
860
861    /**
862     * Returns folder stats. An associative array with properties is expected.
863     *
864     * @param string        $id             id of the folder
865     *
866     * @access public
867     * @return array
868     */
869    public function StatFolder($id) {
870        $folder = $this->GetFolder($id);
871
872        $stat = array();
873        $stat["id"] = $id;
874        $stat["parent"] = $folder->parentid;
875        $stat["mod"] = $folder->displayname;
876
877        return $stat;
878    }
879
880    /**
881     * Creates or modifies a folder
882     * The folder type is ignored in IMAP, as all folders are Email folders
883     *
884     * @param string        $folderid       id of the parent folder
885     * @param string        $oldid          if empty -> new folder created, else folder is to be renamed
886     * @param string        $displayname    new folder name (to be created, or to be renamed to)
887     * @param int           $type           folder type
888     *
889     * @access public
890     * @return boolean                      status
891     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
892     *
893     */
894    public function ChangeFolder($folderid, $oldid, $displayname, $type){
895        ZLog::Write(LOGLEVEL_INFO, sprintf("BackendIMAP->ChangeFolder('%s','%s','%s','%s')", $folderid, $oldid, $displayname, $type));
896
897        // go to parent mailbox
898        $this->imap_reopenFolder($folderid);
899
900        // build name for new mailboxBackendMaildir
901        $displayname = Utils::Utf7_iconv_encode(Utils::Utf8_to_utf7($displayname));
902        $newname = $this->server . $folderid . $this->serverdelimiter . $displayname;
903
904        $csts = false;
905        // if $id is set => rename mailbox, otherwise create
906        if ($oldid) {
907            // rename doesn't work properly with IMAP
908            // the activesync client doesn't support a 'changing ID'
909            // TODO this would be solved by implementing hex ids (Mantis #459)
910            //$csts = imap_renamemailbox($this->mbox, $this->server . imap_utf7_encode(str_replace(".", $this->serverdelimiter, $oldid)), $newname);
911        }
912        else {
913            $csts = @imap_createmailbox($this->mbox, $newname);
914        }
915        if ($csts) {
916            return $this->StatFolder($folderid . $this->serverdelimiter . $displayname);
917        }
918        else
919            return false;
920    }
921
922    /**
923     * Deletes a folder
924     *
925     * @param string        $id
926     * @param string        $parent         is normally false
927     *
928     * @access public
929     * @return boolean                      status - false if e.g. does not exist
930     * @throws StatusException              could throw specific SYNC_FSSTATUS_* exceptions
931     *
932     */
933    public function DeleteFolder($id, $parentid){
934        // TODO implement
935        return false;
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            /* BEGIN fmbiete's contribution r1528, ZP-320 */
1030            $output = new SyncMail();
1031
1032            //Select body type preference
1033            $bpReturnType = SYNC_BODYPREFERENCE_PLAIN;
1034            if ($bodypreference !== false) {
1035                $bpReturnType = Utils::GetBodyPreferenceBestMatch($bodypreference); // changed by mku ZP-330
1036            }
1037            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->GetMessage - getBodyPreferenceBestMatch: %d", $bpReturnType));
1038
1039            //Get body data
1040            $this->getBodyRecursive($message, "plain", $plainBody);
1041            $this->getBodyRecursive($message, "html", $htmlBody);
1042            if ($plainBody == "") {
1043                $plainBody = Utils::ConvertHtmlToText($htmlBody);
1044            }
1045            $htmlBody = str_replace("\n","\r\n", str_replace("\r","",$htmlBody));
1046            $plainBody = str_replace("\n","\r\n", str_replace("\r","",$plainBody));
1047
1048            if (Request::GetProtocolVersion() >= 12.0) {
1049                $output->asbody = new SyncBaseBody();
1050
1051                switch($bpReturnType) {
1052                    case SYNC_BODYPREFERENCE_PLAIN:
1053                        $output->asbody->data = $plainBody;
1054                        break;
1055                    case SYNC_BODYPREFERENCE_HTML:
1056                        if ($htmlBody == "") {
1057                            $output->asbody->data = $plainBody;
1058                            $bpReturnType = SYNC_BODYPREFERENCE_PLAIN;
1059                        }
1060                        else {
1061                            $output->asbody->data = $htmlBody;
1062                        }
1063                        break;
1064                    case SYNC_BODYPREFERENCE_MIME:
1065                        //We don't need to create a new MIME mail, we already have one!!
1066                        $output->asbody->data = $mail;
1067                        break;
1068                    case SYNC_BODYPREFERENCE_RTF:
1069                        ZLog::Write(LOGLEVEL_DEBUG, "BackendIMAP->GetMessage RTF Format NOT CHECKED");
1070                        $output->asbody->data = base64_encode($plainBody);
1071                        break;
1072                }
1073                // truncate body, if requested
1074                if(strlen($output->asbody->data) > $truncsize) {
1075                    $output->asbody->data = Utils::Utf8_truncate($output->asbody->data, $truncsize);
1076                    $output->asbody->truncated = 1;
1077                }
1078
1079                $output->asbody->type = $bpReturnType;
1080                $output->nativebodytype = $bpReturnType;
1081                $output->asbody->estimatedDataSize = strlen($output->asbody->data);
1082
1083                $bpo = $contentparameters->BodyPreference($output->asbody->type);
1084                if (Request::GetProtocolVersion() >= 14.0 && $bpo->GetPreview()) {
1085                    $output->asbody->preview = Utils::Utf8_truncate(Utils::ConvertHtmlToText($plainBody), $bpo->GetPreview());
1086                }
1087                else {
1088                    $output->asbody->truncated = 0;
1089                }
1090            }
1091            /* END fmbiete's contribution r1528, ZP-320 */
1092            else { // ASV_2.5
1093                $output->bodytruncated = 0;
1094                /* BEGIN fmbiete's contribution r1528, ZP-320 */
1095                if ($bpReturnType == SYNC_BODYPREFERENCE_MIME) {
1096                    if (strlen($mail) > $truncsize) {
1097                        $output->mimedata = Utils::Utf8_truncate($mail, $truncsize);
1098                        $output->mimetruncated = 1;
1099                    }
1100                    else {
1101                        $output->mimetruncated = 0;
1102                        $output->mimedata = $mail;
1103                    }
1104                    $output->mimesize = strlen($output->mimedata);
1105                }
1106                else {
1107                    // truncate body, if requested
1108                    if (strlen($plainBody) > $truncsize) {
1109                        $output->body = Utils::Utf8_truncate($plainBody, $truncsize);
1110                        $output->bodytruncated = 1;
1111                    }
1112                    else {
1113                        $output->body = $plainBody;
1114                        $output->bodytruncated = 0;
1115                    }
1116                    $output->bodysize = strlen($output->body);
1117                }
1118                /* END fmbiete's contribution r1528, ZP-320 */
1119            }
1120
1121            $output->datereceived = isset($message->headers["date"]) ? $this->cleanupDate($message->headers["date"]) : null;
1122            $output->messageclass = "IPM.Note";
1123            $output->subject = isset($message->headers["subject"]) ? $message->headers["subject"] : "";
1124            $output->read = $stat["flags"];
1125            $output->from = isset($message->headers["from"]) ? $message->headers["from"] : null;
1126
1127            /* BEGIN fmbiete's contribution r1528, ZP-320 */
1128            if (isset($message->headers["thread-topic"])) {
1129                $output->threadtopic = $message->headers["thread-topic"];
1130            }
1131
1132            // Language Code Page ID: http://msdn.microsoft.com/en-us/library/windows/desktop/dd317756%28v=vs.85%29.aspx
1133            $output->internetcpid = INTERNET_CPID_UTF8;
1134            if (Request::GetProtocolVersion() >= 12.0) {
1135                $output->contentclass = "urn:content-classes:message";
1136            }
1137            /* END fmbiete's contribution r1528, ZP-320 */
1138
1139            $Mail_RFC822 = new Mail_RFC822();
1140            $toaddr = $ccaddr = $replytoaddr = array();
1141            if(isset($message->headers["to"]))
1142                $toaddr = $Mail_RFC822->parseAddressList($message->headers["to"]);
1143            if(isset($message->headers["cc"]))
1144                $ccaddr = $Mail_RFC822->parseAddressList($message->headers["cc"]);
1145            if(isset($message->headers["reply_to"]))
1146                $replytoaddr = $Mail_RFC822->parseAddressList($message->headers["reply_to"]);
1147
1148            $output->to = array();
1149            $output->cc = array();
1150            $output->reply_to = array();
1151            foreach(array("to" => $toaddr, "cc" => $ccaddr, "reply_to" => $replytoaddr) as $type => $addrlist) {
1152                foreach($addrlist as $addr) {
1153                    $address = $addr->mailbox . "@" . $addr->host;
1154                    $name = $addr->personal;
1155
1156                    if (!isset($output->displayto) && $name != "")
1157                        $output->displayto = $name;
1158
1159                    if($name == "" || $name == $address)
1160                        $fulladdr = w2u($address);
1161                    else {
1162                        if (substr($name, 0, 1) != '"' && substr($name, -1) != '"') {
1163                            $fulladdr = "\"" . w2u($name) ."\" <" . w2u($address) . ">";
1164                        }
1165                        else {
1166                            $fulladdr = w2u($name) ." <" . w2u($address) . ">";
1167                        }
1168                    }
1169
1170                    array_push($output->$type, $fulladdr);
1171                }
1172            }
1173
1174            // convert mime-importance to AS-importance
1175            if (isset($message->headers["x-priority"])) {
1176                $mimeImportance =  preg_replace("/\D+/", "", $message->headers["x-priority"]);
1177                //MAIL 1 - most important, 3 - normal, 5 - lowest
1178                //AS 0 - low, 1 - normal, 2 - important
1179                if ($mimeImportance > 3)
1180                    $output->importance = 0;
1181                if ($mimeImportance == 3)
1182                    $output->importance = 1;
1183                if ($mimeImportance < 3)
1184                    $output->importance = 2;
1185            } else { /* fmbiete's contribution r1528, ZP-320 */
1186                $output->importance = 1;
1187            }
1188
1189            // Attachments are not needed for MIME messages
1190            if($bpReturnType != SYNC_BODYPREFERENCE_MIME && isset($message->parts)) {
1191                $mparts = $message->parts;
1192                for ($i=0; $i<count($mparts); $i++) {
1193                    $part = $mparts[$i];
1194                    //recursively add parts
1195                    if($part->ctype_primary == "multipart" && ($part->ctype_secondary == "mixed" || $part->ctype_secondary == "alternative"  || $part->ctype_secondary == "related")) {
1196                        foreach($part->parts as $spart)
1197                            $mparts[] = $spart;
1198                        continue;
1199                    }
1200                    //add part as attachment if it's disposition indicates so or if it is not a text part
1201                    if ((isset($part->disposition) && ($part->disposition == "attachment" || $part->disposition == "inline")) ||
1202                        (isset($part->ctype_primary) && $part->ctype_primary != "text")) {
1203
1204                        if(isset($part->d_parameters['filename']))
1205                            $attname = $part->d_parameters['filename'];
1206                        else if(isset($part->ctype_parameters['name']))
1207                            $attname = $part->ctype_parameters['name'];
1208                        else if(isset($part->headers['content-description']))
1209                            $attname = $part->headers['content-description'];
1210                        else $attname = "unknown attachment";
1211
1212                        /* BEGIN fmbiete's contribution r1528, ZP-320 */
1213                        if (Request::GetProtocolVersion() >= 12.0) {
1214                            if (!isset($output->asattachments) || !is_array($output->asattachments))
1215                                $output->asattachments = array();
1216
1217                            $attachment = new SyncBaseAttachment();
1218
1219                            $attachment->estimatedDataSize = isset($part->d_parameters['size']) ? $part->d_parameters['size'] : isset($part->body) ? strlen($part->body) : 0;
1220
1221                            $attachment->displayname = $attname;
1222                            $attachment->filereference = $folderid . ":" . $id . ":" . $i;
1223                            $attachment->method = 1; //Normal attachment
1224                            $attachment->contentid = isset($part->headers['content-id']) ? str_replace("<", "", str_replace(">", "", $part->headers['content-id'])) : "";
1225                            if (isset($part->disposition) && $part->disposition == "inline") {
1226                                $attachment->isinline = 1;
1227                            }
1228                            else {
1229                                $attachment->isinline = 0;
1230                            }
1231
1232                            array_push($output->asattachments, $attachment);
1233                        }
1234                        else { //ASV_2.5
1235                            if (!isset($output->attachments) || !is_array($output->attachments))
1236                                $output->attachments = array();
1237
1238                            $attachment = new SyncAttachment();
1239
1240                            $attachment->attsize = isset($part->d_parameters['size']) ? $part->d_parameters['size'] : isset($part->body) ? strlen($part->body) : 0;
1241
1242                            $attachment->displayname = $attname;
1243                            $attachment->attname = $folderid . ":" . $id . ":" . $i;
1244                            $attachment->attmethod = 1;
1245                            $attachment->attoid = isset($part->headers['content-id']) ? str_replace("<", "", str_replace(">", "", $part->headers['content-id'])) : "";
1246
1247                            array_push($output->attachments, $attachment);
1248                        }
1249                        /* END fmbiete's contribution r1528, ZP-320 */
1250                    }
1251                }
1252            }
1253            // unset mimedecoder & mail
1254            unset($mobj);
1255            unset($mail);
1256            return $output;
1257        }
1258
1259        return false;
1260    }
1261
1262    /**
1263     * Returns message stats, analogous to the folder stats from StatFolder().
1264     *
1265     * @param string        $folderid       id of the folder
1266     * @param string        $id             id of the message
1267     *
1268     * @access public
1269     * @return array/boolean
1270     */
1271    public function StatMessage($folderid, $id) {
1272        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->StatMessage('%s','%s')", $folderid,  $id));
1273        $folderImapid = $this->getImapIdFromFolderId($folderid);
1274
1275        $this->imap_reopenFolder($folderImapid);
1276        $overview = @imap_fetch_overview( $this->mbox , $id , FT_UID);
1277
1278        if (!$overview) {
1279            ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->StatMessage('%s','%s'): Failed to retrieve overview: %s", $folderid,  $id, imap_last_error()));
1280            return false;
1281        }
1282
1283        // check if variables for this overview object are available
1284        $vars = get_object_vars($overview[0]);
1285
1286        // without uid it's not a valid message
1287        if (! array_key_exists( "uid", $vars)) return false;
1288
1289        $entry = array();
1290        $entry["mod"] = (array_key_exists( "date", $vars)) ? $overview[0]->date : "";
1291        $entry["id"] = $overview[0]->uid;
1292        // 'seen' aka 'read' is the only flag we want to know about
1293        $entry["flags"] = 0;
1294
1295        if(array_key_exists( "seen", $vars) && $overview[0]->seen)
1296            $entry["flags"] = 1;
1297
1298        return $entry;
1299    }
1300
1301    /**
1302     * Called when a message has been changed on the mobile.
1303     * Added support for FollowUp flag
1304     *
1305     * @param string        $folderid       id of the folder
1306     * @param string        $id             id of the message
1307     * @param SyncXXX       $message        the SyncObject containing a message
1308     *
1309     * @access public
1310     * @return array                        same return value as StatMessage()
1311     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1312     */
1313    public function ChangeMessage($folderid, $id, $message) {
1314        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->ChangeMessage('%s','%s','%s')", $folderid, $id, get_class($message)));
1315
1316        /* BEGIN fmbiete's contribution r1529, ZP-321 */
1317        if (isset($message->flag)) {
1318            ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->ChangeMessage('Setting flag')"));
1319
1320            $folderImapid = $this->getImapIdFromFolderId($folderid);
1321
1322            $this->imap_reopenFolder($folderImapid);
1323
1324            if (isset($message->flag->flagstatus) && $message->flag->flagstatus == 2) {
1325                ZLog::Write(LOGLEVEL_DEBUG, "Set On FollowUp -> IMAP Flagged");
1326                $status = @imap_setflag_full($this->mbox, $id, "\\Flagged",ST_UID);
1327            }
1328            else {
1329                ZLog::Write(LOGLEVEL_DEBUG, "Clearing Flagged");
1330                $status = @imap_clearflag_full ( $this->mbox, $id, "\\Flagged", ST_UID);
1331            }
1332
1333            if ($status) {
1334                ZLog::Write(LOGLEVEL_DEBUG, "Flagged changed");
1335            }
1336            else {
1337                ZLog::Write(LOGLEVEL_DEBUG, "Flagged failed");
1338            }
1339        }
1340
1341        return $this->StatMessage($folderid, $id);
1342        /* END fmbiete's contribution r1529, ZP-321 */
1343    }
1344
1345    /**
1346     * Changes the 'read' flag of a message on disk
1347     *
1348     * @param string        $folderid       id of the folder
1349     * @param string        $id             id of the message
1350     * @param int           $flags          read flag of the message
1351     *
1352     * @access public
1353     * @return boolean                      status of the operation
1354     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1355     */
1356    public function SetReadFlag($folderid, $id, $flags) {
1357        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->SetReadFlag('%s','%s','%s')", $folderid, $id, $flags));
1358        $folderImapid = $this->getImapIdFromFolderId($folderid);
1359
1360        $this->imap_reopenFolder($folderImapid);
1361
1362        if ($flags == 0) {
1363            // set as "Unseen" (unread)
1364            $status = @imap_clearflag_full ( $this->mbox, $id, "\\Seen", ST_UID);
1365        } else {
1366            // set as "Seen" (read)
1367            $status = @imap_setflag_full($this->mbox, $id, "\\Seen",ST_UID);
1368        }
1369
1370        return $status;
1371    }
1372
1373    /**
1374     * Called when the user has requested to delete (really delete) a message
1375     *
1376     * @param string        $folderid       id of the folder
1377     * @param string        $id             id of the message
1378     *
1379     * @access public
1380     * @return boolean                      status of the operation
1381     * @throws StatusException              could throw specific SYNC_STATUS_* exceptions
1382     */
1383    public function DeleteMessage($folderid, $id) {
1384        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->DeleteMessage('%s','%s')", $folderid, $id));
1385        $folderImapid = $this->getImapIdFromFolderId($folderid);
1386
1387        $this->imap_reopenFolder($folderImapid);
1388        $s1 = @imap_delete ($this->mbox, $id, FT_UID);
1389        $s11 = @imap_setflag_full($this->mbox, $id, "\\Deleted", FT_UID);
1390        $s2 = @imap_expunge($this->mbox);
1391
1392        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->DeleteMessage('%s','%s'): result: s-delete: '%s' s-expunge: '%s' setflag: '%s'", $folderid, $id, $s1, $s2, $s11));
1393
1394        return ($s1 && $s2 && $s11);
1395    }
1396
1397    /**
1398     * Called when the user moves an item on the PDA from one folder to another
1399     *
1400     * @param string        $folderid       id of the source folder
1401     * @param string        $id             id of the message
1402     * @param string        $newfolderid    id of the destination folder
1403     *
1404     * @access public
1405     * @return boolean                      status of the operation
1406     * @throws StatusException              could throw specific SYNC_MOVEITEMSSTATUS_* exceptions
1407     */
1408    public function MoveMessage($folderid, $id, $newfolderid) {
1409        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->MoveMessage('%s','%s','%s')", $folderid, $id, $newfolderid));
1410        $folderImapid = $this->getImapIdFromFolderId($folderid);
1411        $newfolderImapid = $this->getImapIdFromFolderId($newfolderid);
1412
1413
1414        $this->imap_reopenFolder($folderImapid);
1415
1416        // TODO this should throw a StatusExceptions on errors like SYNC_MOVEITEMSSTATUS_SAMESOURCEANDDEST,SYNC_MOVEITEMSSTATUS_INVALIDSOURCEID,SYNC_MOVEITEMSSTATUS_CANNOTMOVE
1417
1418        // read message flags
1419        $overview = @imap_fetch_overview ( $this->mbox , $id, FT_UID);
1420
1421        if (!$overview)
1422            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);
1423        else {
1424            // get next UID for destination folder
1425            // when moving a message we have to announce through ActiveSync the new messageID in the
1426            // destination folder. This is a "guessing" mechanism as IMAP does not inform that value.
1427            // when lots of simultaneous operations happen in the destination folder this could fail.
1428            // in the worst case the moved message is displayed twice on the mobile.
1429            $destStatus = imap_status($this->mbox, $this->server . $newfolderImapid, SA_ALL);
1430            if (!$destStatus)
1431                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);
1432
1433            $newid = $destStatus->uidnext;
1434
1435            // move message
1436            $s1 = imap_mail_move($this->mbox, $id, $newfolderImapid, CP_UID);
1437            if (! $s1)
1438                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);
1439
1440
1441            // delete message in from-folder
1442            $s2 = imap_expunge($this->mbox);
1443
1444            // open new folder
1445            $stat = $this->imap_reopenFolder($newfolderImapid);
1446            if (! $s1)
1447                throw new StatusException(sprintf("BackendIMAP->MoveMessage('%s','%s','%s'): Error, openeing the destination folder: %s", $folderid, $id, $newfolderid, imap_last_error()), SYNC_MOVEITEMSSTATUS_CANNOTMOVE);
1448
1449
1450            // remove all flags
1451            $s3 = @imap_clearflag_full ($this->mbox, $newid, "\\Seen \\Answered \\Flagged \\Deleted \\Draft", FT_UID);
1452            $newflags = "";
1453            if ($overview[0]->seen) $newflags .= "\\Seen";
1454            if ($overview[0]->flagged) $newflags .= " \\Flagged";
1455            if ($overview[0]->answered) $newflags .= " \\Answered";
1456            $s4 = @imap_setflag_full ($this->mbox, $newid, $newflags, FT_UID);
1457
1458            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)));
1459
1460            // return the new id "as string""
1461            return $newid . "";
1462        }
1463    }
1464
1465
1466    /**----------------------------------------------------------------------------------------------------------
1467     * protected IMAP methods
1468     */
1469
1470    /**
1471     * Unmasks a hex folderid and returns the imap folder id
1472     *
1473     * @param string        $folderid       hex folderid generated by convertImapId()
1474     *
1475     * @access protected
1476     * @return string       imap folder id
1477     */
1478    protected function getImapIdFromFolderId($folderid) {
1479        $this->InitializePermanentStorage();
1480
1481        if (isset($this->permanentStorage->fmFidFimap)) {
1482            if (isset($this->permanentStorage->fmFidFimap[$folderid])) {
1483                $imapId = $this->permanentStorage->fmFidFimap[$folderid];
1484                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, $imapId));
1485                return $imapId;
1486            }
1487            else {
1488                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, 'not found'));
1489                return false;
1490            }
1491        }
1492        ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->getImapIdFromFolderId('%s') = %s", $folderid, 'not initialized!'));
1493        return false;
1494    }
1495
1496    /**
1497     * Retrieves a hex folderid previousily masked imap
1498     *
1499     * @param string        $imapid         Imap folder id
1500     *
1501     * @access protected
1502     * @return string       hex folder id
1503     */
1504    protected function getFolderIdFromImapId($imapid) {
1505        $this->InitializePermanentStorage();
1506
1507        if (isset($this->permanentStorage->fmFimapFid)) {
1508            if (isset($this->permanentStorage->fmFimapFid[$imapid])) {
1509                $folderid = $this->permanentStorage->fmFimapFid[$imapid];
1510                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, $folderid));
1511                return $folderid;
1512            }
1513            else {
1514                ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, 'not found'));
1515                return false;
1516            }
1517        }
1518        ZLog::Write(LOGLEVEL_WARN, sprintf("BackendIMAP->getFolderIdFromImapId('%s') = %s", $imapid, 'not initialized!'));
1519        return false;
1520    }
1521
1522    /**
1523     * Masks a imap folder id into a generated hex folderid
1524     * The method getFolderIdFromImapId() is consulted so that an
1525     * imapid always returns the same hex folder id
1526     *
1527     * @param string        $imapid         Imap folder id
1528     *
1529     * @access protected
1530     * @return string       hex folder id
1531     */
1532    protected function convertImapId($imapid) {
1533        $this->InitializePermanentStorage();
1534
1535        // check if this imap id was converted before
1536        $folderid = $this->getFolderIdFromImapId($imapid);
1537
1538        // nothing found, so generate a new id and put it in the cache
1539        if (!$folderid) {
1540            // generate folderid and add it to the mapping
1541            $folderid = sprintf('%04x%04x', mt_rand( 0, 0xffff ), mt_rand( 0, 0xffff ));
1542
1543            // folderId to folderImap mapping
1544            if (!isset($this->permanentStorage->fmFidFimap))
1545                $this->permanentStorage->fmFidFimap = array();
1546
1547            $a = $this->permanentStorage->fmFidFimap;
1548            $a[$folderid] = $imapid;
1549            $this->permanentStorage->fmFidFimap = $a;
1550
1551            // folderImap to folderid mapping
1552            if (!isset($this->permanentStorage->fmFimapFid))
1553                $this->permanentStorage->fmFimapFid = array();
1554
1555            $b = $this->permanentStorage->fmFimapFid;
1556            $b[$imapid] = $folderid;
1557            $this->permanentStorage->fmFimapFid = $b;
1558        }
1559
1560        ZLog::Write(LOGLEVEL_DEBUG, sprintf("BackendIMAP->convertImapId('%s') = %s", $imapid, $folderid));
1561
1562        return $folderid;
1563    }
1564
1565
1566    /**
1567     * Parses the message and return only the plaintext body
1568     *
1569     * @param string        $message        html message
1570     *
1571     * @access protected
1572     * @return string       plaintext message
1573     */
1574    protected function getBody($message) {
1575        $body = "";
1576        $htmlbody = "";
1577
1578        $this->getBodyRecursive($message, "plain", $body);
1579
1580        if($body === "") {
1581            $this->getBodyRecursive($message, "html", $body);
1582        }
1583
1584        return $body;
1585    }
1586
1587    /**
1588     * Get all parts in the message with specified type and concatenate them together, unless the
1589     * Content-Disposition is 'attachment', in which case the text is apparently an attachment
1590     *
1591     * @param string        $message        mimedecode message(part)
1592     * @param string        $message        message subtype
1593     * @param string        &$body          body reference
1594     *
1595     * @access protected
1596     * @return
1597     */
1598    protected function getBodyRecursive($message, $subtype, &$body) {
1599        if(!isset($message->ctype_primary)) return;
1600        if(strcasecmp($message->ctype_primary,"text")==0 && strcasecmp($message->ctype_secondary,$subtype)==0 && isset($message->body))
1601            $body .= $message->body;
1602
1603        if(strcasecmp($message->ctype_primary,"multipart")==0 && isset($message->parts) && is_array($message->parts)) {
1604            foreach($message->parts as $part) {
1605                if(!isset($part->disposition) || strcasecmp($part->disposition,"attachment"))  {
1606                    $this->getBodyRecursive($part, $subtype, $body);
1607                }
1608            }
1609        }
1610    }
1611
1612    /**
1613     * Returns the serverdelimiter for folder parsing
1614     *
1615     * @access protected
1616     * @return string       delimiter
1617     */
1618    protected function getServerDelimiter() {
1619        $list = @imap_getmailboxes($this->mbox, $this->server, "INBOX*");
1620        if (is_array($list)) {
1621            $val = $list[0];
1622
1623            return $val->delimiter;
1624        }
1625        return "."; // default "."
1626    }
1627
1628    /**
1629     * Helper to re-initialize the folder to speed things up
1630     * Remember what folder is currently open and only change if necessary
1631     *
1632     * @param string        $folderid       id of the folder
1633     * @param boolean       $force          re-open the folder even if currently opened
1634     *
1635     * @access protected
1636     * @return
1637     */
1638    protected function imap_reopenFolder($folderid, $force = false) {
1639        // to see changes, the folder has to be reopened!
1640           if ($this->mboxFolder != $folderid || $force) {
1641               $s = @imap_reopen($this->mbox, $this->server . $folderid);
1642               // TODO throw status exception
1643               if (!$s) {
1644                ZLog::Write(LOGLEVEL_WARN, "BackendIMAP->imap_reopenFolder('%s'): failed to change folder: ",$folderid, implode(", ", imap_errors()));
1645                return false;
1646               }
1647            $this->mboxFolder = $folderid;
1648        }
1649    }
1650
1651
1652    /**
1653     * Build a multipart RFC822, embedding body and one file (for attachments)
1654     *
1655     * @param string        $filenm         name of the file to be attached
1656     * @param long          $filesize       size of the file to be attached
1657     * @param string        $file_cont      content of the file
1658     * @param string        $body           current body
1659     * @param string        $body_ct        content-type
1660     * @param string        $body_cte       content-transfer-encoding
1661     * @param string        $boundary       optional existing boundary
1662     *
1663     * @access protected
1664     * @return array        with [0] => $mail_header and [1] => $mail_body
1665     */
1666    protected function mail_attach($filenm,$filesize,$file_cont,$body, $body_ct, $body_cte, $boundary = false) {
1667        if (!$boundary) $boundary = strtoupper(md5(uniqid(time())));
1668
1669        //remove the ending boundary because we will add it at the end
1670        $body = str_replace("--$boundary--", "", $body);
1671
1672        $mail_header = "Content-Type: multipart/mixed; boundary=$boundary\n";
1673
1674        // build main body with the sumitted type & encoding from the pda
1675        $mail_body  = $this->enc_multipart($boundary, $body, $body_ct, $body_cte);
1676        $mail_body .= $this->enc_attach_file($boundary, $filenm, $filesize, $file_cont);
1677
1678        $mail_body .= "--$boundary--\n\n";
1679        return array($mail_header, $mail_body);
1680    }
1681
1682    /**
1683     * Helper for mail_attach()
1684     *
1685     * @param string        $boundary       boundary
1686     * @param string        $body           current body
1687     * @param string        $body_ct        content-type
1688     * @param string        $body_cte       content-transfer-encoding
1689     *
1690     * @access protected
1691     * @return string       message body
1692     */
1693    protected function enc_multipart($boundary, $body, $body_ct, $body_cte) {
1694        $mail_body = "This is a multi-part message in MIME format\n\n";
1695        $mail_body .= "--$boundary\n";
1696        $mail_body .= "Content-Type: $body_ct\n";
1697        $mail_body .= "Content-Transfer-Encoding: $body_cte\n\n";
1698        $mail_body .= "$body\n\n";
1699
1700        return $mail_body;
1701    }
1702
1703    /**
1704     * Helper for mail_attach()
1705     *
1706     * @param string        $boundary       boundary
1707     * @param string        $filenm         name of the file to be attached
1708     * @param long          $filesize       size of the file to be attached
1709     * @param string        $file_cont      content of the file
1710     * @param string        $content_type   optional content-type
1711     *
1712     * @access protected
1713     * @return string       message body
1714     */
1715    protected function enc_attach_file($boundary, $filenm, $filesize, $file_cont, $content_type = "") {
1716        if (!$content_type) $content_type = "text/plain";
1717        $mail_body = "--$boundary\n";
1718        $mail_body .= "Content-Type: $content_type; name=\"$filenm\"\n";
1719        $mail_body .= "Content-Transfer-Encoding: base64\n";
1720        $mail_body .= "Content-Disposition: attachment; filename=\"$filenm\"\n";
1721        $mail_body .= "Content-Description: $filenm\n\n";
1722        //contrib - chunk base64 encoded attachments
1723        $mail_body .= chunk_split(base64_encode($file_cont)) . "\n\n";
1724
1725        return $mail_body;
1726    }
1727
1728    /**
1729     * Adds a message with seen flag to a specified folder (used for saving sent items)
1730     *
1731     * @param string        $folderid       id of the folder
1732     * @param string        $header         header of the message
1733     * @param long          $body           body of the message
1734     *
1735     * @access protected
1736     * @return boolean      status
1737     */
1738    protected function addSentMessage($folderid, $header, $body) {
1739        $header_body = str_replace("\n", "\r\n", str_replace("\r", "", $header . "\n\n" . $body));
1740
1741        return @imap_append($this->mbox, $this->server . $folderid, $header_body, "\\Seen");
1742    }
1743
1744    /**
1745     * Parses an mimedecode address array back to a simple "," separated string
1746     *
1747     * @param array         $ad             addresses array
1748     *
1749     * @access protected
1750     * @return string       mail address(es) string
1751     */
1752    protected function parseAddr($ad) {
1753        $addr_string = "";
1754        if (isset($ad) && is_array($ad)) {
1755            foreach($ad as $addr) {
1756                if ($addr_string) $addr_string .= ",";
1757                    $addr_string .= $addr->mailbox . "@" . $addr->host;
1758            }
1759        }
1760        return $addr_string;
1761    }
1762
1763    /**
1764     * Recursive way to get mod and parent - repeat until only one part is left
1765     * or the folder is identified as an IMAP folder
1766     *
1767     * @param string        $fhir           folder hierarchy string
1768     * @param string        &$displayname   reference of the displayname
1769     * @param long          &$parent        reference of the parent folder
1770     *
1771     * @access protected
1772     * @return
1773     */
1774    protected function getModAndParentNames($fhir, &$displayname, &$parent) {
1775        // if mod is already set add the previous part to it as it might be a folder which has
1776        // delimiter in its name
1777        $displayname = (isset($displayname) && strlen($displayname) > 0) ? $displayname = array_pop($fhir).$this->serverdelimiter.$displayname : array_pop($fhir);
1778        $parent = implode($this->serverdelimiter, $fhir);
1779
1780        if (count($fhir) == 1 || $this->checkIfIMAPFolder($parent)) {
1781            return;
1782        }
1783        //recursion magic
1784        $this->getModAndParentNames($fhir, $displayname, $parent);
1785    }
1786
1787    /**
1788     * Checks if a specified name is a folder in the IMAP store
1789     *
1790     * @param string        $foldername     a foldername
1791     *
1792     * @access protected
1793     * @return boolean
1794     */
1795    protected function checkIfIMAPFolder($folderName) {
1796        $parent = imap_list($this->mbox, $this->server, $folderName);
1797        if ($parent === false) return false;
1798        return true;
1799    }
1800
1801    /**
1802     * Removes parenthesis (comments) from the date string because
1803     * strtotime returns false if received date has them
1804     *
1805     * @param string        $receiveddate   a date as a string
1806     *
1807     * @access protected
1808     * @return string
1809     */
1810    protected function cleanupDate($receiveddate) {
1811        $receiveddate = strtotime(preg_replace("/\(.*\)/", "", $receiveddate));
1812        if ($receiveddate == false || $receiveddate == -1) {
1813            debugLog("Received date is false. Message might be broken.");
1814            return null;
1815        }
1816
1817        return $receiveddate;
1818    }
1819
1820    /* BEGIN fmbiete's contribution r1528, ZP-320 */
1821    /**
1822     * Indicates which AS version is supported by the backend.
1823     *
1824     * @access public
1825     * @return string       AS version constant
1826     */
1827    public function GetSupportedASVersion() {
1828        return ZPush::ASV_14;
1829    }
1830    /* END fmbiete's contribution r1528, ZP-320 */
1831};
1832
1833?>
Note: See TracBrowser for help on using the repository browser.