]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/InboundEmail/InboundEmail.php
Release 6.4.0beta1
[Github/sugarcrm.git] / modules / InboundEmail / InboundEmail.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:  TODO: To be written.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45
46
47
48 require_once('include/OutboundEmail/OutboundEmail.php');
49 require_once('include/Pear/HTML_Safe/Safe.php');
50
51 function this_callback($str) {
52         foreach($str as $match) {
53                 $ret .= chr(hexdec(str_replace("%","",$match)));
54         }
55         return $ret;
56 }
57
58 /**
59  * Stub for certain interactions;
60  */
61 class temp {
62         var $name;
63 }
64
65 class InboundEmail extends SugarBean {
66         // module specific
67         var $conn;
68         var $purifier; // HTMLPurifier object placeholder
69         var $email;
70
71         // fields
72         var $id;
73         var $deleted;
74         var $date_entered;
75         var $date_modified;
76         var $modified_user_id;
77         var $created_by;
78         var $created_by_name;
79         var $modified_by_name;
80         var $name;
81         var $status;
82         var $server_url;
83         var $email_user;
84         var $email_password;
85         var $port;
86         var $service;
87         var $mailbox;
88         var $mailboxarray;
89         var $delete_seen;
90         var $mailbox_type;
91         var $template_id;
92         var $stored_options;
93         var $group_id;
94         var $is_personal;
95         var $groupfolder_id;
96
97         // email 2.0
98         var $pop3socket;
99         var $outboundInstance; // id to outbound_email instance
100         var $autoImport;
101         var $iconFlagged = "F";
102         var $iconDraft = "D";
103         var $iconAnswered = "A";
104         var $iconDeleted = "del";
105         var $isAutoImport = false;
106         var $smarty;
107         var $attachmentCount = 0;
108         var $tempAttachment = array();
109         var $unsafeChars = array("&", "!", "'", '"', '\\', '/', '<', '>', '|', '$',);
110         var $currentCache;
111         var $defaultSort = 'date';
112         var $defaultDirection = "DESC";
113         var $hrSort = array(
114                         0 => 'flagged',
115                         1 => 'status',
116                         2 => 'from',
117                         3 => 'subj',
118                         4 => 'date',
119                 );
120         var $hrSortLocal = array(
121                         'flagged' => 'flagged',
122                         'status'  => 'answered',
123                         'from'    => 'fromaddr',
124                         'subject' => 'subject',
125                         'date'    => 'senddate',
126                 );
127
128         // default attributes
129         var $transferEncoding                             = array(0 => '7BIT',
130                                                                                                 1 => '8BIT',
131                                                                                                 2 => 'BINARY',
132                                                                                                 3 => 'BASE64',
133                                                                                                 4 => 'QUOTED-PRINTABLE',
134                                                                                                 5 => 'OTHER'
135                                                                                         );
136         // object attributes
137         var $safe; // place holder for HTML_Safe class
138         var $compoundMessageId; // concatenation of messageID and deliveredToEmail
139         var $serverConnectString;
140         var $disable_row_level_security = true;
141         var $InboundEmailCachePath;
142         var $InboundEmailCacheFile                      = 'InboundEmail.cache.php';
143         var $object_name                                        = 'InboundEmail';
144         var $module_dir                                 = 'InboundEmail';
145         var $table_name                                 = 'inbound_email';
146         var $new_schema                                 = true;
147         var $process_save_dates                         = true;
148         var $order_by;
149         var $db;
150         var $dbManager;
151         var $field_defs;
152         var $column_fields;
153         var $required_fields                            = array('name'                  => 'name',
154                                                                                                 'server_url'    => 'server_url',
155                                                                                                 'mailbox'               => 'mailbox',
156                                                                                                 'user'                  => 'user',
157                                                                                                 'port'                  => 'port',
158                                                                                         );
159         var $imageTypes                                 = array("JPG", "JPEG", "GIF", "PNG");
160         var $inlineImages                                       = array();  // temporary space to store ID of inlined images
161         var $defaultEmailNumAutoreplies24Hours = 10;
162         var $maxEmailNumAutoreplies24Hours = 10;
163         // custom ListView attributes
164         var $mailbox_type_name;
165         var $global_personal_string;
166         // service attributes
167         var $tls;
168         var $ca;
169         var $ssl;
170         var $protocol;
171         var $keyForUsersDefaultIEAccount = 'defaultIEAccount';
172         // prefix to use when importing inlinge images in emails
173         public $imagePrefix;
174
175         /**
176          * Sole constructor
177          */
178         function InboundEmail() {
179             $this->InboundEmailCachePath = sugar_cached('modules/InboundEmail');
180             $this->EmailCachePath = sugar_cached('modules/Emails');
181             parent::SugarBean();
182                 if(function_exists("imap_timeout")) {
183                         /*
184                          * 1: Open
185                          * 2: Read
186                          * 3: Write
187                          * 4: Close
188                          */
189                         imap_timeout(1, 60);
190                         imap_timeout(2, 60);
191                         imap_timeout(3, 60);
192                 }
193
194                 $this->safe = new HTML_Safe();
195                 $this->safe->whiteProtocols[] = "cid";
196                 $this->safe->clear();
197
198                 $this->smarty = new Sugar_Smarty();
199                 $this->overview = new Overview();
200                 $this->imagePrefix = "{$GLOBALS['sugar_config']['site_url']}/cache/images/";
201         }
202
203         /**
204          * retrieves I-E bean
205          * @param string id
206          * @return object Bean
207          */
208         function retrieve($id) {
209                 $ret = parent::retrieve($id);
210                 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
211                 $this->retrieveMailBoxFolders();
212                 return $ret;
213         }
214
215         /**
216          * wraps SugarBean->save()
217          * @param string ID of saved bean
218          */
219         function save($check_notify=false) {
220                 // generate cache table for email 2.0
221                 $multiDImArray = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
222                 $raw = $this->generateFlatArrayFromMultiDimArray($multiDImArray, $this->retrieveDelimiter());
223                 sort($raw);
224                 //_pp(explode(",", $this->mailbox));
225                 //_ppd($raw);
226                 $raw = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $raw);
227                 $this->mailbox = implode(",", $raw);
228                 if(!empty($this->email_password)) {
229                     $this->email_password = blowfishEncode(blowfishGetKey('InboundEmail'), $this->email_password);
230                 }
231                 $ret = parent::save($check_notify);
232                 return $ret;
233         }
234
235         function filterMailBoxFromRaw($mailboxArray, $rawArray) {
236                 $newArray = array_intersect($mailboxArray, $rawArray);
237                 sort($newArray);
238                 return $newArray;
239         } // fn
240
241         /**
242          * Overrides SugarBean's mark_deleted() to drop the related cache table
243          * @param string $id GUID of I-E instance
244          */
245         function mark_deleted($id) {
246                 parent::mark_deleted($id);
247                 $q = "update inbound_email set groupfolder_id = null WHERE id = $id";
248                 $r = $this->db->query($q);
249                 $this->deleteCache();
250         }
251
252         /**
253          * Mark cached email answered (replied)
254          * @param string $mailid (uid for imap, message_id for pop3)
255          */
256         function mark_answered($mailid, $type = 'smtp') {
257                 switch ($type) {
258                         case 'smtp' :
259                                 $q = "update email_cache set answered = 1 WHERE imap_uid = $mailid and ie_id = '$this->id'";
260                                 $this->db->query($q);
261                                 break;
262                         case 'pop3' :
263                                 $q = "update email_cache set answered = 1 WHERE message_id = '$mailid' and ie_id = '$this->id'";
264                                 $this->db->query($q);
265                                 break;
266                 }
267         }
268
269         /**
270          * Renames an IMAP mailbox
271          * @param string $newName
272          */
273         function renameFolder($oldName, $newName) {
274                 //$this->mailbox = "INBOX"
275                 $this->connectMailserver();
276         $oldConnect = $this->getConnectString('', $oldName);
277         $newConnect = $this->getConnectString('', $newName);
278                 if(!imap_renamemailbox($this->conn, $oldConnect , $newConnect)) {
279                         $GLOBALS['log']->debug("***INBOUNDEMAIL: failed to rename mailbox [ {$oldConnect} ] to [ {$newConnect} ]");
280                 } else {
281                 $this->mailbox = str_replace($oldName, $newName, $this->mailbox);
282                 $this->save();
283                 $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
284                 $sessionFoldersString = str_replace($oldName, $newName, $sessionFoldersString);
285                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
286
287                 }
288         }
289
290         ///////////////////////////////////////////////////////////////////////////
291         ////    CUSTOM LOGIC HOOKS
292         /**
293          * Called from $this->getMessageText()
294          * Allows upgrade-safe custom processing of message text.
295          *
296          * To use:
297          * 1. Create a directory path: ./custom/modules/InboundEmail if it does not exist
298          * 2. Create a file in the ./custom/InboundEmail/ folder called "getMessageText.php"
299          * 3. Define a function named "custom_getMessageText()" that takes a string as an argument and returns a string
300          *
301          * @param string $msgPart
302          * @return string
303          */
304         function customGetMessageText($msgPart) {
305                 $custom = "custom/modules/InboundEmail/getMessageText.php";
306
307                 if(file_exists($custom)) {
308                         include_once($custom);
309
310                         if(function_exists("custom_getMessageText")) {
311                                 $GLOBALS['log']->debug("*** INBOUND EMAIL-CUSTOM_LOGIC: calling custom_getMessageText()");
312                                 $msgPart = custom_getMessageText($msgPart);
313                         }
314                 }
315
316                 return $msgPart;
317         }
318         ////    END CUSTOM LOGIC HOOKS
319         ///////////////////////////////////////////////////////////////////////////
320
321
322
323         ///////////////////////////////////////////////////////////////////////////
324         ////    EMAIL 2.0 SPECIFIC
325         /**
326          * constructs a nicely formatted version of raw source
327          * @param int $uid UID of email
328          * @return string
329          */
330         function getFormattedRawSource($uid) {
331                 global $app_strings;
332
333                 //if($this->protocol == 'pop3') {
334                 //$raw = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
335                 //} else {
336                         if (empty($this->id)) {
337                                 $q = "SELECT raw_source FROM emails_text WHERE email_id = '{$uid}'";
338                                 $r = $this->db->query($q);
339                                 $a = $this->db->fetchByAssoc($r);
340                                 $ret = array();
341                                 $raw = utf8_encode($a['raw_source']);
342                                 if (empty($raw)) {
343                                         $raw = $app_strings['LBL_EMAIL_ERROR_VIEW_RAW_SOURCE'];
344                                 }
345                         } else {
346                                 if ($this->isPop3Protocol()) {
347                                         $uid = $this->getCorrectMessageNoForPop3($uid);
348                                 }
349                                 $raw  = imap_fetchheader($this->conn, $uid, FT_UID+FT_PREFETCHTEXT);
350                                 $raw .= utf8_encode(imap_body($this->conn, $uid, FT_UID));
351                         } // else
352                         $raw = to_html($raw);
353                         $raw = nl2br($raw);
354                 //}
355
356                 return $raw;
357         }
358
359         /**
360          * constructs a nicely formatted version of email headers.
361          * @param int $uid
362          * @return string
363          */
364         function getFormattedHeaders($uid) {
365                 global $app_strings;
366
367                 //if($this->protocol == 'pop3') {
368                 //      $header = $app_strings['LBL_EMAIL_VIEW_UNSUPPORTED'];
369                 //} else {
370                         if ($this->isPop3Protocol()) {
371                                 $uid = $this->getCorrectMessageNoForPop3($uid);
372                         }
373                         $headers = imap_fetchheader($this->conn, $uid, FT_UID);
374
375                         $lines = explode("\n", $headers);
376
377                         $header = "<table cellspacing='0' cellpadding='2' border='0' width='100%'>";
378
379                         foreach($lines as $line) {
380                                 $line = trim($line);
381
382                                 if(!empty($line)) {
383                                         $key = trim(substr($line, 0, strpos($line, ":")));
384                                         $value = trim(substr($line, strpos($line, ":") + 1));
385                                         $value = to_html($value);
386
387                                         $header .= "<tr>";
388                                         $header .= "<td class='displayEmailLabel' NOWRAP><b>{$key}</b>&nbsp;</td>";
389                                         $header .= "<td class='displayEmailValueWhite'>{$value}&nbsp;</td>";
390                                         $header .= "</tr>";
391                                 }
392                         }
393
394                         $header .= "</table>";
395                 //}
396                 return $header;
397         }
398
399         /**
400          * Empties Trash folders
401          */
402         function emptyTrash() {
403                 global $sugar_config;
404
405                 $this->mailbox = $this->get_stored_options("trashFolder");
406                 if (empty($this->mailbox)) {
407                         $this->mailbox = 'INBOX.Trash';
408                 }
409                 $this->connectMailserver();
410
411                 $uids = imap_search($this->conn, "ALL", SE_UID);
412
413                 foreach($uids as $uid) {
414                         if(!imap_delete($this->conn, $uid, FT_UID)) {
415                                 $lastError = imap_last_error();
416                                 $GLOBALS['log']->warn("INBOUNDEMAIL: emptyTrash() Could not delete message [ {$uid} ] from [ {$this->mailbox} ].  IMAP_ERROR [ {$lastError} ]");
417                         }
418                 }
419
420                 // remove local cache file
421                 $q = "DELETE FROM email_cache WHERE mbox = '{$this->mailbox}' AND ie_id = '{$this->id}'";
422                 $r = $this->db->query($q);
423         }
424
425         /**
426          * Fetches a timestamp
427          */
428         function getCacheTimestamp($mbox) {
429                 $key = $this->db->quote("{$this->id}_{$mbox}");
430                 $q = "SELECT ie_timestamp FROM inbound_email_cache_ts WHERE id = '{$key}'";
431                 $r = $this->db->query($q);
432                 $a = $this->db->fetchByAssoc($r);
433
434                 if(empty($a)) {
435                         return -1;
436                 }
437                 return $a['ie_timestamp'];
438         }
439
440         /**
441          * sets the cache timestamp
442          * @param string mbox
443          */
444         function setCacheTimestamp($mbox) {
445                 $key = $this->db->quote("{$this->id}_{$mbox}");
446                 $ts = mktime();
447                 $tsOld = $this->getCacheTimestamp($mbox);
448
449                 if($tsOld < 0) {
450                         $q = "INSERT INTO inbound_email_cache_ts (id, ie_timestamp) VALUES ('{$key}', {$ts})";
451                 } else {
452                         $q = "UPDATE inbound_email_cache_ts SET ie_timestamp = {$ts} WHERE id = '{$key}'";
453                 }
454
455                 $r = $this->db->query($q, true);
456                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: setting timestamp query [ {$q} ]");
457         }
458
459
460         /**
461          * Gets a count of all rows that are flagged seen = 0
462          * @param string $mbox
463          * @return int
464          */
465         function getCacheUnreadCount($mbox) {
466                 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND seen = 0 AND ie_id = '{$this->id}'";
467                 $r = $this->db->query($q);
468                 $a = $this->db->fetchByAssoc($r);
469
470                 return $a['c'];
471         }
472
473         /**
474          * Returns total number of emails for a mailbox
475          * @param string mbox
476          * @return int
477          */
478         function getCacheCount($mbox) {
479                 $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}'";
480                 $r = $this->db->query($q);
481                 $a = $this->db->fetchByAssoc($r);
482
483                 return $a['c'];
484         }
485
486     function getCacheUnread($mbox) {
487         $q = "SELECT count(*) c FROM email_cache WHERE mbox = '{$mbox}' AND ie_id = '{$this->id}' AND seen = '0'";
488         $r = $this->db->query($q);
489         $a = $this->db->fetchByAssoc($r);
490
491         return $a['c'];
492     }
493
494
495         /**
496          * Deletes all rows for a given instance
497          */
498         function deleteCache() {
499                 $q = "DELETE FROM email_cache WHERE ie_id = '{$this->id}'";
500
501                 $GLOBALS['log']->info("INBOUNDEMAIL: deleting cache using query [ {$q} ]");
502
503                 $r = $this->db->query($q);
504         }
505
506         /**
507          * Deletes all the pop3 data which has been deleted from server
508          */
509         function deletePop3Cache() {
510                 global $sugar_config;
511                 $UIDLs = $this->pop3_getUIDL();
512                 $cacheUIDLs = $this->pop3_getCacheUidls();
513                 foreach($cacheUIDLs as $msgNo => $msgId) {
514                         if (!in_array($msgId, $UIDLs)) {
515                                 $md5msgIds = md5($msgId);
516                                 $file = "{$this->EmailCachePath}/{$this->id}/messages/INBOX{$md5msgIds}.PHP";
517                                 $GLOBALS['log']->debug("INBOUNDEMAIL: deleting file [ {$file} ] ");
518                                 if(file_exists($file)) {
519                                         if(!unlink($file)) {
520                                                 $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ] ");
521                                         } // if
522                                 } // if
523                                 $q = "DELETE from email_cache where imap_uid = {$msgNo} AND msgno = {$msgNo} AND ie_id = '{$this->id}' AND message_id = '{$msgId}'";
524                                 $r = $this->db->query($q);
525                         } // if
526                 } // for
527         } // fn
528
529         /**
530          * Retrieves cached headers
531          * @return array
532          */
533         function getCacheValueForUIDs($mbox, $UIDs) {
534                 if (!is_array($UIDs) || empty($UIDs)) {
535                         return array();
536                 }
537
538                 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' AND ";
539                 $startIndex = 0;
540                 $endIndex = 5;
541
542                 $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
543                 $columnName = ($this->isPop3Protocol() ? "message_id" : "imap_uid");
544                 $ret = array(
545                         'timestamp'     => $this->getCacheTimestamp($mbox),
546                         'uids'          => array(),
547                         'retArr'        => array(),
548                 );
549                 while (!empty($slicedArray)) {
550                         $messageIdString = implode(',', $slicedArray);
551                         $GLOBALS['log']->debug("sliced array = {$messageIdString}");
552                         $extraWhere = "{$columnName} IN (";
553                         $i = 0;
554                         foreach($slicedArray as $UID) {
555                                 if($i != 0) {
556                                         $extraWhere = $extraWhere . ",";
557                                 } // if
558                                 $i++;
559                                 $extraWhere = "{$extraWhere} '{$UID}'";
560                         } // foreach
561                         $newQuery = $q . $extraWhere . ")";
562                         $r = $this->db->query($newQuery);
563
564                         while($a = $this->db->fetchByAssoc($r)) {
565                                 if (isset($a['uid'])) {
566                                         if ($this->isPop3Protocol()) {
567                                                 $ret['uids'][] = $a['message_id'];
568                                         } else {
569                                         $ret['uids'][] = $a['uid'];
570                                         }
571                                 }
572
573                                 $overview = new Overview();
574
575                                 foreach($a as $k => $v) {
576                                         $k=strtolower($k);
577                                         switch($k) {
578                                                 case "imap_uid":
579                                                         $overview->imap_uid = $v;
580                                                         if ($this->isPop3Protocol()) {
581                                                                 $overview->uid = $a['message_id'];
582                                                         } else {
583                                                                 $overview->uid = $v;
584                                                         }
585                                                 break;
586                                                 case "toaddr":
587                                                         $overview->to = from_html($v);
588                                                 break;
589
590                                                 case "fromaddr":
591                                                         $overview->from = from_html($v);
592                                                 break;
593
594                                                 case "mailsize":
595                                                         $overview->size = $v;
596                                                 break;
597
598                                                 case "senddate":
599                                                         $overview->date = $v;
600                                                 break;
601
602                                                 default:
603                                                         $overview->$k = from_html($v);
604                                                 break;
605                                         } // switch
606                                 } // foreach
607                                 $ret['retArr'][] = $overview;
608                         } // while
609                         $startIndex = $startIndex + $endIndex;
610                         $slicedArray = array_slice($UIDs, $startIndex ,$endIndex);
611                         $messageIdString = implode(',', $slicedArray);
612                         $GLOBALS['log']->debug("sliced array = {$messageIdString}");
613                 } // while
614                 return $ret;
615         }
616
617         /**
618          * Retrieves cached headers
619          * @return array
620          */
621         function getCacheValue($mbox, $limit = 20, $page = 1, $sort='', $direction='') {
622                 // try optimizing this call as we don't want repeat queries
623                 if(!empty($this->currentCache)) {
624                         return $this->currentCache;
625                 }
626
627                 $sort = (empty($sort)) ? $this->defaultSort : $sort;
628                 $direction = (empty($direction)) ? $this->defaultDirection : $direction;
629                 $order = " ORDER BY {$this->hrSortLocal[$sort]} {$direction}";
630
631                 $q = "SELECT * FROM email_cache WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}' {$order}";
632
633                 if(!empty($limit)) {
634                         $start = ( $page - 1 ) * $limit;
635                         $r = $this->db->limitQuery($q, $start, $limit);
636                 } else {
637                         $r = $this->db->query($q);
638                 }
639
640                 $ret = array(
641                         'timestamp'     => $this->getCacheTimestamp($mbox),
642                         'uids'          => array(),
643                         'retArr'        => array(),
644                 );
645
646                 while($a = $this->db->fetchByAssoc($r)) {
647                         if (isset($a['uid'])) {
648                                 if ($this->isPop3Protocol()) {
649                                         $ret['uids'][] = $a['message_id'];
650                                 } else {
651                                 $ret['uids'][] = $a['uid'];
652                                 }
653                         }
654
655                         $overview = new Overview();
656
657                         foreach($a as $k => $v) {
658                                 $k=strtolower($k);
659                                 switch($k) {
660                                         case "imap_uid":
661                                                 $overview->imap_uid = $v;
662                                                 if ($this->isPop3Protocol()) {
663                                                         $overview->uid = $a['message_id'];
664                                                 } else {
665                                                         $overview->uid = $v;
666                                                 }
667                                         break;
668                                         case "toaddr":
669                                                 $overview->to = from_html($v);
670                                         break;
671
672                                         case "fromaddr":
673                                                 $overview->from = from_html($v);
674                                         break;
675
676                                         case "mailsize":
677                                                 $overview->size = $v;
678                                         break;
679
680                                         case "senddate":
681                                                 $overview->date = $v;
682                                         break;
683
684                                         default:
685                                                 $overview->$k = from_html($v);
686                                         break;
687                                 }
688                         }
689                         $ret['retArr'][] = $overview;
690                 }
691
692                 $this->currentCache = $ret;
693
694                 return $ret;
695         }
696
697         /**
698          * Sets cache values
699          */
700         function setCacheValue($mbox, $insert, $update=array(), $remove=array()) {
701                 if(empty($mbox)) {
702                         return;
703                 }
704                 global $timedate;
705
706
707                 // reset in-memory cache
708                 $this->currentCache = null;
709
710                 $table = 'email_cache';
711                 $where = "WHERE ie_id = '{$this->id}' AND mbox = '{$mbox}'";
712
713                 // handle removed rows
714                 if(!empty($remove)) {
715                         $removeIds = '';
716                         foreach($remove as $overview) {
717                                 if(!empty($removeIds)) {
718                                         $removeIds .= ",";
719                                 }
720
721                                 $removeIds .= "'{$overview->imap_uid}'";
722                         }
723
724                         $q = "DELETE FROM {$table} {$where} AND imap_uid IN ({$removeIds})";
725
726                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: delete query [ {$q} ]");
727
728                         $r = $this->db->query($q, true, $q);
729                 }
730
731                 // handle insert rows
732                 if(!empty($insert)) {
733                         $q = "SELECT imap_uid FROM {$table} {$where}";
734                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs query [ {$q} ]");
735                         $r = $this->db->query($q);
736                         $uids = array();
737
738                         while($a = $this->db->fetchByAssoc($r)) {
739                                 $uids[] = $a['imap_uid'];
740                         }
741                         $count = count($uids);
742                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: found [ {$count} ] UIDs to filter against");
743
744                         $tmp = '';
745                         foreach($uids as $uid) {
746                                 if(!empty($tmp))
747                                         $tmp .= ", ";
748                                 $tmp .= "{$uid}";
749                         }
750                         $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: filter UIDs: [ {$tmp} ]");
751
752                         $cols = "";
753
754                         foreach($this->overview->fieldDefs as $colDef) {
755                                 if(!empty($cols))
756                                         $cols .= ",";
757
758                                 $cols .= "{$colDef['name']}";
759                         }
760                         foreach($insert as $overview) {
761                                 if(in_array($overview->imap_uid, $uids)) {
762                                         $update[] = $overview;
763                                         continue;
764                                 }
765
766                                 $values = '';
767
768                                 foreach($this->overview->fieldDefs as $colDef) {
769                                         if(!empty($values)) {
770                                                 $values .= ", ";
771                                         }
772
773                                         // trim values for Oracle/MSSql
774                                         if(     isset($colDef['len']) && !empty($colDef['len']) &&
775                                                 isset($colDef['type']) && !empty($colDef['type']) &&
776                                                 $colDef['type'] == 'varchar'
777                                         ) {
778                                                 $overview->$colDef['name'] = substr($overview->$colDef['name'], 0, $colDef['len']);
779                                         }
780
781                                         switch($colDef['name']) {
782                                                 case "imap_uid":
783                                                         if(isset($overview->uid) && !empty($overview->uid)) {
784                                                                 $this->imap_uid = $overview->uid;
785                                                         }
786                                                         $values .= "'{$this->imap_uid}'";
787                                                 break;
788
789                                                 case "ie_id":
790                                                         $values .= "'{$this->id}'";
791                                                 break;
792
793                                                 case "toaddr":
794                                                         $values .= $this->db->quoted($overview->to);
795                                                 break;
796
797                                                 case "fromaddr":
798                                                         $values .= $this->db->quoted($overview->from);
799                                                 break;
800
801                                                 case "message_id" :
802                                                         $values .= $this->db->quoted($overview->message_id);
803                                                 break;
804
805                                                 case "mailsize":
806                                                         $values .= $overview->size;
807                                                 break;
808
809                                                 case "senddate":
810                                                         $conv=$timedate->fromString($overview->date);
811                                                         if (!empty($conv)) {
812                                                                 $values .= $this->db->quoted($conv->asDb());
813                                                         } else {
814                                                                 $values .= "NULL";
815                                                         }
816                                                 break;
817
818                                                 case "mbox":
819                                                         $values .= "'{$mbox}'";
820                                                 break;
821
822                                                 default:
823                                                         $overview->$colDef['name'] = from_html($overview->$colDef['name']);
824                                                         $overview->$colDef['name'] = $this->cleanContent($overview->$colDef['name']);
825                                                         $values .= $this->db->quoted($overview->$colDef['name']);
826                                                 break;
827                                         }
828                                 }
829
830                                 $q = "INSERT INTO {$table} ({$cols}) VALUES ({$values})";
831                                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: insert query [ {$q} ]");
832                                 $r = $this->db->query($q, true, $q);
833                         }
834                 }
835
836                 // handle update rows
837                 if(!empty($update)) {
838                         $cols = "";
839                         foreach($this->overview->fieldDefs as $colDef) {
840                                 if(!empty($cols))
841                                         $cols .= ",";
842
843                                 $cols .= "{$colDef['name']}";
844                         }
845
846                         foreach($update as $overview) {
847                                 $q = "UPDATE {$table} SET ";
848
849                                 $set = '';
850                                 foreach($this->overview->fieldDefs as $colDef) {
851
852                                         switch($colDef['name']) {
853                                                 case "toaddr":
854                                                 case "fromaddr":
855                                                 case "mailsize":
856                                                 case "senddate":
857                                                 case "mbox":
858                                                 break;
859
860                                                 default:
861                                                         if(!empty($set)) {
862                                                                 $set .= ",";
863                                                         }
864                                                         $set .= "{$colDef['name']} = ".$this->db->quoted($overview->$colDef['name']);
865                                                 break;
866                                         }
867                                 }
868
869                                 $q .= $set . " WHERE ie_id = '{$this->id}' AND mbox = '{$overview->mbox}' AND imap_uid = '{$overview->imap_uid}'";
870                                 $GLOBALS['log']->info("INBOUNDEMAIL-CACHE: update query [ {$q} ]");
871                                 $r = $this->db->query($q, true, $q);
872                         }
873                 }
874
875         }
876
877         /**
878          * Opens a socket connection to the pop3 server
879          * @return bool
880          */
881         function pop3_open() {
882                 if(!is_resource($this->pop3socket)) {
883                         $GLOBALS['log']->info("*** INBOUNDEMAIL: opening socket connection");
884                         $exServ = explode('::', $this->service);
885                         $socket  = ($exServ[2] == 'ssl') ? "ssl://" : "tcp://";
886                         $socket .= $this->server_url;
887                         $this->pop3socket = fsockopen($socket, $this->port);
888                 } else {
889                         $GLOBALS['log']->info("*** INBOUNDEMAIL: REUSING socket connection");
890                         return true;
891                 }
892
893                 if(!is_resource($this->pop3socket)) {
894                         $GLOBALS['log']->debug("*** INBOUNDEMAIL: unable to open socket connection");
895                         return false;
896                 }
897
898                 // clear buffer
899                 $ret = trim(fgets($this->pop3socket, 1024));
900                 $GLOBALS['log']->info("*** INBOUNDEMAIL: got socket connection [ {$ret} ]");
901                 return true;
902         }
903
904         /**
905          * Closes connections and runs clean-up routines
906          */
907         function pop3_cleanUp() {
908                 $GLOBALS['log']->info("*** INBOUNDEMAIL: cleaning up socket connection");
909                 fputs($this->pop3socket, "QUIT\r\n");
910                 $buf = fgets($this->pop3socket, 1024);
911                 fclose($this->pop3socket);
912         }
913
914         /**
915          * sends a command down to the POP3 server
916          * @param string command
917          * @param string args
918          * @param bool return
919          * @return string
920          */
921         function pop3_sendCommand($command, $args='', $return=true) {
922                 $command .= " {$args}";
923                 $command = trim($command);
924                 $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() SEND [ {$command} ]");
925                 $command .= "\r\n";
926
927                 fputs($this->pop3socket, $command);
928
929                 if($return) {
930                         $ret = trim(fgets($this->pop3socket, 1024));
931                         $GLOBALS['log']->info("*** INBOUNDEMAIL: pop3_sendCommand() RECEIVE [ {$ret} ]");
932                         return $ret;
933                 }
934         }
935
936         function getPop3NewMessagesToDownload() {
937                 $pop3UIDL = $this->pop3_getUIDL();
938                 $cacheUIDLs = $this->pop3_getCacheUidls();
939                 // new email cache values we should deal with
940                 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
941                 // this is msgNo to UIDL array
942                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
943                 // get all the keys which are msgnos;
944                 return array_keys($diff);
945         }
946
947         function getPop3NewMessagesToDownloadForCron() {
948                 $pop3UIDL = $this->pop3_getUIDL();
949                 $cacheUIDLs = $this->pop3_getCacheUidls();
950                 // new email cache values we should deal with
951                 $diff = array_diff_assoc($pop3UIDL, $cacheUIDLs);
952                 // this is msgNo to UIDL array
953                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
954                 // insert data into email_cache
955                 if ($this->groupfolder_id != null && $this->groupfolder_id != "" && $this->isPop3Protocol()) {
956                         $searchResults = array_keys($diff);
957                         $concatResults = implode(",", $searchResults);
958                         if ($this->connectMailserver() == 'true') {
959                                 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
960                                 // clean up cache entry
961                                 foreach($fetchedOverviews as $k => $overview) {
962                                         $overview->message_id = trim($diff[$overview->msgno]);
963                                         $fetchedOverviews[$k] = $overview;
964                                 }
965                                 $this->updateOverviewCacheFile($fetchedOverviews);
966                         }
967                 } // if
968                 return $diff;
969         }
970
971         /**
972          * This method returns all the UIDL for this account. This should be called if the protocol is pop3
973          * @return array od messageno to UIDL array
974          */
975         function pop3_getUIDL() {
976                 $UIDLs = array();
977                 if($this->pop3_open()) {
978                         // authenticate
979                         $this->pop3_sendCommand("USER", $this->email_user);
980                         $this->pop3_sendCommand("PASS", $this->email_password);
981
982                         // get UIDLs
983                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
984                         fgets($this->pop3socket, 1024); // handle "OK+";
985                         $UIDLs = array();
986
987                         $buf = '!';
988
989                         if(is_resource($this->pop3socket)) {
990                                 while(!feof($this->pop3socket)) {
991                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
992                                         //_pp(trim($buf));
993
994                                         if(trim($buf) == '.') {
995                                                 $GLOBALS['log']->debug("*** GOT '.'");
996                                                 break;
997                                         }
998
999                                         // format is [msgNo] [UIDL]
1000                                         $exUidl = explode(" ", $buf);
1001                                         $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1002                                 } // while
1003                         } // if
1004                         $this->pop3_cleanUp();
1005                 } // if
1006                 return $UIDLs;
1007         } // fn
1008
1009         /**
1010          * Special handler for POP3 boxes.  Standard IMAP commands are useless.
1011          * This will fetch only partial emails for POP3 and hence needs to be call again and again based on status it returns
1012          */
1013         function pop3_checkPartialEmail($synch = false) {
1014                 require_once('include/utils/array_utils.php');
1015                 global $current_user;
1016                 global $sugar_config;
1017
1018                 $cacheDataExists = false;
1019                 $diff = array();
1020                 $results = array();
1021                 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/MsgNOToUIDLData.php");
1022                 if(file_exists($cacheFilePath)) {
1023                         $cacheDataExists = true;
1024                         if($fh = @fopen($cacheFilePath, "rb")) {
1025                                 $data = "";
1026                                 $chunksize = 1*(1024*1024); // how many bytes per chunk
1027                                 while(!feof($fh)) {
1028                                         $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1029                                         $data = $data . $buf;
1030                                 flush();
1031                                 } // while
1032                                 fclose($fh);
1033                                 $diff = unserialize($data);
1034                                 if (!empty($diff)) {
1035                                         if (count($diff)> 50) {
1036                                 $newDiff = array_slice($diff, 50, count($diff), true);
1037                                         } else {
1038                                                 $newDiff=array();
1039                                         }
1040                         $results = array_slice(array_keys($diff), 0 ,50);
1041                                         $data = serialize($newDiff);
1042                                     if($fh = @fopen($cacheFilePath, "w")) {
1043                                         fputs($fh, $data);
1044                                         fclose($fh);
1045                                     } // if
1046                                 }
1047                         } // if
1048                 } // if
1049                 if (!$cacheDataExists) {
1050                         if ($synch) {
1051                             $this->deletePop3Cache();
1052                         }
1053                         $UIDLs = $this->pop3_getUIDL();
1054                         if(count($UIDLs) > 0) {
1055                                 // get cached UIDLs
1056                                 $cacheUIDLs = $this->pop3_getCacheUidls();
1057
1058                                 // new email cache values we should deal with
1059                                 $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1060                                 $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1061                                 require_once('modules/Emails/EmailUI.php');
1062                                 EmailUI::preflightEmailCache("{$this->EmailCachePath}/{$this->id}");
1063
1064                                 if (count($diff)> 50) {
1065                         $newDiff = array_slice($diff, 50, count($diff), true);
1066                                 } else {
1067                                         $newDiff=array();
1068                                 }
1069
1070                                 $results = array_slice(array_keys($diff), 0 ,50);
1071                                 $data = serialize($newDiff);
1072                             if($fh = @fopen($cacheFilePath, "w")) {
1073                                 fputs($fh, $data);
1074                                 fclose($fh);
1075                             } // if
1076                         } else {
1077                                 $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1078                                 return "could not open socket connection to POP3 server";
1079                         } // else
1080                 } // if
1081
1082                 // build up msgNo request
1083                 if(count($diff) > 0) {
1084                         // remove dirty cache entries
1085                         $startingNo = 0;
1086                         if (isset($_REQUEST['currentCount']) && $_REQUEST['currentCount'] > -1) {
1087                              $startingNo = $_REQUEST['currentCount'];
1088                         }
1089
1090                         $this->mailbox = 'INBOX';
1091                         $this->connectMailserver();
1092                         //$searchResults = array_keys($diff);
1093                         //$fetchedOverviews = array();
1094                         //$chunkArraySerachResults = array_chunk($searchResults, 50);
1095                         $concatResults = implode(",", $results);
1096                         $GLOBALS['log']->info('$$$$ '.$concatResults);
1097                         $GLOBALS['log']->info("[EMAIL] Start POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on 50 data");
1098                         $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1099                         $GLOBALS['log']->info("[EMAIL] End POP3 fetch overview on mailbox [{$this->mailbox}] for user [{$current_user->user_name}] on "
1100                         . sizeof($fetchedOverviews) . " data");
1101
1102                         // clean up cache entry
1103                         foreach($fetchedOverviews as $k => $overview) {
1104                                 $overview->message_id = trim($diff[$overview->msgno]);
1105                                 $fetchedOverviews[$k] = $overview;
1106                         }
1107
1108                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1109                         $this->updateOverviewCacheFile($fetchedOverviews);
1110                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for pop3 mailbox [{$this->mailbox}] for user [{$current_user->user_name}]");
1111                         return array('status' => "In Progress", 'mbox' => $this->mailbox, 'count'=> (count($results) + $startingNo), 'totalcount' => count($diff), 'ieid' => $this->id);
1112                 } // if
1113                 unlink($cacheFilePath);
1114                 return  array('status' => "done");
1115         }
1116
1117
1118         /**
1119          * Special handler for POP3 boxes.  Standard IMAP commands are useless.
1120          */
1121         function pop3_checkEmail() {
1122                 if($this->pop3_open()) {
1123                         // authenticate
1124                         $this->pop3_sendCommand("USER", $this->email_user);
1125                         $this->pop3_sendCommand("PASS", $this->email_password);
1126
1127                         // get UIDLs
1128                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
1129                         fgets($this->pop3socket, 1024); // handle "OK+";
1130                         $UIDLs = array();
1131
1132                         $buf = '!';
1133
1134                         if(is_resource($this->pop3socket)) {
1135                                 while(!feof($this->pop3socket)) {
1136                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1137                                         //_pp(trim($buf));
1138
1139                                         if(trim($buf) == '.') {
1140                                                 $GLOBALS['log']->debug("*** GOT '.'");
1141                                                 break;
1142                                         }
1143
1144                                         // format is [msgNo] [UIDL]
1145                                         $exUidl = explode(" ", $buf);
1146                                         $UIDLs[$exUidl[0]] = trim($exUidl[1]);
1147                                 }
1148                         }
1149
1150                         $this->pop3_cleanUp();
1151
1152                         // get cached UIDLs
1153                         $cacheUIDLs = $this->pop3_getCacheUidls();
1154 //                      _pp($UIDLs);_pp($cacheUIDLs);
1155
1156                         // new email cache values we should deal with
1157                         $diff = array_diff_assoc($UIDLs, $cacheUIDLs);
1158
1159                         // remove dirty cache entries
1160                         $diff = $this->pop3_shiftCache($diff, $cacheUIDLs);
1161
1162                         // build up msgNo request
1163                         if(!empty($diff)) {
1164                                 $this->mailbox = 'INBOX';
1165                                 $this->connectMailserver();
1166                                 $searchResults = array_keys($diff);
1167                                 $concatResults = implode(",", $searchResults);
1168                                 $fetchedOverviews = imap_fetch_overview($this->conn, $concatResults);
1169
1170                                 // clean up cache entry
1171                                 foreach($fetchedOverviews as $k => $overview) {
1172                                         $overview->message_id = trim($diff[$overview->msgno]);
1173                                         $fetchedOverviews[$k] = $overview;
1174                                 }
1175
1176                                 $this->updateOverviewCacheFile($fetchedOverviews);
1177                         }
1178                 } else {
1179                         $GLOBALS['log']->debug("*** INBOUNDEMAIL: could not open socket connection to POP3 server");
1180                         return false;
1181                 }
1182         }
1183
1184         /**
1185          * Iterates through msgno and message_id to remove dirty cache entries
1186          * @param array diff
1187          */
1188         function pop3_shiftCache($diff, $cacheUIDLs) {
1189                 $msgNos = "";
1190                 $msgIds = "";
1191                 $newArray = array();
1192                 foreach($diff as $msgNo => $msgId) {
1193                         if (in_array($msgId, $cacheUIDLs)) {
1194                                 $q1 = "UPDATE email_cache SET imap_uid = {$msgNo}, msgno = {$msgNo} WHERE ie_id = '{$this->id}' AND message_id = '{$msgId}'";
1195                                 $this->db->query($q1);
1196                         } else {
1197                                 $newArray[$msgNo] = $msgId;
1198                         }
1199                 }
1200                 return $newArray;
1201                 /*
1202                 foreach($diff as $msgNo => $msgId) {
1203                         if(!empty($msgNos)) {
1204                                 $msgNos .= ", ";
1205                         }
1206                         if(!empty($msgIds)) {
1207                                 $msgIds .= ", ";
1208                         }
1209
1210                         $msgNos .= $msgNo;
1211                         $msgIds .= "'{$msgId}'";
1212                 }
1213
1214                 if(!empty($msgNos)) {
1215                         $q1 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND msgno IN ({$msgNos})";
1216                         $this->db->query($q1);
1217                 }
1218                 if(!empty($msgIds)) {
1219                         $q2 = "DELETE FROM email_cache WHERE ie_id = '{$this->id}' AND message_id IN ({$msgIds})";
1220                         $this->db->query($q2);
1221                 }
1222                 */
1223         }
1224
1225         /**
1226          * retrieves cached uidl values.
1227          * When dealing with POP3 accounts, the message_id column in email_cache will contain the UIDL.
1228          * @return array
1229          */
1230         function pop3_getCacheUidls() {
1231                 $q = "SELECT msgno, message_id FROM email_cache WHERE ie_id = '{$this->id}'";
1232                 $r = $this->db->query($q);
1233
1234                 $ret = array();
1235                 while($a = $this->db->fetchByAssoc($r)) {
1236                         $ret[$a['msgno']] = $a['message_id'];
1237                 }
1238
1239                 return $ret;
1240         }
1241
1242         /**
1243          * This function is used by cron job for group mailbox without group folder
1244          * @param string $msgno for pop
1245          * @param string $uid for imap
1246          */
1247         function getMessagesInEmailCache($msgno, $uid) {
1248                 $fetchedOverviews = array();
1249                 if ($this->isPop3Protocol()) {
1250                         $fetchedOverviews = imap_fetch_overview($this->conn, $msgno);
1251                         foreach($fetchedOverviews as $k => $overview) {
1252                                 $overview->message_id = $uid;
1253                                 $fetchedOverviews[$k] = $overview;
1254                         }
1255                 } else {
1256                         $fetchedOverviews = imap_fetch_overview($this->conn, $uid, FT_UID);
1257                 } // else
1258                 $this->updateOverviewCacheFile($fetchedOverviews);
1259
1260         } // fn
1261
1262         /**
1263          * Checks email (local caching too) for one mailbox
1264          * @param string $mailbox IMAP Mailbox path
1265          * @param bool $prefetch Flag to prefetch email body on check
1266          */
1267         function checkEmailOneMailbox($mailbox, $prefetch=true, $synchronize=false) {
1268                 global $sugar_config;
1269                 global $current_user;
1270                 global $app_strings;
1271
1272                 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1273                 $this->mailbox = $mailbox;
1274                 $this->connectMailserver();
1275
1276                 $checkTime = '';
1277                 $shouldProcessRules = true;
1278
1279                 $timestamp = $this->getCacheTimestamp($mailbox);
1280
1281                 if($timestamp > 0) {
1282                         $checkTime = date('r', $timestamp);
1283                 }
1284
1285                 /* first time through, process ALL emails */
1286                 if(empty($checkTime) || $synchronize) {
1287                         // do not process rules for the first time or sunchronize
1288                         $shouldProcessRules = false;
1289                         $criteria = "ALL UNDELETED";
1290                         $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1291                         $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1292                 } else {
1293                         $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1294                 }
1295                 $this->setCacheTimestamp($mailbox);
1296                 $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1297                 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1298                 $GLOBALS['log']->info("[EMAIL] Done IMAP search on mailbox [{$mailbox}] for user [{$current_user->user_name}]. Result count = ".count($searchResults));
1299
1300                 if(!empty($searchResults)) {
1301
1302                         $concatResults = implode(",", $searchResults);
1303                         $GLOBALS['log']->info("[EMAIL] Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1304                         $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1305                         $GLOBALS['log']->info("[EMAIL] Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1306
1307                         $GLOBALS['log']->info("[EMAIL] Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1308                         $this->updateOverviewCacheFile($fetchedOverview);
1309                         $GLOBALS['log']->info("[EMAIL] Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1310
1311                         // prefetch emails
1312                         if($prefetch == true) {
1313                                 $GLOBALS['log']->info("[EMAIL] Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1314                                 $this->fetchCheckedEmails($fetchedOverview);
1315                                 $GLOBALS['log']->info("[EMAIL] Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1316                         }
1317                 } else {
1318                         $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1319                 }
1320
1321                 /**
1322                  * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1323                  * local cache of all emails with the "DELETED" flag
1324                  */
1325                 $criteria  = 'DELETED';
1326                 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1327                 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1328
1329                 $trashFolder = $this->get_stored_options("trashFolder");
1330                 if (empty($trashFolder)) {
1331                         $trashFolder = "INBOX.Trash";
1332                 }
1333
1334                 if($this->mailbox != $trashFolder) {
1335                         $searchResults = imap_search($this->conn, $criteria, SE_UID);
1336                         if(!empty($searchResults)) {
1337                                 $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1338                                 $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1339                                 $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1340                         }
1341                 }
1342         }
1343
1344            /**
1345      * Checks email (local caching too) for one mailbox
1346      * @param string $mailbox IMAP Mailbox path
1347      * @param bool $prefetch Flag to prefetch email body on check
1348      */
1349     function checkEmailOneMailboxPartial($mailbox, $prefetch=true, $synchronize=false, $start = 0, $max = -1) {
1350         global $sugar_config;
1351         global $current_user;
1352         global $app_strings;
1353
1354         $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1355         $this->mailbox = $mailbox;
1356         $this->connectMailserver();
1357
1358         $checkTime = '';
1359         $shouldProcessRules = true;
1360
1361         $timestamp = $this->getCacheTimestamp($mailbox);
1362
1363         if($timestamp > 0) {
1364             $checkTime = date('r', $timestamp);
1365         }
1366
1367         /* first time through, process ALL emails */
1368         if(empty($checkTime) || $synchronize) {
1369             // do not process rules for the first time or sunchronize
1370             $shouldProcessRules = false;
1371             $criteria = "ALL UNDELETED";
1372             $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1373             $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1374         } else {
1375             $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1376         }
1377         $this->setCacheTimestamp($mailbox);
1378         $GLOBALS['log']->info("[EMAIL] Performing IMAP search using criteria [{$criteria}] on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1379         $searchResults = $this->getCachedIMAPSearch($criteria);
1380
1381         if(!empty($searchResults)) {
1382
1383             $total = sizeof($searchResults);
1384             $searchResults = array_slice($searchResults, $start, $max);
1385
1386             $GLOBALS['log']->info("INBOUNDEMAIL: there are  $total messages in [{$mailbox}], we are on $start");
1387             $GLOBALS['log']->info("INBOUNDEMAIL: getting the next " . sizeof($searchResults) . " messages");
1388             $concatResults = implode(",", $searchResults);
1389             $GLOBALS['log']->info("INBOUNDEMAIL: Start IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1390             $fetchedOverview = imap_fetch_overview($this->conn, $concatResults, FT_UID);
1391             $GLOBALS['log']->info("INBOUNDEMAIL: Done IMAP fetch overview on mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1392
1393             $GLOBALS['log']->info("INBOUNDEMAIL: Start updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1394             $this->updateOverviewCacheFile($fetchedOverview);
1395             $GLOBALS['log']->info("INBOUNDEMAIL: Done updating overview cache for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1396
1397             // prefetch emails
1398             if($prefetch == true) {
1399                 $GLOBALS['log']->info("INBOUNDEMAIL: Start fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1400                 $this->fetchCheckedEmails($fetchedOverview);
1401                 $GLOBALS['log']->info("INBOUNDEMAIL: Done fetching emails for mailbox [{$mailbox}] for user [{$current_user->user_name}]");
1402             }
1403             $status = ($total > $start + sizeof($searchResults)) ? 'continue' : 'done';
1404             $ret = array('status' => $status, 'count' => $start + sizeof($searchResults), 'mbox' => $mailbox, 'totalcount' => $total);
1405             $GLOBALS['log']->info("INBOUNDEMAIL: $status : Downloaded " . $start + sizeof($searchResults) . "messages of $total");
1406
1407         } else {
1408             $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1409             $ret = array('status' =>'done');
1410         }
1411
1412         if ($ret['status'] == 'done') {
1413                 //Remove the cached search if we are done with this mailbox
1414                 $cacheFilePath = clean_path("{$this->EmailCachePath}/{$this->id}/folders/SearchData.php");
1415             unlink($cacheFilePath);
1416                 /**
1417                  * To handle the use case where an external client is also connected, deleting emails, we need to clear our
1418                  * local cache of all emails with the "DELETED" flag
1419                  */
1420                 $criteria  = 'DELETED';
1421                 $criteria .= (!empty($checkTime)) ? " SINCE \"{$checkTime}\"" : "";
1422                 $GLOBALS['log']->info("INBOUNDEMAIL: checking for deleted emails using [ {$criteria} ]");
1423
1424                         $trashFolder = $this->get_stored_options("trashFolder");
1425                         if (empty($trashFolder)) {
1426                                 $trashFolder = "INBOX.Trash";
1427                         }
1428
1429                 if($this->mailbox != $trashFolder) {
1430                     $searchResults = imap_search($this->conn, $criteria, SE_UID);
1431                     if(!empty($searchResults)) {
1432                         $uids = implode($app_strings['LBL_EMAIL_DELIMITER'], $searchResults);
1433                         $GLOBALS['log']->info("INBOUNDEMAIL: removing UIDs found deleted [ {$uids} ]");
1434                         $this->getOverviewsFromCacheFile($uids, $mailbox, true);
1435                     }
1436                 }
1437         }
1438         return $ret;
1439     }
1440
1441     function getCachedIMAPSearch($criteria) {
1442         global $current_user;
1443         global $sugar_config;
1444
1445         $cacheDataExists = false;
1446         $diff = array();
1447         $results = array();
1448         $cacheFolderPath = clean_path("{$this->EmailCachePath}/{$this->id}/folders");
1449         if (!file_exists($cacheFolderPath)) {
1450                 mkdir_recursive($cacheFolderPath);
1451         }
1452         $cacheFilePath = $cacheFolderPath . '/SearchData.php';
1453         $GLOBALS['log']->info("INBOUNDEMAIL: Cache path is $cacheFilePath");
1454         if(file_exists($cacheFilePath)) {
1455             $cacheDataExists = true;
1456             if($fh = @fopen($cacheFilePath, "rb")) {
1457                 $data = "";
1458                 $chunksize = 1*(1024*1024); // how many bytes per chunk
1459                 while(!feof($fh)) {
1460                     $buf = fgets($fh, $chunksize); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
1461                     $data = $data . $buf;
1462                     flush();
1463                 } // while
1464                 fclose($fh);
1465                 $results = unserialize($data);
1466             } // if
1467         } // if
1468         if (!$cacheDataExists) {
1469             $searchResults = imap_search($this->conn, $criteria, SE_UID);
1470             if(count($searchResults) > 0) {
1471                 $results = $searchResults;
1472                 $data = serialize($searchResults);
1473                 if($fh = @fopen($cacheFilePath, "w")) {
1474                     fputs($fh, $data);
1475                     fclose($fh);
1476                 } // if
1477             }
1478         } // if
1479         return $results;
1480     }
1481
1482     function checkEmailIMAPPartial($prefetch=true, $synch = false) {
1483         $GLOBALS['log']->info("*****************INBOUNDEMAIL: at IMAP check partial");
1484         global $sugar_config;
1485         $this->connectMailserver();
1486         $mailboxes = $this->getMailboxes(true);
1487         if (!in_array('INBOX', $mailboxes)) {
1488             $mailboxes[] = 'INBOX';
1489         }
1490         sort($mailboxes);
1491         if (isset($_REQUEST['mbox']) && !empty($_REQUEST['mbox']) && isset($_REQUEST['currentCount'])) {
1492                 $GLOBALS['log']->info("INBOUNDEMAIL: Picking up from where we left off");
1493             $mbox = $_REQUEST['mbox'];
1494             $count = $_REQUEST['currentCount'];
1495         } else {
1496                 if ($synch) {
1497                         $GLOBALS['log']->info("INBOUNDEMAIL: Cleaning out the cache");
1498                         $this->cleanOutCache();
1499                 }
1500             $mbox = $mailboxes[0];
1501             $count = 0;
1502         }
1503         $GLOBALS['log']->info("INBOUNDEMAIL:found " . sizeof($mailboxes) . " Mailboxes");
1504         $index = array_search($mbox, $mailboxes) + 1;
1505         $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, $count, 100);
1506         while($ret['status'] == 'done' && $index < sizeof($mailboxes)) {
1507             if ($ret['count'] > 100) {
1508                 $ret['mbox'] = $mailboxes[$index];
1509                 $ret['status'] = 'continue';
1510                 return $ret;
1511             }
1512             $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ $index => $mbox : $count]");
1513             $mbox = $mailboxes[$index];
1514             $ret = $this->checkEmailOneMailboxPartial($mbox, $prefetch, $synch, 0, 100);
1515             $index++;
1516         }
1517
1518         return $ret;
1519     }
1520
1521         function checkEmail2_meta() {
1522                 global $sugar_config;
1523
1524                 $this->connectMailserver();
1525                 $mailboxes = $this->getMailboxes(true);
1526                 $mailboxes[] = 'INBOX';
1527                 sort($mailboxes);
1528
1529                 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1530
1531                 $mailboxes_meta = array();
1532                 foreach($mailboxes as $mailbox) {
1533                         $mailboxes_meta[$mailbox] = $this->getMailboxProcessCount($mailbox);
1534                 }
1535
1536                 $ret = array();
1537                 $ret['mailboxes'] = $mailboxes_meta;
1538
1539                 foreach($mailboxes_meta as $count) {
1540                         $ret['processCount'] += $count;
1541                 }
1542                 return $ret;
1543         }
1544
1545         function getMailboxProcessCount($mailbox) {
1546                 global $sugar_config;
1547
1548                 $GLOBALS['log']->info("INBOUNDEMAIL: checking mailbox [ {$mailbox} ]");
1549                 $this->mailbox = $mailbox;
1550                 $this->connectMailserver();
1551
1552                 $timestamp = $this->getCacheTimestamp($mailbox);
1553
1554                 $checkTime = '';
1555                 if($timestamp > 0) {
1556                         $checkTime = date('r', $timestamp);
1557                 }
1558
1559                 /* first time through, process ALL emails */
1560                 if(empty($checkTime)) {
1561                         $criteria = "ALL UNDELETED";
1562                         $prefetch = false; // do NOT prefetch emails on a brand new account - timeouts happen.
1563                         $GLOBALS['log']->info("INBOUNDEMAIL: new account detected - not prefetching email bodies.");
1564                 } else {
1565                         $criteria = "SINCE \"{$checkTime}\" UNDELETED"; // not using UNSEEN
1566                 }
1567
1568                 $GLOBALS['log']->info("INBOUNDEMAIL: using [ {$criteria} ]");
1569                 $searchResults = imap_search($this->conn, $criteria, SE_UID);
1570
1571                 if(!empty($searchResults)) {
1572                         $concatResults = implode(",", $searchResults);
1573                 } else {
1574                         $GLOBALS['log']->info("INBOUNDEMAIL: no results for mailbox [ {$mailbox} ]");
1575                 }
1576
1577                 if(empty($searchResults)) {
1578                         return 0;
1579                 }
1580
1581                 return count($searchResults);
1582         }
1583
1584         /**
1585          * update INBOX
1586          */
1587         function checkEmail($prefetch=true, $synch = false) {
1588                 global $sugar_config;
1589
1590                 if($this->protocol == 'pop3') {
1591                         $this->pop3_checkEmail();
1592                 } else {
1593                         $this->connectMailserver();
1594                         $mailboxes = $this->getMailboxes(true);
1595                         $mailboxes[] = 'INBOX';
1596                         sort($mailboxes);
1597
1598                         $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$this->name} ]");
1599
1600                         foreach($mailboxes as $mailbox) {
1601                                 $this->checkEmailOneMailbox($mailbox, $prefetch, $synch);
1602                         }
1603                 }
1604         }
1605
1606         /**
1607          * full synchronization
1608          */
1609         function syncEmail() {
1610                 global $sugar_config;
1611                 global $current_user;
1612
1613                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1614
1615                 if(empty($showFolders)) {
1616                         $showFolders = array();
1617                 }
1618
1619                 $email = new Email();
1620                 $email->email2init();
1621
1622                 // personal accounts
1623                 if($current_user->hasPersonalEmail()) {
1624                         $personals = $this->retrieveByGroupId($current_user->id);
1625
1626                         foreach($personals as $personalAccount) {
1627                                 if(in_array($personalAccount->id, $showFolders)) {
1628                                         $personalAccount->email = $email;
1629                                         if ($personalAccount->isPop3Protocol()) {
1630                                                 $personalAccount->deletePop3Cache();
1631                                                 continue;
1632                                         }
1633                                         $personalAccount->cleanOutCache();
1634                                         $personalAccount->connectMailserver();
1635                                         $mailboxes = $personalAccount->getMailboxes(true);
1636                                         $mailboxes[] = 'INBOX';
1637                                         sort($mailboxes);
1638
1639                                         $GLOBALS['log']->info("[EMAIL] Start checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1640
1641                                         foreach($mailboxes as $mailbox) {
1642                                                 $GLOBALS['log']->info("[EMAIL] Start checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1643                                                 $personalAccount->checkEmailOneMailbox($mailbox, false, true);
1644                                                 $GLOBALS['log']->info("[EMAIL] Done checking mailbox [{$mailbox}] of account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1645                                         }
1646                                         $GLOBALS['log']->info("[EMAIL] Done checking account [{$personalAccount->name}] for user [{$current_user->user_name}]");
1647                                 }
1648                         }
1649                 }
1650
1651                 // group accounts
1652                 $beans = $this->retrieveAllByGroupId($current_user->id, false);
1653                 foreach($beans as $k => $groupAccount) {
1654                         if(in_array($groupAccount->id, $showFolders)) {
1655                                 $groupAccount->email = $email;
1656                                 $groupAccount->cleanOutCache();
1657                                 $groupAccount->connectMailserver();
1658                                 $mailboxes = $groupAccount->getMailboxes(true);
1659                                 $mailboxes[] = 'INBOX';
1660                                 sort($mailboxes);
1661
1662                                 $GLOBALS['log']->info("INBOUNDEMAIL: checking account [ {$groupAccount->name} ]");
1663
1664                                 foreach($mailboxes as $mailbox) {
1665                                         $groupAccount->checkEmailOneMailbox($mailbox, false, true);
1666                                 }
1667                         }
1668                 }
1669         }
1670
1671
1672         /**
1673          * Deletes cached messages when moving from folder to folder
1674          * @param string $uids
1675          * @param string $fromFolder
1676          * @param string $toFolder
1677          */
1678         function deleteCachedMessages($uids, $fromFolder) {
1679                 global $sugar_config;
1680
1681                 if(!isset($this->email) && !isset($this->email->et)) {
1682                         $this->email = new Email();
1683                         $this->email->email2init();
1684                 }
1685
1686                 $uids = $this->email->et->_cleanUIDList($uids);
1687
1688                 foreach($uids as $uid) {
1689                         $file = "{$this->EmailCachePath}/{$this->id}/messages/{$fromFolder}{$uid}.php";
1690
1691                         if(file_exists($file)) {
1692                                 if(!unlink($file)) {
1693                                         $GLOBALS['log']->debug("INBOUNDEMAIL: Could not delete [ {$file} ]");
1694                                 }
1695                         }
1696                 }
1697         }
1698
1699         /**
1700          * similar to imap_fetch_overview, but it gets overviews from a local cache
1701          * file.
1702          * @param string $uids UIDs in comma-delimited format
1703          * @param string $mailbox The mailbox in focus, will default to $this->mailbox
1704          * @param bool $remove Default false
1705          * @return array
1706          */
1707         function getOverviewsFromCacheFile($uids, $mailbox='', $remove=false) {
1708                 global $app_strings;
1709                 if(!isset($this->email) && !isset($this->email->et)) {
1710                         $this->email = new Email();
1711                         $this->email->email2init();
1712                 }
1713
1714                 $uids = $this->email->et->_cleanUIDList($uids, true);
1715
1716                 // load current cache file
1717                 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1718                 $cacheValue = $this->getCacheValue($mailbox);
1719                 $ret = array();
1720
1721                 // prep UID array
1722                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1723                 foreach($exUids as $k => $uid) {
1724                         $exUids[$k] = trim($uid);
1725                 }
1726
1727                 // fill $ret will requested $uids
1728                 foreach($cacheValue['retArr'] as $k => $overview) {
1729                         if(in_array($overview->imap_uid, $exUids)) {
1730                                 $ret[] = $overview;
1731                         }
1732                 }
1733
1734                 // remove requested $uids from current cache file (move_mail() type action)
1735                 if($remove) {
1736                         $this->setCacheValue($mailbox, array(), array(), $ret);
1737                 }
1738                 return $ret;
1739         }
1740
1741         /**
1742          * merges new info with the saved cached file
1743          * @param array $array Array of email Overviews
1744          * @param string $type 'append' or 'remove'
1745          * @param string $mailbox Target mailbox if not current assigned
1746          */
1747         function updateOverviewCacheFile($array, $type='append', $mailbox='') {
1748                 $mailbox = empty($mailbox) ? $this->mailbox : $mailbox;
1749
1750                 $cacheValue = $this->getCacheValue($mailbox);
1751                 $uids = $cacheValue['uids'];
1752
1753                 $updateRows = array();
1754                 $insertRows = array();
1755                 $removeRows = array();
1756
1757                 // update values
1758                 if($type == 'append') { // append
1759                         /* we are adding overviews to the cache file */
1760                         foreach($array as $overview) {
1761                                 if(isset($overview->uid)) {
1762                                         $overview->imap_uid = $overview->uid; // coming from imap_fetch_overview() call
1763                                 }
1764
1765                                 if(!in_array($overview->imap_uid, $uids)) {
1766                                         $insertRows[] = $overview;
1767                                 }
1768                         }
1769                 } else {
1770                         $updatedCacheOverviews = array();
1771                         // compare against generated list
1772                         /* we are removing overviews from the cache file */
1773                         foreach($cacheValue['retArr'] as $cacheOverview) {
1774                                 if(!in_array($cacheOverview->imap_uid, $uids)) {
1775                                         $insertRows[] = $cacheOverview;
1776                                 } else {
1777                                         $removeRows[] = $cacheOverview;
1778                                 }
1779                         }
1780
1781                         $cacheValue['retArr'] = $updatedCacheOverviews;
1782                 }
1783
1784                 $this->setCacheValue($mailbox, $insertRows, $updateRows, $removeRows);
1785         }
1786
1787         /**
1788          * Check email prefetches email bodies for quicker display
1789          * @param array array of fetched overviews
1790          */
1791         function fetchCheckedEmails($fetchedOverviews) {
1792                 global $sugar_config;
1793
1794                 if(is_array($fetchedOverviews) && !empty($fetchedOverviews)) {
1795                         foreach($fetchedOverviews as $overview) {
1796                                 if($overview->size < 10000) {
1797
1798                                         $uid = $overview->imap_uid;
1799
1800                                         if(!empty($uid)) {
1801                                                 $file = "{$this->mailbox}{$uid}.php";
1802                                                 $cacheFile = clean_path("{$this->EmailCachePath}/{$this->id}/messages/{$file}");
1803
1804                                                 if(!file_exists($cacheFile)) {
1805                                                         $GLOBALS['log']->info("INBOUNDEMAIL: Prefetching email [ {$file} ]");
1806                                                         $this->setEmailForDisplay($uid);
1807                                                         $out = $this->displayOneEmail($uid, $this->mailbox);
1808                                                         $this->email->et->writeCacheFile('out', $out, $this->id, 'messages', "{$this->mailbox}{$uid}.php");
1809                                                 } else {
1810                                                         $GLOBALS['log']->debug("INBOUNDEMAIL: Trying to prefetch an email we already fetched! [ {$cacheFile} ]");
1811                                                 }
1812                                         } else {
1813                                                 $GLOBALS['log']->debug("*** INBOUNDEMAIL: prefetch has a message with no UID");
1814                                         }
1815                                 } else {
1816                                         $GLOBALS['log']->debug("INBOUNDEMAIL: skipping email prefetch - size too large [ {$overview->size} ]");
1817                                 }
1818                         }
1819                 }
1820         }
1821
1822         /**
1823          * Sets flags on emails.  Assumes that connection is live, correct folder is
1824          * set.
1825          * @param string $uids Sequence of UIDs, comma separated
1826          * @param string $type Flag to mark
1827          */
1828         function markEmails($uids, $type) {
1829                 switch($type) {
1830                         case 'unread':
1831                                 $result = imap_clearflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1832                         break;
1833                         case 'read':
1834                                 $result = imap_setflag_full($this->conn, $uids, '\\SEEN', ST_UID);
1835                         break;
1836                         case 'flagged':
1837                                 $result = imap_setflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1838                         break;
1839                         case 'unflagged':
1840                                 $result = imap_clearflag_full($this->conn, $uids, '\\FLAGGED', ST_UID);
1841                         break;
1842                         case 'answered':
1843                                 $result = imap_setflag_full($this->conn, $uids, '\\Answered', ST_UID);
1844                         break;
1845                 }
1846         }
1847         ////    END EMAIL 2.0 SPECIFIC
1848         ///////////////////////////////////////////////////////////////////////////
1849
1850
1851
1852         ///////////////////////////////////////////////////////////////////////////
1853         ////    SERVER MANIPULATION METHODS
1854         /**
1855          * Deletes the specified folder
1856          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1857          * @return bool
1858          */
1859         function deleteFolder($mbox) {
1860                 $returnArray = array();
1861                 if ($this->getCacheCount($mbox) > 0) {
1862                         $returnArray['status'] = false;
1863                         $returnArray['errorMessage'] = "Can not delete {$mbox} as it has emails.";
1864                         return $returnArray;
1865                 }
1866                 $connectString = $this->getConnectString('', $mbox);
1867                 //Remove Folder cache
1868                 global $sugar_config;
1869                 unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1870
1871                 if(imap_unsubscribe($this->conn, imap_utf7_encode($connectString))) {
1872                         if(imap_deletemailbox($this->conn, $connectString)) {
1873                         $this->mailbox = str_replace(("," . $mbox), "", $this->mailbox);
1874                         $this->save();
1875                         $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1876                         $sessionFoldersString = str_replace(("," . $mbox), "", $sessionFoldersString);
1877                                 $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1878                                 $returnArray['status'] = true;
1879                                 return $returnArray;
1880                         } else {
1881                                 $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not delete IMAP mailbox with path: [ {$connectString} ]");
1882                                 $returnArray['status'] = false;
1883                                 $returnArray['errorMessage'] = "NOOP: could not delete folder: {$connectString}";
1884                                 return $returnArray;
1885                                 return false;
1886                         }
1887                 } else {
1888                         $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not unsubscribe from folder, {$connectString} before deletion.");
1889                         $returnArray['status'] = false;
1890                         $returnArray['errorMessage'] = "NOOP: could not unsubscribe from folder, {$connectString} before deletion.";
1891                         return $returnArray;
1892                 }
1893         }
1894
1895         /**
1896          * Saves new folders
1897          * @param string $name Name of new IMAP mailbox
1898          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1899          * @return bool True on success
1900          */
1901         function saveNewFolder($name, $mbox) {
1902                 global $sugar_config;
1903         //Remove Folder cache
1904         global $sugar_config;
1905         //unlink("{$this->EmailCachePath}/{$this->id}/folders/folders.php");
1906
1907         //$mboxImap = $this->getImapMboxFromSugarProprietary($mbox);
1908         $delimiter = $this->get_stored_options('folderDelimiter');
1909         if (!$delimiter) {
1910                 $delimiter = '.';
1911         }
1912
1913         $newFolder = $mbox . $delimiter . $name;
1914         $mbox .= $delimiter.str_replace($delimiter, "_", $name);
1915         $connectString = $this->getConnectString('', $mbox);
1916
1917                 if(imap_createmailbox($this->conn, imap_utf7_encode($connectString))) {
1918                         imap_subscribe($this->conn, imap_utf7_encode($connectString));
1919                         $status = imap_status($this->conn, str_replace("{$delimiter}{$name}","",$connectString), SA_ALL);
1920                 $this->mailbox = $this->mailbox . "," . $newFolder;
1921                 $this->save();
1922                 $sessionFoldersString  = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
1923                 $sessionFoldersString = $sessionFoldersString . "," . $newFolder;
1924                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, $sessionFoldersString);
1925
1926                         echo json_encode($status);
1927                         return true;
1928                 } else {
1929                         echo "NOOP: could not create folder";
1930                         $GLOBALS['log']->error("*** ERROR: EMAIL2.0 - could not create IMAP mailbox with path: [ {$connectString} ]");
1931                         return false;
1932                 }
1933
1934         }
1935
1936         /**
1937          * Constructs an IMAP c-client compatible folder path from Sugar proprietary
1938          * @param string $mbox "::" delimited IMAP mailbox path, ie, INBOX.saved.stuff
1939          * @return string
1940          */
1941         function getImapMboxFromSugarProprietary($mbox) {
1942                 $exMbox = explode("::", $mbox);
1943
1944                 $mboxImap = '';
1945
1946                 for($i=2; $i<count($exMbox); $i++) {
1947                         if(!empty($mboxImap)) {
1948                                 $mboxImap .= ".";
1949                         }
1950                         $mboxImap .= $exMbox[$i];
1951                 }
1952
1953                 return $mboxImap;
1954         }
1955
1956         /**
1957          * Searches IMAP (and POP3?) accounts/folders for emails with qualifying criteria
1958          */
1959         function search($ieId, $subject='', $from='', $to='', $body='', $dateFrom='', $dateTo='') {
1960                 global $current_user;
1961                 global $app_strings;
1962                 global $timedate;
1963
1964                 $beans = array();
1965                 $bean = new InboundEmail();
1966                 $bean->retrieve($ieId);
1967                 $beans[] = $bean;
1968                 //$beans = $this->retrieveAllByGroupId($current_user->id, true);
1969
1970                 $subject = urldecode($subject);
1971
1972                 $criteria  = "";
1973                 $criteria .= (!empty($subject)) ? 'SUBJECT '.from_html($subject).'' : "";
1974                 $criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1975                 $criteria .= (!empty($to)) ? ' FROM "'.$to.'"' : "";
1976                 $criteria .= (!empty($body)) ? ' TEXT "'.$body.'"' : "";
1977                 $criteria .= (!empty($dateFrom)) ? ' SINCE "'.$timedate->fromString($dateFrom)->format('d-M-Y').'"' : "";
1978                 $criteria .= (!empty($dateTo)) ? ' BEFORE "'.$timedate->fromString($dateTo)->format('d-M-Y').'"' : "";
1979                 //$criteria .= (!empty($from)) ? ' FROM "'.$from.'"' : "";
1980
1981                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
1982
1983                 $out = array();
1984
1985                 foreach($beans as $bean) {
1986                         if(!in_array($bean->id, $showFolders)) {
1987                                 continue;
1988                         }
1989
1990                         $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$bean->name} ] for [ {$subject}{$from}{$to}{$body}{$dateFrom}{$dateTo} ]");
1991                         $group = (!$bean->is_personal) ? 'group.' : '';
1992                         $bean->connectMailServer();
1993                         $mailboxes = $bean->getMailboxes(true);
1994                         if (!in_array('INBOX', $mailboxes)) {
1995                                 $mailboxes[] = 'INBOX';
1996                         }
1997                         $totalHits = 0;
1998
1999                         foreach($mailboxes as $mbox) {
2000                                 $bean->mailbox = $mbox;
2001                                 $searchOverviews = array();
2002                                 if ($bean->protocol == 'pop3') {
2003                                         $pop3Criteria = "SELECT * FROM email_cache WHERE ie_id = '{$bean->id}' AND mbox = '{$mbox}'";
2004                                         $pop3Criteria .= (!empty($subject)) ? ' AND subject like "%'.$bean->db->quote($subject).'%"' : "";
2005                                         $pop3Criteria .= (!empty($from)) ? ' AND fromaddr like "%'.$from.'%"' : "";
2006                                         $pop3Criteria .= (!empty($to)) ? ' AND toaddr like "%'.$to.'%"' : "";
2007                                         $pop3Criteria .= (!empty($dateFrom)) ? ' AND senddate > "'.$dateFrom.'"' : "";
2008                                         $pop3Criteria .= (!empty($dateTo)) ? ' AND senddate < "'.$dateTo.'"' : "";
2009                                         $GLOBALS['log']->info("*** INBOUNDEMAIL: searching [ {$mbox} ] using criteria [ {$pop3Criteria} ]");
2010
2011                                         $r = $bean->db->query($pop3Criteria);
2012                                         while($a = $bean->db->fetchByAssoc($r)) {
2013                                                 $overview = new Overview();
2014
2015                                                 foreach($a as $k => $v) {
2016                                                         $k=strtolower($k);
2017                                                         switch($k) {
2018                                                                 case "imap_uid":
2019                                                                         $overview->imap_uid = $v;
2020                                                                         $overview->uid = $a['message_id'];
2021                                                                 break;
2022                                                                 case "toaddr":
2023                                                                         $overview->to = from_html($v);
2024                                                                 break;
2025
2026                                                                 case "fromaddr":
2027                                                                         $overview->from = from_html($v);
2028                                                                 break;
2029
2030                                                                 case "mailsize":
2031                                                                         $overview->size = $v;
2032                                                                 break;
2033
2034                                                                 case "senddate":
2035                                                                         $overview->date = $timedate->fromString($v)->format('r');
2036                                                                 break;
2037
2038                                                                 default:
2039                                                                         $overview->$k = from_html($v);
2040                                                                 break;
2041                                                         } // sqitch
2042                                                 } // foreach
2043                                                 $searchOverviews[] = $overview;
2044                                         } // while
2045                                 } else {
2046                                         $bean->connectMailServer();
2047                                         $searchResult = imap_search($bean->conn, $criteria, SE_UID);
2048                                         if (!empty($searchResult)) {
2049                                                 $searchOverviews = imap_fetch_overview($bean->conn, implode(',', $searchResult), FT_UID);
2050                                         } // if
2051                                 } // else
2052                                 $numHits = count($searchOverviews);
2053
2054                                 if($numHits > 0) {
2055                                         $totalHits = $totalHits + $numHits;
2056                                         $ret = $bean->sortFetchedOverview($searchOverviews, 'date', 'desc', true);
2057                                         $mbox = "{$bean->id}.SEARCH";
2058                                         $out = array_merge($out, $bean->displayFetchedSortedListXML($ret, $mbox, false));
2059                                 }
2060                         }
2061                 }
2062
2063                 $metadata = array();
2064                 $metadata['mbox'] = $app_strings['LBL_EMAIL_SEARCH_RESULTS_TITLE'];
2065                 $metadata['ieId'] = $this->id;
2066                 $metadata['name'] = $this->name;
2067                 $metadata['unreadChecked'] = ($current_user->getPreference('showUnreadOnly', 'Emails') == 1) ? 'CHECKED' : '';
2068                 $metadata['out'] = $out;
2069
2070                 return $metadata;
2071         }
2072
2073         /**
2074          * repairs the encrypted password for a given I-E account
2075          * @return bool True on success
2076          */
2077         function repairAccount() {
2078
2079                 for($i=0; $i<3; $i++) {
2080                         if($i != 0) { // decode is performed on retrieve already
2081                                 $this->email_password = blowfishDecode(blowfishGetKey('InboundEmail'), $this->email_password);
2082                         }
2083
2084                         if($this->connectMailserver() == 'true') {
2085                                 $this->save(); // save decoded password (is encoded on save())
2086                                 return true;
2087                         }
2088                 }
2089
2090                 return false;
2091         }
2092
2093         /**
2094          * soft deletes a User's personal inbox
2095          * @param string id I-E id
2096          * @param string user_name User name of User in focus, NOT current_user
2097          * @return bool True on success
2098          */
2099         function deletePersonalEmailAccount($id, $user_name) {
2100                 $q = "SELECT ie.id FROM inbound_email ie LEFT JOIN users u ON ie.group_id = u.id WHERE u.user_name = '{$user_name}'";
2101                 $r = $this->db->query($q, true);
2102
2103                 while($a = $this->db->fetchByAssoc($r)) {
2104                         if(!empty($a) && $a['id'] == $id) {
2105                                 $this->retrieve($id);
2106                                 $this->deleted = 1;
2107                                 $this->save();
2108                                 return true;
2109                         }
2110                 }
2111                 return false;
2112         }
2113
2114         function getTeamSetIdForTeams($teamIds) {
2115                 if(!is_array($teamIds)){
2116                    $teamIds = array($teamIds);
2117                 } // if
2118                 $teamSet = new TeamSet();
2119                 $team_set_id = $teamSet->addTeams($teamIds);
2120                 return $team_set_id;
2121         } // fn
2122
2123         /**
2124          * Saves Personal Inbox settings for Users
2125          * @param string userId ID of user to assign all emails for this account
2126          * @param strings userName Name of account, for Sugar purposes
2127          * @param bool forceSave Default true.  Flag to save errored settings.
2128          * @return boolean true on success, false on fail
2129          */
2130         function savePersonalEmailAccount($userId = '', $userName = '', $forceSave=true) {
2131                 $groupId = $userId;
2132                 $accountExists = false;
2133                 if(isset($_REQUEST['ie_id']) && !empty($_REQUEST['ie_id'])) {
2134                         $this->retrieve($_REQUEST['ie_id']);
2135                         $accountExists = true;
2136                 }
2137                 $ie_name = $_REQUEST['ie_name'];
2138
2139                 $this->is_personal = 1;
2140                 $this->name = $ie_name;
2141                 $this->group_id = $groupId;
2142                 $this->status = $_REQUEST['ie_status'];
2143                 $this->server_url = trim($_REQUEST['server_url']);
2144                 $this->email_user = trim($_REQUEST['email_user']);
2145                 if(!empty($_REQUEST['email_password'])) {
2146                     $this->email_password = html_entity_decode($_REQUEST['email_password'], ENT_QUOTES);
2147                 }
2148                 $this->port = trim($_REQUEST['port']);
2149                 $this->protocol = $_REQUEST['protocol'];
2150                 if ($this->protocol == "pop3") {
2151                         $_REQUEST['mailbox'] = "INBOX";
2152                 }
2153                 $this->mailbox = $_REQUEST['mailbox'];
2154                 $this->mailbox_type = 'pick'; // forcing this
2155
2156
2157                 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) { $useSsl = true; }
2158                 else $useSsl = false;
2159                 $this->service = '::::::::::';
2160
2161                 if($forceSave) {
2162                         $id = $this->save(); // saving here to prevent user from having to re-enter all the info in case of error
2163                         $this->retrieve($id);
2164                 }
2165
2166                 $this->protocol = $_REQUEST['protocol']; // need to set this again since we safe the "service" string to empty explode values
2167                 $opts = $this->getSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol);
2168                 $detectedOpts = $this->findOptimumSettings($useSsl);
2169
2170                 //If $detectedOpts is empty, there was an error connecting, so clear $opts. If $opts was empty, use $detectedOpts
2171                 if (empty($opts) || empty($detectedOpts) || (empty($detectedOpts['good']) && empty($detectedOpts['serial'])))
2172                 {
2173                   $opts = $detectedOpts;
2174                 }
2175                 $delimiter = $this->getSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol);
2176
2177                 if(isset($opts['serial']) && !empty($opts['serial'])) {
2178                         $this->service = $opts['serial'];
2179                         if(isset($_REQUEST['mark_read']) && $_REQUEST['mark_read'] == 1) {
2180                                 $this->delete_seen = 0;
2181                         } else {
2182                                 $this->delete_seen = 1;
2183                         }
2184
2185                         // handle stored_options serialization
2186                         if(isset($_REQUEST['only_since']) && $_REQUEST['only_since'] == 1) {
2187                                 $onlySince = true;
2188                         } else {
2189                                 $onlySince = false;
2190                         }
2191
2192                         $focusUser = new User();
2193                         $focusUser->retrieve($groupId);
2194                         $mailerId = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : "";
2195
2196                         $oe = new OutboundEmail();
2197                         $oe->getSystemMailerSettings($focusUser, $mailerId);
2198
2199                         $stored_options = array();
2200                         $stored_options['from_name'] = trim($_REQUEST['from_name']);
2201                         $stored_options['from_addr'] = trim($_REQUEST['from_addr']);
2202                         $stored_options['reply_to_addr'] = trim($_REQUEST['reply_to_addr']);
2203
2204                         if (!$this->isPop3Protocol()) {
2205                                 $stored_options['trashFolder'] = (isset($_REQUEST['trashFolder']) ? trim($_REQUEST['trashFolder']) : "");
2206                                 $stored_options['sentFolder'] = (isset($_REQUEST['sentFolder']) ? trim($_REQUEST['sentFolder']) : "");
2207                         } // if
2208                         $stored_options['only_since'] = $onlySince;
2209                         $stored_options['filter_domain'] = '';
2210                         $storedOptions['folderDelimiter'] = $delimiter;
2211                         $stored_options['outbound_email'] = (isset($_REQUEST['outbound_email'])) ? $_REQUEST['outbound_email'] : $oe->id;
2212                         $this->stored_options = base64_encode(serialize($stored_options));
2213
2214                         $ieId = $this->save();
2215
2216                         //If this is the first personal account the user has setup mark it as default for them.
2217                         $currentIECount = $this->getUserPersonalAccountCount($focusUser);
2218                         if($currentIECount == 1)
2219                             $this->setUsersDefaultOutboundServerId($focusUser, $ieId);
2220
2221                         return true;
2222                 } else {
2223                         // could not find opts, no save
2224                         $GLOBALS['log']->debug('-----> InboundEmail could not find optimums for User: '.$ie_name);
2225                         return false;
2226                 }
2227         }
2228         /**
2229          * Determines if this instance of I-E is for a Group Inbox or Personal Inbox
2230          */
2231         function handleIsPersonal() {
2232                 $qp = 'SELECT users.id, users.user_name FROM users WHERE users.is_group = 0 AND users.deleted = 0 AND users.status = \'active\' AND users.id = \''.$this->group_id.'\'';
2233                 $rp = $this->db->query($qp, true);
2234                 $personalBox = array();
2235                 while($ap = $this->db->fetchByAssoc($rp)) {
2236                         $personalBox[] = array($ap['id'], $ap['user_name']);
2237                 }
2238                 if(count($personalBox) > 0) {
2239                         return true;
2240                 } else {
2241                         return false;
2242                 }
2243         }
2244
2245         function getUserNameFromGroupId() {
2246                 $r = $this->db->query('SELECT users.user_name FROM users WHERE deleted=0 AND id=\''.$this->group_id.'\'', true);
2247                 while($a = $this->db->fetchByAssoc($r)) {
2248                         return $a['user_name'];
2249                 }
2250                 return '';
2251         }
2252
2253         function getFoldersListForMailBox() {
2254                 $return = array();
2255                 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2256                 if (empty($foldersList)) {
2257                         global $mod_strings;
2258                         $msg = $this->connectMailserver(true);
2259                         if (strpos($msg, "successfully")) {
2260                                 $foldersList = $this->getSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol);
2261                                 $return['status'] = true;
2262                                 $return['foldersList'] = $foldersList;
2263                                 $return['statusMessage'] = "";
2264                         } else {
2265                                 $return['status'] = false;
2266                                 $return['statusMessage'] = $msg;
2267                         } // else
2268                 } else {
2269                         $return['status'] = true;
2270                         $return['foldersList'] = $foldersList;
2271                         $return['statusMessage'] = "";
2272                 }
2273                 return $return;
2274         } // fn
2275         /**
2276          * Programatically determines best-case settings for imap_open()
2277          */
2278         function findOptimumSettings($useSsl=false, $user='', $pass='', $server='', $port='', $prot='', $mailbox='') {
2279                 global $mod_strings;
2280                 $serviceArr = array();
2281                 $returnService = array();
2282                 $badService = array();
2283                 $goodService = array();
2284                 $errorArr = array();
2285                 $raw = array();
2286                 $retArray = array(      'good' => $goodService,
2287                                                         'bad' => $badService,
2288                                                         'err' => $errorArr);
2289
2290                 if(!function_exists('imap_open')) {
2291                         $retArray['err'][0] = $mod_strings['ERR_NO_IMAP'];
2292                         return $retArray;
2293                 }
2294
2295                 imap_errors(); // clearing error stack
2296                 error_reporting(0); // turn off notices from IMAP
2297
2298                 if(isset($_REQUEST['ssl']) && $_REQUEST['ssl'] == 1) {
2299                         $useSsl = true;
2300                 }
2301
2302                 $exServ = explode('::', $this->service);
2303                 $service = '/'.$exServ[1];
2304
2305                 $nonSsl = array('both-secure'                   => '/notls/novalidate-cert/secure',
2306                                                 'both'                                  => '/notls/novalidate-cert',
2307                                                 'nocert-secure'                 => '/novalidate-cert/secure',
2308                                                 'nocert'                                => '/novalidate-cert',
2309                                                 'notls-secure'                  => '/notls/secure',
2310                                                 'secure'                                => '/secure', // for POP3 servers that force CRAM-MD5
2311                                                 'notls'                                 => '/notls',
2312                                                 'none'                                  => '', // try default nothing
2313                                         );
2314                 $ssl = array(
2315                                                 'ssl-both-on-secure'    => '/ssl/tls/validate-cert/secure',
2316                                                 'ssl-both-on'                   => '/ssl/tls/validate-cert',
2317                                                 'ssl-cert-secure'               => '/ssl/validate-cert/secure',
2318                                                 'ssl-cert'                              => '/ssl/validate-cert',
2319                                                 'ssl-tls-secure'                => '/ssl/tls/secure',
2320                                                 'ssl-tls'                               => '/ssl/tls',
2321                                                 'ssl-both-off-secure'   => '/ssl/notls/novalidate-cert/secure',
2322                                                 'ssl-both-off'                  => '/ssl/notls/novalidate-cert',
2323                                                 'ssl-nocert-secure'             => '/ssl/novalidate-cert/secure',
2324                                                 'ssl-nocert'                    => '/ssl/novalidate-cert',
2325                                                 'ssl-notls-secure'              => '/ssl/notls/secure',
2326                                                 'ssl-notls'                             => '/ssl/notls',
2327                                                 'ssl-secure'                    => '/ssl/secure',
2328                                                 'ssl-none'                              => '/ssl',
2329                                         );
2330
2331                 if(isset($user) && !empty($user) && isset($pass) && !empty($pass)) {
2332                         $this->email_password = $pass;
2333                         $this->email_user = $user;
2334                         $this->server_url = $server;
2335                         $this->port = $port;
2336                         $this->protocol = $prot;
2337                         $this->mailbox = $mailbox;
2338                 }
2339
2340                 // in case we flip from IMAP to POP3
2341                 if($this->protocol == 'pop3')
2342                   $this->mailbox = 'INBOX';
2343
2344                 //If user has selected multiple mailboxes, we only need to test the first mailbox for the connection string.
2345                 $a_mailbox = explode(",", $this->mailbox);
2346                 $tmpMailbox = isset($a_mailbox[0]) ? $a_mailbox[0] : "";
2347
2348                 if($useSsl == true)
2349                 {
2350                         foreach($ssl as $k => $service)
2351                         {
2352                                 $returnService[$k] = 'foo'.$service;
2353                                 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2354                         }
2355                 }
2356                 else
2357                 {
2358                         foreach($nonSsl as $k => $service)
2359                         {
2360                                 $returnService[$k] = 'foo'.$service;
2361                                 $serviceArr[$k] = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}'.$tmpMailbox;
2362                         }
2363                 }
2364
2365                 $GLOBALS['log']->debug('---------------STARTING FINDOPTIMUMS LOOP----------------');
2366                 $l = 1;
2367
2368                 //php imap library will capture c-client library warnings as errors causing good connections to be ignored.
2369                 //Check against known warnings to ensure good connections are used.
2370                 $acceptableWarnings = array("SECURITY PROBLEM: insecure server advertised AUTH=PLAIN", //c-client auth_pla.c
2371                                                 "Mailbox is empty");
2372                 $login = $this->email_user;
2373                 $passw = $this->email_password;
2374                 $foundGoodConnection = false;
2375                 foreach($serviceArr as $k => $serviceTest) {
2376                         $errors = '';
2377                         $alerts = '';
2378                         $GLOBALS['log']->debug($l.': I-E testing string: '.$serviceTest);
2379
2380                         // open the connection and try the test string
2381                         $this->conn = imap_open($serviceTest, $login, $passw);
2382
2383                         if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
2384                                 if($errors == 'Too many login failures' || $errors == '[CLOSED] IMAP connection broken (server response)') { // login failure means don't bother trying the rest
2385                                         $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.']');
2386                                         $retArray['err'][$k] = $mod_strings['ERR_BAD_LOGIN_PASSWORD'];
2387                                         $retArray['bad'][$k] = $serviceTest;
2388                                         $GLOBALS['log']->debug($l.': I-E ERROR: $ie->findOptimums() failed due to bad user credentials for user login: '.$this->email_user);
2389                                         return $retArray;
2390                                 } elseif( in_array($errors, $acceptableWarnings, TRUE)) { // false positive
2391                                         $GLOBALS['log']->debug($l.': I-E found good connection but with warnings ['.$serviceTest.'] Errors:' . $errors);
2392                                         $retArray['good'][$k] = $returnService[$k];
2393                                         $foundGoodConnection = true;
2394                                 }
2395                                 else {
2396                                         $GLOBALS['log']->debug($l.': I-E failed using ['.$serviceTest.'] - error: '.$errors);
2397                                         $retArray['err'][$k] = $errors;
2398                                         $retArray['bad'][$k] = $serviceTest;
2399                                 }
2400                         } else {
2401                                 $GLOBALS['log']->debug($l.': I-E found good connect using ['.$serviceTest.']');
2402                                 $retArray['good'][$k] = $returnService[$k];
2403                                 $foundGoodConnection = true;
2404                         }
2405
2406                         if(is_resource($this->conn)) {
2407                                 if (!$this->isPop3Protocol()) {
2408                                         $serviceTest = str_replace("INBOX", "", $serviceTest);
2409                                         $boxes = imap_getmailboxes($this->conn, $serviceTest, "*");
2410                                         $delimiter = '.';
2411                                         // clean MBOX path names
2412                                         foreach($boxes as $k => $mbox) {
2413                                                 $raw[] = $mbox->name;
2414                                                 if ($mbox->delimiter) {
2415                                                         $delimiter = $mbox->delimiter;
2416                                                 } // if
2417                                         } // foreach
2418                                         $this->setSessionInboundDelimiterString($this->server_url, $this->email_user, $this->port, $this->protocol, $delimiter);
2419                                 } // if
2420
2421                                 if(!imap_close($this->conn)) $GLOBALS['log']->debug('imap_close() failed!');
2422                         }
2423
2424                         $GLOBALS['log']->debug($l.': I-E clearing error and alert stacks.');
2425                         imap_errors(); // clear stacks
2426                         imap_alerts();
2427                         // If you find a good connection, then don't do any further testing to find URL
2428                         if ($foundGoodConnection) {
2429                                 break;
2430                         } // if
2431                         $l++;
2432                 }
2433                 $GLOBALS['log']->debug('---------------end FINDOPTIMUMS LOOP----------------');
2434
2435                 if(!empty($retArray['good'])) {
2436                         $newTls                         = '';
2437                         $newCert                        = '';
2438                         $newSsl                         = '';
2439                         $newNotls                       = '';
2440                         $newNovalidate_cert     = '';
2441                         $good = array_pop($retArray['good']); // get most complete string
2442                         $exGood = explode('/', $good);
2443                         foreach($exGood as $v) {
2444                                 switch($v) {
2445                                         case 'ssl':
2446                                                 $newSsl = 'ssl';
2447                                         break;
2448                                         case 'tls':
2449                                                 $newTls = 'tls';
2450                                         break;
2451                                         case 'notls':
2452                                                 $newNotls = 'notls';
2453                                         break;
2454                                         case 'cert':
2455                                                 $newCert = 'validate-cert';
2456                                         break;
2457                                         case 'novalidate-cert':
2458                                                 $newNovalidate_cert = 'novalidate-cert';
2459                                         break;
2460                                         case 'secure':
2461                                                 $secure = 'secure';
2462                                         break;
2463                                 }
2464                         }
2465
2466                         $goodStr['serial'] = $newTls.'::'.$newCert.'::'.$newSsl.'::'.$this->protocol.'::'.$newNovalidate_cert.'::'.$newNotls.'::'.$secure;
2467                         $goodStr['service'] = $good;
2468                         $testConnectString = str_replace('foo','', $good);
2469                         $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$testConnectString.'}';
2470                         $this->setSessionConnectionString($this->server_url, $this->email_user, $this->port, $this->protocol, $goodStr);
2471                         $i = 0;
2472                         foreach($raw as $mbox)
2473                         {
2474                                 $raw[$i] = str_replace($testConnectString, "", $GLOBALS['locale']->translateCharset($mbox, "UTF7-IMAP", "UTF8" ));
2475                                 $i++;
2476                         } // foreach
2477                         sort($raw);
2478                         $this->setSessionInboundFoldersString($this->server_url, $this->email_user, $this->port, $this->protocol, implode(",", $raw));
2479                         return $goodStr;
2480                 } else {
2481                         return false;
2482                 }
2483         }
2484
2485         function getSessionConnectionString($server_url, $email_user, $port, $protocol) {
2486                 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2487                 return (isset($_SESSION[$sessionConnectionString]) ? $_SESSION[$sessionConnectionString] : "");
2488         }
2489
2490         function setSessionConnectionString($server_url, $email_user, $port, $protocol, $goodStr) {
2491                 $sessionConnectionString = $server_url . $email_user . $port . $protocol;
2492                 $_SESSION[$sessionConnectionString] = $goodStr;
2493         }
2494
2495         function getSessionInboundDelimiterString($server_url, $email_user, $port, $protocol) {
2496                 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2497                 return (isset($_SESSION[$sessionInboundDelimiterString]) ? $_SESSION[$sessionInboundDelimiterString] : "");
2498         }
2499
2500         function setSessionInboundDelimiterString($server_url, $email_user, $port, $protocol, $delimiter) {
2501                 $sessionInboundDelimiterString = $server_url . $email_user . $port . $protocol . "delimiter";
2502                 $_SESSION[$sessionInboundDelimiterString] = $delimiter;
2503         }
2504
2505         function getSessionInboundFoldersString($server_url, $email_user, $port, $protocol) {
2506                 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2507                 return (isset($_SESSION[$sessionInboundFoldersListString]) ? $_SESSION[$sessionInboundFoldersListString] : "");
2508         }
2509
2510         function setSessionInboundFoldersString($server_url, $email_user, $port, $protocol, $foldersList) {
2511                 $sessionInboundFoldersListString = $server_url . $email_user . $port . $protocol . "foldersList";
2512                 $_SESSION[$sessionInboundFoldersListString] = $foldersList;
2513         }
2514
2515         /**
2516          * Checks for duplicate Group User names when creating a new one at save()
2517          * @return      GUID            returns GUID of Group User if user_name match is
2518          * found
2519          * @return      boolean         false if NO DUPE IS FOUND
2520          */
2521         function groupUserDupeCheck() {
2522                 $q = "SELECT u.id FROM users u WHERE u.deleted=0 AND u.is_group=1 AND u.user_name = '".$this->name."'";
2523                 $r = $this->db->query($q, true);
2524                 $uid = '';
2525                 while($a = $this->db->fetchByAssoc($r)) {
2526                         $uid = $a['id'];
2527                 }
2528
2529                 if(strlen($uid) > 0) {
2530                         return $uid;
2531                 } else {
2532                         return false;
2533                 }
2534         }
2535
2536         /**
2537          * Returns <option> markup with the contents of Group users
2538          * @param array $groups default empty array
2539          * @return string HTML options
2540          */
2541         function getGroupsWithSelectOptions($groups = array()) {
2542                 $r = $this->db->query('SELECT id, user_name FROM users WHERE users.is_group = 1 AND deleted = 0', true);
2543                 if(is_resource($r)) {
2544                         while($a = $this->db->fetchByAssoc($r)) {
2545                                 $groups[$a['id']] = $a['user_name'];
2546                         }
2547                 }
2548
2549                 $selectOptions = get_select_options_with_id_separate_key($groups, $groups, $this->group_id);
2550                 return $selectOptions;
2551         }
2552
2553         /**
2554          * handles auto-responses to inbound emails
2555          *
2556          * @param object email Email passed as reference
2557          */
2558         function handleAutoresponse(&$email, &$contactAddr) {
2559                 if($this->template_id) {
2560                         $GLOBALS['log']->debug('found auto-reply template id - prefilling and mailing response');
2561
2562                         if($this->getAutoreplyStatus($contactAddr)
2563                         && $this->checkOutOfOffice($email->name)
2564                         && $this->checkFilterDomain($email)) { // if we haven't sent this guy 10 replies in 24hours
2565
2566                                 if(!empty($this->stored_options)) {
2567                                         $storedOptions = unserialize(base64_decode($this->stored_options));
2568                                 }
2569                                 // get FROM NAME
2570                                 if(!empty($storedOptions['from_name'])) {
2571                                         $from_name = $storedOptions['from_name'];
2572                                         $GLOBALS['log']->debug('got from_name from storedOptions: '.$from_name);
2573                                 } else { // use system default
2574                                         $rName = $this->db->query('SELECT value FROM config WHERE name = \'fromname\'', true);
2575                                         if(is_resource($rName)) {
2576                                                 $aName = $this->db->fetchByAssoc($rName);
2577                                         }
2578                                         if(!empty($aName['value'])) {
2579                                                 $from_name = $aName['value'];
2580                                         } else {
2581                                                 $from_name = '';
2582                                         }
2583                                 }
2584                                 // get FROM ADDRESS
2585                                 if(!empty($storedOptions['from_addr'])) {
2586                                         $from_addr = $storedOptions['from_addr'];
2587                                 } else {
2588                                         $rAddr = $this->db->query('SELECT value FROM config WHERE name = \'fromaddress\'', true);
2589                                         if(is_resource($rAddr)) {
2590                                                 $aAddr = $this->db->fetchByAssoc($rAddr);
2591                                         }
2592                                         if(!empty($aAddr['value'])) {
2593                                                 $from_addr = $aAddr['value'];
2594                                         } else {
2595                                                 $from_addr = '';
2596                                         }
2597                                 }
2598
2599                                 $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$from_name ;
2600                                 $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $from_addr;
2601
2602
2603                                 if(!empty($email->reply_to_email)) {
2604                                         $to[0]['email'] = $email->reply_to_email;
2605                                 } else {
2606                                         $to[0]['email'] = $email->from_addr;
2607                                 }
2608                                 // handle to name: address, prefer reply-to
2609                                 if(!empty($email->reply_to_name)) {
2610                                         $to[0]['display'] = $email->reply_to_name;
2611                                 } elseif(!empty($email->from_name)) {
2612                                         $to[0]['display'] = $email->from_name;
2613                                 }
2614
2615                                 $et = new EmailTemplate();
2616                                 $et->retrieve($this->template_id);
2617                                 if(empty($et->subject))         { $et->subject = ''; }
2618                                 if(empty($et->body))            { $et->body = ''; }
2619                                 if(empty($et->body_html))       { $et->body_html = ''; }
2620
2621                                 $reply = new Email();
2622                                 $reply->type                            = 'out';
2623                                 $reply->to_addrs                        = $to[0]['email'];
2624                                 $reply->to_addrs_arr            = $to;
2625                                 $reply->cc_addrs_arr            = array();
2626                                 $reply->bcc_addrs_arr           = array();
2627                                 $reply->from_name                       = $from_name;
2628                                 $reply->from_addr                       = $from_addr;
2629                                 $reply->name                            = $et->subject;
2630                                 $reply->description                     = $et->body;
2631                                 $reply->description_html        = $et->body_html;
2632                                 $reply->reply_to_name           = $replyToName;
2633                                 $reply->reply_to_addr           = $replyToAddr;
2634
2635                                 $GLOBALS['log']->debug('saving and sending auto-reply email');
2636                                 //$reply->save(); // don't save the actual email.
2637                                 $reply->send();
2638                                 $this->setAutoreplyStatus($contactAddr);
2639                         } else {
2640                                 $GLOBALS['log']->debug('InboundEmail: auto-reply threshold reached for email ('.$contactAddr.') - not sending auto-reply');
2641                         }
2642                 }
2643         }
2644
2645         function handleCaseAssignment($email) {
2646                 $c = new aCase();
2647                 if($caseId = $this->getCaseIdFromCaseNumber($email->name, $c)) {
2648                         $c->retrieve($caseId);
2649                         $c->load_relationship('emails');
2650                         $c->emails->add($email->id);
2651
2652                         $email->retrieve($email->id);
2653                         $email->parent_type = "Cases";
2654                         $email->parent_id = $caseId;
2655                         // assign the email to the case owner
2656                         $email->assigned_user_id = $c->assigned_user_id;
2657                         $email->save();
2658                         $GLOBALS['log']->debug('InboundEmail found exactly 1 match for a case: '.$c->name);
2659                         return true;
2660                 } // if
2661                 return false;
2662         } // fn
2663
2664         /**
2665          * handles functionality specific to the Mailbox type (Cases, bounced
2666          * campaigns, etc.)
2667          *
2668          * @param object email Email object passed as a reference
2669          * @param object header Header object generated by imap_headerinfo();
2670          */
2671         function handleMailboxType(&$email, &$header) {
2672                 switch($this->mailbox_type) {
2673                         case 'support':
2674                                 $this->handleCaseAssignment($email);
2675                                 break;
2676                         case 'bug':
2677
2678                                 break;
2679
2680                         case 'info':
2681                                 // do something with this?
2682                                 break;
2683                         case 'sales':
2684                                 // do something with leads? we don't have an email_leads table
2685                                 break;
2686                         case 'task':
2687                                 // do something?
2688                                 break;
2689                         case 'bounce':
2690                                 require_once('modules/Campaigns/ProcessBouncedEmails.php');
2691                                 campaign_process_bounced_emails($email, $header);
2692                                 break;
2693                         case 'pick': // do all except bounce handling
2694                                 $GLOBALS['log']->debug('looking for a case for '.$email->name);
2695                                 $this->handleCaseAssignment($email);
2696                                 break;
2697                 }
2698         }
2699
2700         function isMailBoxTypeCreateCase() {
2701                 return ($this->mailbox_type == 'createcase' && !empty($this->groupfolder_id));
2702         } // fn
2703
2704         function handleCreateCase($email, $userId) {
2705                 global $current_user, $mod_strings, $current_language;
2706                 $mod_strings = return_module_language($current_language, "Emails");
2707                 $GLOBALS['log']->debug('In handleCreateCase');
2708                 $c = new aCase();
2709                 $this->getCaseIdFromCaseNumber($email->name, $c);
2710
2711                 if (!$this->handleCaseAssignment($email) && $this->isMailBoxTypeCreateCase()) {
2712                         // create a case
2713                         $GLOBALS['log']->debug('retrieveing email');
2714                         $email->retrieve($email->id);
2715                         $c = new aCase();
2716                         $c->description = $email->description;
2717                         $c->assigned_user_id = $userId;
2718                         $c->name = $email->name;
2719                         $c->status = 'New';
2720                         $c->priority = 'P1';
2721
2722                         if(!empty($email->reply_to_email)) {
2723                                 $contactAddr = $email->reply_to_email;
2724                         } else {
2725                                 $contactAddr = $email->from_addr;
2726                         }
2727
2728                         $GLOBALS['log']->debug('finding related accounts with address ' . $contactAddr);
2729                         if($accountIds = $this->getRelatedId($contactAddr, 'accounts')) {
2730                                 if (sizeof($accountIds) == 1) {
2731                                         $c->account_id = $accountIds[0];
2732
2733                                         $acct = new Account();
2734                                         $acct->retrieve($c->account_id);
2735                                         $c->account_name = $acct->name;
2736                                 } // if
2737                         } // if
2738                         $c->save(true);
2739                         $caseId = $c->id;
2740                         $c = new aCase();
2741                         $c->retrieve($caseId);
2742                         if($c->load_relationship('emails')) {
2743                                 $c->emails->add($email->id);
2744                         } // if
2745                         if($contactIds = $this->getRelatedId($contactAddr, 'contacts')) {
2746                                 if(!empty($contactIds) && $c->load_relationship('contacts')) {
2747                                         $c->contacts->add($contactIds);
2748                                 } // if
2749                         } // if
2750                         $c->email_id = $email->id;
2751                         $email->parent_type = "Cases";
2752                         $email->parent_id = $caseId;
2753                         // assign the email to the case owner
2754                         $email->assigned_user_id = $c->assigned_user_id;
2755                         $email->name = str_replace('%1', $c->case_number, $c->getEmailSubjectMacro()) . " ". $email->name;
2756                         $email->save();
2757                         $GLOBALS['log']->debug('InboundEmail created one case with number: '.$c->case_number);
2758                         $createCaseTemplateId = $this->get_stored_options('create_case_email_template', "");
2759                         if(!empty($this->stored_options)) {
2760                                 $storedOptions = unserialize(base64_decode($this->stored_options));
2761                         }
2762                         if(!empty($createCaseTemplateId)) {
2763                                 $fromName = "";
2764                                 $fromAddress = "";
2765                                 if (!empty($this->stored_options)) {
2766                                         $fromAddress = $storedOptions['from_addr'];
2767                                         $fromName = from_html($storedOptions['from_name']);
2768                                         $replyToName = (!empty($storedOptions['reply_to_name']))? from_html($storedOptions['reply_to_name']) :$fromName ;
2769                                         $replyToAddr = (!empty($storedOptions['reply_to_addr'])) ? $storedOptions['reply_to_addr'] : $fromAddress;
2770                                 } // if
2771                                 $defaults = $current_user->getPreferredEmail();
2772                                 $fromAddress = (!empty($fromAddress)) ? $fromAddress : $defaults['email'];
2773                                 $fromName = (!empty($fromName)) ? $fromName : $defaults['name'];
2774                                 $to[0]['email'] = $contactAddr;
2775
2776                                 // handle to name: address, prefer reply-to
2777                                 if(!empty($email->reply_to_name)) {
2778                                         $to[0]['display'] = $email->reply_to_name;
2779                                 } elseif(!empty($email->from_name)) {
2780                                         $to[0]['display'] = $email->from_name;
2781                                 }
2782
2783                                 $et = new EmailTemplate();
2784                                 $et->retrieve($createCaseTemplateId);
2785                                 if(empty($et->subject))         { $et->subject = ''; }
2786                                 if(empty($et->body))            { $et->body = ''; }
2787                                 if(empty($et->body_html))       { $et->body_html = ''; }
2788
2789                                 $et->subject = "Re:" . " " . str_replace('%1', $c->case_number, $c->getEmailSubjectMacro() . " ". $c->name);
2790
2791                                 $html = trim($email->description_html);
2792                                 $plain = trim($email->description);
2793
2794                                 $email->email2init();
2795                     $email->from_addr = $email->from_addr_name;
2796                     $email->to_addrs = $email->to_addrs_names;
2797                     $email->cc_addrs = $email->cc_addrs_names;
2798                     $email->bcc_addrs = $email->bcc_addrs_names;
2799                     $email->from_name = $email->from_addr;
2800
2801                 $email = $email->et->handleReplyType($email, "reply");
2802                 $ret = $email->et->displayComposeEmail($email);
2803                 $ret['description'] = empty($email->description_html) ?  str_replace("\n", "\n<BR/>", $email->description) : $email->description_html;
2804
2805                                 $reply = new Email();
2806                                 $reply->type                            = 'out';
2807                                 $reply->to_addrs                        = $to[0]['email'];
2808                                 $reply->to_addrs_arr            = $to;
2809                                 $reply->cc_addrs_arr            = array();
2810                                 $reply->bcc_addrs_arr           = array();
2811                                 $reply->from_name                       = $fromName;
2812                                 $reply->from_addr                       = $fromAddress;
2813                                 $reply->reply_to_name           = $replyToName;
2814                                 $reply->reply_to_addr           = $replyToAddr;
2815                                 $reply->name                            = $et->subject;
2816                                 $reply->description                     = $et->body . "<div><hr /></div>" .  $email->description;
2817                                 if (!$et->text_only) {
2818                                         $reply->description_html        = $et->body_html .  "<div><hr /></div>" . $email->description;
2819                                 }
2820                                 $GLOBALS['log']->debug('saving and sending auto-reply email');
2821                                 //$reply->save(); // don't save the actual email.
2822                                 $reply->send();
2823                         } // if
2824
2825                 } else {
2826                         if(!empty($email->reply_to_email)) {
2827                                 $contactAddr = $email->reply_to_email;
2828                         } else {
2829                                 $contactAddr = $email->from_addr;
2830                         }
2831                         $this->handleAutoresponse($email, $contactAddr);
2832                 }
2833
2834         } // fn
2835
2836         /**
2837          * handles linking contacts, accounts, etc. to an email
2838          *
2839          * @param object Email bean to be linked against
2840          * @return string contactAddr is the email address of the sender
2841          */
2842         function handleLinking(&$email) {
2843                 // link email to an User if emails match TO addr
2844                 if($userIds = $this->getRelatedId($email->to_addrs, 'users')) {
2845                         $GLOBALS['log']->debug('I-E linking email to User');
2846                         // link the user to the email
2847                         $email->load_relationship('users');
2848                         $email->users->add($userIds);
2849                 }
2850
2851                 // link email to a Contact, Lead, or Account if the emails match
2852                 // give precedence to REPLY-TO above FROM
2853                 if(!empty($email->reply_to_email)) {
2854                         $contactAddr = $email->reply_to_email;
2855                 } else {
2856                         $contactAddr = $email->from_addr;
2857                 }
2858
2859                 // Samir Gandhi : 12/06/07
2860                 // This changes has been done because the linking was done only with the from address and
2861                 // not with to address
2862                 $relationShipAddress = $contactAddr;
2863                 if (empty($relationShipAddress)) {
2864                         $relationShipAddress .= $email->to_addrs;
2865                 } else {
2866                         $relationShipAddress = $relationShipAddress . "," . $email->to_addrs;
2867                 }
2868                 if($leadIds = $this->getRelatedId($relationShipAddress, 'leads')) {
2869                         $GLOBALS['log']->debug('I-E linking email to Lead');
2870                         $email->load_relationship('leads');
2871                         $email->leads->add($leadIds);
2872
2873                         foreach($leadIds as $leadId) {
2874                                 $lead = new Lead();
2875                                 $lead->retrieve($leadId);
2876                                 $lead->load_relationship('emails');
2877                                 $lead->emails->add($email->id);
2878                         }
2879                 }
2880
2881                 if($contactIds = $this->getRelatedId($relationShipAddress, 'contacts')) {
2882                         $GLOBALS['log']->debug('I-E linking email to Contact');
2883                         // link the contact to the email
2884                         $email->load_relationship('contacts');
2885                         $email->contacts->add($contactIds);
2886                 }
2887
2888                 if($accountIds = $this->getRelatedId($relationShipAddress, 'accounts')) {
2889                         $GLOBALS['log']->debug('I-E linking email to Account');
2890                         // link the account to the email
2891                         $email->load_relationship('accounts');
2892                         $email->accounts->add($accountIds);
2893
2894                         /* cn: bug 9171 another cause of dying I-E - bad linking
2895                         foreach($accountIds as $accountId) {
2896                                 $GLOBALS['log']->debug('I-E reverse-linking Accounts to Emails');
2897                                 $acct = new Account();
2898                                 $acct->retrieve($accountId);
2899                                 $acct->load_relationship('emails');
2900                                 $acct->account_emails->add($email->id);
2901                         }
2902                         */
2903                 }
2904                 return $contactAddr;
2905         }
2906
2907         /**
2908          * Gets part by following breadcrumb path
2909          * @param string $bc the breadcrumb string in format (1.1.1)
2910          * @param array parts the root level parts array
2911          */
2912         protected function getPartByPath($bc, $parts)
2913         {
2914                 if(strstr($bc,'.')) {
2915                         $exBc = explode('.', $bc);
2916                 } else {
2917                         $exBc = array($bc);
2918                 }
2919
2920                 foreach($exBc as $step) {
2921                     if(empty($parts)) return false;
2922                     $res = $parts[$step-1]; // MIME starts with 1, array starts with 0
2923                     if(!empty($res->parts)) {
2924                         $parts = $res->parts;
2925                     } else {
2926                         $parts = false;
2927                     }
2928                 }
2929                 return $res;
2930         }
2931
2932         /**
2933          * takes a breadcrumb and returns the encoding at that level
2934          * @param       string bc the breadcrumb string in format (1.1.1)
2935          * @param       array parts the root level parts array
2936          * @return      int retInt Int key to transfer encoding (see handleTranserEncoding())
2937          */
2938         function getEncodingFromBreadCrumb($bc, $parts) {
2939                 if(strstr($bc,'.')) {
2940                         $exBc = explode('.', $bc);
2941                 } else {
2942                         $exBc[0] = $bc;
2943                 }
2944
2945                 $depth = count($exBc);
2946
2947                 for($i=0; $i<$depth; $i++) {
2948                         $tempObj[$i] = $parts[($exBc[$i]-1)];
2949                         $retInt = imap_utf8($tempObj[$i]->encoding);
2950                         if(!empty($tempObj[$i]->parts)) {
2951                                 $parts = $tempObj[$i]->parts;
2952                         }
2953                 }
2954                 return $retInt;
2955         }
2956
2957         /**
2958          * retrieves the charset for a given part of an email body
2959          *
2960          * @param string bc target part of the message in format (1.1.1)
2961          * @param array parts 1 level above ROOT array of Objects representing a multipart body
2962          * @return string charset name
2963          */
2964         function getCharsetFromBreadCrumb($bc, $parts)
2965         {
2966                 $tempObj = $this->getPartByPath($bc, $parts);
2967                 // now we have the tempObj at the end of the breadCrumb trail
2968
2969                 if(!empty($tempObj->ifparameters)) {
2970                         foreach($tempObj->parameters as $param) {
2971                                 if(strtolower($param->attribute) == 'charset') {
2972                                         return $param->value;
2973                                 }
2974                         }
2975                 }
2976
2977                 return 'default';
2978         }
2979
2980         /**
2981          * Get the message text from a single mime section, html or plain.
2982          *
2983          * @param string $msgNo
2984          * @param string $section
2985          * @param stdObject $structure
2986          * @return string
2987          */
2988         function getMessageTextFromSingleMimePart($msgNo,$section,$structure)
2989         {
2990             $msgPartTmp = imap_fetchbody($this->conn, $msgNo, $section);
2991             $enc = $this->getEncodingFromBreadCrumb($section, $structure->parts);
2992             $charset = $this->getCharsetFromBreadCrumb($section, $structure->parts);
2993             $msgPartTmp = $this->handleTranserEncoding($msgPartTmp, $enc);
2994             return $this->handleCharsetTranslation($msgPartTmp, $charset);
2995         }
2996
2997         /**
2998          * Givin an existing breadcrumb add a cooresponding offset
2999          *
3000          * @param string $bc
3001          * @param string $offset
3002          * @return string
3003          */
3004         function addBreadCrumbOffset($bc, $offset)
3005         {
3006             if( (empty($bc) || is_null($bc)) && !empty($offset) )
3007                return $offset;
3008
3009             $a_bc = explode(".", $bc);
3010             $a_offset = explode(".",$offset);
3011             if(count($a_bc) < count($a_offset))
3012                $a_bc = array_merge($a_bc,array_fill( count($a_bc), count($a_offset) - count($a_bc), 0));
3013
3014             $results = array();
3015             for($i=0;$i < count($a_bc); $i++)
3016             {
3017                 if(isset($a_offset[$i]))
3018                    $results[] = $a_bc[$i] + $a_offset[$i];
3019                 else
3020                    $results[] = $a_bc[$i];
3021             }
3022             return implode(".", $results);
3023         }
3024
3025         /**
3026          * returns the HTML text part of a multi-part message
3027          *
3028          * @param int msgNo the relative message number for the monitored mailbox
3029          * @param string $type the type of text processed, either 'PLAIN' or 'HTML'
3030          * @return string UTF-8 encoded version of the requested message text
3031          */
3032         function getMessageText($msgNo, $type, $structure, $fullHeader,$clean_email=true, $bcOffset = "") {
3033                 global $sugar_config;
3034
3035                 $msgPart = '';
3036                 $bc = $this->buildBreadCrumbs($structure->parts, $type);
3037                 //Add an offset if specified
3038                 if(!empty($bcOffset))
3039             $bc = $this->addBreadCrumbOffset($bc, $bcOffset);
3040
3041                 if(!empty($bc)) { // multi-part
3042                         // HUGE difference between PLAIN and HTML
3043                         if($type == 'PLAIN') {
3044                                 $msgPart = $this->getMessageTextFromSingleMimePart($msgNo,$bc,$structure);
3045                         } else {
3046                                 // get part of structure that will
3047                                 $msgPartRaw = '';
3048                                 $bcArray = $this->buildBreadCrumbsHTML($structure->parts,$bcOffset);
3049                                 // construct inline HTML/Rich msg
3050                                 foreach($bcArray as $bcArryKey => $bcArr) {
3051                                         foreach($bcArr as $type => $bcTrail) {
3052                                                 if($type == 'html')
3053                                                     $msgPartRaw .= $this->getMessageTextFromSingleMimePart($msgNo,$bcTrail,$structure);
3054                                                  else {
3055                                                         // deal with inline image
3056                                                         $part = $this->getPartByPath($bcTrail, $structure->parts);
3057                                                         if(empty($part) || empty($part->id)) continue;
3058                                                         $partid = substr($part->id, 1, -1); // strip <> around
3059                                                         if(isset($this->inlineImages[$partid])) {
3060                                                                 $imageName = $this->inlineImages[$partid];
3061                                                                 $newImagePath = "class=\"image\" src=\"{$this->imagePrefix}{$imageName}\"";
3062                                                                 $preImagePath = "src=\"cid:$partid\"";
3063                                                                 $msgPartRaw = str_replace($preImagePath, $newImagePath, $msgPartRaw);
3064                                                         }
3065                                                 }
3066                                         }
3067                                 }
3068                                 $msgPart = $msgPartRaw;
3069                         }
3070                 } else { // either PLAIN message type (flowed) or b0rk3d RFC
3071                         // make sure we're working on valid data here.
3072                         if($structure->subtype != $type) {
3073                                 return '';
3074                         }
3075
3076                         $decodedHeader = $this->decodeHeader($fullHeader);
3077
3078                         // now get actual body contents
3079                         $text = imap_body($this->conn, $msgNo);
3080
3081                         $upperCaseKeyDecodeHeader = array();
3082                         if (is_array($decodedHeader)) {
3083                                 $upperCaseKeyDecodeHeader = array_change_key_case($decodedHeader, CASE_UPPER);
3084                         } // if
3085                         if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])) {
3086                                 $flip = array_flip($this->transferEncoding);
3087                                 $text = $this->handleTranserEncoding($text, $flip[strtoupper($upperCaseKeyDecodeHeader[strtoupper('Content-Transfer-Encoding')])]);
3088                         }
3089
3090                         $msgPart = $text;
3091                         if(isset($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']) && !empty($upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset'])) {
3092                                 $msgPart = $this->handleCharsetTranslation($text, $upperCaseKeyDecodeHeader[strtoupper('Content-Type')]['charset']);
3093                         }
3094                 } // end else clause
3095
3096                 $msgPart = $this->customGetMessageText($msgPart);
3097                 /* cn: bug 9176 - htmlEntitites hide XSS attacks.
3098                  * decode to pass refreshed HTML to HTML_Safe */
3099                 if ($type == 'PLAIN')
3100                     return $this->cleanXssContent(to_html($msgPart));
3101                 else
3102                 {
3103             $safedMsgPart = $this->cleanContent($msgPart);
3104                     return str_replace("<img />", '', $safedMsgPart); /*SKIP_IMAGE_TAG*/
3105                 }
3106         }
3107
3108         /**
3109          * decodes raw header information and passes back an associative array with
3110          * the important elements key'd by name
3111          * @param header string the raw header
3112          * @return decodedHeader array the associative array
3113          */
3114         function decodeHeader($fullHeader) {
3115                 $decodedHeader = array();
3116                 $exHeaders = explode("\r", $fullHeader);
3117                 if (!is_array($exHeaders)) {
3118                         $exHeaders = explode("\r\n", $fullHeader);
3119                 }
3120                 $quotes = array('"', "'");
3121
3122                 foreach($exHeaders as $lineNum => $head) {
3123                         $key    = '';
3124                         $key    = trim(substr($head, 0, strpos($head, ':')));
3125                         $value  = '';
3126                         $value  = trim(substr($head, (strpos($head, ':') + 1), strlen($head)));
3127
3128                         // handle content-type section in headers
3129                         if(strtolower($key) == 'content-type' && strpos($value, ';')) { // ";" means something follows related to (such as Charset)
3130                                 $semiColPos = mb_strpos($value, ';');
3131                                 $strLenVal = mb_strlen($value);
3132                                 if(($semiColPos + 4) >= $strLenVal) {
3133                                         // the charset="[something]" is on the next line
3134                                         $value .= str_replace($quotes, "", trim($exHeaders[$lineNum+1]));
3135                                 }
3136
3137                                 $newValue = array();
3138                                 $exValue = explode(';', $value);
3139                                 $newValue['type'] = $exValue[0];
3140
3141                                 for($i=1; $i<count($exValue); $i++) {
3142                                         $exContent = explode('=', $exValue[$i]);
3143                                         $newValue[trim($exContent[0])] = trim($exContent[1]);
3144                                 }
3145                                 $value = $newValue;
3146                         }
3147
3148                         if(!empty($key) && !empty($value)) {
3149                                 $decodedHeader[$key] = $value;
3150                         }
3151                 }
3152
3153                 return $decodedHeader;
3154         }
3155
3156         /**
3157          * handles translating message text from orignal encoding into UTF-8
3158          *
3159          * @param string text test to be re-encoded
3160          * @param string charset original character set
3161          * @return string utf8 re-encoded text
3162          */
3163         function handleCharsetTranslation($text, $charset) {
3164                 global $locale;
3165
3166                 if(empty($charset)) {
3167                         $GLOBALS['log']->debug("***ERROR: InboundEmail::handleCharsetTranslation() called without a \$charset!");
3168                         $GLOBALS['log']->debug("***STACKTRACE: ".print_r(debug_backtrace(), true));
3169                         return $text;
3170                 }
3171
3172                 // typical headers have no charset - let destination pick (since it's all ASCII anyways)
3173                 if(strtolower($charset) == 'default' || strtolower($charset) == 'utf-8') {
3174                         return $text;
3175                 }
3176
3177                 return $locale->translateCharset($text, $charset);
3178         }
3179
3180
3181
3182         /**
3183          * Builds up the "breadcrumb" trail that imap_fetchbody() uses to return
3184          * parts of an email message, including attachments and inline images
3185          * @param       $parts  array of objects
3186          * @param       $subtype        what type of trail to return? HTML? Plain? binaries?
3187          * @param       $breadcrumb     text trail to build up
3188          */
3189         function buildBreadCrumbs($parts, $subtype, $breadcrumb = '0') {
3190                 //_pp('buildBreadCrumbs building for '.$subtype.' with BC at '.$breadcrumb);
3191                 // loop through available parts in the array
3192                 foreach($parts as $k => $part) {
3193                         // mark passage through level
3194                         $thisBc = ($k+1);
3195                         // if this is not the first time through, start building the map
3196                         if($breadcrumb != 0) {
3197                                 $thisBc = $breadcrumb.'.'.$thisBc;
3198                         }
3199
3200                         // found a multi-part/mixed 'part' - keep digging
3201                         if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3202                                 //_pp('in loop: going deeper with subtype: '.$part->subtype.' $k is: '.$k);
3203                                 $thisBc = $this->buildBreadCrumbs($part->parts, $subtype, $thisBc);
3204                                 return $thisBc;
3205
3206                         } elseif(strtolower($part->subtype) == strtolower($subtype)) { // found the subtype we want, return the breadcrumb value
3207                                 //_pp('found '.$subtype.' bc! returning: '.$thisBc);
3208                                 return $thisBc;
3209                         } else {
3210                                 //_pp('found '.$part->subtype.' instead');
3211                         }
3212                 }
3213         }
3214
3215         /**
3216          * Similar to buildBreadCrumbs() but returns an ordered array containing all parts of the message that would be
3217          * considered "HTML" or Richtext (embedded images, formatting, etc.).
3218          * @param array parts Array of parts of a message
3219          * @param int breadcrumb Passed integer value to start breadcrumb trail
3220          * @param array stackedBreadcrumbs Persistent trail of breadcrumbs
3221          * @return array Ordered array of parts to retrieve via imap_fetchbody()
3222          */
3223         function buildBreadCrumbsHTML($parts, $breadcrumb = '0', $stackedBreadcrumbs = array()) {
3224                 $subtype = 'HTML';
3225                 $disposition = 'inline';
3226
3227                 foreach($parts as $k => $part) {
3228                         // mark passage through level
3229                         $thisBc = ($k+1);
3230
3231                         if($breadcrumb != 0) {
3232                                 $thisBc = $breadcrumb.'.'.$thisBc;
3233                         }
3234                         // found a multi-part/mixed 'part' - keep digging
3235                         if($part->type == 1 && (strtoupper($part->subtype) == 'RELATED' || strtoupper($part->subtype) == 'ALTERNATIVE' || strtoupper($part->subtype) == 'MIXED')) {
3236                                 $stackedBreadcrumbs = $this->buildBreadCrumbsHTML($part->parts, $thisBc, $stackedBreadcrumbs);
3237                         } elseif(
3238                                 (strtolower($part->subtype) == strtolower($subtype)) ||
3239                                         (
3240                                                 isset($part->disposition) && strtolower($part->disposition) == 'inline' &&
3241                                                 in_array(strtoupper($part->subtype), $this->imageTypes)
3242                                         )
3243                         ) {
3244                                 // found the subtype we want, return the breadcrumb value
3245                                 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3246                         } elseif($part->type == 5) {
3247                                 $stackedBreadcrumbs[] = array(strtolower($part->subtype) => $thisBc);
3248                         }
3249                 }
3250
3251                 return $stackedBreadcrumbs;
3252         }
3253
3254         /**
3255          * Takes a PHP imap_* object's to/from/cc/bcc address field and converts it
3256          * to a standard string that SugarCRM expects
3257          * @param       $arr    an array of email address objects
3258          */
3259         function convertImapToSugarEmailAddress($arr) {
3260                 if(is_array($arr)) {
3261                         $addr = '';
3262                         foreach($arr as $key => $obj) {
3263                                 $addr .= $obj->mailbox.'@'.$obj->host.', ';
3264                         }
3265                         // strip last comma
3266                         $ret = substr_replace($addr,'',-2,-1);
3267                         return trim($ret);
3268                 }
3269         }
3270
3271         /**
3272          * tries to figure out what character set a given filename is using and
3273          * decode based on that
3274          *
3275          * @param string name Name of attachment
3276          * @return string decoded name
3277          */
3278         function handleEncodedFilename($name) {
3279                 $imapDecode = imap_mime_header_decode($name);
3280                 /******************************
3281                 $imapDecode => stdClass Object
3282                         (
3283                                 [charset] => utf-8
3284                                 [text] => w�hlen.php
3285                         )
3286
3287                                         OR
3288
3289                 $imapDecode => stdClass Object
3290                         (
3291                                 [charset] => default
3292                                 [text] => UTF-8''%E3%83%8F%E3%82%99%E3%82%A4%E3%82%AA%E3%82%AF%E3%82%99%E3%83%A9%E3%83%95%E3%82%A3%E3%83%BC.txt
3293                         )
3294                 *******************************/
3295                 if($imapDecode[0]->charset != 'default') { // mime-header encoded charset
3296                         $encoding = $imapDecode[0]->charset;
3297                         $name = $imapDecode[0]->text; // encoded in that charset
3298                 } else {
3299                         /* encoded filenames are formatted as [encoding]''[filename] */
3300                         if(strpos($name, "''") !== false) {
3301
3302                                 $encoding = substr($name, 0, strpos($name, "'"));
3303
3304                                 while(strpos($name, "'") !== false) {
3305                                         $name = trim(substr($name, (strpos($name, "'")+1), strlen($name)));
3306                                 }
3307                         }
3308                         $name = urldecode($name);
3309                 }
3310                 return (strtolower($encoding) == 'utf-8') ? $name : $GLOBALS['locale']->translateCharset($name, $encoding, 'UTF-8');
3311         }
3312
3313         /*
3314                 Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3315                 0 => text
3316                 1 => multipart
3317                 2 => message
3318                 3 => application
3319                 4 => audio
3320                 5 => image
3321                 6 => video
3322                 7 => other
3323         */
3324
3325         /**
3326         Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3327         @var array $imap_types
3328         */
3329         public $imap_types = array(
3330                         0 => 'text',
3331                         1 => 'multipart',
3332                         2 => 'message',
3333                         3 => 'application',
3334                         4 => 'audio',
3335                         5 => 'image',
3336                         6 => 'video',
3337         );
3338
3339         public function getMimeType($type, $subtype)
3340         {
3341                 if(isset($this->imap_types[$type])) {
3342                         return $this->imap_types[$type]."/$subtype";
3343                 } else {
3344                         return "other/$subtype";
3345                 }
3346         }
3347
3348         /**
3349          * Takes the "parts" attribute of the object that imap_fetchbody() method
3350          * returns, and recursively goes through looking for objects that have a
3351          * disposition of "attachement" or "inline"
3352          * @param int $msgNo The relative message number for the monitored mailbox
3353          * @param object $parts Array of objects to examine
3354          * @param string $emailId The GUID of the email saved prior to calling this method
3355          * @param array $breadcrumb Default 0, build up of the parts mapping
3356          * @param bool $forDisplay Default false
3357          */
3358         function saveAttachments($msgNo, $parts, $emailId, $breadcrumb='0', $forDisplay) {
3359                 global $sugar_config;
3360                 /*
3361                         Primary body types for a part of a mail structure (imap_fetchstructure returned object)
3362                         0 => text
3363                         1 => multipart
3364                         2 => message
3365                         3 => application
3366                         4 => audio
3367                         5 => image
3368                         6 => video
3369                         7 => other
3370                 */
3371
3372                 foreach($parts as $k => $part) {
3373                         $thisBc = $k+1;
3374                         if($breadcrumb != '0') {
3375                                 $thisBc = $breadcrumb.'.'.$thisBc;
3376                         }
3377                         $attach = null;
3378                         // check if we need to recurse into the object
3379                         //if($part->type == 1 && !empty($part->parts)) {
3380                         if(isset($part->parts) && !empty($part->parts) && !( isset($part->subtype) && strtolower($part->subtype) == 'rfc822')  ) {
3381                                 $this->saveAttachments($msgNo, $part->parts, $emailId, $thisBc, $forDisplay);
3382                 continue;
3383                         } elseif($part->ifdisposition) {
3384                                 // we will take either 'attachments' or 'inline'
3385                                 if(strtolower($part->disposition) == 'attachment' || ((strtolower($part->disposition) == 'inline') && $part->type != 0)) {
3386                                         $attach = $this->getNoteBeanForAttachment($emailId);
3387                                         $fname = $this->handleEncodedFilename($this->retrieveAttachmentNameFromStructure($part->dparameters));
3388
3389                                         if(!empty($fname)) {//assign name to attachment
3390                                                 $attach->name = $fname;
3391                                         } else {//if name is empty, default to filename
3392                                                 $attach->name = urlencode($this->retrieveAttachmentNameFromStructure($part->dparameters));
3393                                         }
3394                                         $attach->filename = $attach->name;
3395                                         if (empty($attach->filename)) {
3396                                                 continue;
3397                                         }
3398
3399                                         // deal with the MIME types email has
3400                                         $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3401                                         $attach->safeAttachmentName();
3402                                         if($forDisplay) {
3403                                                 $attach->id = $this->getTempFilename();
3404                                         } else {
3405                                                 // only save if doing a full import, else we want only the binaries
3406                                                 $attach->save();
3407                                         }
3408                                 } // end if disposition type 'attachment'
3409                         }// end ifdisposition
3410                         //Retrieve contents of subtype rfc8822
3411                         elseif ($part->type == 2 && isset($part->subtype) && strtolower($part->subtype) == 'rfc822' )
3412                         {
3413                             $tmp_eml =  imap_fetchbody($this->conn, $msgNo, $thisBc);
3414                             $attach = $this->getNoteBeanForAttachment($emailId);
3415                             $attach->file_mime_type = 'messsage/rfc822';
3416                             $attach->description = $tmp_eml;
3417                             $attach->filename = 'bounce.eml';
3418                             $attach->safeAttachmentName();
3419                             if($forDisplay) {
3420                                 $attach->id = $this->getTempFilename();
3421                             } else {
3422                                 // only save if doing a full import, else we want only the binaries
3423                                 $attach->save();
3424                             }
3425                         } elseif(!$part->ifdisposition && $part->type != 1 && $part->type != 2 && $thisBc != '1') {
3426                         // No disposition here, but some IMAP servers lie about disposition headers, try to find the truth
3427                                 // Also Outlook puts inline attachments as type 5 (image) without a disposition
3428                                 if($part->ifparameters) {
3429                     foreach($part->parameters as $param) {
3430                         if(strtolower($param->attribute) == "name" || strtolower($param->attribute) == "filename") {
3431                             $fname = $this->handleEncodedFilename($param->value);
3432                             break;
3433                         }
3434                     }
3435                     if(empty($fname)) continue;
3436
3437                                         // we assume that named parts are attachments too
3438                     $attach = $this->getNoteBeanForAttachment($emailId);
3439
3440                                         $attach->filename = $attach->name = $fname;
3441                                         $attach->file_mime_type = $this->getMimeType($part->type, $part->subtype);
3442
3443                                         $attach->safeAttachmentName();
3444                                         if($forDisplay) {
3445                                                 $attach->id = $this->getTempFilename();
3446                                         } else {
3447                                                 // only save if doing a full import, else we want only the binaries
3448                                                 $attach->save();
3449                                         }
3450                                 }
3451                         }
3452                         $this->saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay);
3453                 } // end foreach
3454         }
3455
3456         /**
3457          * Return a new note object for attachments.
3458          *
3459          * @param string $emailId
3460          * @return Note
3461          */
3462         function getNoteBeanForAttachment($emailId)
3463         {
3464             $attach = new Note();
3465             $attach->parent_id = $emailId;
3466             $attach->parent_type = 'Emails';
3467
3468             return $attach;
3469         }
3470
3471         /**
3472          * Return the filename of the attachment by examining the dparameters returned from imap_fetch_structure which
3473          * represet the content-disposition of the MIME header.
3474          *
3475          * @param array $dparamaters
3476          * @return string
3477          */
3478         function retrieveAttachmentNameFromStructure($dparamaters)
3479         {
3480            $result = "";
3481
3482            foreach ($dparamaters as $k => $v)
3483            {
3484                if( strtolower($v->attribute) == 'filename')
3485                {
3486                    $result = $v->value;
3487                    break;
3488                }
3489            }
3490
3491            return $result;
3492
3493     }
3494         /**
3495          * saves the actual binary file of a given attachment
3496          * @param object attach Note object that is attached to the binary file
3497          * @param string msgNo Message Number on IMAP/POP3 server
3498          * @param string thisBc Breadcrumb to navigate email structure to find the content
3499          * @param object part IMAP standard object that contains the "parts" of this section of email
3500          * @param bool $forDisplay
3501          */
3502         function saveAttachmentBinaries($attach, $msgNo, $thisBc, $part, $forDisplay) {
3503                 // decide where to place the file temporarily
3504                 $uploadDir = ($forDisplay) ? "{$this->EmailCachePath}/{$this->id}/attachments/" : "upload://";
3505
3506                 // decide what name to save file as
3507                 $fileName = $attach->id;
3508
3509                 // download the attachment if we didn't do it yet
3510                 if(!file_exists($uploadDir.$fileName)) {
3511                         $msgPartRaw = imap_fetchbody($this->conn, $msgNo, $thisBc);
3512                 // deal with attachment encoding and decode the text string
3513                         $msgPart = $this->handleTranserEncoding($msgPartRaw, $part->encoding);
3514
3515                         if(file_put_contents($uploadDir.$fileName, $msgPart)) {
3516                                 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$attach->filename);
3517                         } else {
3518                 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$attach->filename ." - temp file target: [ {$uploadDir}{$fileName} ]");
3519                 return;
3520                         }
3521                 }
3522
3523                 $this->tempAttachment[$fileName] = urldecode($attach->filename);
3524                 // if all was successful, feel for inline and cache Note ID for display:
3525                 if((strtolower($part->disposition) == 'inline' && in_array($part->subtype, $this->imageTypes))
3526                     || ($part->type == 5)) {
3527                     if(copy($uploadDir.$fileName, sugar_cached("images/{$fileName}.").strtolower($part->subtype))) {
3528                             $id = substr($part->id, 1, -1); //strip <> around
3529                             $this->inlineImages[$id] = $attach->id.".".strtolower($part->subtype);
3530                         } else {
3531                                 $GLOBALS['log']->debug('InboundEmail could not copy '.$uploadDir.$fileName.' to cache');
3532                         }
3533                 }
3534         }
3535
3536         /**
3537          * decodes a string based on its associated encoding
3538          * if nothing is passed, we default to no-encoding type
3539          * @param       $str    encoded string
3540          * @param       $enc    detected encoding
3541          */
3542         function handleTranserEncoding($str, $enc=0) {
3543                 switch($enc) {
3544                         case 2:// BINARY
3545                                 $ret = $str;
3546                                 break;
3547                         case 3:// BASE64
3548                                 $ret = base64_decode($str);
3549                                 break;
3550                         case 4:// QUOTED-PRINTABLE
3551                                 $ret = quoted_printable_decode($str);
3552                                 break;
3553                         case 0:// 7BIT or 8BIT
3554                         case 1:// already in a string-useable format - do nothing
3555                         case 5:// OTHER
3556                         default:// catch all
3557                                 $ret = $str;
3558                                 break;
3559                 }
3560
3561                 return $ret;
3562         }
3563
3564
3565         /**
3566          * Some emails do not get assigned a message_id, specifically from
3567          * Outlook/Exchange.
3568          *
3569          * We need to derive a reliable one for duplicate import checking.
3570          */
3571         function getMessageId($header) {
3572                 $message_id = md5(print_r($header, true));
3573                 return $message_id;
3574         }
3575
3576         /**
3577          * checks for duplicate emails on polling.  The uniqueness of a given email message is determined by a concatenation
3578          * of 2 values, the messageID and the delivered-to field.  This allows multiple To: and B/CC: destination addresses
3579          * to be imported by Sugar without violating the true duplicate-email issues.
3580          *
3581          * @param string message_id message ID generated by sending server
3582          * @param int message number (mailserver's key) of email
3583          * @param object header object generated by imap_headerinfo()
3584          * @param string textHeader Headers in normal text format
3585          * @return bool
3586          */
3587         function importDupeCheck($message_id, $header, $textHeader) {
3588                 $GLOBALS['log']->debug('*********** InboundEmail doing dupe check.');
3589
3590                 // generate "delivered-to" seed for email duplicate check
3591                 $deliveredTo = $this->id; // cn: bug 12236 - cc's failing dupe check
3592                 $exHeader = explode("\n", $textHeader);
3593
3594                 foreach($exHeader as $headerLine) {
3595                         if(strpos(strtolower($headerLine), 'delivered-to:') !== false) {
3596                                 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3597                                 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] as the destination address for email [ '.$message_id.' ]');
3598                         } elseif(strpos(strtolower($headerLine), 'x-real-to:') !== false) {
3599                                 $deliveredTo = substr($headerLine, strpos($headerLine, " "), strlen($headerLine));
3600                                 $GLOBALS['log']->debug('********* InboundEmail found [ '.$deliveredTo.' ] for non-standards compliant email x-header [ '.$message_id.' ]');
3601                         }
3602                 }
3603
3604                 //if(empty($message_id) && !isset($message_id)) {
3605                 if(empty($message_id) || !isset($message_id)) {
3606                         $GLOBALS['log']->debug('*********** NO MESSAGE_ID.');
3607                         $message_id = $this->getMessageId($header);
3608                 }
3609
3610                 // generate compound messageId
3611                 $this->compoundMessageId = trim($message_id).trim($deliveredTo);
3612                 // if the length > 255 then md5 it so that the data will be of smaller length
3613                 if (strlen($this->compoundMessageId) > 255) {
3614                         $this->compoundMessageId = md5($this->compoundMessageId);
3615                 } // if
3616
3617                 if (empty($this->compoundMessageId)) {
3618                         $GLOBALS['log']->error('Inbound Email found a message without a header and message_id');
3619                         return false;
3620                 } // if
3621
3622                 $potentials = clean_xss($this->compoundMessageId, false);
3623
3624                 if(is_array($potentials) && !empty($potentials)) {
3625                         foreach($potentials as $bad) {
3626                                 $this->compoundMessageId = str_replace($bad, "", $this->compoundMessageId);
3627                         }
3628                 }
3629
3630                 $query = 'SELECT count(emails.id) AS c FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3631                 $r = $this->db->query($query, true);
3632                 $a = $this->db->fetchByAssoc($r);
3633
3634                 if($a['c'] > 0) {
3635                         $GLOBALS['log']->debug('InboundEmail found a duplicate email with ID ('.$this->compoundMessageId.')');
3636                         return false; // we have a dupe and don't want to import the email'
3637                 } else {
3638                         return true;
3639                 }
3640         }
3641
3642         /**
3643          * takes the output from imap_mime_hader_decode() and handles multiple types of encoding
3644          * @param string subject Raw subject string from email
3645          * @return string ret properly formatted UTF-8 string
3646          */
3647         function handleMimeHeaderDecode($subject) {
3648                 $subjectDecoded = imap_mime_header_decode($subject);
3649
3650                 $ret = '';
3651                 foreach($subjectDecoded as $object) {
3652                         if($object->charset != 'default') {
3653                                 $ret .= $this->handleCharsetTranslation($object->text, $object->charset);
3654                         } else {
3655                                 $ret .= $object->text;
3656                         }
3657                 }
3658                 return $ret;
3659         }
3660
3661    /**
3662         * URL cleanup function
3663         * Until we have comprehensive CSRF protection, we need to sanitize URLs in emails
3664         * to avoid CSRF attacks
3665         */
3666         public function urlCleaner($attr, $value)
3667         {
3668         // hrefs are ok
3669             if(strtolower($attr) == "href") return true;
3670             $items = parse_url($value);
3671             if(empty($items)) return false;
3672             if(!empty($items['scheme']) && strtolower($items['scheme']) != 'http' && strtolower($items['scheme']) != 'https') {
3673                 // do not touch non-HTTP URLs
3674                 return true;
3675             }
3676         // don't allow relative URLs
3677                 if(empty($items['host'])) return false;
3678         // allow URLs with no query
3679                 if(empty($items['query'])) return true;
3680         // allow URLs that don't start with /? or /index.php?
3681                 if(!empty($items['path']) && $items['path'] != '/' && strtolower(substr($items['path'], -10)) != '/index.php') {
3682                         return true;
3683                 }
3684         // now we have blah-blah/index.php?query - let's see if query looks dangerous
3685                 $query_items = array();
3686                 parse_str(from_html($items['query']), $query_items);
3687         // weird query, probably harmless
3688                 if(empty($query_items)) return true;
3689         // suspiciously like SugarCRM query, reject
3690                 if(!empty($query_items['module']) && !empty($query_items['action'])) return false;
3691         // looks like non-download entry point - allow only specific entry points
3692                 if(!empty($query_items['entryPoint']) && !in_array($query_items['entryPoint'], array('download', 'image', 'getImage'))) {
3693                         return false;
3694                 }
3695
3696                 return true;
3697         }
3698
3699         /**
3700          * Cleans content for XSS and other types of attack vectors
3701          * @param string str String to clean
3702          * @return string
3703          */
3704         function cleanContent($str) {
3705                 // Safe_HTML
3706                 $this->safe->clear();
3707                 $this->safe->setUrlCallback(array($this, "urlCleaner"));
3708                 $str = $this->safe->parse($str);
3709                 return $this->cleanXssContent($str);
3710         }
3711
3712         /**
3713          * Cleans content for XSS
3714          * @param string str String to clean
3715          * @return string
3716          */
3717         function cleanXssContent($str) {
3718
3719                 $potentials = clean_xss($str, false);
3720                 if(is_array($potentials) && !empty($potentials)) {
3721                         foreach($potentials as $bad) {
3722                                 $str = str_replace($bad, "", $str);
3723                         }
3724                 }
3725                 return $str;
3726         }
3727         /**
3728          * Calculates the appropriate display date/time sent for an email.
3729          * @param string headerDate The date sent of email in MIME header format
3730          * @return string GMT-0 Unix timestamp
3731          */
3732         function getUnixHeaderDate($headerDate) {
3733                 global $timedate;
3734
3735                 if (empty($headerDate)) {
3736                         return "";
3737                 }
3738                 ///////////////////////////////////////////////////////////////////
3739                 ////    CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3740                 if(!empty($headerDate)) {
3741                     // Bug 25254 - Strip trailing space that come in some header dates (maybe ones with 1-digit day number)
3742                     $headerDate = trim($headerDate);
3743                         // need to hack PHP/windows' bad handling of strings when using POP3
3744                         if(strstr($headerDate,'+0000 GMT')) {
3745                                 $headerDate = str_replace('GMT','', $headerDate);
3746                         } elseif(!strtotime($headerDate)) {
3747                                 $headerDate = 'now'; // catch non-standard format times.
3748                         } else {
3749                                 // cn: bug 9196 parse the GMT offset
3750                                 if(strpos($headerDate, '-') || strpos($headerDate, '+')) {
3751                                         // cn: bug make sure last 5 chars are [+|-]nnnn
3752                                         if(strpos($headerDate, "(")) {
3753                                                 $headerDate = preg_replace('/\([\w]+\)/i', "", $headerDate);
3754                                                 $headerDate = trim($headerDate);
3755                                         }
3756
3757                                         // parse mailserver time
3758                                         $gmtEmail = trim(substr($headerDate, -5, 5));
3759                                         $posNeg = substr($gmtEmail, 0, 1);
3760                                         $gmtHours = substr($gmtEmail, 1, 2);
3761                                         $gmtMins = substr($gmtEmail, -2, 2);
3762
3763                                         // get seconds
3764                                         $secsHours = $gmtHours * 60 * 60;
3765                                         $secsTotal = $secsHours + ($gmtMins * 60);
3766                                         $secsTotal = ($posNeg == '-') ? $secsTotal : -1 * $secsTotal;
3767
3768                                         $headerDate = trim(substr_replace($headerDate, '', -5)); // mfh: bug 10961/12855 - date time values with GMT offsets not properly formatted
3769                                 }
3770                         }
3771                 } else {
3772                         $headerDate = 'now';
3773                 }
3774
3775                 $unixHeaderDate = strtotime($headerDate);
3776
3777                 if(isset($secsTotal)) {
3778                         // this gets the timestamp to true GMT-0
3779                         $unixHeaderDate += $secsTotal;
3780                 }
3781
3782                 if(strtotime('Jan 1, 2001') > $unixHeaderDate) {
3783                         $unixHeaderDate = strtotime('now');
3784                 }
3785
3786                 return $unixHeaderDate;
3787                 ////    END CALCULATE CORRECT SENT DATE/TIME FOR EMAIL
3788                 ///////////////////////////////////////////////////////////////////
3789         }
3790
3791         /**
3792          * This method returns the correct messageno for the pop3 protocol
3793          * @param String UIDL
3794          * @return returnMsgNo
3795          */
3796         function getCorrectMessageNoForPop3($messageId) {
3797                 $returnMsgNo = -1;
3798                 if ($this->protocol == 'pop3') {
3799                         if($this->pop3_open()) {
3800                                 // get the UIDL from database;
3801                                 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageId}'";
3802                                 $r = $this->db->query($query);
3803                                 $a = $this->db->fetchByAssoc($r);
3804                                 $msgNo = $a['msgno'];
3805                                 $returnMsgNo = $msgNo;
3806
3807                                 // authenticate
3808                                 $this->pop3_sendCommand("USER", $this->email_user);
3809                                 $this->pop3_sendCommand("PASS", $this->email_password);
3810
3811                                 // get UIDL for this msgNo
3812                                 $this->pop3_sendCommand("UIDL {$msgNo}", '', false); // leave socket buffer alone until the while()
3813                                 $buf = fgets($this->pop3socket, 1024); // handle "OK+ msgNo UIDL(UIDL for this messageno)";
3814
3815                                 // if it returns OK then we have found the message else get all the UIDL
3816                                 // and search for the correct msgNo;
3817                                 $foundMessageNo = false;
3818                                 if (preg_match("/OK/", $buf) > 0) {
3819                                         $mailserverResponse = explode(" ", $buf);
3820                                         // if the cachedUIDL and the UIDL from mail server matches then its the correct messageno
3821                                         if (trim($mailserverResponse[sizeof($mailserverResponse) - 1]) == $messageId) {
3822                                                 $foundMessageNo = true;
3823                                         }
3824                                 } //if
3825
3826                                 //get all the UIDL and then find the correct messageno
3827                                 if (!$foundMessageNo) {
3828                                         // get UIDLs
3829                                         $this->pop3_sendCommand("UIDL", '', false); // leave socket buffer alone until the while()
3830                                         fgets($this->pop3socket, 1024); // handle "OK+";
3831                                         $UIDLs = array();
3832                                         $buf = '!';
3833                                         if(is_resource($this->pop3socket)) {
3834                                                 while(!feof($this->pop3socket)) {
3835                                                         $buf = fgets($this->pop3socket, 1024); // 8kb max buffer - shouldn't be more than 80 chars via pop3...
3836                                                         if(trim($buf) == '.') {
3837                                                                 $GLOBALS['log']->debug("*** GOT '.'");
3838                                                                 break;
3839                                                         } // if
3840                                                         // format is [msgNo] [UIDL]
3841                                                         $exUidl = explode(" ", $buf);
3842                                                         $UIDLs[trim($exUidl[1])] = trim($exUidl[0]);
3843                                                 } // while
3844                                                 if (array_key_exists($messageId, $UIDLs)) {
3845                                                         $returnMsgNo = $UIDLs[$messageId];
3846                                                 } else {
3847                                                         // message could not be found on server
3848                                                         $returnMsgNo = -1;
3849                                                 } // else
3850                                         } // if
3851
3852                                 } // if
3853                                 $this->pop3_cleanUp();
3854                         } //if
3855                 } //if
3856                 return $returnMsgNo;
3857         }
3858
3859         /**
3860          * If the importOneEmail returns false, then findout if the duplicate email
3861          */
3862         function getDuplicateEmailId($msgNo, $uid) {
3863                 global $timedate;
3864                 global $app_strings;
3865                 global $app_list_strings;
3866                 global $sugar_config;
3867                 global $current_user;
3868
3869                 $header = imap_headerinfo($this->conn, $msgNo);
3870                 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3871
3872                 // reset inline images cache
3873                 $this->inlineImages = array();
3874
3875                 // handle messages deleted on server
3876                 if(empty($header)) {
3877                         if(!isset($this->email) || empty($this->email)) {
3878                                 $this->email = new Email();
3879                         } // if
3880                         return "";
3881                 } else {
3882                         $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3883                         if (!$dupeCheckResult && !empty($this->compoundMessageId)) {
3884                                 // we have a duplicate email
3885                                 $query = 'SELECT id FROM emails WHERE emails.message_id = \''.$this->compoundMessageId.'\' and emails.deleted = 0';
3886                                 $r = $this->db->query($query, true);
3887                                 $a = $this->db->fetchByAssoc($r);
3888
3889                                 $this->email = new Email();
3890                                 $this->email->id = $a['id'];
3891                                 return $a['id'];
3892                         } // if
3893                         return "";
3894                 } // else
3895         } // fn
3896
3897
3898         /**
3899          * shiny new importOneEmail() method
3900          * @param int msgNo
3901          * @param bool forDisplay
3902          * @param clean_email boolean, default true,
3903          */
3904         function importOneEmail($msgNo, $uid, $forDisplay=false, $clean_email=true) {
3905                 $GLOBALS['log']->debug("InboundEmail processing 1 email {$msgNo}-----------------------------------------------------------------------------------------");
3906                 global $timedate;
3907                 global $app_strings;
3908                 global $app_list_strings;
3909                 global $sugar_config;
3910                 global $current_user;
3911
3912         // Bug # 45477
3913         // So, on older versions of PHP (PHP VERSION < 5.3),
3914         // calling imap_headerinfo and imap_fetchheader can cause a buffer overflow for exteremly large headers,
3915         // This leads to the remaining messages not being read because Sugar crashes everytime it tries to read the headers.
3916         // The workaround is to mark a message as read before making trying to read the header of the msg in question
3917         // This forces this message not be read again, and we can continue processing remaining msgs.
3918
3919         // UNCOMMENT THIS IF YOU HAVE THIS PROBLEM!  See notes on Bug # 45477
3920         // $this->markEmails($uid, "read");
3921
3922                 $header = imap_headerinfo($this->conn, $msgNo);
3923                 $fullHeader = imap_fetchheader($this->conn, $msgNo); // raw headers
3924
3925                 // reset inline images cache
3926                 $this->inlineImages = array();
3927
3928                 // handle messages deleted on server
3929                 if(empty($header)) {
3930                         if(!isset($this->email) || empty($this->email)) {
3931                                 $this->email = new Email();
3932                         }
3933
3934                         $q = "";
3935                         if ($this->isPop3Protocol()) {
3936                                 $this->email->name = $app_strings['LBL_EMAIL_ERROR_MESSAGE_DELETED'];
3937                                 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3938                         } else {
3939                                 $this->email->name = $app_strings['LBL_EMAIL_ERROR_IMAP_MESSAGE_DELETED'];
3940                                 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}' AND mbox = '{$this->mailbox}'";
3941                         } // else
3942                         // delete local cache
3943                         $r = $this->db->query($q);
3944
3945                         $this->email->date_sent = $timedate->nowDb();
3946                         return false;
3947                         //return "Message deleted from server.";
3948                 }
3949
3950                 ///////////////////////////////////////////////////////////////////////
3951                 ////    DUPLICATE CHECK
3952                 $dupeCheckResult = $this->importDupeCheck($header->message_id, $header, $fullHeader);
3953                 if($forDisplay || $dupeCheckResult) {
3954                         $GLOBALS['log']->debug('*********** NO duplicate found, continuing with processing.');
3955
3956                         $structure = imap_fetchstructure($this->conn, $msgNo); // map of email
3957
3958                         ///////////////////////////////////////////////////////////////////
3959                         ////    CREATE SEED EMAIL OBJECT
3960                         $email = new Email();
3961                         $email->isDuplicate = ($dupeCheckResult) ? false : true;
3962                         $email->mailbox_id = $this->id;
3963                         $message = array();
3964                         $email->id = create_guid();
3965                         $email->new_with_id = true; //forcing a GUID here to prevent double saves.
3966                         ////    END CREATE SEED EMAIL
3967                         ///////////////////////////////////////////////////////////////////
3968
3969                         ///////////////////////////////////////////////////////////////////
3970                         ////    PREP SYSTEM USER
3971                         if(empty($current_user)) {
3972                                 // I-E runs as admin, get admin prefs
3973
3974                                 $current_user = new User();
3975                                 $current_user->getSystemUser();
3976                         }
3977                         $tPref = $current_user->getUserDateTimePreferences();
3978                         ////    END USER PREP
3979                         ///////////////////////////////////////////////////////////////////
3980             if(!empty($header->date)) {
3981                             $unixHeaderDate = $timedate->fromString($header->date);
3982             }
3983                         ///////////////////////////////////////////////////////////////////
3984                         ////    HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
3985                         ////    Inline images require that I-E handle attachments before body text
3986                         // parts defines attachments - be mindful of .html being interpreted as an attachment
3987                         if($structure->type == 1 && !empty($structure->parts)) {
3988                                 $GLOBALS['log']->debug('InboundEmail found multipart email - saving attachments if found.');
3989                                 $this->saveAttachments($msgNo, $structure->parts, $email->id, 0, $forDisplay);
3990                         } elseif($structure->type == 0) {
3991                                 $uuemail = ($this->isUuencode($email->description)) ? true : false;
3992                                 /*
3993                                  * UUEncoded attachments - legacy, but still have to deal with it
3994                                  * format:
3995                                  * begin 777 filename.txt
3996                                  * UUENCODE
3997                                  *
3998                                  * end
3999                                  */
4000                                 // set body to the filtered one
4001                                 if($uuemail) {
4002                                         $email->description = $this->handleUUEncodedEmailBody($email->description, $email->id);
4003                                         $email->retrieve($email->id);
4004                                         $email->save();
4005                                 }
4006                         } else {
4007                                 if($this->port != 110) {
4008                                         $GLOBALS['log']->debug('InboundEmail found a multi-part email (id:'.$msgNo.') with no child parts to parse.');
4009                                 }
4010                         }
4011                         ////    END HANDLE EMAIL ATTACHEMENTS OR HTML TEXT
4012                         ///////////////////////////////////////////////////////////////////
4013
4014                         ///////////////////////////////////////////////////////////////////
4015                         ////    ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4016                         // handle UTF-8/charset encoding in the ***headers***
4017                         global $db;
4018                         $email->name                    = $this->handleMimeHeaderDecode($header->subject);
4019                         $email->date_start = (!empty($unixHeaderDate)) ? $timedate->asUserDate($unixHeaderDate) : "";
4020                         $email->time_start = (!empty($unixHeaderDate)) ? $timedate->asUserTime($unixHeaderDate) : "";
4021                         $email->type = 'inbound';
4022                         $email->date_created = (!empty($unixHeaderDate)) ? $timedate->asUser($unixHeaderDate) : "";
4023                         $email->status = 'unread'; // this is used in Contacts' Emails SubPanel
4024                         if(!empty($header->toaddress)) {
4025                                 $email->to_name  = $this->handleMimeHeaderDecode($header->toaddress);
4026                                 $email->to_addrs_names = $email->to_name;
4027                         }
4028                         if(!empty($header->to)) {
4029                                 $email->to_addrs        = $this->convertImapToSugarEmailAddress($header->to);
4030                         }
4031                         $email->from_name               = $this->handleMimeHeaderDecode($header->fromaddress);
4032                         $email->from_addr_name = $email->from_name;
4033                         $email->from_addr               = $this->convertImapToSugarEmailAddress($header->from);
4034                         if(!empty($header->cc)) {
4035                                 $email->cc_addrs        = $this->convertImapToSugarEmailAddress($header->cc);
4036                         }
4037                         if(!empty($header->ccaddress)) {
4038                                 $email->cc_addrs_names   = $this->handleMimeHeaderDecode($header->ccaddress);
4039                         } // if
4040                         $email->reply_to_name   = $this->handleMimeHeaderDecode($header->reply_toaddress);
4041                         $email->reply_to_email  = $this->convertImapToSugarEmailAddress($header->reply_to);
4042                         if (!empty($email->reply_to_email)) {
4043                                 $email->reply_to_addr   = $email->reply_to_name;
4044                         }
4045                         $email->intent                  = $this->mailbox_type;
4046
4047                         $email->message_id              = $this->compoundMessageId; // filled by importDupeCheck();
4048
4049                         $oldPrefix = $this->imagePrefix;
4050                         if(!$forDisplay) {
4051                                 // Store CIDs in imported messages, convert on display
4052                                 $this->imagePrefix = "cid:";
4053                         }
4054                         // handle multi-part email bodies
4055                         $email->description_html= $this->getMessageText($msgNo, 'HTML', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4056                         $email->description     = $this->getMessageText($msgNo, 'PLAIN', $structure, $fullHeader,$clean_email); // runs through handleTranserEncoding() already
4057                         $this->imagePrefix = $oldPrefix;
4058
4059                         // empty() check for body content
4060                         if(empty($email->description)) {
4061                                 $GLOBALS['log']->debug('InboundEmail Message (id:'.$email->message_id.') has no body');
4062                         }
4063
4064                         // assign_to group
4065                         if (!empty($_REQUEST['user_id'])) {
4066                                 $email->assigned_user_id = $_REQUEST['user_id'];
4067                         } else {
4068                                 // Samir Gandhi : Commented out this code as its not needed
4069                                 //$email->assigned_user_id = $this->group_id;
4070                         }
4071
4072                 //Assign Parent Values if set
4073                 if (!empty($_REQUEST['parent_id']) && !empty($_REQUEST['parent_type'])) {
4074                 $email->parent_id = $_REQUEST['parent_id'];
4075                 $email->parent_type = $_REQUEST['parent_type'];
4076
4077                 $mod = strtolower($email->parent_type);
4078                 $rel = array_key_exists($mod, $email->field_defs) ? $mod : $mod . "_activities_emails"; //Custom modules rel name
4079
4080                 if(! $email->load_relationship($rel) )
4081                     return FALSE;
4082                 $email->$rel->add($email->parent_id);
4083                 }
4084
4085                         // override $forDisplay w/user pref
4086                         if($forDisplay) {
4087                                 if($this->isAutoImport()) {
4088                                         $forDisplay = false; // triggers save of imported email
4089                                 }
4090                         }
4091
4092                         if(!$forDisplay) {
4093                                 $email->save();
4094
4095                                 $email->new_with_id = false; // to allow future saves by UPDATE, instead of INSERT
4096                                 ////    ASSIGN APPROPRIATE ATTRIBUTES TO NEW EMAIL OBJECT
4097                                 ///////////////////////////////////////////////////////////////////
4098
4099                                 ///////////////////////////////////////////////////////////////////
4100                                 ////    LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4101                                 //$contactAddr = $this->handleLinking($email);
4102                                 ////    END LINK APPROPRIATE BEANS TO NEWLY SAVED EMAIL
4103                                 ///////////////////////////////////////////////////////////////////
4104
4105                                 ///////////////////////////////////////////////////////////////////
4106                                 ////    MAILBOX TYPE HANDLING
4107                                 $this->handleMailboxType($email, $header);
4108                                 ////    END MAILBOX TYPE HANDLING
4109                                 ///////////////////////////////////////////////////////////////////
4110
4111                                 ///////////////////////////////////////////////////////////////////
4112                                 ////    SEND AUTORESPONSE
4113                                 if(!empty($email->reply_to_email)) {
4114                                         $contactAddr = $email->reply_to_email;
4115                                 } else {
4116                                         $contactAddr = $email->from_addr;
4117                                 }
4118                                 if (!$this->isMailBoxTypeCreateCase()) {
4119                                         $this->handleAutoresponse($email, $contactAddr);
4120                                 }
4121                                 ////    END SEND AUTORESPONSE
4122                                 ///////////////////////////////////////////////////////////////////
4123                                 ////    END IMPORT ONE EMAIL
4124                                 ///////////////////////////////////////////////////////////////////
4125                         }
4126                 } else {
4127                         // only log if not POP3; pop3 iterates through ALL mail
4128                         if($this->protocol != 'pop3') {
4129                                 $GLOBALS['log']->info("InboundEmail found a duplicate email: ".$header->message_id);
4130                                 //echo "This email has already been imported";
4131                         }
4132                         return false;
4133                 }
4134                 ////    END DUPLICATE CHECK
4135                 ///////////////////////////////////////////////////////////////////////
4136
4137                 ///////////////////////////////////////////////////////////////////////
4138                 ////    DEAL WITH THE MAILBOX
4139                 if(!$forDisplay) {
4140                         imap_setflag_full($this->conn, $msgNo, '\\SEEN');
4141
4142                         // if delete_seen, mark msg as deleted
4143                         if($this->delete_seen == 1  && !$forDisplay) {
4144                                 $GLOBALS['log']->info("INBOUNDEMAIL: delete_seen == 1 - deleting email");
4145                                 imap_setflag_full($this->conn, $msgNo, '\\DELETED');
4146                         }
4147                 } else {
4148                         // for display - don't touch server files?
4149                         //imap_setflag_full($this->conn, $msgNo, '\\UNSEEN');
4150                 }
4151
4152                 $GLOBALS['log']->debug('********************************* InboundEmail finished import of 1 email: '.$email->name);
4153                 ////    END DEAL WITH THE MAILBOX
4154                 ///////////////////////////////////////////////////////////////////////
4155
4156                 ///////////////////////////////////////////////////////////////////////
4157                 ////    TO SUPPORT EMAIL 2.0
4158                 $this->email = $email;
4159
4160                 if(empty($this->email->et)) {
4161                         $this->email->email2init();
4162                 }
4163
4164                 return true;
4165         }
4166
4167         /**
4168          * figures out if a plain text email body has UUEncoded attachments
4169          * @param string string The email body
4170          * @return bool True if UUEncode is detected.
4171          */
4172         function isUuencode($string) {
4173                 $rx = "begin [0-9]{3} .*";
4174
4175                 $exBody = explode("\r", $string);
4176                 foreach($exBody as $line) {
4177                         if(preg_match("/begin [0-9]{3} .*/i", $line)) {
4178                                 return true;
4179                         }
4180                 }
4181
4182                 return false;
4183         }
4184
4185         /**
4186          * handles UU Encoded emails - a legacy from pre-RFC 822 which must still be supported (?)
4187          * @param string raw The raw email body
4188          * @param string id Parent email ID
4189          * @return string The filtered email body, stripped of attachments
4190          */
4191         function handleUUEncodedEmailBody($raw, $id) {
4192                 global $locale;
4193
4194                 $emailBody = '';
4195                 $attachmentBody = '';
4196                 $inAttachment = false;
4197
4198                 $exRaw = explode("\n", $raw);
4199
4200                 foreach($exRaw as $k => $line) {
4201                         $line = trim($line);
4202
4203                         if(preg_match("/begin [0-9]{3} .*/i", $line, $m)) {
4204                                 $inAttachment = true;
4205                                 $fileName = $this->handleEncodedFilename(substr($m[0], 10, strlen($m[0])));
4206
4207                                 $attachmentBody = ''; // reset for next part of loop;
4208                                 continue;
4209                         }
4210
4211                         // handle "end"
4212                         if(strpos($line, "end") === 0) {
4213                                 if(!empty($fileName) && !empty($attachmentBody)) {
4214                                         $this->handleUUDecode($id, $fileName, trim($attachmentBody));
4215                                         $attachmentBody = ''; // reset for next part of loop;
4216                                 }
4217                         }
4218
4219                         if($inAttachment === false) {
4220                                 $emailBody .= "\n".$line;
4221                         } else {
4222                                 $attachmentBody .= "\n".$line;
4223                         }
4224                 }
4225
4226                 /* since UUEncode was developed before MIME, we have NO idea what character set encoding was used.  we will assume the user's locale character set */
4227                 $emailBody = $locale->translateCharset($emailBody, $locale->getExportCharset(), 'UTF-8');
4228                 return $emailBody;
4229         }
4230
4231         /**
4232          * wrapper for UUDecode
4233          * @param string id Id of the email
4234          * @param string UUEncode Encode US-ASCII
4235          */
4236         function handleUUDecode($id, $fileName, $UUEncode) {
4237                 global $sugar_config;
4238                 /* include PHP_Compat library; it auto-feels for PHP5's compiled convert_uuencode() function */
4239                 require_once('include/PHP_Compat/convert_uudecode.php');
4240
4241                 $attach = new Note();
4242                 $attach->parent_id = $id;
4243                 $attach->parent_type = 'Emails';
4244
4245                 $fname = $this->handleEncodedFilename($fileName);
4246
4247                 if(!empty($fname)) {//assign name to attachment
4248                         $attach->name = $fname;
4249                 } else {//if name is empty, default to filename
4250                         $attach->name = urlencode($fileName);
4251                 }
4252
4253                 $attach->filename = urlencode($attach->name);
4254
4255                 //get position of last "." in file name
4256                 $file_ext_beg = strrpos($attach->filename,".");
4257                 $file_ext = "";
4258                 //get file extension
4259                 if($file_ext_beg >0) {
4260                         $file_ext = substr($attach->filename, $file_ext_beg+1);
4261                 }
4262                 //check to see if this is a file with extension located in "badext"
4263                 foreach($sugar_config['upload_badext'] as $badExt) {
4264                         if(strtolower($file_ext) == strtolower($badExt)) {
4265                                 //if found, then append with .txt and break out of lookup
4266                                 $attach->name = $attach->name . ".txt";
4267                                 $attach->file_mime_type = 'text/';
4268                                 $attach->filename = $attach->filename . ".txt";
4269                                 break; // no need to look for more
4270                         }
4271                 }
4272                 $attach->save();
4273
4274                 $bin = convert_uudecode($UUEncode);
4275                 $filename = "upload://{$attach->id}";
4276                 if(file_put_contents($filename, $bin)) {
4277                 $GLOBALS['log']->debug('InboundEmail saved attachment file: '.$filename);
4278                 } else {
4279                 $GLOBALS['log']->debug('InboundEmail could not create attachment file: '.$filename);
4280                 }
4281         }
4282
4283         /**
4284          * returns true if the email's domain is NOT in the filter domain string
4285          *
4286          * @param object email Email object in question
4287          * @return bool true if not filtered, false if filtered
4288          */
4289         function checkFilterDomain($email) {
4290                 $filterDomain = $this->get_stored_options('filter_domain');
4291                 if(!isset($filterDomain) || empty($filterDomain)) {
4292                         return true; // nothing set for this
4293                 } else {
4294                         $replyTo = strtolower($email->reply_to_email);
4295                         $from = strtolower($email->from_addr);
4296                         $filterDomain = '@'.strtolower($filterDomain);
4297                         if(strpos($replyTo, $filterDomain) !== false) {
4298                                 $GLOBALS['log']->debug('Autoreply cancelled - [reply to] address domain matches filter domain.');
4299                                 return false;
4300                         } elseif(strpos($from, $filterDomain) !== false) {
4301                                 $GLOBALS['log']->debug('Autoreply cancelled - [from] address domain matches filter domain.');
4302                                 return false;
4303                         } else {
4304                                 return true; // no match
4305                         }
4306                 }
4307         }
4308
4309         /**
4310          * returns true if subject is NOT "out of the office" type
4311          *
4312          * @param string subject Subject line of email in question
4313          * @return bool returns false if OOTO found
4314          */
4315         function checkOutOfOffice($subject) {
4316                 $ooto = array("Out of the Office", "Out of Office");
4317
4318                 foreach($ooto as $str) {
4319                         if(preg_match('/'.$str.'/i', $subject)) {
4320                                 $GLOBALS['log']->debug('Autoreply cancelled - found "Out of Office" type of subject.');
4321                                 return false;
4322                         }
4323                 }
4324                 return true; // no matches to ooto strings
4325         }
4326
4327
4328         /**
4329          * sets a timestamp for an autoreply to a single email addy
4330          *
4331          * @param string addr Address of auto-replied target
4332          */
4333         function setAutoreplyStatus($addr) {
4334             $timedate = TimeDate::getInstance();
4335                 $this->db->query(       'INSERT INTO inbound_email_autoreply (id, deleted, date_entered, date_modified, autoreplied_to, ie_id) VALUES (
4336                                                         \''.create_guid().'\',
4337                                                         0,
4338                                                         \''.$timedate->nowDb().'\',
4339                                                         \''.$timedate->nowDb().'\',
4340                                                         \''.$addr.'\',
4341                                     \''.$this->id.'\') ', true);
4342         }
4343
4344
4345         /**
4346          * returns true if recipient has NOT received 10 auto-replies in 24 hours
4347          *
4348          * @param string from target address for auto-reply
4349          * @return bool true if target is valid/under limit
4350          */
4351         function getAutoreplyStatus($from) {
4352                 global $sugar_config;
4353         $timedate = TimeDate::getInstance();
4354
4355                 $q_clean = 'UPDATE inbound_email_autoreply SET deleted = 1 WHERE date_entered < \''.$timedate->getNow()->modify("-24 hours")->asDb().'\'';
4356                 $r_clean = $this->db->query($q_clean, true);
4357
4358                 $q = 'SELECT count(*) AS c FROM inbound_email_autoreply WHERE deleted = 0 AND autoreplied_to = \''.$from.'\' AND ie_id = \''.$this->id.'\'';
4359                 $r = $this->db->query($q, true);
4360                 $a = $this->db->fetchByAssoc($r);
4361
4362                 $email_num_autoreplies_24_hours = $this->get_stored_options('email_num_autoreplies_24_hours');
4363                 $maxReplies = (isset($email_num_autoreplies_24_hours)) ? $email_num_autoreplies_24_hours : $this->maxEmailNumAutoreplies24Hours;
4364
4365                 if($a['c'] >= $maxReplies) {
4366                         $GLOBALS['log']->debug('Autoreply cancelled - more than ' . $maxReplies . ' replies sent in 24 hours.');
4367                         return false;
4368                 } else {
4369                         return true;
4370                 }
4371         }
4372
4373         /**
4374          * returns exactly 1 id match. if more than one, than returns false
4375          * @param       $emailName              the subject of the email to match
4376          * @param       $tableName              the table of the matching bean type
4377          */
4378         function getSingularRelatedId($emailName, $tableName) {
4379                 $repStrings = array('RE:','Re:','re:');
4380                 $preppedName = str_replace($repStrings,'',trim($emailName));
4381
4382                 //TODO add team security to this query
4383                 $q = 'SELECT count(id) AS c FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4384                 $r = $this->db->query($q, true);
4385                 $a = $this->db->fetchByAssoc($r);
4386
4387                 if($a['c'] == 0) {
4388                         $q = 'SELECT id FROM '.$tableName.' WHERE deleted = 0 AND name LIKE \'%'.$preppedName.'%\'';
4389                         $r = $this->db->query($q, true);
4390                         $a = $this->db->fetchByAssoc($r);
4391                         return $a['id'];
4392                 } else {
4393                         return false;
4394                 }
4395         }
4396
4397         /**
4398          * saves InboundEmail parse macros to config.php
4399          * @param string type Bean to link
4400          * @param string macro The new macro
4401          */
4402         function saveInboundEmailSystemSettings($type, $macro) {
4403                 global $sugar_config;
4404
4405                 // inbound_email_case_subject_macro
4406                 $var = "inbound_email_".strtolower($type)."_subject_macro";
4407                 $sugar_config[$var] = $macro;
4408
4409                 ksort($sugar_config);
4410
4411                 $sugar_config_string = "<?php\n" .
4412                         '// created: ' . date('Y-m-d H:i:s') . "\n" .
4413                         '$sugar_config = ' .
4414                         var_export($sugar_config, true) .
4415                         ";\n?>\n";
4416
4417                 write_array_to_file("sugar_config", $sugar_config, "config.php");
4418         }
4419
4420         /**
4421          * returns the HTML for InboundEmail system settings
4422          * @return string HTML
4423          */
4424         function getSystemSettingsForm() {
4425                 global $sugar_config;
4426                 global $mod_strings;
4427                 global $app_strings;
4428                 global $app_list_strings;
4429
4430                 ////    Case Macro
4431                 $c = new aCase();
4432
4433                 $macro = $c->getEmailSubjectMacro();
4434
4435                 $ret =<<<eoq
4436                         <form action="index.php" method="post" name="Macro" id="form">
4437                                                 <input type="hidden" name="module" value="InboundEmail">
4438                                                 <input type="hidden" name="action" value="ListView">
4439                                                 <input type="hidden" name="save" value="true">
4440
4441                         <table width="100%" cellpadding="0" cellspacing="0" border="0">
4442                                 <tr>
4443                                         <td>
4444                                                 <input  title="{$app_strings['LBL_SAVE_BUTTON_TITLE']}"
4445                                                                 accessKey="{$app_strings['LBL_SAVE_BUTTON_KEY']}"
4446                                                                 class="button"
4447                                                                 onclick="this.form.return_module.value='InboundEmail'; this.form.return_action.value='ListView';"
4448                                                                 type="submit" name="Edit" value="  {$app_strings['LBL_SAVE_BUTTON_LABEL']}  ">
4449                                         </td>
4450                                 </tr>
4451                         </table>
4452
4453                         <table width="100%" border="0" cellspacing="0" cellpadding="0" class="detail view">
4454                                 <tr>
4455                                         <td valign="top" width='10%' NOWRAP scope="row">
4456                                                 <slot>
4457                                                         <b>{$mod_strings['LBL_CASE_MACRO']}:</b>
4458                                                 </slot>
4459                                         </td>
4460                                         <td valign="top" width='20%'>
4461                                                 <slot>
4462                                                         <input name="inbound_email_case_macro" type="text" value="{$macro}">
4463                                                 </slot>
4464                                         </td>
4465                                         <td valign="top" width='70%'>
4466                                                 <slot>
4467                                                         {$mod_strings['LBL_CASE_MACRO_DESC']}
4468                                                         <br />
4469                                                         <i>{$mod_strings['LBL_CASE_MACRO_DESC2']}</i>
4470                                                 </slot>
4471                                         </td>
4472                                 </tr>
4473                         </table>
4474                         </form>
4475 eoq;
4476                 return $ret;
4477         }
4478
4479         /**
4480          * for mailboxes of type "Support" parse for '[CASE:%1]'
4481          * @param       $emailName              the subject line of the email
4482          * @param       $aCase                  a Case object
4483          */
4484         function getCaseIdFromCaseNumber($emailName, $aCase) {
4485                 //$emailSubjectMacro
4486                 $exMacro = explode('%1', $aCase->getEmailSubjectMacro());
4487                 $open = $exMacro[0];
4488                 $close = $exMacro[1];
4489
4490                 if($sub = stristr($emailName, $open)) { // eliminate everything up to the beginning of the macro and return the rest
4491                         // $sub is [CASE:XX] xxxxxxxxxxxxxxxxxxxxxx
4492                         $sub2 = str_replace($open, '', $sub);
4493                         // $sub2 is XX] xxxxxxxxxxxxxx
4494                         $sub3 = substr($sub2, 0, strpos($sub2, $close));
4495
4496                         $r = $this->db->query("SELECT id FROM cases WHERE case_number = '{$sub3}'", true);
4497                         $a = $this->db->fetchByAssoc($r);
4498                         if(!empty($a['id'])) {
4499                                 return $a['id'];
4500                         } else {
4501                                 return false;
4502                         }
4503                 } else {
4504                         return false;
4505                 }
4506         }
4507
4508         function get_stored_options($option_name,$default_value=null,$stored_options=null) {
4509                 if (empty($stored_options)) {
4510                         $stored_options=$this->stored_options;
4511                 }
4512                 if(!empty($stored_options)) {
4513                         $storedOptions = unserialize(base64_decode($stored_options));
4514                         if (isset($storedOptions[$option_name])) {
4515                                 $default_value=$storedOptions[$option_name];
4516                         }
4517                 }
4518                 return $default_value;
4519         }
4520
4521
4522         /**
4523          * This function returns a contact or user ID if a matching email is found
4524          * @param       $email          the email address to match
4525          * @param       $table          which table to query
4526          */
4527         function getRelatedId($email, $module) {
4528                 $email = trim(strtoupper($email));
4529                 if(strpos($email, ',') !== false) {
4530                         $emailsArray = explode(',', $email);
4531                         $emailAddressString = "";
4532                         foreach($emailsArray as $emailAddress) {
4533                                 if (!empty($emailAddressString)) {
4534                                         $emailAddressString .= ",";
4535                                 }
4536                                 $emailAddressString .=  "'" . $emailAddress. "'";
4537                         } // foreach
4538                         $email = $emailAddressString;
4539                 } else {
4540                         $email = "'" . $email . "'";
4541                 } // else
4542                 $module = ucfirst($module);
4543
4544                 $q = "SELECT bean_id FROM email_addr_bean_rel eabr
4545                                 JOIN email_addresses ea ON (eabr.email_address_id = ea.id)
4546                                 WHERE bean_module = '{$module}' AND ea.email_address_caps in ( {$email} ) AND eabr.deleted=0";
4547
4548                 $r = $this->db->query($q, true);
4549
4550                 $retArr = array();
4551                 while($a = $this->db->fetchByAssoc($r)) {
4552                         $retArr[] = $a['bean_id'];
4553                 }
4554                 if(count($retArr) > 0) {
4555                         return $retArr;
4556                 } else {
4557                         return false;
4558                 }
4559         }
4560
4561         /**
4562          * finds emails tagged "//UNSEEN" on mailserver and "SINCE: [date]" if that
4563          * option is set
4564          *
4565          * @return array Array of messageNumbers (mail server's internal keys)
4566          */
4567         function getNewMessageIds() {
4568                 $storedOptions = unserialize(base64_decode($this->stored_options));
4569
4570                 //TODO figure out if the since date is UDT
4571                 if($storedOptions['only_since']) {// POP3 does not support Unseen flags
4572                         if(!isset($storedOptions['only_since_last']) && !empty($storedOptions['only_since_last'])) {
4573                                 $q = 'SELECT last_run FROM schedulers WHERE job = \'function::pollMonitoredInboxes\'';
4574                                 $r = $this->db->query($q, true);
4575                                 $a = $this->db->fetchByAssoc($r);
4576
4577                                 $date = date('r', strtotime($a['last_run']));
4578                         } else {
4579                                 $date = $storedOptions['only_since_last'];
4580                         }
4581                         $ret = imap_search($this->conn, 'SINCE "'.$date.'" UNDELETED UNSEEN');
4582                         $check = imap_check($this->conn);
4583                         $storedOptions['only_since_last'] = $check->Date;
4584                         $this->stored_options = base64_encode(serialize($storedOptions));
4585                         $this->save();
4586                 } else {
4587                         $ret = imap_search($this->conn, 'UNDELETED UNSEEN');
4588                 }
4589
4590                 $GLOBALS['log']->debug('-----> getNewMessageIds() got '.count($ret).' new Messages');
4591                 return $ret;
4592         }
4593
4594         /**
4595          * Constructs the resource connection string that IMAP needs
4596          * @param string $service Service string, will generate if not passed
4597          * @return string
4598          */
4599         function getConnectString($service='', $mbox='', $includeMbox=true) {
4600                 $service = empty($service) ? $this->getServiceString() : $service;
4601                 $mbox = empty($mbox) ? $this->mailbox : $mbox;
4602
4603                 $connectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4604                 $connectString .= ($includeMbox) ? $mbox : "";
4605
4606                 return $connectString;
4607         }
4608
4609         function disconnectMailserver() {
4610                 if(is_resource($this->conn)) {
4611                         imap_close($this->conn);
4612                 }
4613         }
4614
4615         /**
4616          * Connects to mailserver.  If an existing IMAP resource is available, it
4617          * will attempt to reuse the connection, updating the mailbox path.
4618          *
4619          * @param bool test Flag to test connection
4620          * @param bool force Force reconnect
4621          * @return string "true" on success, "false" or $errorMessage on failure
4622          */
4623         function connectMailserver($test=false, $force=false) {
4624                 global $mod_strings;
4625                 if(!function_exists("imap_open")) {
4626                         $GLOBALS['log']->debug('------------------------- IMAP libraries NOT available!!!! die()ing thread.----');
4627                         return $mod_strings['LBL_WARN_NO_IMAP'];
4628                 }
4629
4630                 imap_errors(); // clearing error stack
4631                 error_reporting(0); // turn off notices from IMAP
4632
4633                 // tls::ca::ssl::protocol::novalidate-cert::notls
4634                 $useSsl = ($_REQUEST['ssl'] == 'true') ? true : false;
4635                 if($test) {
4636                         imap_timeout(1, 15); // 60 secs is the default
4637                         imap_timeout(2, 15);
4638                         imap_timeout(3, 15);
4639
4640                         $opts = $this->findOptimumSettings($useSsl);
4641                         if(isset($opts['good']) && empty($opts['good'])) {
4642                                 return array_pop($opts['err']);
4643                         } else {
4644                                 $service = $opts['service'];
4645                                 $service = str_replace('foo','', $service); // foo there to support no-item explodes
4646                         }
4647                 } else {
4648                         $service = $this->getServiceString();
4649                 }
4650
4651                 $connectString = $this->getConnectString($service, $this->mailbox);
4652
4653                 /*
4654                  * Try to recycle the current connection to reduce response times
4655                  */
4656                 if(is_resource($this->conn)) {
4657                         if($force) {
4658                                 // force disconnect
4659                                 imap_close($this->conn);
4660                         }
4661
4662                         if(imap_ping($this->conn)) {
4663                                 // we have a live connection
4664                                 imap_reopen($this->conn, $connectString, CL_EXPUNGE);
4665                         }
4666                 }
4667
4668                 // final test
4669                 if(!is_resource($this->conn) && !$test) {
4670                         $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4671                 }
4672
4673                 if($test) {
4674                         if ($opts == false && !is_resource($this->conn)) {
4675                                 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4676                         }
4677                         $errors = '';
4678                         $alerts = '';
4679                         $successful = false;
4680                         if(($errors = imap_last_error()) || ($alerts = imap_alerts())) {
4681                                 if($errors == 'Mailbox is empty') { // false positive
4682                                         $successful = true;
4683                                 } else {
4684                                         $msg .= $errors;
4685                                         $msg .= '<p>'.$alerts.'<p>';
4686                                         $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'];
4687                                 }
4688                         } else {
4689                                 $successful = true;
4690                         }
4691
4692                         if($successful) {
4693                                 if($this->protocol == 'imap') {
4694                                         $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4695                                         /*
4696                                         $testConnectString = '{'.$this->server_url.':'.$this->port.'/service='.$this->protocol.$service.'}';
4697                                         if (!is_resource($this->conn)) {
4698                                                 $this->conn = imap_open($connectString, $this->email_user, $this->email_password, CL_EXPUNGE);
4699                                         }
4700                                         $list = imap_getmailboxes($this->conn, $testConnectString, "*");
4701                                         if(isset($_REQUEST['personal']) && $_REQUEST['personal'] == 'true') {
4702                                                 $msg .= $mod_strings['LBL_TEST_SUCCESSFUL'];
4703                                         } elseif (is_array($list)) {
4704                                                 sort($list);
4705                                                 _ppd($boxes);
4706
4707                                                 $msg .= '<b>'.$mod_strings['LBL_FOUND_MAILBOXES'].'</b><p>';
4708                                                 foreach ($list as $key => $val) {
4709                                                         $mb = imap_utf7_decode(str_replace($testConnectString,'',$val->name));
4710                                                         $msg .= '<a onClick=\'setMailbox(\"'.$mb.'\"); window.close();\'>';
4711                                                         $msg .= $mb;
4712                                                         $msg .= '</a><br>';
4713                                                 }
4714                                         } else {
4715                                                 $msg .= $errors;
4716                                                 $msg .= '<p>'.$mod_strings['ERR_MAILBOX_FAIL'].imap_last_error().'</p>';
4717                                                 $msg .= '<p>'.$mod_strings['ERR_TEST_MAILBOX'].'</p>';
4718                                         }
4719                                         */
4720                                 } else {
4721                                         $msg .= $mod_strings['LBL_POP3_SUCCESS'];
4722                                 }
4723                         }
4724
4725                         imap_errors(); // collapse error stack
4726                         imap_close($this->conn);
4727                         return $msg;
4728                 } elseif(!is_resource($this->conn)) {
4729                         return "false";
4730                 } else {
4731                         return "true";
4732                 }
4733         }
4734
4735
4736
4737         function checkImap() {
4738                 global $mod_strings;
4739
4740                 if(!function_exists('imap_open')) {
4741                         echo '
4742                         <table cellpadding="0" cellspacing="0" width="100%" border="0" class="list view">
4743                                 <tr height="20">
4744                                         <td scope="col" width="25%"  colspan="2"><slot>
4745                                                 '.$mod_strings['LBL_WARN_IMAP_TITLE'].'
4746                                         </slot></td>
4747                                 </tr>
4748                                 <tr>
4749                                         <td scope="row" valign=TOP bgcolor="#fdfdfd" width="20%"><slot>
4750                                                 '.$mod_strings['LBL_WARN_IMAP'].'
4751                                         <td scope="row" valign=TOP class="oddListRowS1" bgcolor="#fdfdfd" width="80%"><slot>
4752                                                 <span class=error>'.$mod_strings['LBL_WARN_NO_IMAP'].'</span>
4753                                         </slot></td>
4754                                 </tr>
4755                         </table>
4756                         <br>';
4757                 }
4758         }
4759
4760         /**
4761          * retrieves an array of I-E beans based on the group_id
4762          * @param       string  $groupId        GUID of the group user or Individual
4763          * @return      array   $beans          array of beans
4764          * @return      boolean false if none returned
4765          */
4766         function retrieveByGroupId($groupId) {
4767                 $q = 'SELECT id FROM inbound_email WHERE group_id = \''.$groupId.'\' AND deleted = 0 AND status = \'Active\'';
4768                 $r = $this->db->query($q, true);
4769
4770                 $beans = array();
4771                 while($a = $this->db->fetchByAssoc($r)) {
4772                         $ie = new InboundEmail();
4773                         $ie->retrieve($a['id']);
4774                         $beans[$a['id']] = $ie;
4775                 }
4776                 return $beans;
4777         }
4778
4779         /**
4780          * Retrieves the current count of personal accounts for the user specified.
4781          *
4782          * @param unknown_type $user
4783          */
4784         function getUserPersonalAccountCount($user = null)
4785         {
4786             if($user == null)
4787                $user = $GLOBALS['current_user'];
4788
4789             $query = "SELECT count(*) as c FROM inbound_email WHERE deleted=0 AND is_personal='1' AND group_id='{$user->id}' AND status='Active'";
4790
4791             $rs = $this->db->query($query);
4792                 $row = $this->db->fetchByAssoc($rs);
4793         return $row['c'];
4794         }
4795
4796         /**
4797          * retrieves an array of I-E beans based on the group folder id
4798          * @param       string  $groupFolderId  GUID of the group folder
4799          * @return      array   $beans          array of beans
4800          * @return      boolean false if none returned
4801          */
4802         function retrieveByGroupFolderId($groupFolderId) {
4803                 $q = 'SELECT id FROM inbound_email WHERE groupfolder_id = \''.$groupFolderId.'\' AND deleted = 0 ';
4804                 $r = $this->db->query($q, true);
4805
4806                 $beans = array();
4807                 while($a = $this->db->fetchByAssoc($r)) {
4808                         $ie = new InboundEmail();
4809                         $ie->retrieve($a['id']);
4810                         $beans[] = $ie;
4811                 }
4812                 return $beans;
4813         }
4814
4815         /**
4816          * Retrieves an array of I-E beans that the user has team access to
4817          */
4818         function retrieveAllByGroupId($id, $includePersonal=true) {
4819                 global $current_user;
4820
4821                 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4822
4823                 $teamJoin = '';
4824
4825
4826
4827                 $q = "SELECT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND groupfolder_id is null AND mailbox_type not like 'bounce' AND inbound_email.deleted = 0 AND status = 'Active' ";
4828
4829
4830
4831                 $r = $this->db->query($q, true);
4832
4833                 while($a = $this->db->fetchByAssoc($r)) {
4834                         $found = false;
4835                         foreach($beans as $bean) {
4836                                 if($bean->id == $a['id']) {
4837                                         $found = true;
4838                                 }
4839                         }
4840
4841                         if(!$found) {
4842                                 $ie = new InboundEmail();
4843                                 $ie->retrieve($a['id']);
4844                                 $beans[$a['id']] = $ie;
4845                         }
4846                 }
4847
4848                 return $beans;
4849         }
4850
4851         /**
4852          * Retrieves an array of I-E beans that the user has team access to including group
4853          */
4854         function retrieveAllByGroupIdWithGroupAccounts($id, $includePersonal=true) {
4855                 global $current_user;
4856
4857                 $beans = ($includePersonal) ? $this->retrieveByGroupId($id) : array();
4858
4859                 $teamJoin = '';
4860
4861
4862
4863
4864
4865
4866                 $q = "SELECT DISTINCT inbound_email.id FROM inbound_email {$teamJoin} WHERE is_personal = 0 AND mailbox_type not like 'bounce' AND status = 'Active' AND inbound_email.deleted = 0 ";
4867
4868                 $r = $this->db->query($q, true);
4869
4870                 while($a = $this->db->fetchByAssoc($r)) {
4871                         $found = false;
4872                         foreach($beans as $bean) {
4873                                 if($bean->id == $a['id']) {
4874                                         $found = true;
4875                                 }
4876                         }
4877
4878                         if(!$found) {
4879                                 $ie = new InboundEmail();
4880                                 $ie->retrieve($a['id']);
4881                                 $beans[$a['id']] = $ie;
4882                         }
4883                 }
4884
4885                 return $beans;
4886         }
4887
4888
4889         /**
4890          * returns the bean name - overrides SugarBean's
4891          */
4892         function get_summary_text() {
4893                 return $this->name;
4894         }
4895
4896         /**
4897          * Override's SugarBean's
4898          */
4899         function create_export_query($order_by, $where, $show_deleted = 0) {
4900                 return $this->create_new_list_query($order_by, $where, $show_deleted = 0);
4901         }
4902
4903         /**
4904          * Override's SugarBean's
4905          */
4906
4907         /**
4908          * Override's SugarBean's
4909          */
4910         function get_list_view_data(){
4911                 global $mod_strings;
4912                 global $app_list_strings;
4913                 $temp_array = $this->get_list_view_array();
4914                 $temp_array['MAILBOX_TYPE_NAME']= $app_list_strings['dom_mailbox_type'][$this->mailbox_type];
4915                 //cma, fix bug 21670.
4916         $temp_array['GLOBAL_PERSONAL_STRING']= ($this->is_personal ? $mod_strings['LBL_IS_PERSONAL'] : $mod_strings['LBL_IS_GROUP']);
4917         $temp_array['STATUS'] = ($this->status == 'Active') ? $mod_strings['LBL_STATUS_ACTIVE'] : $mod_strings['LBL_STATUS_INACTIVE'];
4918                 return $temp_array;
4919         }
4920
4921         /**
4922          * Override's SugarBean's
4923          */
4924         function fill_in_additional_list_fields() {
4925                 $this->fill_in_additional_detail_fields();
4926         }
4927
4928         /**
4929          * Override's SugarBean's
4930          */
4931         function fill_in_additional_detail_fields() {
4932                 if(!empty($this->service)) {
4933                         $exServ = explode('::', $this->service);
4934                         $this->tls              = $exServ[0];
4935                         if ( isset($exServ[1]) )
4936                             $this->ca           = $exServ[1];
4937                         if ( isset($exServ[2]) )
4938                             $this->ssl          = $exServ[2];
4939                         if ( isset($exServ[3]) )
4940                             $this->protocol     = $exServ[3];
4941                 }
4942         }
4943
4944
4945
4946
4947
4948
4949
4950
4951
4952
4953
4954
4955
4956
4957         ///////////////////////////////////////////////////////////////////////////
4958         ////    IN SUPPORT OF EMAIL 2.0
4959         /**
4960          * Checks for $user's autoImport setting and returns the current value
4961          * @param object $user User in focus, defaults to $current_user
4962          * @return bool
4963          */
4964         function isAutoImport($user=null) {
4965                 if(!empty($this->autoImport)) {
4966                         return $this->autoImport;
4967                 }
4968
4969                 global $current_user;
4970                 if(empty($user)) $user = $current_user;
4971
4972                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
4973                 $emailSettings = is_string($emailSettings) ? unserialize($emailSettings) : $emailSettings;
4974
4975                 $this->autoImport = (isset($emailSettings['autoImport']) && !empty($emailSettings['autoImport'])) ? true : false;
4976                 return $this->autoImport;
4977         }
4978
4979         /**
4980          * Clears out cache files for a user
4981          */
4982         function cleanOutCache() {
4983                 $GLOBALS['log']->debug("INBOUNDEMAIL: at cleanOutCache()");
4984                 $this->deleteCache();
4985         }
4986
4987         /**
4988          * moves emails from folder to folder
4989          * @param string $fromIe I-E id
4990          * @param string $fromFolder IMAP path to folder in which the email lives
4991          * @param string $toIe I-E id
4992          * @param string $toFolder
4993          * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
4994          * UIDs
4995          */
4996         function copyEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids) {
4997                 $this->moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, true);
4998         }
4999
5000         /**
5001          * moves emails from folder to folder
5002          * @param string $fromIe I-E id
5003          * @param string $fromFolder IMAP path to folder in which the email lives
5004          * @param string $toIe I-E id
5005          * @param string $toFolder
5006          * @param string $uids UIDs of emails to move, either Sugar GUIDS or IMAP
5007          * UIDs
5008          * @param bool $copy Default false
5009          * @return bool True on successful execution
5010          */
5011         function moveEmails($fromIe, $fromFolder, $toIe, $toFolder, $uids, $copy=false) {
5012                 global $app_strings;
5013                 global $current_user;
5014
5015
5016                 // same I-E server
5017                 if($fromIe == $toIe) {
5018                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to I-E");
5019                         //$exDestFolder = explode("::", $toFolder);
5020                         //preserve $this->mailbox
5021                 if (isset($this->mailbox)) {
5022                     $oldMailbox = $this->mailbox;
5023                 }
5024
5025
5026                         $this->retrieve($fromIe);
5027                     $this->mailbox = $fromFolder;
5028                         $this->connectMailserver();
5029                         $exUids = explode('::;::', $uids);
5030                         $uids = implode(",", $exUids);
5031                         // imap_mail_move accepts comma-delimited lists of UIDs
5032                         if($copy) {
5033                                 if(imap_mail_copy($this->conn, $uids, $toFolder, CP_UID)) {
5034                                         $this->mailbox = $toFolder;
5035                                         $this->connectMailserver();
5036                                         $newOverviews = imap_fetch_overview($this->conn, $uids, FT_UID);
5037                                         $this->updateOverviewCacheFile($newOverviews, 'append');
5038                                     if (isset($oldMailbox)) {
5039                         $this->mailbox = $oldMailbox;
5040                     }
5041                                         return true;
5042                                 } else {
5043                                         $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_copy() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5044                                 }
5045                         } else {
5046                                 if(imap_mail_move($this->conn, $uids, $toFolder, CP_UID)) {
5047                                         $GLOBALS['log']->info("INBOUNDEMAIL: imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5048                                         imap_expunge($this->conn); // hard deletes moved messages
5049
5050                                         // update cache on fromFolder
5051                                         $newOverviews = $this->getOverviewsFromCacheFile($uids, $fromFolder, true);
5052                                         $this->deleteCachedMessages($uids, $fromFolder);
5053
5054                                         // update cache on toFolder
5055                                         $this->checkEmailOneMailbox($toFolder, true, true);
5056                                     if (isset($oldMailbox)) {
5057                         $this->mailbox = $oldMailbox;
5058                     }
5059
5060                                         return true;
5061                                 } else {
5062                                         $GLOBALS['log']->debug("INBOUNDEMAIL: could not imap_mail_move() [ {$uids} ] to folder [ {$toFolder} ] from folder [ {$fromFolder} ]");
5063                                 }
5064                         }
5065                 } elseif($toIe == 'folder' && $fromFolder == 'sugar::Emails') {
5066                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from SugarFolder to SugarFolder");
5067                         // move from sugar folder to sugar folder
5068                         require_once("include/SugarFolders/SugarFolders.php");
5069                         $sugarFolder = new SugarFolder();
5070                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5071                         foreach($exUids as $id) {
5072                                 if($copy) {
5073                                         $sugarFolder->copyBean($fromIe, $toFolder, $id, "Emails");
5074                                 } else {
5075                                         $fromSugarFolder = new SugarFolder();
5076                                         $fromSugarFolder->retrieve($fromIe);
5077                                         $toSugarFolder = new SugarFolder();
5078                                         $toSugarFolder->retrieve($toFolder);
5079
5080                                         $email = new Email();
5081                                         $email->retrieve($id);
5082                                         $email->status = 'unread';
5083
5084                                         // when you move from My Emails to Group Folder, Assign To field for the Email should become null
5085                                         if ($fromSugarFolder->is_dynamic && $toSugarFolder->is_group) {
5086                                                 $email->assigned_user_id = "";
5087                                                 $email->save();
5088                                                 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5089                                                         $fromSugarFolder->deleteEmailFromAllFolder($id);
5090                                                         $toSugarFolder->addBean($email);
5091                                                 }
5092                                         } elseif ($fromSugarFolder->is_group && $toSugarFolder->is_dynamic) {
5093                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5094                                                 $email->assigned_user_id = $current_user->id;
5095                                                 $email->save();
5096                                         } else {
5097                                                 // If you are moving something from personal folder then delete an entry from all folder
5098                                                 if (!$fromSugarFolder->is_dynamic && !$fromSugarFolder->is_group) {
5099                                                         $fromSugarFolder->deleteEmailFromAllFolder($id);
5100                                                 } // if
5101
5102                                                 if ($fromSugarFolder->is_dynamic && !$toSugarFolder->is_dynamic && !$toSugarFolder->is_group) {
5103                                                         $email->assigned_user_id = "";
5104                                                         $toSugarFolder->addBean($email);
5105                                                 } // if
5106                                                 if (!$toSugarFolder->checkEmailExistForFolder($id)) {
5107                                                         if (!$toSugarFolder->is_dynamic) {
5108                                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5109                                                                 $toSugarFolder->addBean($email);
5110                                                         } else {
5111                                                                 $fromSugarFolder->deleteEmailFromAllFolder($id);
5112                                                                 $email->assigned_user_id = $current_user->id;
5113                                                         }
5114                                                 } else {
5115                                                         $sugarFolder->move($fromIe, $toFolder, $id);
5116                                                 } // else
5117                                                 $email->save();
5118                                         } // else
5119                                 }
5120                         }
5121
5122                         return true;
5123                 } elseif($toIe == 'folder') {
5124                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() moving email from I-E to SugarFolder");
5125                         // move to Sugar folder
5126                         require_once("include/SugarFolders/SugarFolders.php");
5127                         $sugarFolder = new SugarFolder();
5128                         $sugarFolder->retrieve($toFolder);
5129                         //Show the import form if we don't have the required info
5130                         if (!isset($_REQUEST['delete'])) {
5131                                 $json = getJSONobj();
5132                                 if ($sugarFolder->is_group) {
5133                                         $_REQUEST['showTeam'] = false;
5134                                         $_REQUEST['showAssignTo'] = false;
5135                                 }
5136                     $ret = $this->email->et->getImportForm($_REQUEST, $this->email);
5137                     $ret['move'] = true;
5138                     $ret['srcFolder'] = $fromFolder;
5139                     $ret['srcIeId']   = $fromIe;
5140                     $ret['dstFolder'] = $toFolder;
5141                     $ret['dstIeId']   = $toIe;
5142                     $out = trim($json->encode($ret, false));
5143                     echo  $out;
5144                     return true;
5145                         }
5146
5147
5148                         // import to Sugar
5149                         $this->retrieve($fromIe);
5150                         $this->mailbox = $fromFolder;
5151                         $this->connectMailserver();
5152                         // If its a group folder the team should be of the folder team
5153                         if ($sugarFolder->is_group) {
5154                                 $_REQUEST['team_id'] = $sugarFolder->team_id;
5155                                 $_REQUEST['team_set_id'] = $sugarFolder->team_set_id;
5156                         } else {
5157                                 // TODO - set team_id, team_set for new UI
5158                         } // else
5159
5160                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5161
5162                         if(!empty($sugarFolder->id)) {
5163                                 $count = 1;
5164                                 $return = array();
5165                                 $json = getJSONobj();
5166                                 foreach($exUids as $k => $uid) {
5167                                         $msgNo = $uid;
5168                                         if ($this->isPop3Protocol()) {
5169                                                 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5170                                         } else {
5171                                                 $msgNo = imap_msgno($this->conn, $uid);
5172                                         }
5173
5174                                         if(!empty($msgNo)) {
5175                                                 $importStatus = $this->importOneEmail($msgNo, $uid);
5176                                                 // add to folder
5177                                                 if($importStatus) {
5178                                                         $sugarFolder->addBean($this->email);
5179                                                         if(!$copy && isset($_REQUEST['delete']) && ($_REQUEST['delete'] == "true") && $importStatus) {
5180                                                                 $GLOBALS['log']->error("********* delete from mailserver [ {explode(",", $uids)} ]");
5181                                                                 // delete from mailserver
5182                                                                 $this->deleteMessageOnMailServer($uid);
5183                                                                 $this->deleteMessageFromCache($uid);
5184                                                         } // if
5185                                                 }
5186                                                 $return[] = $app_strings['LBL_EMAIL_MESSAGE_NO'] . " " . $count . ", " . $app_strings['LBL_STATUS'] . " " . ($importStatus ? $app_strings['LBL_EMAIL_IMPORT_SUCCESS'] : $app_strings['LBL_EMAIL_IMPORT_FAIL']);
5187                                                 $count++;
5188                                         } // if
5189                                 } // foreach
5190                                 echo $json->encode($return);
5191                                 return true;
5192                         } else {
5193                                 $GLOBALS['log']->error("********* SUGARFOLDER - failed to retrieve folder ID [ {$toFolder} ]");
5194                         }
5195                 } else {
5196                         $GLOBALS['log']->debug("********* SUGARFOLDER - moveEmails() called with no passing criteria");
5197                 }
5198
5199                 return false;
5200         }
5201
5202
5203         /**
5204          * Hard deletes an I-E account
5205          * @param string id GUID
5206          */
5207         function hardDelete($id) {
5208                 $q = "DELETE FROM inbound_email WHERE id = '{$id}'";
5209                 $r = $this->db->query($q, true);
5210         }
5211
5212         /**
5213          * Generate a unique filename for attachments based on the message id.  There are no maximum
5214          * specifications for the length of the message id, the only requirement is that it be globally unique.
5215          *
5216          * @param bool $nameOnly Whether or not the attachment count should be appended to the filename.
5217          * @return string The temp file name
5218          */
5219         function getTempFilename($nameOnly=false) {
5220
5221         $str = md5($this->compoundMessageId);
5222
5223                 if(!$nameOnly) {
5224                         $str = $str.$this->attachmentCount;
5225                         $this->attachmentCount++;
5226                 }
5227
5228                 return $str;
5229         }
5230
5231         /**
5232          * deletes and expunges emails on server
5233          * @param string $uid UID(s), comma delimited, of email(s) on server
5234          * @return bool true on success
5235          */
5236         function deleteMessageOnMailServer($uid) {
5237                 global $app_strings;
5238                 $this->connectMailserver();
5239
5240                 if(strpos($uid, $app_strings['LBL_EMAIL_DELIMITER']) !== false) {
5241                         $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uid);
5242                 } else {
5243                         $uids[] = $uid;
5244                 }
5245
5246                 $return = true;
5247
5248                 if($this->protocol == 'imap') {
5249                         $trashFolder = $this->get_stored_options("trashFolder");
5250                         if (empty($trashFolder)) {
5251                                 $trashFolder = "INBOX.Trash";
5252                         }
5253                         foreach($uids as $uid) {
5254                         if($this->moveEmails($this->id, $this->mailbox, $this->id, $trashFolder, $uid))
5255                         $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} successful.");
5256                     else {
5257                         $GLOBALS['log']->debug("INBOUNDEMAIL: MoveEmail to {$trashFolder} FAILED - trying hard delete for message: $uid");
5258                         imap_delete($this->conn, $uid, FT_UID);
5259                                         $return = true;
5260                     }
5261                 }
5262                 }
5263         else {
5264             $msgnos = array();
5265                 foreach($uids as $uid) {
5266                 $msgnos[] = $this->getCorrectMessageNoForPop3($uid);
5267                         }
5268                         $msgnos = implode(',', $msgnos);
5269                         imap_delete($this->conn, $msgnos);
5270                         $return = true;
5271                 }
5272
5273                 if(!imap_expunge($this->conn)) {
5274             $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5275             $return = false;
5276          }
5277          else
5278             $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$msgnos} ]");
5279
5280                 return $return;
5281         }
5282
5283         /**
5284          * deletes and expunges emails on server
5285          * @param string $uid UID(s), comma delimited, of email(s) on server
5286          */
5287         function deleteMessageOnMailServerForPop3($uid) {
5288                 if(imap_delete($this->conn, $uid)) {
5289             if(!imap_expunge($this->conn)) {
5290                 $GLOBALS['log']->debug("NOOP: could not expunge deleted email.");
5291                 $return = false;
5292             } else {
5293                 $GLOBALS['log']->info("INBOUNDEMAIL: hard-deleted mail with MSgno's' [ {$uid} ]");
5294             }
5295                 }
5296         }
5297
5298         /**
5299          * Checks if this is a pop3 type of an account or not
5300          * @return boolean
5301          */
5302         function isPop3Protocol() {
5303                 return ($this->protocol == 'pop3');
5304         }
5305
5306         /**
5307          * Gets the UIDL from database for the corresponding msgno
5308          * @param int messageNo of a message
5309          * @return UIDL for the message
5310          */
5311         function getUIDLForMessage($msgNo) {
5312                 $query = "SELECT message_id FROM email_cache WHERE ie_id = '{$this->id}' AND msgno = '{$msgNo}'";
5313                 $r = $this->db->query($query);
5314                 $a = $this->db->fetchByAssoc($r);
5315                 return $a['message_id'];
5316         }
5317                 /**
5318          * Get the users default IE account id
5319          *
5320          * @param User $user
5321          * @return string
5322          */
5323         function getUsersDefaultOutboundServerId($user)
5324         {
5325                 $id =  $user->getPreference($this->keyForUsersDefaultIEAccount,'Emails',$user);
5326                 //If no preference has been set, grab the default system id.
5327                 if(empty($id))
5328                 {
5329                         $oe = new OutboundEmail();
5330                         $system = $oe->getSystemMailerSettings();
5331                         $id=empty($system->id) ? '' : $system->id;
5332                 }
5333
5334                 return $id;
5335         }
5336
5337         /**
5338          * Get the users default IE account id
5339          *
5340          * @param User $user
5341          */
5342         function setUsersDefaultOutboundServerId($user,$oe_id)
5343         {
5344                 $user->setPreference($this->keyForUsersDefaultIEAccount, $oe_id, '', 'Emails');
5345         }
5346         /**
5347          * Gets the UIDL from database for the corresponding msgno
5348          * @param int messageNo of a message
5349          * @return UIDL for the message
5350          */
5351         function getMsgnoForMessageID($messageid) {
5352                 $query = "SELECT msgno FROM email_cache WHERE ie_id = '{$this->id}' AND message_id = '{$messageid}'";
5353                 $r = $this->db->query($query);
5354                 $a = $this->db->fetchByAssoc($r);
5355                 return $a['message_id'];
5356         }
5357
5358         /**
5359          * fills InboundEmail->email with an email's details
5360          * @param int uid Unique ID of email
5361          * @param bool isMsgNo flag that passed ID is msgNo, default false
5362          * @param bool setRead Sets the 'seen' flag in cache
5363          * @param bool forceRefresh Skips cache file
5364          * @return string
5365          */
5366         function setEmailForDisplay($uid, $isMsgNo=false, $setRead=false, $forceRefresh=false) {
5367
5368                 if(empty($uid)) {
5369                         $GLOBALS['log']->debug("*** ERROR: INBOUNDEMAIL trying to setEmailForDisplay() with no UID");
5370                         return 'NOOP';
5371                 }
5372
5373                 global $sugar_config;
5374                 global $app_strings;
5375
5376                 // if its a pop3 then get the UIDL and see if this file name exist or not
5377                 if ($this->isPop3Protocol()) {
5378                         // get the UIDL from database;
5379                         $cachedUIDL = md5($uid);
5380                         $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$cachedUIDL}.php";
5381                 } else {
5382                         $cache = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5383                 }
5384
5385                 if(file_exists($cache) && !$forceRefresh) {
5386                         $GLOBALS['log']->info("INBOUNDEMAIL: Using cache file for setEmailForDisplay()");
5387
5388                         include($cache); // profides $cacheFile
5389             /** @var $cacheFile array */
5390
5391             $metaOut = unserialize($cacheFile['out']);
5392                         $meta = $metaOut['meta']['email'];
5393                         $email = new Email();
5394
5395                         foreach($meta as $k => $v) {
5396                                 $email->$k = $v;
5397                         }
5398
5399                         $email->to_addrs = $meta['toaddrs'];
5400                         $email->date_sent = $meta['date_start'];
5401                         //_ppf($email,true);
5402
5403                         $this->email = $email;
5404                         $this->email->email2init();
5405                         $ret = 'cache';
5406                 } else {
5407                         $GLOBALS['log']->info("INBOUNDEMAIL: opening new connection for setEmailForDisplay()");
5408             if($this->isPop3Protocol()) {
5409                 $msgNo = $this->getCorrectMessageNoForPop3($uid);
5410             } else {
5411                                 if(empty($this->conn)) {
5412                                         $this->connectMailserver();
5413                                 }
5414                 $msgNo = ($isMsgNo) ? $uid : imap_msgno($this->conn, $uid);
5415             }
5416                         if(empty($this->conn)) {
5417                                 $status = $this->connectMailserver();
5418                                 if($status == "false") {
5419                                         $this->email = new Email();
5420                                         $this->email->name = $app_strings['LBL_EMAIL_ERROR_MAILSERVERCONNECTION'];
5421                                         $ret = 'error';
5422                                         return $ret;
5423                                 }
5424
5425                         }
5426
5427                         $this->importOneEmail($msgNo, $uid, true);
5428                         $this->email->id = '';
5429                         $this->email->new_with_id = false;
5430                         $ret = 'import';
5431                 }
5432
5433                 if($setRead) {
5434                         $this->setStatuses($uid, 'seen', 1);
5435                 }
5436
5437                 return $ret;
5438         }
5439
5440
5441         /**
5442          * Sets status for a particular attribute on the mailserver and the local cache file
5443          */
5444         function setStatuses($uid, $field, $value) {
5445                 global $sugar_config;
5446                 /** available status fields
5447                     [subject] => aaa
5448                     [from] => Some Name
5449                     [to] => Some Name
5450                     [date] => Mon, 22 Jan 2007 17:32:57 -0800
5451                     [message_id] =>
5452                     [size] => 718
5453                     [uid] => 191
5454                     [msgno] => 141
5455                     [recent] => 0
5456                     [flagged] => 0
5457                     [answered] => 0
5458                     [deleted] => 0
5459                     [seen] => 1
5460                     [draft] => 0
5461                 */
5462                 // local cache
5463                 $file = "{$this->mailbox}.imapFetchOverview.php";
5464                 $overviews = $this->getCacheValueForUIDs($this->mailbox, array($uid));
5465
5466                 if(!empty($overviews)) {
5467                         $updates = array();
5468
5469                         foreach($overviews['retArr'] as $k => $obj) {
5470                                 if($obj->imap_uid == $uid) {
5471                                         $obj->$field = $value;
5472                                         $updates[] = $obj;
5473                                 }
5474                         }
5475
5476                         if(!empty($updates)) {
5477                                 $this->setCacheValue($this->mailbox, array(), $updates);
5478                         }
5479                 }
5480         }
5481
5482         /**
5483          * Removes an email from the cache file, deletes the message from the cache too
5484          * @param string String of uids, comma delimited
5485          */
5486         function deleteMessageFromCache($uids) {
5487                 global $sugar_config;
5488                 global $app_strings;
5489
5490                 // delete message cache file and email_cache file
5491                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
5492
5493                 foreach($exUids as $uid) {
5494                         // local cache
5495                         if ($this->isPop3Protocol()) {
5496                                 $q = "DELETE FROM email_cache WHERE message_id = '{$uid}' AND ie_id = '{$this->id}'";
5497                         } else {
5498                                 $q = "DELETE FROM email_cache WHERE imap_uid = {$uid} AND ie_id = '{$this->id}'";
5499                         }
5500                         $r = $this->db->query($q);
5501                         if ($this->isPop3Protocol()) {
5502                                 $uid = md5($uid);
5503                         } // if
5504                         $msgCacheFile = "{$this->EmailCachePath}/{$this->id}/messages/{$this->mailbox}{$uid}.php";
5505                         if(file_exists($msgCacheFile)) {
5506                                 if(!unlink($msgCacheFile)) {
5507                                         $GLOBALS['log']->error("***ERROR: InboundEmail could not delete the cache file [ {$msgCacheFile} ]");
5508                                 }
5509                         }
5510                 }
5511         }
5512
5513
5514         /**
5515          * Shows one email.
5516          * @param int uid UID of email to display
5517          * @param string mbox Mailbox to look in for the message
5518          * @param bool isMsgNo Flag to assume $uid is a MessageNo, not UniqueID, default false
5519          */
5520         function displayOneEmail($uid, $mbox, $isMsgNo=false) {
5521                 require_once("include/JSON.php");
5522
5523                 global $timedate;
5524                 global $app_strings;
5525                 global $app_list_strings;
5526                 global $sugar_smarty;
5527                 global $theme;
5528                 global $current_user;
5529                 global $sugar_config;
5530
5531                 $fetchedAttributes = array(
5532                         'name',
5533                         'from_name',
5534                         'from_addr',
5535                         'date_start',
5536                         'time_start',
5537                         'message_id',
5538                 );
5539
5540                 $souEmail = array();
5541                 foreach($fetchedAttributes as $k) {
5542                         if ($k == 'date_start') {
5543                                 $this->email->$k . " " . $this->email->time_start;
5544                                 $souEmail[$k] = $this->email->$k . " " . $this->email->time_start;
5545                         } elseif ($k == 'time_start') {
5546                                 $souEmail[$k] = "";
5547                         } else {
5548                                 $souEmail[$k] = trim($this->email->$k);
5549                         }
5550                 }
5551
5552                 // if a MsgNo is passed in, convert to UID
5553                 if($isMsgNo)
5554                         $uid = imap_uid($this->conn, $uid);
5555
5556                 // meta object to allow quick retrieval for replies
5557                 $meta = array();
5558                 $meta['type'] = $this->email->type;
5559                 $meta['uid'] = $uid;
5560                 $meta['ieId'] = $this->id;
5561                 $meta['email'] = $souEmail;
5562                 $meta['mbox'] = $this->mailbox;
5563                 $ccs = '';
5564                 // imap vs pop3
5565
5566                 // self mapping
5567                 $exMbox = explode("::", $mbox);
5568
5569                 // CC section
5570                 $cc = '';
5571                 if(!empty($this->email->cc_addrs)) {
5572                         //$ccs = $this->collapseLongMailingList($this->email->cc_addrs);
5573                         $ccs = to_html($this->email->cc_addrs_names);
5574                         $cc =<<<eoq
5575                                 <tr>
5576                                         <td NOWRAP valign="top" class="displayEmailLabel">
5577                                                 {$app_strings['LBL_EMAIL_CC']}:
5578                                         </td>
5579                                         <td class="displayEmailValue">
5580                                                 {$ccs}
5581                                         </td>
5582                                 </tr>
5583 eoq;
5584                 }
5585                 $meta['cc'] = $cc;
5586                 $meta['email']['cc_addrs'] = $ccs;
5587                 // attachments
5588                 $attachments = '';
5589                 if ($mbox == "sugar::Emails") {
5590
5591                         $q = "SELECT id, filename, file_mime_type FROM notes WHERE parent_id = '{$uid}' AND deleted = 0";
5592                         $r = $this->db->query($q);
5593                         $i = 0;
5594                         while($a = $this->db->fetchByAssoc($r)) {
5595                                 $url = "index.php?entryPoint=download&type=notes&id={$a['id']}";
5596                                 $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5597                                 $i++;
5598                                 $attachments .=<<<EOQ
5599                                 <tr>
5600                                                         <td NOWRAP valign="top" class="displayEmailLabel">
5601                                                                 {$lbl}
5602                                                         </td>
5603                                                         <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5604                                                                 <a href="{$url}">{$a['filename']}</a>
5605                                                         </td>
5606                                                 </tr>
5607 EOQ;
5608                                 $this->email->cid2Link($a['id'], $a['file_mime_type']);
5609                     } // while
5610
5611
5612                 } else {
5613
5614                         if($this->attachmentCount > 0) {
5615                                 $theCount = $this->attachmentCount;
5616
5617                                 for($i=0; $i<$theCount; $i++) {
5618                                         $lbl = ($i == 0) ? $app_strings['LBL_EMAIL_ATTACHMENTS'].":" : '';
5619                                         $name = $this->getTempFilename(true).$i;
5620                                         $tempName = urlencode($this->tempAttachment[$name]);
5621
5622                                         $url = "index.php?entryPoint=download&type=temp&isTempFile=true&ieId={$this->id}&tempName={$tempName}&id={$name}";
5623
5624                                         $attachments .=<<<eoq
5625                                                 <tr>
5626                                                         <td NOWRAP valign="top" class="displayEmailLabel">
5627                                                                 {$lbl}
5628                                                         </td>
5629                                                         <td NOWRAP valign="top" colspan="2" class="displayEmailValue">
5630                                                                 <a href="{$url}">{$this->tempAttachment[$name]}</a>
5631                                                         </td>
5632                                                 </tr>
5633 eoq;
5634                                 } // for
5635                         } // if
5636                 } // else
5637                 $meta['email']['attachments'] = $attachments;
5638
5639                 // toasddrs
5640                 $meta['email']['toaddrs'] = $this->collapseLongMailingList($this->email->to_addrs);
5641                 $meta['email']['cc_addrs'] = $ccs;
5642
5643                 // body
5644                 $description = (empty($this->email->description_html)) ? nl2br($this->email->description) : $this->email->description_html;
5645                 $meta['email']['description'] = $description;
5646
5647                 // meta-metadata
5648                 $meta['is_sugarEmail'] = ($exMbox[0] == 'sugar') ? true : false;
5649
5650                 if(!$meta['is_sugarEmail']) {
5651                         if($this->isAutoImport) {
5652                                 $meta['is_sugarEmail'] = true;
5653                         }
5654                 } else {
5655                         if( $this->email->status != 'sent' ){
5656                                 // mark SugarEmail read
5657                                 $q = "UPDATE emails SET status = 'read' WHERE id = '{$uid}'";
5658                                 $r = $this->db->query($q);
5659                         }
5660                 }
5661
5662                 $return = array();
5663         $meta['email']['name'] = to_html($this->email->name);
5664         $meta['email']['from_addr'] = ( !empty($this->email->from_addr_name) ) ? to_html($this->email->from_addr_name) : to_html($this->email->from_addr);
5665         $meta['email']['toaddrs'] = ( !empty($this->email->to_addrs_names) ) ? to_html($this->email->to_addrs_names) : to_html($this->email->to_addrs);
5666         $meta['email']['cc_addrs'] = to_html($this->email->cc_addrs_names);
5667         $meta['email']['reply_to_addr'] = to_html($this->email->reply_to_addr);
5668                 $return['meta'] = $meta;
5669
5670                 return $return;
5671         }
5672
5673         /**
5674          * Takes a long list of email addresses from a To or CC field and shows the first 3, the rest hidden
5675          * @param string emails
5676          * @return string
5677          */
5678         function collapseLongMailingList($emails) {
5679                 global $app_strings;
5680
5681                 $ex = explode(",", $emails);
5682                 $i = 0;
5683                 $j = 0;
5684
5685                 if(count($ex) > 3) {
5686                         $emails = "";
5687                         $emailsHidden = "";
5688
5689                         foreach($ex as $email) {
5690                                 if($i < 2) {
5691                                         if(!empty($emails)) {
5692                                                 $emails .= ", ";
5693                                         }
5694                                         $emails .= trim($email);
5695                                 } else {
5696                                         if(!empty($emailsHidden)) {
5697                                                 $emailsHidden .= ", ";
5698                                         }
5699                                         $emailsHidden .= trim($email);
5700                                         $j++;
5701                                 }
5702                                 $i++;
5703                         }
5704
5705                         if(!empty($emailsHidden)) {
5706                                 $email2 = $emails;
5707                                 $emails = "<span onclick='javascript:SUGAR.email2.detailView.showFullEmailList(this);' style='cursor:pointer;'>{$emails} [...{$j} {$app_strings['LBL_MORE']}]</span>";
5708                                 $emailsHidden = "<span onclick='javascript:SUGAR.email2.detailView.showCroppedEmailList(this)' style='cursor:pointer; display:none;'>{$email2}, {$emailsHidden} [ {$app_strings['LBL_LESS']} ]</span>";
5709                         }
5710
5711                         $emails .= $emailsHidden;
5712                 }
5713
5714                 return $emails;
5715         }
5716
5717
5718         /**
5719          * Sorts IMAP's imap_fetch_overview() results
5720          * @param array $arr Array of standard objects
5721          * @param string $sort Column to sort by
5722          * @param string direction Direction to sort by (asc/desc)
5723          * @return array Sorted array of obj.
5724          */
5725         function sortFetchedOverview($arr, $sort=4, $direction='DESC', $forceSeen=false) {
5726                 global $current_user;
5727
5728                 $sortPrefs = $current_user->getPreference('folderSortOrder', 'Emails');
5729                 if(!empty($sortPrefs))
5730                         $listPrefs = $sortPrefs;
5731                 else
5732                         $listPrefs = array();
5733
5734                 if(isset($listPrefs[$this->id][$this->mailbox])) {
5735                         $currentNode = $listPrefs[$this->id][$this->mailbox];
5736                 }
5737
5738                 if(isset($currentNode['current']) && !empty($currentNode['current'])) {
5739                         $sort = $currentNode['current']['sort'];
5740                         $direction = $currentNode['current']['direction'];
5741                 }
5742
5743                 // sort defaults
5744                 if(empty($sort)) {
5745                         $sort = $this->defaultSort;//4;
5746                         $direction = $this->defaultDirection; //'DESC';
5747                 } elseif(!is_numeric($sort)) {
5748                         // handle bad sort index
5749                         $sort = $this->defaultSort;
5750                 } else {
5751                         // translate numeric index to human readable
5752             $sort = $this->hrSort[$sort];
5753                 }
5754                 if(empty($direction)) {
5755                         $direction = 'DESC';
5756                 }
5757
5758
5759
5760                 $retArr = array();
5761                 $sorts = array();
5762
5763                 foreach($arr as $k => $overview) {
5764                         $sorts['flagged'][$k] = $overview->flagged;
5765                         $sorts['status'][$k] = $overview->answered;
5766                         $sorts['from'][$k] = str_replace('"', "", $this->handleMimeHeaderDecode($overview->from));
5767                         $sorts['subj'][$k] = $this->handleMimeHeaderDecode(quoted_printable_decode($overview->subject));
5768                         $sorts['date'][$k] = $overview->date;
5769                 }
5770
5771                 // sort by column
5772                 natcasesort($sorts[$sort]);
5773                 //_ppd($sorts[$sort]);
5774                 // direction
5775                 if(strtolower($direction) == 'desc') {
5776                         $revSorts = array();
5777                         $keys = array_reverse(array_keys($sorts[$sort]));
5778 //                      _pp("count keys in DESC: ".count($keys));
5779 //                      _pp("count elements in sort[sort]: ".count($sorts[$sort]));
5780
5781                         for($i=0; $i<count($keys); $i++) {
5782                                 $v = $keys[$i];
5783                                 $revSorts[$v] = $sorts[$sort][$v];
5784                         }
5785
5786                         //_pp("count post-sort: ".count($revSorts));
5787                         $sorts[$sort] = $revSorts;
5788                 }
5789         $timedate = TimeDate::getInstance();
5790                 foreach($sorts[$sort] as $k2 => $overview2) {
5791                     $arr[$k2]->date = $timedate->fromString($arr[$k2]->date)->asDb();
5792                         $retArr[] = $arr[$k2];
5793                 }
5794                 //_pp("final count: ".count($retArr));
5795
5796                 $finalReturn = array();
5797                 $finalReturn['retArr'] = $retArr;
5798                 $finalReturn['sortBy'] = $sort;
5799                 $finalReturn['direction'] = $direction;
5800                 return $finalReturn;
5801         }
5802
5803
5804         function setReadFlagOnFolderCache($mbox, $uid) {
5805                 global $sugar_config;
5806
5807                 $this->mailbox = $mbox;
5808
5809                 // cache
5810                 if($this->validCacheExists($this->mailbox)) {
5811                         $ret = $this->getCacheValue($this->mailbox);
5812
5813                         $updates = array();
5814
5815                         foreach($ret as $k => $v) {
5816                                 if($v->imap_uid == $uid) {
5817                                         $v->seen = 1;
5818                                         $updates[] = $v;
5819                                         break;
5820                                 }
5821                         }
5822
5823                         $this->setCacheValue($this->mailbox, array(), $updates);
5824                 }
5825         }
5826
5827         /**
5828          * Returns a list of emails in a mailbox.
5829          * @param string mbox Name of mailbox using dot notation paths to display
5830          * @param string $forceRefresh Flag to use cache or not
5831          */
5832         function displayFolderContents($mbox, $forceRefresh='false', $page) {
5833                 global $current_user;
5834
5835                 $delimiter = $this->get_stored_options('folderDelimiter');
5836                 if ($delimiter) {
5837                         $mbox = str_replace('.', $delimiter, $mbox);
5838                 }
5839
5840                 $this->mailbox = $mbox;
5841
5842                 // jchi #9424, get sort and direction from user preference
5843                 $sort = 'date';
5844                 $direction = 'desc';
5845                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
5846                 if(!empty($sortSerial) && !empty($_REQUEST['ieId']) && !empty($_REQUEST['mbox'])) {
5847                         $sortArray = unserialize($sortSerial);
5848                         $sort = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['sort'];
5849                         $direction = $sortArray[$_REQUEST['ieId']][$_REQUEST['mbox']]['current']['direction'];
5850                 }
5851                 //end
5852
5853                 // save sort order
5854                 if(!empty($_REQUEST['sort']) && !empty($_REQUEST['dir'])) {
5855                         $this->email->et->saveListViewSortOrder($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['sort'], $_REQUEST['dir']);
5856                         $sort = $_REQUEST['sort'];
5857                         $direction = $_REQUEST['dir'];
5858                 } else {
5859                         $_REQUEST['sort'] = '';
5860                         $_REQUEST['dir'] = '';
5861                 }
5862
5863                 // cache
5864                 $ret = array();
5865                 $cacheUsed = false;
5866                 if($forceRefresh == 'false' && $this->validCacheExists($this->mailbox)) {
5867                         $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
5868
5869                         // cn: default to a low number until user specifies otherwise
5870                         if(empty($emailSettings['showNumInList'])) {
5871                                 $emailSettings['showNumInList'] = 20;
5872                         }
5873
5874                         $ret = $this->getCacheValue($this->mailbox, $emailSettings['showNumInList'], $page, $sort, $direction);
5875                         $cacheUsed = true;
5876                 }
5877
5878                 $out = $this->displayFetchedSortedListXML($ret, $mbox);
5879
5880                 $metadata = array();
5881                 $metadata['mbox'] = $mbox;
5882                 $metadata['ieId'] = $this->id;
5883                 $metadata['name'] = $this->name;
5884                 $metadata['fromCache'] = $cacheUsed ? 1 : 0;
5885                 $metadata['out'] = $out;
5886
5887                 return $metadata;
5888         }
5889
5890         /**
5891          * For a group email account, create subscriptions for all users associated with the
5892          * team assigned to the account.
5893          *
5894          */
5895         function createUserSubscriptionsForGroupAccount()
5896         {
5897             $team = new Team();
5898             $team->retrieve($this->team_id);
5899             $usersList = $team->get_team_members(true);
5900             foreach($usersList as $userObject)
5901             {
5902                 $previousSubscriptions = unserialize(base64_decode($userObject->getPreference('showFolders', 'Emails',$userObject)));
5903                 if($previousSubscriptions === FALSE)
5904                     $previousSubscriptions = array();
5905
5906                 $previousSubscriptions[] = $this->id;
5907
5908                 $encodedSubs = base64_encode(serialize($previousSubscriptions));
5909                 $userObject->setPreference('showFolders',$encodedSubs , '', 'Emails');
5910                 $userObject->savePreferencesToDB();
5911             }
5912     }
5913         /**
5914     * Create a sugar folder for this inbound email account
5915     * if the Enable Auto Import option is selected
5916     *
5917     * @return String Id of the sugar folder created.
5918     */
5919         function createAutoImportSugarFolder()
5920         {
5921             global $current_user;
5922             $guid = create_guid();
5923             $GLOBALS['log']->debug("Creating Sugar Folder for IE with id $guid");
5924             $folder = new SugarFolder();
5925             $folder->id = $guid;
5926             $folder->new_with_id = TRUE;
5927             $folder->name = $this->name;
5928             $folder->has_child = 0;
5929             $folder->is_group = 1;
5930             $folder->assign_to_id = $current_user->id;
5931             $folder->parent_folder = "";
5932
5933
5934             //If this inbound email is marked as inactive, don't add subscriptions.
5935             $addSubscriptions = ($this->status == 'Inactive' || $this->mailbox_type == 'bounce') ? FALSE : TRUE;
5936             $folder->save($addSubscriptions);
5937
5938             return $guid;
5939         }
5940
5941         function validCacheExists($mbox) {
5942                 $q = "SELECT count(*) c FROM email_cache WHERE ie_id = '{$this->id}'";
5943                 $r = $this->db->query($q);
5944                 $a = $this->db->fetchByAssoc($r);
5945                 $count = $a['c'];
5946
5947                 if($count > 0) {
5948                         return true;
5949                 }
5950
5951                 return false;
5952         }
5953
5954
5955
5956
5957         function displayFetchedSortedListXML($ret, $mbox) {
5958
5959                 global $timedate;
5960                 global $current_user;
5961                 global $sugar_config;
5962
5963                 if(empty($ret['retArr'])) {
5964                     return array();
5965                 }
5966
5967                 $tPref = $current_user->getUserDateTimePreferences();
5968
5969                 $return = array();
5970
5971                 foreach($ret['retArr'] as $msg) {
5972
5973                         $flagged        = ($msg->flagged == 0) ? "" : $this->iconFlagged;
5974                         $status         = ($msg->deleted) ? $this->iconDeleted : "";
5975                         $status         = ($msg->draft == 0) ? $status : $this->iconDraft;
5976                         $status         = ($msg->answered == 0) ? $status : $this->iconAnswered;
5977                         $from           = $this->handleMimeHeaderDecode($msg->from);
5978                         $subject        = $this->handleMimeHeaderDecode($msg->subject);
5979                         //$date         = date($tPref['date']." ".$tPref['time'], $msg->date);
5980                         $date           = $timedate->to_display_date_time($msg->date);
5981                         //$date         = date($tPref['date'], $this->getUnixHeaderDate($msg->date));
5982
5983                         $temp = array();
5984                         $temp['flagged'] = $flagged;
5985                         $temp['status'] = $status;
5986                         $temp['from']   = to_html($from);
5987                         $temp['subject'] = $subject;
5988                         $temp['date']   = $date;
5989                         $temp['uid'] = $msg->uid; // either from an imap_search() or massaged cache value
5990                         $temp['mbox'] = $this->mailbox;
5991                         $temp['ieId'] = $this->id;
5992                         $temp['site_url'] = $sugar_config['site_url'];
5993                         $temp['seen'] = $msg->seen;
5994                         $temp['type'] = (isset($msg->type)) ? $msg->type: 'remote';
5995                         $temp['to_addrs'] = to_html($msg->to);
5996                         $temp['hasAttach'] = '0';
5997
5998                         $return[] = $temp;
5999                 }
6000
6001                 return $return;
6002         }
6003
6004
6005
6006         /**
6007          * retrieves the mailboxes for a given account in the following format
6008          * Array(
6009             [INBOX] => Array
6010                 (
6011                     [Bugs] => Bugs
6012                     [Builder] => Builder
6013                     [DEBUG] => Array
6014                         (
6015                             [out] => out
6016                             [test] => test
6017                         )
6018                 )
6019          * @param bool $justRaw Default false
6020          * @return array
6021          */
6022         function getMailboxes($justRaw=false) {
6023                 if($justRaw == true) {
6024                         return $this->mailboxarray;
6025                 } // if
6026
6027                 return $this->generateMultiDimArrayFromFlatArray($this->mailboxarray, $this->retrieveDelimiter());
6028                 /*
6029                 $serviceString = $this->getConnectString('', '', false);
6030
6031                 if(strpos($serviceString, 'pop3')) {
6032                         $obj = new temp();
6033                         $obj->name = $serviceString."INBOX";
6034                         $boxes = array("INBOX" => $obj);
6035                 } else {
6036                         $boxes = imap_getmailboxes($this->conn, $serviceString, "*");
6037                 }
6038                 $raw = array();
6039                 //_ppd($boxes);
6040                 $delimiter = '.';
6041                 // clean MBOX path names
6042                 foreach($boxes as $k => $mbox) {
6043                         $raw[] = str_replace($serviceString, "", $mbox->name);
6044                         if ($mbox->delimiter) {
6045                                 $delimiter = $mbox->delimiter;
6046                         }
6047                 }
6048                 $storedOptions = unserialize(base64_decode($this->stored_options));
6049                 $storedOptions['folderDelimiter'] = $delimiter;
6050                 $this->stored_options = base64_encode(serialize($storedOptions));
6051         $this->save();
6052
6053                 sort($raw);
6054                 //_ppd($raw);
6055
6056                 // used by $this->search()
6057                 if($justRaw == true) {
6058                         return $raw;
6059                 }
6060
6061
6062                 // generate a multi-dimensional array to iterate through
6063                 $ret = array();
6064                 foreach($raw as $mbox) {
6065                         $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6066                 }
6067                 //_ppd($ret);
6068                 return $ret;
6069                 */
6070         }
6071
6072         function getMailBoxesForGroupAccount() {
6073                 $mailboxes = $this->generateMultiDimArrayFromFlatArray(explode(",", $this->mailbox), $this->retrieveDelimiter());
6074                 $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6075                 $mailboxesArray = $this->filterMailBoxFromRaw(explode(",", $this->mailbox), $mailboxesArray);
6076                 $this->saveMailBoxFolders($mailboxesArray);
6077                 /*
6078                 if ($this->mailbox != $this->$email_user) {
6079                         $mailboxes = $this->sortMailboxes($this->mailbox, $this->retrieveDelimiter());
6080                         $mailboxesArray = $this->generateFlatArrayFromMultiDimArray($mailboxes, $this->retrieveDelimiter());
6081                         $this->saveMailBoxFolders($mailboxesArray);
6082                         // save mailbox value of an inbound email account to email user
6083                         $this->saveMailBoxValueOfInboundEmail();
6084                 } else {
6085                         $mailboxes = $this->getMailboxes();
6086                 }
6087                 */
6088                 return $mailboxes;
6089         } // fn
6090
6091         function saveMailBoxFolders($value) {
6092                 if (is_array($value)) {
6093                         $value = implode(",", $value);
6094                 }
6095                 $this->mailboxarray = explode(",", $value);
6096                 $value = $this->db->quoted($value);
6097                 $query = "update inbound_email set mailbox = $value where id ='{$this->id}'";
6098                 $this->db->query($query);
6099         }
6100
6101         function insertMailBoxFolders($value) {
6102                 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6103                 $r = $this->db->query($query);
6104                 $a = $this->db->fetchByAssoc($r);
6105                 if (empty($a['value'])) {
6106                         if (is_array($value)) {
6107                                 $value = implode(",", $value);
6108                         }
6109                         $this->mailboxarray = explode(",", $value);
6110                         $value = $this->db->quoted($value);
6111
6112                         $query = "INSERT INTO config VALUES('InboundEmail', '{$this->id}', $value)";
6113                         $this->db->query($query);
6114                 } // if
6115         }
6116
6117         function saveMailBoxValueOfInboundEmail() {
6118                 $query = "update Inbound_email set mailbox = '{$this->email_user}'";
6119                 $this->db->query($query);
6120         }
6121
6122         function retrieveMailBoxFolders() {
6123                 $this->mailboxarray = explode(",", $this->mailbox);
6124                 /*
6125                 $query = "select value from config where category='InboundEmail' and name='{$this->id}'";
6126                 $r = $this->db->query($query);
6127                 $a = $this->db->fetchByAssoc($r);
6128                 $this->mailboxarray = explode(",", $a['value']);
6129                 */
6130         } // fn
6131
6132
6133         function retrieveDelimiter() {
6134                 $delimiter = $this->get_stored_options('folderDelimiter');
6135         if (!$delimiter) {
6136                 $delimiter = '.';
6137         }
6138                 return $delimiter;
6139         } // fn
6140
6141         function generateFlatArrayFromMultiDimArray($arraymbox, $delimiter) {
6142                 $ret = array();
6143                 foreach($arraymbox as $key => $value) {
6144                         $this->generateArrayData($key, $value, $ret, $delimiter);
6145                 } // foreach
6146                 return $ret;
6147
6148         } // fn
6149
6150         function generateMultiDimArrayFromFlatArray($raw, $delimiter) {
6151                 // generate a multi-dimensional array to iterate through
6152                 $ret = array();
6153                 foreach($raw as $mbox) {
6154                         $ret = $this->sortMailboxes($mbox, $ret, $delimiter);
6155                 }
6156                 return $ret;
6157
6158         } // fn
6159
6160         function generateArrayData($key, $arraymbox, &$ret, $delimiter) {
6161                 $ret [] = $key;
6162                 if (is_array($arraymbox)) {
6163                         foreach($arraymbox as $mboxKey => $value) {
6164                                 $newKey = $key . $delimiter . $mboxKey;
6165                                 $this->generateArrayData($newKey, $value, $ret, $delimiter);
6166                         } // foreach
6167                 } // if
6168         }
6169
6170         /**
6171          * sorts the folders in a mailbox in a multi-dimensional array
6172          * @param string $MBOX
6173          * @param array $ret
6174          * @return array
6175          */
6176         function sortMailboxes($mbox, $ret, $delimeter = ".") {
6177                 if(strpos($mbox, $delimeter)) {
6178                         $node = substr($mbox, 0, strpos($mbox, $delimeter));
6179                         $nodeAfter = substr($mbox, strpos($mbox, $node) + strlen($node) + 1, strlen($mbox));
6180
6181                         if(!isset($ret[$node])) {
6182                                 $ret[$node] = array();
6183                         } elseif(isset($ret[$node]) && !is_array($ret[$node])) {
6184                                 $ret[$node] = array();
6185                         }
6186                         $ret[$node] = $this->sortMailboxes($nodeAfter, $ret[$node], $delimeter);
6187                 } else {
6188                         $ret[$mbox] = $mbox;
6189                 }
6190
6191                 return $ret;
6192         }
6193
6194         /**
6195          * parses Sugar's storage method for imap server service strings
6196          * @return string
6197          */
6198         function getServiceString() {
6199                 $service = '';
6200                 $exServ = explode('::', $this->service);
6201
6202                 foreach($exServ as $v) {
6203                         if(!empty($v) && ($v != 'imap' && $v !='pop3')) {
6204                                 $service .= '/'.$v;
6205                         }
6206                 }
6207                 return $service;
6208         }
6209
6210 } // end class definition
6211
6212
6213 /**
6214  * Simple class to mirror the passed object from an imap_fetch_overview() call
6215  */
6216 class Overview {
6217         var $subject;
6218         var $from;
6219         var $fromaddr;
6220         var $to;
6221         var $toaddr;
6222         var $date;
6223         var $message_id;
6224         var $size;
6225         var $uid;
6226         var $msgno;
6227         var $recent;
6228         var $flagged;
6229         var $answered;
6230         var $deleted;
6231         var $seen;
6232         var $draft;
6233         var $indices; /* = array(
6234
6235                         array(
6236                                 'name'                  => 'mail_date',
6237                                 'type'                  => 'index',
6238                                 'fields'                => array(
6239                                         'mbox',
6240                                         'senddate',
6241                                 )
6242                         ),
6243                         array(
6244                                 'name'                  => 'mail_from',
6245                                 'type'                  => 'index',
6246                                 'fields'                => array(
6247                                         'mbox',
6248                                         'fromaddr',
6249                                 )
6250                         ),
6251                         array(
6252                                 'name'                  => 'mail_subj',
6253                                 'type'                  => 'index',
6254                                 'fields'                => array(
6255                                         'mbox',
6256                                         'subject',
6257                                 )
6258                         ),
6259                 );
6260         */
6261         var $fieldDefs;/* = array(
6262                         'mbox' => array(
6263                                 'name'          => 'mbox',
6264                                 'type'          => 'varchar',
6265                                 'len'           => 60,
6266                                 'required'      => true,
6267                         ),
6268                         'subject' => array(
6269                                 'name'          => 'subject',
6270                                 'type'          => 'varchar',
6271                                 'len'           => 100,
6272                                 'required'      => false,
6273                         ),
6274                         'fromaddr' => array(
6275                                 'name'          => 'fromaddr',
6276                                 'type'          => 'varchar',
6277                                 'len'           => 100,
6278                                 'required'      => true,
6279                         ),
6280                         'toaddr' => array(
6281                                 'name'          => 'toaddr',
6282                                 'type'          => 'varchar',
6283                                 'len'           => 100,
6284                                 'required'      => true,
6285                         ),
6286                         'senddate' => array(
6287                                 'name'          => 'senddate',
6288                                 'type'          => 'datetime',
6289                                 'required'      => true,
6290                         ),
6291                         'message_id' => array(
6292                                 'name'          => 'message_id',
6293                                 'type'          => 'varchar',
6294                                 'len'           => 255,
6295                                 'required'      => false,
6296                         ),
6297                         'mailsize' => array(
6298                                 'name'          => 'mailsize',
6299                                 'type'          => 'uint',
6300                                 'len'           => 16,
6301                                 'required'      => true,
6302                         ),
6303                         'uid' => array(
6304                                 'name'          => 'uid',
6305                                 'type'          => 'uint',
6306                                 'len'           => 32,
6307                                 'required'      => true,
6308                         ),
6309                         'msgno' => array(
6310                                 'name'          => 'msgno',
6311                                 'type'          => 'uint',
6312                                 'len'           => 32,
6313                                 'required'      => false,
6314                         ),
6315                         'recent' => array(
6316                                 'name'          => 'recent',
6317                                 'type'          => 'tinyint',
6318                                 'len'           => 1,
6319                                 'required'      => true,
6320                         ),
6321                         'flagged' => array(
6322                                 'name'          => 'flagged',
6323                                 'type'          => 'tinyint',
6324                                 'len'           => 1,
6325                                 'required'      => true,
6326                         ),
6327                         'answered' => array(
6328                                 'name'          => 'answered',
6329                                 'type'          => 'tinyint',
6330                                 'len'           => 1,
6331                                 'required'      => true,
6332                         ),
6333                         'deleted' => array(
6334                                 'name'          => 'deleted',
6335                                 'type'          => 'tinyint',
6336                                 'len'           => 1,
6337                                 'required'      => true,
6338                         ),
6339                         'seen' => array(
6340                                 'name'          => 'seen',
6341                                 'type'          => 'tinyint',
6342                                 'len'           => 1,
6343                                 'required'      => true,
6344                         ),
6345                         'draft' => array(
6346                                 'name'          => 'draft',
6347                                 'type'          => 'tinyint',
6348                                 'len'           => 1,
6349                                 'required'      => true,
6350                         ),
6351                 );
6352         */
6353         function Overview() {
6354                 global $dictionary;
6355
6356                 if(!isset($dictionary['email_cache']) || empty($dictionary['email_cache'])) {
6357                         if(file_exists('custom/metadata/email_cacheMetaData.php')) {
6358                            include('custom/metadata/email_cacheMetaData.php');
6359                         } else {
6360                            include('metadata/email_cacheMetaData.php');
6361                         }
6362                 }
6363
6364                 $this->fieldDefs = $dictionary['email_cache']['fields'];
6365                 $this->indices = $dictionary['email_cache']['indices'];
6366         }
6367 }