]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Emails/EmailUI.php
Release 6.5.0
[Github/sugarcrm.git] / modules / Emails / EmailUI.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-2012 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:
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42  * Reserved. Contributor(s): ______________________________________..
43  *********************************************************************************/
44
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
47 require_once("include/SugarFolders/SugarFolders.php");
48
49
50
51 class EmailUI {
52         var $db;
53         var $folder; // place holder for SugarFolder object
54         var $folderStates = array(); // array of folderPath names and their states (1/0)
55         var $smarty;
56         var $addressSeparators = array(";", ",");
57         var $rolloverStyle = "<style>div#rollover {position: relative;float: left;margin: none;text-decoration: none;}div#rollover a:hover {padding: 0;}div#rollover a span {display: none;}div#rollover a:hover span {text-decoration: none;display: block;width: 250px;margin-top: 5px;margin-left: 5px;position: absolute;padding: 10px;color: #333; border: 1px solid #ccc; background-color: #fff; font-size: 12px;z-index: 1000;}</style>\n";
58         var $groupCss = "<span class='groupInbox'>";
59         var $cacheTimeouts = array(
60                 'messages'              => 86400,       // 24 hours
61                 'folders'               => 300,         // 5 mins
62                 'attachments'   => 86400,       // 24 hours
63         );
64         var $userCacheDir = '';
65         var $coreDynamicFolderQuery = "SELECT emails.id polymorphic_id, 'Emails' polymorphic_module FROM emails
66                                                                    JOIN emails_text on emails.id = emails_text.email_id
67                                    WHERE (type = '::TYPE::' OR status = '::STATUS::') AND assigned_user_id = '::USER_ID::' AND emails.deleted = '0'";
68
69         /**
70          * Sole constructor
71          */
72         function EmailUI() {
73                 global $sugar_config;
74                 global $current_user;
75
76                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
77
78                 if(!empty($folderStateSerial)) {
79                         $this->folderStates = unserialize($folderStateSerial);
80                 }
81
82                 $this->smarty = new Sugar_Smarty();
83                 $this->folder = new SugarFolder();
84                 $this->userCacheDir = sugar_cached("modules/Emails/{$current_user->id}");
85                 $this->db = DBManagerFactory::getInstance();
86         }
87
88
89         ///////////////////////////////////////////////////////////////////////////
90         ////    CORE
91         /**
92          * Renders the frame for emails
93          */
94         function displayEmailFrame() {
95
96                 require_once("include/OutboundEmail/OutboundEmail.php");
97
98                 global $app_strings, $app_list_strings;
99                 global $mod_strings;
100                 global $sugar_config;
101                 global $current_user;
102                 global $locale;
103                 global $timedate;
104                 global $theme;
105                 global $sugar_version;
106                 global $sugar_flavor;
107                 global $current_language;
108                 global $server_unique_key;
109
110                 $this->preflightUserCache();
111                 $ie = new InboundEmail();
112
113                 // focus listView
114                 $list = array(
115                         'mbox' => 'Home',
116                         'ieId' => '',
117                         'name' => 'Home',
118                         'unreadChecked' => 0,
119                         'out' => array(),
120                 );
121
122                 $this->_generateComposeConfigData('email_compose');
123
124
125         //Check quick create module access
126         $QCAvailableModules = $this->_loadQuickCreateModules();
127
128         //Get the quickSearch js needed for assigned user id on Search Tab
129         require_once('include/QuickSearchDefaults.php');
130         $qsd = QuickSearchDefaults::getQuickSearchDefaults();
131         $qsd->setFormName('advancedSearchForm');
132         $quicksearchAssignedUser = "if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}";
133         $quicksearchAssignedUser .= "sqs_objects['advancedSearchForm_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
134         $qsd->setFormName('Distribute');
135         $quicksearchAssignedUser .= "sqs_objects['Distribute_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
136         $this->smarty->assign('quickSearchForAssignedUser', $quicksearchAssignedUser);
137
138
139                 ///////////////////////////////////////////////////////////////////////
140                 ////    BASIC ASSIGNS
141                 $this->smarty->assign("currentUserId",$current_user->id);
142                 $this->smarty->assign("CURRENT_USER_EMAIL",$current_user->email1);
143         $this->smarty->assign("currentUserName",$current_user->name);
144                 $this->smarty->assign('yuiPath', 'modules/Emails/javascript/yui-ext/');
145                 $this->smarty->assign('app_strings', $app_strings);
146                 $this->smarty->assign('mod_strings', $mod_strings);
147                 $this->smarty->assign('theme', $theme);
148                 $this->smarty->assign('sugar_config', $sugar_config);
149                 $this->smarty->assign('is_admin', $current_user->is_admin);
150                 $this->smarty->assign('sugar_version', $sugar_version);
151                 $this->smarty->assign('sugar_flavor', $sugar_flavor);
152                 $this->smarty->assign('current_language', $current_language);
153                 $this->smarty->assign('server_unique_key', $server_unique_key);
154                 $this->smarty->assign('qcModules', json_encode($QCAvailableModules));
155                 $extAllDebugValue = "ext-all.js";
156                 $this->smarty->assign('extFileName', $extAllDebugValue);
157
158                 // settings: general
159                 $e2UserPreferences = $this->getUserPrefsJS();
160                 $emailSettings = $e2UserPreferences['emailSettings'];
161
162                 ///////////////////////////////////////////////////////////////////////
163                 ////    USER SETTINGS
164                 // settings: accounts
165
166                 $cuDatePref = $current_user->getUserDateTimePreferences();
167                 $this->smarty->assign('dateFormat', $cuDatePref['date']);
168                 $this->smarty->assign('dateFormatExample', str_replace(array("Y", "m", "d"), array("yyyy", "mm", "dd"), $cuDatePref['date']));
169                 $this->smarty->assign('calFormat', $timedate->get_cal_date_format());
170         $this->smarty->assign('TIME_FORMAT', $timedate->get_user_time_format());
171
172                 $ieAccounts = $ie->retrieveByGroupId($current_user->id);
173                 $ieAccountsOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
174
175                 foreach($ieAccounts as $k => $v) {
176                         $disabled = (!$v->is_personal) ? "DISABLED" : "";
177                         $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
178                         $ieAccountsOptions .= "<option value='{$v->id}' $disabled>{$group}{$v->name}</option>\n";
179                 }
180
181                 $this->smarty->assign('ieAccounts', $ieAccountsOptions);
182                 $this->smarty->assign('rollover', $this->rolloverStyle);
183
184                 $protocol = filterInboundEmailPopSelection($app_list_strings['dom_email_server_type']);
185                 $this->smarty->assign('PROTOCOL', get_select_options_with_id($protocol, ''));
186                 $this->smarty->assign('MAIL_SSL_OPTIONS', get_select_options_with_id($app_list_strings['email_settings_for_ssl'], ''));
187                 $this->smarty->assign('ie_mod_strings', return_module_language($current_language, 'InboundEmail'));
188
189                 $charsetSelectedValue = isset($emailSettings['defaultOutboundCharset']) ? $emailSettings['defaultOutboundCharset'] : false;
190                 if (!$charsetSelectedValue) {
191                         $charsetSelectedValue = $current_user->getPreference('default_export_charset', 'global');
192                         if (!$charsetSelectedValue) {
193                                 $charsetSelectedValue = $locale->getPrecedentPreference('default_email_charset');
194                         }
195                 }
196                 $charset = array(
197                         'options' => $locale->getCharsetSelect(),
198                         'selected' => $charsetSelectedValue,
199                 );
200                 $this->smarty->assign('charset', $charset);
201
202                 $emailCheckInterval = array('options' => $app_strings['LBL_EMAIL_CHECK_INTERVAL_DOM'], 'selected' => $emailSettings['emailCheckInterval']);
203                 $this->smarty->assign('emailCheckInterval', $emailCheckInterval);
204                 $this->smarty->assign('attachmentsSearchOptions', $app_list_strings['checkbox_dom']);
205                 $this->smarty->assign('sendPlainTextChecked', ($emailSettings['sendPlainText'] == 1) ? 'CHECKED' : '');
206                 $this->smarty->assign('showNumInList', get_select_options_with_id($app_list_strings['email_settings_num_dom'], $emailSettings['showNumInList']));
207
208                 ////    END USER SETTINGS
209                 ///////////////////////////////////////////////////////////////////////
210
211                 ///////////////////////////////////////////////////////////////////////
212                 ////    SIGNATURES
213                 $prependSignature = ($current_user->getPreference('signature_prepend')) ? 'true' : 'false';
214                 $defsigID = $current_user->getPreference('signature_default');
215                 $this->smarty->assign('signatures', $current_user->getSignatures(false, $defsigID));
216                 $this->smarty->assign('signaturesSettings', $current_user->getSignatures(false, $defsigID, false));
217                 $signatureButtons = $current_user->getSignatureButtons('SUGAR.email2.settings.createSignature', !empty($defsigID));
218                 if (!empty($defsigID)) {
219                         $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:inherit;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
220                                         </span>';
221                 } else {
222                         $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:hidden;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
223                                         </span>';
224                 }
225                 $this->smarty->assign('signatureButtons', $signatureButtons);
226                 $this->smarty->assign('signaturePrepend', $prependSignature == 'true' ? 'CHECKED' : '');
227                 ////    END SIGNATURES
228                 ///////////////////////////////////////////////////////////////////////
229
230                 ///////////////////////////////////////////////////////////////////////
231                 ////    EMAIL TEMPLATES
232                 $email_templates_arr = $this->getEmailTemplatesArray();
233                 natcasesort($email_templates_arr);
234                 $this->smarty->assign('EMAIL_TEMPLATE_OPTIONS', get_select_options_with_id($email_templates_arr, ''));
235                 ////    END EMAIL TEMPLATES
236                 ///////////////////////////////////////////////////////////////////////
237
238                 ///////////////////////////////////////////////////////////////////////
239                 ////    FOLDERS & TreeView
240                 $this->smarty->assign('groupUserOptions', $ie->getGroupsWithSelectOptions(array('' => $app_strings['LBL_EMAIL_CREATE_NEW'])));
241
242                 $tree = $this->getMailboxNodes();
243
244                 // preloaded folder
245                 $preloadFolder = 'lazyLoadFolder = ';
246                 $focusFolderSerial = $current_user->getPreference('focusFolder', 'Emails');
247                 if(!empty($focusFolderSerial)) {
248                         $focusFolder = unserialize($focusFolderSerial);
249                         //$focusFolder['ieId'], $focusFolder['folder']
250                         $preloadFolder .= json_encode($focusFolder).";";
251                 } else {
252                         $preloadFolder .= "new Object();";
253                 }
254                 ////    END FOLDERS
255                 ///////////////////////////////////////////////////////////////////////
256
257                 $out = "";
258                 $out .= $this->smarty->fetch("modules/Emails/templates/_baseEmail.tpl");
259                 $out .= $tree->generate_header();
260                 $out .= $tree->generateNodesNoInit(true, 'email2treeinit');
261                 $out .=<<<eoq
262                         <script type="text/javascript" language="javascript">
263
264                                 var loader = new YAHOO.util.YUILoader({
265                                     require : [
266                                         "layout", "element", "tabview", "menu",
267                                         "cookie", "sugarwidgets"
268                                     ],
269                                     loadOptional: true,
270                                     skin: { base: 'blank', defaultSkin: '' },
271                                     onSuccess: email2init,
272                                     allowRollup: true,
273                                     base: "include/javascript/yui/build/"
274                                 });
275                                 loader.addModule({
276                                     name :"sugarwidgets",
277                                     type : "js",
278                                     fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
279                                     varName: "YAHOO.SUGAR",
280                                     requires: ["datatable", "dragdrop", "treeview", "tabview", "calendar"]
281                                 });
282                                 loader.insert();
283
284                                 {$preloadFolder};
285
286                         </script>
287 eoq;
288
289
290                 return $out;
291         }
292
293         /**
294          * Generate the frame needed for the quick compose email UI.  This frame is loaded dynamically
295          * by an ajax call.
296          *
297          * @return JSON An object containing html markup and js script variables.
298          */
299         function displayQuickComposeEmailFrame()
300         {
301         $this->preflightUserCache();
302
303             $this->_generateComposeConfigData('email_compose_light');
304                 $javascriptOut = $this->smarty->fetch("modules/Emails/templates/_baseConfigData.tpl");
305
306         $divOut = $this->smarty->fetch("modules/Emails/templates/overlay.tpl");
307         $divOut .= $this->smarty->fetch("modules/Emails/templates/addressSearchContent.tpl");
308
309         $outData = array('jsData' => $javascriptOut,'divData'=> $divOut);
310         $out = json_encode($outData);
311         return $out;
312     }
313
314     /**
315      * Load the modules from the metadata file and include in a custom one if it exists
316      *
317      * @return array
318      */
319     protected function _loadQuickCreateModules()
320     {
321         $QCAvailableModules = array();
322         $QCModules = array();
323
324         include('modules/Emails/metadata/qcmodulesdefs.php');
325         if (file_exists('custom/modules/Emails/metadata/qcmodulesdefs.php')) {
326             include('custom/modules/Emails/metadata/qcmodulesdefs.php');
327         }
328
329         foreach($QCModules as $module) {
330             $seed = SugarModule::get($module)->loadBean();
331             if ( ( $seed instanceOf SugarBean ) && $seed->ACLAccess('edit') ) {
332                 $QCAvailableModules[] = $module;
333             }
334         }
335
336         return $QCAvailableModules;
337     }
338
339     /**
340      * Given an email link url (eg. index.php?action=Compose&parent_type=Contacts...) break up the
341      * request components and create a compose package that can be used by the quick compose UI. The
342      * result is typically passed into the js call SUGAR.quickCompose.init which initalizes the quick compose
343      * UI.
344      *
345      * @param String $emailLinkUrl
346      * @return JSON Object containing the composePackage and full link url
347      */
348     function generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, $lazyLoad=false)
349     {
350         $composeData = explode("&",$emailLinkUrl);
351         $a_composeData = array();
352         foreach ($composeData as $singleRequest)
353         {
354                 $tmp = explode("=",$singleRequest);
355                 $a_composeData[$tmp[0]] = urldecode($tmp[1]);
356         }
357
358         return $this->generateComposePackageForQuickCreate($a_composeData,$emailLinkUrl, $lazyLoad);
359     }
360     /**
361      * Generate the composePackage for the quick compose email UI.  The package contains
362      * key/value pairs generated by the Compose.php file which are then set into the
363      * quick compose email UI (eg. to addr, parent id, parent type, etc)
364      *
365      * @param Array $composeData Associative array read and processed by generateComposeDataPackage.
366      * @param String $fullLinkUrl A link that contains all pertinant information so the user can be
367      *                              directed to the full compose screen if needed
368      * @param SugarBean $bean Optional - the parent object bean with data
369      * @return JSON Object containg composePackage and fullLinkUrl
370      */
371     function generateComposePackageForQuickCreate($composeData,$fullLinkUrl, $lazyLoad=false, $bean = null)
372     {
373         $_REQUEST['forQuickCreate'] = true;
374
375         if(!$lazyLoad){
376             require_once('modules/Emails/Compose.php');
377             $composePackage = generateComposeDataPackage($composeData,FALSE, $bean);
378         }else{
379             $composePackage = $composeData;
380         }
381
382         // JSON object is passed into the function defined within the a href onclick event
383         // which is delimeted by '.  Need to escape all single quotes and &, <, >
384         // but not double quotes since json would escape them
385         foreach ($composePackage as $key => $singleCompose)
386         {
387            if (is_string($singleCompose))
388                $composePackage[$key] = str_replace("&nbsp;", " ", from_html($singleCompose));
389         }
390
391         $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
392
393         $j_quickComposeOptions = JSON::encode($quickComposeOptions, false ,true);
394
395
396         return $j_quickComposeOptions;
397     }
398
399     /**
400      * Generate the config data needed for the Full Compose UI and the Quick Compose UI.  The set of config data
401      * returned is the minimum set needed by the quick compose UI.
402      *
403      * @param String $type Drives which tinyMCE options will be included.
404      */
405         function _generateComposeConfigData($type = "email_compose_light" )
406         {
407                 global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
408
409                 //Link drop-downs
410                 $parent_types = $app_list_strings['record_type_display'];
411                 $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
412
413                 foreach($disabled_parent_types as $disabled_parent_type) {
414                   unset($parent_types[$disabled_parent_type]);
415                 }
416                 asort($parent_types);
417                 $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
418
419                 //TinyMCE Config
420                 require_once("include/SugarTinyMCE.php");
421         $tiny = new SugarTinyMCE();
422         $tinyConf = $tiny->getConfig($type);
423
424         //Generate Language Packs
425                 $lang = "var app_strings = new Object();\n";
426                 foreach($app_strings as $k => $v) {
427                         if(strpos($k, 'LBL_EMAIL_') !== false) {
428                                 $lang .= "app_strings.{$k} = '{$v}';\n";
429                         }
430                 }
431                 //Get the email mod strings but don't use the global variable as this may be overridden by
432                 //other modules when the quick create is rendered.
433                 $email_mod_strings = return_module_language($current_language,'Emails');
434                 $modStrings = "var mod_strings = new Object();\n";
435                 foreach($email_mod_strings as $k => $v) {
436                         $v = str_replace("'", "\'", $v);
437                         $modStrings .= "mod_strings.{$k} = '{$v}';\n";
438                 }
439                 $lang .= "\n\n{$modStrings}\n";
440
441                 //Grab the Inboundemail language pack
442                 $ieModStrings = "var ie_mod_strings = new Object();\n";
443                 $ie_mod_strings = return_module_language($current_language,'InboundEmail');
444                 foreach($ie_mod_strings as $k => $v) {
445                         $v = str_replace("'", "\'", $v);
446                         $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
447                 }
448                 $lang .= "\n\n{$ieModStrings}\n";
449
450                 $this->smarty->assign('linkBeans', $linkBeans);
451         $this->smarty->assign('linkBeansOptions', $parent_types);
452         $this->smarty->assign('tinyMCE', $tinyConf);
453         $this->smarty->assign('lang', $lang);
454         $this->smarty->assign('app_strings', $app_strings);
455                 $this->smarty->assign('mod_strings', $email_mod_strings);
456         $ie1 = new InboundEmail();
457
458         //Signatures
459         $defsigID = $current_user->getPreference('signature_default');
460                 $defaultSignature = $current_user->getDefaultSignature();
461                 $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
462                 $this->smarty->assign('defaultSignature', $sigJson);
463                 $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
464                 //User Preferences
465                 $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
466
467                 //Get the users default outbound id
468                 $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
469                 $this->smarty->assign('defaultOutID', $defaultOutID);
470
471                 //Character Set
472                 $charsets = json_encode($locale->getCharsetSelect());
473                 $this->smarty->assign('emailCharsets', $charsets);
474
475                 //Relateable List of People for address book search
476                 //#20776 jchi
477                 $peopleTables = array("users",
478                                       "contacts",
479                                       "leads",
480                                       "prospects",
481                                       "accounts");
482                 $filterPeopleTables = array();
483                 global $app_list_strings, $app_strings;
484                 $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
485                 foreach($peopleTables as $table) {
486                         $module = ucfirst($table);
487             $class = substr($module, 0, strlen($module) - 1);
488             require_once("modules/{$module}/{$class}.php");
489             $person = new $class();
490
491             if (!$person->ACLAccess('list')) continue;
492             $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
493                 }
494                 $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
495
496         }
497
498
499
500         ////    END CORE
501         ///////////////////////////////////////////////////////////////////////////
502
503         ///////////////////////////////////////////////////////////////////////////
504         ////    ADDRESS BOOK
505         /**
506          * Retrieves all relationship metadata for a user's address book
507          * @return array
508          */
509         function getContacts() {
510                 global $current_user;
511
512                 $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
513                 $r = $this->db->query($q);
514
515                 $ret = array();
516
517                 while($a = $this->db->fetchByAssoc($r)) {
518                         $ret[$a['bean_id']] = array(
519                                 'id'            => $a['bean_id'],
520                                 'module'        => $a['bean'],
521                         );
522                 }
523
524                 return $ret;
525         }
526
527         /**
528          * Saves changes to a user's address book
529          * @param array contacts
530          */
531         function setContacts($contacts) {
532                 global $current_user;
533
534                 $oldContacts = $this->getContacts();
535
536                 foreach($contacts as $cid => $contact) {
537                         if(!in_array($contact['id'], $oldContacts)) {
538                                 $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
539                                 $r = $this->db->query($q, true);
540                         }
541                 }
542         }
543
544         /**
545          * Removes contacts from the user's address book
546          * @param array ids
547          */
548         function removeContacts($ids) {
549                 global $current_user;
550
551                 $concat = "";
552
553                 foreach($ids as $id) {
554                         if(!empty($concat))
555                                 $concat .= ", ";
556
557                         $concat .= "'{$id}'";
558                 }
559
560                 $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
561                 $r = $this->db->query($q);
562         }
563
564         /**
565          * saves editted Contact info
566          * @param string $str JSON serialized object
567          */
568         function saveContactEdit($str) {
569
570                 $json = getJSONobj();
571
572                 $str = from_html($str);
573                 $obj = $json->decode($str);
574
575                 $contact = new Contact();
576                 $contact->retrieve($obj['contact_id']);
577                 $contact->first_name = $obj['contact_first_name'];
578                 $contact->last_name = $obj['contact_last_name'];
579                 $contact->save();
580
581                 // handle email address changes
582                 $addresses = array();
583
584                 foreach($obj as $k => $req) {
585                         if(strpos($k, 'emailAddress') !== false) {
586                                 $addresses[$k] = $req;
587                         }
588                 }
589
590                 // prefill some REQUEST vars for emailAddress save
591                 $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
592                 $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
593                 $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
594         }
595
596         /**
597          * Prepares the Edit Contact mini-form via template assignment
598          * @param string id ID of contact in question
599          * @param string module Module in focus
600          * @return array
601          */
602         function getEditContact($id, $module) {
603                 global $app_strings;
604
605
606                 if(!class_exists("Contact")) {
607
608                 }
609
610                 $contact = new Contact();
611                 $contact->retrieve($_REQUEST['id']);
612                 $ret = array();
613
614                 if($contact->ACLAccess('edit')) {
615                         $contactMeta = array();
616                         $contactMeta['id'] = $contact->id;
617                         $contactMeta['module'] = $contact->module_dir;
618                         $contactMeta['first_name'] = $contact->first_name;
619                         $contactMeta['last_name'] = $contact->last_name;
620
621                         $this->smarty->assign("app_strings", $app_strings);
622                         $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
623                         $this->smarty->assign("contact", $contactMeta);
624
625                         $ea = new SugarEmailAddress();
626                         $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
627                         $this->smarty->assign("emailWidget", $newEmail['html']);
628
629                         $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
630                         $ret['prefillData'] = $newEmail['prefillData'];
631                 } else {
632                         $id = "";
633                         $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
634                         $ret['prefillData'] = '{}';
635                 }
636
637                 $ret['id'] = $id;
638                 $ret['contactName'] = $contact->full_name;
639
640                 return $ret;
641         }
642
643
644         /**
645          * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
646          * table
647          * @param array $contacts Array of contact types -> IDs
648          * @param object $user User in focus
649          * @return array
650          */
651         function getUserContacts($contacts, $user=null) {
652
653                 global $current_user;
654                 global $locale;
655
656                 if(empty($user)) {
657                         $user = $current_user;
658                 }
659
660                 $emailAddress = new SugarEmailAddress();
661                 $ret = array();
662
663                 $union = '';
664
665                 $modules = array();
666                 foreach($contacts as $contact) {
667                         if(!isset($modules[$contact['module']])) {
668                                 $modules[$contact['module']] = array();
669                         }
670                         $modules[$contact['module']][] = $contact;
671                 }
672
673                 foreach($modules as $module => $contacts) {
674                         if(!empty($union)) {
675                                 $union .= " UNION ALL ";
676                         }
677
678                         $table = strtolower($module);
679                         $idsSerial = '';
680
681                         foreach($contacts as $contact) {
682                                 if(!empty($idsSerial)) {
683                                         $idsSerial .= ",";
684                                 }
685                                 $idsSerial .= "'{$contact['id']}'";
686                         }
687
688                         $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
689                 }
690                 if(!empty($union)) {
691                         $union .= " ORDER BY last_name";
692                 }
693
694                 $r = $user->db->query($union);
695
696                 //_pp($union);
697
698                 while($a = $user->db->fetchByAssoc($r)) {
699                         $c = array();
700
701                         $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
702                         $c['id'] = $a['id'];
703                         $c['module'] = $a['module'];
704                         $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
705                         $ret[$a['id']] = $c;
706                 }
707
708                 return $ret;
709         }
710         ////    END ADDRESS BOOK
711         ///////////////////////////////////////////////////////////////////////////
712
713
714         ///////////////////////////////////////////////////////////////////////////
715         ////    EMAIL 2.0 Preferences
716         function getUserPrefsJS() {
717                 global $current_user;
718                 global $locale;
719
720                 // sort order per mailbox view
721                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
722                 $sortArray = array();
723                 if(!empty($sortSerial)) {
724                         $sortArray = unserialize($sortSerial);
725                 }
726
727                 // treeview collapsed/open states
728                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
729                 $folderStates = array();
730                 if(!empty($folderStateSerial)) {
731                         $folderStates = unserialize($folderStateSerial);
732                 }
733
734                 // subscribed accounts
735                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
736
737                 // general settings
738                 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
739
740                 if(empty($emailSettings)) {
741                         $emailSettings = array();
742                         $emailSettings['emailCheckInterval'] = -1;
743                         $emailSettings['autoImport'] = '';
744                         $emailSettings['alwaysSaveOutbound'] = '1';
745                         $emailSettings['sendPlainText'] = '';
746                         $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
747                         $emailSettings['showNumInList'] = 20;
748                 }
749
750                 // focus folder
751                 $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
752                 $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
753
754                 // unread only flag
755                 $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
756
757                 $listViewSort = array(
758                         "sortBy" => 'date',
759                         "sortDirection" => 'DESC',
760                 );
761
762                 // signature prefs
763                 $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
764                 $signatureDefault = $current_user->getPreference('signature_default');
765                 $signatures = array(
766                         'signature_prepend' => $signaturePrepend,
767                         'signature_default' => $signatureDefault
768                 );
769
770
771                 // current_user
772                 $user = array(
773                         'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
774                         'full_name' => from_html($current_user->full_name),
775                 );
776
777                 $userPreferences = array();
778                 $userPreferences['sort'] = $sortArray;
779                 $userPreferences['folderStates'] = $folderStates;
780                 $userPreferences['showFolders'] = $showFolders;
781                 $userPreferences['emailSettings'] = $emailSettings;
782                 $userPreferences['focusFolder'] = $focusFolder;
783                 $userPreferences['showUnreadOnly'] = $showUnreadOnly;
784                 $userPreferences['listViewSort'] = $listViewSort;
785                 $userPreferences['signatures'] = $signatures;
786                 $userPreferences['current_user'] = $user;
787                 return $userPreferences;
788         }
789
790
791
792         ///////////////////////////////////////////////////////////////////////////
793         ////    FOLDER FUNCTIONS
794
795         /**
796          * Creates a new Sugar folder
797          * @param string $nodeLabel New sugar folder name
798          * @param string $parentLabel Parent folder name
799          */
800         function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
801                 global $current_user;
802
803                 $this->folder->name = $nodeLabel;
804                 $this->folder->is_group = $isGroup;
805                 $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
806                 $this->folder->has_child = 0;
807                 $this->folder->created_by = $current_user->id;
808                 $this->folder->modified_by = $current_user->id;
809                 $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
810
811                 $this->folder->save();
812                 return array(
813                         'action' => 'newFolderSave',
814                         'id' => $this->folder->id,
815                         'name' => $this->folder->name,
816                         'is_group' => $this->folder->is_group,
817                         'is_dynamic' => $this->folder->is_dynamic
818                 );
819         }
820
821         /**
822          * Saves user sort prefernces
823          */
824         function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
825                 global $current_user;
826
827                 $sortArray = array();
828
829                 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
830                 if(!empty($sortSerial)) {
831                         $sortArray = unserialize($sortSerial);
832                 }
833
834                 $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
835                 $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
836                 $sortSerial = serialize($sortArray);
837                 $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
838         }
839
840         /**
841          * Stickies folder collapse/open state
842          */
843         function saveFolderOpenState($focusFolder, $focusFolderOpen) {
844                 global $current_user;
845
846                 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
847                 $folderStates = array();
848
849                 if(!empty($folderStateSerial)) {
850                         $folderStates = unserialize($folderStateSerial);
851                 }
852
853                 $folderStates[$focusFolder] = $focusFolderOpen;
854                 $newFolderStateSerial = serialize($folderStates);
855                 $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
856         }
857
858         /**
859          * saves a folder's view state
860          */
861         function saveListView($ieId, $folder) {
862                 global $current_user;
863
864                 $saveState = array();
865                 $saveState['ieId'] = $ieId;
866                 $saveState['folder'] = $folder;
867                 $saveStateSerial = serialize($saveState);
868                 $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
869         }
870
871         /**
872          * Generates cache folder structure
873          */
874         function preflightEmailCache($cacheRoot) {
875                 // base
876                 if(!file_exists($cacheRoot))
877                         mkdir_recursive(clean_path($cacheRoot));
878
879                 // folders
880                 if(!file_exists($cacheRoot."/folders"))
881                         mkdir_recursive(clean_path("{$cacheRoot}/folders"));
882
883                 // messages
884                 if(!file_exists($cacheRoot."/messages"))
885                         mkdir_recursive(clean_path("{$cacheRoot}/messages"));
886
887                 // attachments
888                 if(!file_exists($cacheRoot."/attachments"))
889                         mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
890         }
891
892         function deleteEmailCacheForFolders($cacheRoot) {
893                 $filePath = $cacheRoot."/folders/folders.php";
894                 if (file_exists($filePath)) {
895                         unlink($filePath);
896                 }
897         }
898         ///////////////////////////////////////////////////////////////////////////
899         ////    IMAP FUNCTIONS
900         /**
901          * Identifies subscribed mailboxes and empties the trash
902          * @param object $ie InboundEmail
903          */
904         function emptyTrash(&$ie) {
905                 global $current_user;
906
907                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
908
909                 if(is_array($showFolders)) {
910                         foreach($showFolders as $ieId) {
911                                 if(!empty($ieId)) {
912                                         $ie->retrieve($ieId);
913                                         $ie->emptyTrash();
914                                 }
915                         }
916                 }
917         }
918
919         /**
920          * returns an array of nodes that correspond to IMAP mailboxes.
921          * @param bool $forceRefresh
922          * @return object TreeView object
923          */
924         function getMailboxNodes() {
925                 global $sugar_config;
926                 global $current_user;
927                 global $app_strings;
928
929                 $tree = new Tree("frameFolders");
930                 $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
931
932                 $nodes = array();
933                 $ie = new InboundEmail();
934                 $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins.  this will be set via user prefs
935
936                 $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
937                 $rootNode->dynamicloadfunction = '';
938                 $rootNode->expanded = true;
939                 $rootNode->dynamic_load = true;
940                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
941
942                 if(empty($showFolders)) {
943                         $showFolders = array();
944                 }
945
946                 // INBOX NODES
947                 if($current_user->hasPersonalEmail()) {
948                         $personals = $ie->retrieveByGroupId($current_user->id);
949
950                         foreach($personals as $k => $personalAccount) {
951                                 if(in_array($personalAccount->id, $showFolders)) {
952                                         // check for cache value
953                                         $cacheRoot = sugar_cached("modules/Emails/{$personalAccount->id}");
954                                         $this->preflightEmailCache($cacheRoot);
955
956                                         if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
957                                                 $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
958                                         } else {
959                                                 $mailboxes = $personalAccount->getMailboxes();
960                                         }
961
962                                         $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
963                                         $acctNode->dynamicloadfunction = '';
964                                         $acctNode->expanded = false;
965                                         $acctNode->set_property('cls', 'ieFolder');
966                                         $acctNode->set_property('ieId', $personalAccount->id);
967                                 $acctNode->set_property('protocol', $personalAccount->protocol);
968
969                                         if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
970                                                 if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
971                                                         $acctNode->expanded = true;
972                                                 }
973                                         }
974                                         $acctNode->dynamic_load = true;
975
976                                         $nodePath = $acctNode->_properties['id'];
977
978                                         foreach($mailboxes as $k => $mbox) {
979                                                 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
980                                                     $nodePath, false, $personalAccount));
981                                         }
982
983                                         $rootNode->add_node($acctNode);
984                                 }
985                         }
986                 }
987
988                 // GROUP INBOX NODES
989                 $beans = $ie->retrieveAllByGroupId($current_user->id, false);
990                 foreach($beans as $k => $groupAccount) {
991                         if(in_array($groupAccount->id, $showFolders)) {
992                                 // check for cache value
993                                 $cacheRoot = sugar_cached("modules/Emails/{$groupAccount->id}");
994                                 $this->preflightEmailCache($cacheRoot);
995                                 //$groupAccount->connectMailserver();
996
997                                 if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
998                                         $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
999                                 } else {
1000                                         $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
1001                                 }
1002
1003                                 $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
1004                                 $acctNode->dynamicloadfunction = '';
1005                                 $acctNode->expanded = false;
1006                         $acctNode->set_property('isGroup', 'true');
1007                         $acctNode->set_property('ieId', $groupAccount->id);
1008                         $acctNode->set_property('protocol', $groupAccount->protocol);
1009
1010                                 if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
1011                                         if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
1012                                                 $acctNode->expanded = true;
1013                                         }
1014                                 }
1015                                 $acctNode->dynamic_load = true;
1016                                 $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
1017
1018                                 foreach($mailboxes as $k => $mbox) {
1019                                         $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
1020                                            $nodePath, true, $groupAccount));
1021                                 }
1022
1023                                 $rootNode->add_node($acctNode);
1024                         }
1025                 }
1026
1027                 // SugarFolder nodes
1028                 /* SugarFolders are built at onload when the UI renders */
1029
1030                 $tree->add_node($rootNode);
1031                 return $tree;
1032         }
1033
1034         function getMailBoxesFromCacheValue($mailAccount) {
1035                 $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
1036                 $mailboxes = $foldersCache['mailboxes'];
1037                 $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
1038                 $mailAccount->saveMailBoxFolders($mailboxesArray);
1039                 $this->deleteEmailCacheForFolders($cacheRoot);
1040                 return $mailboxes;
1041         } // fn
1042
1043         /**
1044          * Builds up a TreeView Node object
1045          * @param mixed
1046          * @param mixed
1047          * @param string
1048          * @param string ID of InboundEmail instance
1049          * @param string nodePath Serialized path from root node to current node
1050          * @param bool isGroup
1051          * @param bool forceRefresh
1052          * @return mixed
1053          */
1054         function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
1055                 global $sugar_config;
1056
1057                 // get unread counts
1058                 $exMbox = explode("::", $nodePath);
1059                 $unseen = 0;
1060                 $GLOBALS['log']->debug("$key --- $nodePath::$label");
1061
1062                 if(count($exMbox) >= 2) {
1063                         $mailbox = "";
1064                         for($i=2; $i<count($exMbox); $i++) {
1065                                 if($mailbox != "") {
1066                                         $mailbox .= ".";
1067                                 }
1068                                 $mailbox .= "{$exMbox[$i]}";
1069                         }
1070
1071                     $mailbox = substr($key, strpos($key, '.'));
1072
1073                         $unseen = $this->getUnreadCount($ie, $mailbox);
1074
1075                         if($unseen > 0) {
1076                                 //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
1077                         }
1078                 }
1079
1080                 $nodePath = $nodePath."::".$label;
1081         $node = new ExtNode($nodePath, $label);
1082         $node->dynamicloadfunction = '';
1083         $node->expanded = false;
1084         $node->set_property('labelStyle', "remoteFolder");
1085
1086
1087         if(array_key_exists($nodePath, $this->folderStates)) {
1088                 if($this->folderStates[$nodePath] == 'open') {
1089                         $node->expanded = true;
1090                 }
1091         }
1092
1093                 $group = ($isGroup) ? 'true' : 'false';
1094         $node->dynamic_load = true;
1095         //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
1096         $node->set_property('isGroup', $group);
1097         $node->set_property('isDynamic', 'false');
1098         $node->set_property('ieId', $ieId);
1099         $node->set_property('mbox', $key);
1100         $node->set_property('unseen', $unseen);
1101         $node->set_property('cls', 'ieFolder');
1102
1103         if(is_array($mbox)) {
1104                 foreach($mbox as $k => $v) {
1105                         $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
1106                 }
1107         }
1108
1109         return $node;
1110         }
1111
1112         /**
1113          * Totals the unread emails
1114          */
1115         function getUnreadCount(&$ie, $mailbox) {
1116                 global $sugar_config;
1117                 $unseen = 0;
1118
1119                 // use cache
1120                 return $ie->getCacheUnreadCount($mailbox);
1121         }
1122
1123         ///////////////////////////////////////////////////////////////////////////
1124         ////    DISPLAY CODE
1125         /**
1126          * Used exclusively by draft code.  Returns Notes and Documents as attachments.
1127          * @param array $ret
1128          * @return array
1129          */
1130         function getDraftAttachments($ret) {
1131                 global $db;
1132
1133                 // $ret['uid'] is the draft Email object's GUID
1134                 $ret['attachments'] = array();
1135
1136                 $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
1137                 $r = $db->query($q);
1138
1139                 while($a = $db->fetchByAssoc($r)) {
1140                         $ret['attachments'][$a['id']] = array(
1141                                 'id'            => $a['id'],
1142                                 'filename'      => $a['filename'],
1143                         );
1144                 }
1145
1146                 return $ret;
1147         }
1148
1149         function createCopyOfInboundAttachment($ie, $ret, $uid) {
1150                 global $sugar_config;
1151                 if ($ie->isPop3Protocol()) {
1152                         // get the UIDL from database;
1153                         $cachedUIDL = md5($uid);
1154                         $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php");
1155                 } else {
1156                         $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php");
1157                 }
1158                 if(file_exists($cache)) {
1159                         include($cache); // profides $cacheFile
1160                         $metaOut = unserialize($cacheFile['out']);
1161                         $meta = $metaOut['meta']['email'];
1162                         if (isset($meta['attachments'])) {
1163                                 $attachmentHtmlData = $meta['attachments'];
1164                                 $actualAttachmentInfo = array();
1165                                 $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
1166                                 if (sizeof($actualAttachmentInfo) > 0) {
1167                                         foreach($actualAttachmentInfo as $key => $value) {
1168                                             $info_vars = array();
1169                                             parse_str($value, $info_vars);
1170                                             $fileName = $info_vars['tempName'];
1171                                             $attachmentid = $info_vars['id'];
1172                                                 $guid = create_guid();
1173                                                 $destination = clean_path("{$this->userCacheDir}/{$guid}");
1174
1175                                                 $attachmentFilePath = sugar_cached("modules/Emails/{$ie->id}/attachments/{$attachmentid}");
1176                                                 copy($attachmentFilePath, $destination);
1177                                                 $ret['attachments'][$guid] = array();
1178                                                 $ret['attachments'][$guid]['id'] = $guid . $fileName;
1179                                                 $ret['attachments'][$guid]['filename'] = $fileName;
1180                                         } // for
1181                                 } // if
1182                         } // if
1183
1184                 } // if
1185                 return $ret;
1186
1187         } // fn
1188
1189         function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
1190                 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1191                 while ($downLoadPHP) {
1192                         $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
1193                         $final = strpos($attachmentHtmlData, "\">");
1194                         $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
1195                         $attachmentHtmlData = substr($attachmentHtmlData, $final);
1196                         $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1197                 } // while
1198         }
1199         /**
1200          * Renders the QuickCreate form from Smarty and returns HTML
1201          * @param array $vars request variable global
1202          * @param object $email Fetched email object
1203          * @param bool $addToAddressBook
1204          * @return array
1205          */
1206         function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
1207                 require_once("include/EditView/EditView2.php");
1208                 global $app_strings;
1209                 global $mod_strings;
1210                 global $current_user;
1211                 global $beanList;
1212                 global $beanFiles;
1213                 global $current_language;
1214
1215                 //Setup the current module languge
1216                 $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
1217
1218                 $bean = $beanList[$_REQUEST['qc_module']];
1219                 $class = $beanFiles[$bean];
1220                 require_once($class);
1221
1222                 $focus = new $bean();
1223
1224                 $people = array(
1225                 'Contact'
1226                 ,'Lead'
1227                 );
1228                 $emailAddress = array();
1229
1230                 // people
1231                 if(in_array($bean, $people)) {
1232                         // lead specific
1233                         $focus->lead_source = 'Email';
1234                         $focus->lead_source_description = trim($email->name);
1235
1236                         $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
1237
1238                         if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
1239                 $from = (isset($email->to_addrs_names) && !empty($email->to_addrs_names)) ? $email->to_addrs_names : $email->to_addrs;
1240
1241
1242                         $name = explode(" ", trim($from));
1243
1244                         $address = trim(array_pop($name));
1245                         $address = str_replace(array("<",">","&lt;","&gt;"), "", $address);
1246
1247                         $emailAddress[] = array(
1248                                 'email_address'         => $address,
1249                                 'primary_address'       => 1,
1250                                 'invalid_email'         => 0,
1251                                 'opt_out'                       => 0,
1252                                 'reply_to_address'      => 1
1253                         );
1254
1255                         $focus->email1 = $address;
1256
1257                         if(!empty($name)) {
1258                                 $focus->last_name = trim(array_pop($name));
1259
1260                                 foreach($name as $first) {
1261                                         if(!empty($focus->first_name)) {
1262                                                 $focus->first_name .= " ";
1263                                         }
1264                                         $focus->first_name .= trim($first);
1265                                 }
1266                         }
1267                 } else {
1268                         // bugs, cases, tasks
1269                         $focus->name = trim($email->name);
1270                 }
1271
1272                 $focus->description = trim(strip_tags($email->description));
1273                 $focus->assigned_user_id = $current_user->id;
1274
1275
1276                 $EditView = new EditView();
1277                 $EditView->ss = new Sugar_Smarty();
1278                 //MFH BUG#20283 - checks for custom quickcreate fields
1279                 $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
1280                 $EditView->process();
1281                 $EditView->render();
1282
1283                 $EditView->defs['templateMeta']['form']['buttons'] = array(
1284                         'email2save' => array(
1285                                 'id' => 'e2AjaxSave',
1286                                 'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_SAVE_BUTTON_LABEL']
1287                                               . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
1288                         ),
1289                         'email2saveandreply' => array(
1290                             'id' => 'e2SaveAndReply',
1291                             'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
1292                                           . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
1293                         ),
1294                         'email2cancel' => array(
1295                              'id' => 'e2cancel',
1296                              'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_CANCEL']
1297                               . '   " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
1298                         )
1299                 );
1300
1301
1302                 if($addToAddressBookButton) {
1303                         $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
1304                                 'id' => 'e2addToAddressBook',
1305                                 'customCode' => '<input type="button" class="button" value="   '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
1306                                               . '   " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
1307                         );
1308                 }
1309
1310                 //Get the module language for javascript
1311             if(!is_file(sugar_cached('jsLanguage/') . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
1312             require_once('include/language/jsLanguage.php');
1313             jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
1314         }
1315                 $jsLanguage = getVersionedScript("cache/jsLanguage/{$_REQUEST['qc_module']}/{$GLOBALS['current_language']}.js", $GLOBALS['sugar_config']['js_lang_version']);
1316
1317
1318                 $EditView->view = 'EmailQCView';
1319                 $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
1320                 $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
1321                 $meta = array();
1322                 $meta['html'] = $jsLanguage . $EditView->display(false, true);
1323                 $meta['html'] = str_replace("src='".getVersionedPath('include/SugarEmailAddress/SugarEmailAddress.js')."'", '', $meta['html']);
1324                 $meta['emailAddress'] = $emailAddress;
1325
1326                 $mod_strings = return_module_language($current_language, 'Emails');
1327
1328                 return $meta;
1329         }
1330
1331         /**
1332      * Renders the Import form from Smarty and returns HTML
1333      * @param array $vars request variable global
1334      * @param object $email Fetched email object
1335      * @param bool $addToAddressBook
1336      * @return array
1337      */
1338     function getImportForm($vars, $email, $formName = 'ImportEditView') {
1339                 require_once("include/EditView/EditView2.php");
1340         require_once("include/TemplateHandler/TemplateHandler.php");
1341                 require_once('include/QuickSearchDefaults.php');
1342         $qsd = QuickSearchDefaults::getQuickSearchDefaults();
1343                 $qsd->setFormName($formName);
1344
1345         global $app_strings;
1346         global $current_user;
1347         global $app_list_strings;
1348                 $sqs_objects = array(
1349                                      "{$formName}_parent_name" => $qsd->getQSParent(),
1350                 );
1351         $smarty = new Sugar_Smarty();
1352         $smarty->assign("APP",$app_strings);
1353         $smarty->assign('formName',$formName);
1354         $showAssignTo = false;
1355         if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
1356                 $showAssignTo = true;
1357                 } // if
1358                 if ($showAssignTo) {
1359                 if(empty($email->assigned_user_id) && empty($email->id))
1360                     $email->assigned_user_id = $current_user->id;
1361                 if(empty($email->assigned_name) && empty($email->id))
1362                     $email->assigned_user_name = $current_user->user_name;
1363                 $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
1364                 }
1365                 $smarty->assign("showAssignedTo",$showAssignTo);
1366
1367         $showDelete = false;
1368         if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
1369             $showDelete = true;
1370         }
1371         $smarty->assign("showDelete",$showDelete);
1372
1373         $smarty->assign("userId",$email->assigned_user_id);
1374         $smarty->assign("userName",$email->assigned_user_name);
1375         $parent_types = $app_list_strings['record_type_display'];
1376         $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
1377
1378                 $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
1379         $smarty->assign('SQS', $quicksearch_js);
1380
1381         $meta = array();
1382         $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
1383         return $meta;
1384     }
1385
1386     /**
1387      * This function returns the detail view for email in new 2.0 interface
1388      *
1389      */
1390     function getDetailViewForEmail2($emailId) {
1391
1392                 require_once('include/DetailView/DetailView.php');
1393                 global $app_strings, $app_list_strings;
1394                 global $mod_strings;
1395
1396         $smarty = new Sugar_Smarty();
1397
1398                 // SETTING DEFAULTS
1399                 $focus          = new Email();
1400                 $focus->retrieve($emailId);
1401                 $detailView->ss = new Sugar_Smarty();
1402                 $detailView     = new DetailView();
1403                 $title = "";
1404                 $offset         = 0;
1405                 if($focus->type == 'out') {
1406                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name), true);
1407                 } elseif ($focus->type == 'draft') {
1408                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_LIST_FORM_DRAFTS_TITLE'],$focus->name), true);
1409                 } elseif($focus->type == 'inbound') {
1410                         $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_INBOUND_TITLE'],$focus->name), true);
1411                 }
1412                 $smarty->assign("emailTitle", $title);
1413
1414                 // DEFAULT TO TEXT IF NO HTML CONTENT:
1415                 $html = trim(from_html($focus->description_html));
1416                 if(empty($html)) {
1417                         $smarty->assign('SHOW_PLAINTEXT', 'true');
1418                 } else {
1419                         $smarty->assign('SHOW_PLAINTEXT', 'false');
1420                 }
1421
1422                 //if not empty or set to test (from test campaigns)
1423                 if (!empty($focus->parent_type) && $focus->parent_type !='test') {
1424                         $smarty->assign('PARENT_MODULE', $focus->parent_type);
1425                         $smarty->assign('PARENT_TYPE', $app_list_strings['record_type_display'][$focus->parent_type] . ":");
1426                 }
1427
1428         global $gridline;
1429                 $smarty->assign('MOD', $mod_strings);
1430                 $smarty->assign('APP', $app_strings);
1431                 $smarty->assign('GRIDLINE', $gridline);
1432                 $smarty->assign('PRINT_URL', 'index.php?'.$GLOBALS['request_string']);
1433                 $smarty->assign('ID', $focus->id);
1434                 $smarty->assign('TYPE', $focus->type);
1435                 $smarty->assign('PARENT_NAME', $focus->parent_name);
1436                 $smarty->assign('PARENT_ID', $focus->parent_id);
1437                 $smarty->assign('NAME', $focus->name);
1438                 $smarty->assign('ASSIGNED_TO', $focus->assigned_user_name);
1439                 $smarty->assign('DATE_MODIFIED', $focus->date_modified);
1440                 $smarty->assign('DATE_ENTERED', $focus->date_entered);
1441                 $smarty->assign('DATE_START', $focus->date_start);
1442                 $smarty->assign('TIME_START', $focus->time_start);
1443                 $smarty->assign('FROM', $focus->from_addr);
1444                 $smarty->assign('TO', nl2br($focus->to_addrs));
1445                 $smarty->assign('CC', nl2br($focus->cc_addrs));
1446                 $smarty->assign('BCC', nl2br($focus->bcc_addrs));
1447                 $smarty->assign('CREATED_BY', $focus->created_by_name);
1448                 $smarty->assign('MODIFIED_BY', $focus->modified_by_name);
1449                 $smarty->assign('DATE_SENT', $focus->date_entered);
1450                 $smarty->assign('EMAIL_NAME', 'RE: '.$focus->name);
1451                 $smarty->assign("TAG", $focus->listviewACLHelper());
1452                 $smarty->assign("SUGAR_VERSION", $GLOBALS['sugar_version']);
1453                 $smarty->assign("JS_CUSTOM_VERSION", $GLOBALS['sugar_config']['js_custom_version']);
1454                 if(!empty($focus->reply_to_email)) {
1455                         $replyTo = "
1456                                 <tr>
1457                         <td class=\"tabDetailViewDL\"><slot>".$mod_strings['LBL_REPLY_TO_NAME']."</slot></td>
1458                         <td colspan=3 class=\"tabDetailViewDF\"><slot>".$focus->reply_to_addr."</slot></td>
1459                         </tr>";
1460                         $smarty->assign("REPLY_TO", $replyTo);
1461                 }
1462                 ///////////////////////////////////////////////////////////////////////////////
1463                 ////    JAVASCRIPT VARS
1464                 $jsVars  = '';
1465                 $jsVars .= "var showRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL']}';";
1466                 $jsVars .= "var hideRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL_HIDE']}';";
1467                 $smarty->assign("JS_VARS", $jsVars);
1468                 ///////////////////////////////////////////////////////////////////////////////
1469                 ////    NOTES (attachements, etc.)
1470                 ///////////////////////////////////////////////////////////////////////////////
1471
1472                 $note = new Note();
1473                 $where = "notes.parent_id='{$focus->id}'";
1474                 //take in account if this is from campaign and the template id is stored in the macros.
1475
1476                 if(isset($macro_values) && isset($macro_values['email_template_id'])){
1477                     $where = "notes.parent_id='{$macro_values['email_template_id']}'";
1478                 }
1479                 $notes_list = $note->get_full_list("notes.name", $where, true);
1480
1481                 if(! isset($notes_list)) {
1482                         $notes_list = array();
1483                 }
1484
1485                 $attachments = '';
1486                 for($i=0; $i<count($notes_list); $i++) {
1487                         $the_note = $notes_list[$i];
1488                         $attachments .= "<a href=\"index.php?entryPoint=download&id={$the_note->id}&type=Notes\">".$the_note->name."</a><br />";
1489                         $focus->cid2Link($the_note->id, $the_note->file_mime_type);
1490                 }
1491                 $smarty->assign('DESCRIPTION', nl2br($focus->description));
1492                 $smarty->assign('DESCRIPTION_HTML', from_html($focus->description_html));
1493                 $smarty->assign("ATTACHMENTS", $attachments);
1494                 ///////////////////////////////////////////////////////////////////////////////
1495                 ////    SUBPANELS
1496                 ///////////////////////////////////////////////////////////////////////////////
1497                 $show_subpanels = true;
1498                 if ($show_subpanels) {
1499                     require_once('include/SubPanel/SubPanelTiles.php');
1500                     $subpanel = new SubPanelTiles($focus, 'Emails');
1501                     $smarty->assign("SUBPANEL", $subpanel->display());
1502                 }
1503         $meta['html'] = $smarty->fetch("modules/Emails/templates/emailDetailView.tpl");
1504         return $meta;
1505
1506     } // fn
1507
1508         /**
1509          * Sets the "read" flag in the overview cache
1510          */
1511         function setReadFlag($ieId, $mbox, $uid) {
1512                 $this->markEmails('read', $ieId, $mbox, $uid);
1513         }
1514
1515         /**
1516          * Marks emails with the passed flag type.  This will be applied to local
1517          * cache files as well as remote emails.
1518          * @param string $type Flag type
1519          * @param string $ieId
1520          * @param string $folder IMAP folder structure or SugarFolder GUID
1521          * @param string $uids Comma sep list of UIDs or GUIDs
1522          */
1523         function markEmails($type, $ieId, $folder, $uids) {
1524
1525                 global $app_strings;
1526                 $uids = $this->_cleanUIDList($uids);
1527                 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1528
1529                 if(strpos($folder, 'sugar::') !== false) {
1530                         // dealing with a sugar email object, uids are GUIDs
1531                         foreach($exUids as $id) {
1532                                 $email = new Email();
1533                                 $email->retrieve($id);
1534
1535                                 switch($type) {
1536                                         case "unread":
1537                                                 $email->status = 'unread';
1538                                                 $email->save();
1539                                         break;
1540
1541                                         case "read":
1542                                                 $email->status = 'read';
1543                                                 $email->save();
1544                                         break;
1545
1546                                         case "deleted":
1547                                                 $email->delete();
1548                                         break;
1549
1550                                         case "flagged":
1551                                                 $email->flagged = 1;
1552                                                 $email->save();
1553                                         break;
1554
1555                                         case "unflagged":
1556                                                 $email->flagged = 0;
1557                                                 $email->save();
1558                                         break;
1559
1560                                 }
1561                         }
1562                 } else {
1563                         /* dealing with IMAP email, uids are IMAP uids */
1564                         global $ie; // provided by EmailUIAjax.php
1565                         if(empty($ie)) {
1566
1567                                 $ie = new InboundEmail();
1568                         }
1569                         $ie->retrieve($ieId);
1570                         $ie->mailbox = $folder;
1571                         $ie->connectMailserver();
1572                         // mark cache files
1573                         if($type == 'deleted') {
1574                                 $ie->deleteMessageOnMailServer($uids);
1575                                 $ie->deleteMessageFromCache($uids);
1576                         } else {
1577                                 $overviews = $ie->getCacheValueForUIDs($ie->mailbox, $exUids);
1578                                 $manipulated = array();
1579
1580                                 foreach($overviews['retArr'] as $k => $overview) {
1581                                         if(in_array($overview->uid, $exUids)) {
1582                                                 switch($type) {
1583                                                         case "unread":
1584                                                                 $overview->seen = 0;
1585                                                         break;
1586
1587                                                         case "read":
1588                                                                 $overview->seen = 1;
1589                                                         break;
1590
1591                                                         case "flagged":
1592                                                                 $overview->flagged = 1;
1593                                                         break;
1594
1595                                                         case "unflagged":
1596                                                                 $overview->flagged = 0;
1597                                                         break;
1598                                                 }
1599                                                 $manipulated[] = $overview;
1600                                         }
1601                                 }
1602
1603                                 if(!empty($manipulated)) {
1604                                         $ie->setCacheValue($ie->mailbox, array(), $manipulated);
1605                                         /* now mark emails on email server */
1606                                         $ie->markEmails(implode(",", explode($app_strings['LBL_EMAIL_DELIMITER'], $uids)), $type);
1607                                 }
1608                         } // end not type == deleted
1609                 }
1610         }
1611
1612 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users) {
1613         global $app_strings;
1614         $users = explode(",", $users);
1615         $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1616         $out = "";
1617         if($folder != 'sugar::Emails') {
1618                 $emailIds = array();
1619                 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1620                 $ie = new InboundEmail();
1621                 $ie->retrieve($ieid);
1622                 $messageIndex = 1;
1623                 // dealing with an inbound email data so we need to import an email and then
1624                 foreach($uids as $uid) {
1625                         $ie->mailbox = $folder;
1626                         $ie->connectMailserver();
1627                         $msgNo = $uid;
1628                         if (!$ie->isPop3Protocol()) {
1629                                 $msgNo = imap_msgno($ie->conn, $uid);
1630                         } else {
1631                                 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
1632                         }
1633
1634                         if(!empty($msgNo)) {
1635                                 if ($ie->importOneEmail($msgNo, $uid)) {
1636                                         $emailIds[] = $ie->email->id;
1637                                         $ie->deleteMessageOnMailServer($uid);
1638                                         //$ie->retrieve($ieid);
1639                                         //$ie->connectMailserver();
1640                                         $ie->mailbox = $folder;
1641                                         $ie->deleteMessageFromCache(($uids[] = $uid));
1642                                 } else {
1643                                         $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
1644                                 }
1645                         }
1646                         $messageIndex++;
1647                 } // for
1648         } // if
1649
1650         if (count($emailIds) > 0) {
1651                 $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
1652         } // if
1653         return $out;
1654 } // fn
1655
1656 /**
1657  * get team id and team set id from request
1658  * @return  array
1659  */
1660 function getTeams() {
1661 }
1662
1663 function doDistributionWithMethod($users, $emailIds, $distributionMethod) {
1664         // we have users and the items to distribute
1665         if($distributionMethod == 'roundRobin') {
1666                 $this->distRoundRobin($users, $emailIds);
1667         } elseif($distributionMethod == 'leastBusy') {
1668                 $this->distLeastBusy($users, $emailIds);
1669         } elseif($distributionMethod == 'direct') {
1670                 if(count($users) > 1) {
1671                         // only 1 user allowed in direct assignment
1672                         $error = 1;
1673                 } else {
1674                         $user = $users[0];
1675                         $this->distDirect($user, $emailIds);
1676                 } // else
1677         } // elseif
1678
1679 } // fn
1680
1681 /**
1682  * distributes emails to users on Round Robin basis
1683  * @param       $userIds        array of users to dist to
1684  * @param       $mailIds        array of email ids to push on those users
1685  * @return  boolean             true on success
1686  */
1687 function distRoundRobin($userIds, $mailIds) {
1688         // check if we have a 'lastRobin'
1689         $lastRobin = $userIds[0];
1690         foreach($mailIds as $k => $mailId) {
1691                 $userIdsKeys = array_flip($userIds); // now keys are values
1692                 $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
1693                 if(!empty($userIds[$thisRobinKey])) {
1694                         $thisRobin = $userIds[$thisRobinKey];
1695                         $lastRobin = $userIds[$thisRobinKey];
1696                 } else {
1697                         $thisRobin = $userIds[0];
1698                         $lastRobin = $userIds[0];
1699                 }
1700
1701                 $email = new Email();
1702                 $email->retrieve($mailId);
1703                 $email->assigned_user_id = $thisRobin;
1704                 $email->status = 'unread';
1705                 $email->save();
1706         }
1707
1708         return true;
1709 }
1710
1711 /**
1712  * distributes emails to users on Least Busy basis
1713  * @param       $userIds        array of users to dist to
1714  * @param       $mailIds        array of email ids to push on those users
1715  * @return  boolean             true on success
1716  */
1717 function distLeastBusy($userIds, $mailIds) {
1718         foreach($mailIds as $k => $mailId) {
1719                 $email = new Email();
1720                 $email->retrieve($mailId);
1721                 foreach($userIds as $k => $id) {
1722                         $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '.$id.' AND status = 'unread'");
1723                         $a = $this->db->fetchByAssoc($r);
1724                         $counts[$id] = $a['c'];
1725                 }
1726                 asort($counts); // lowest to highest
1727                 $countsKeys = array_flip($counts); // keys now the 'count of items'
1728                 $leastBusy = array_shift($countsKeys); // user id of lowest item count
1729                 $email->assigned_user_id = $leastBusy;
1730                 $email->status = 'unread';
1731                 $email->save();
1732         }
1733         return true;
1734 }
1735
1736 /**
1737  * distributes emails to 1 user
1738  * @param       $user           users to dist to
1739  * @param       $mailIds        array of email ids to push
1740  * @return  boolean             true on success
1741  */
1742 function distDirect($user, $mailIds) {
1743         foreach($mailIds as $k => $mailId) {
1744                 $email = new Email();
1745                 $email->retrieve($mailId);
1746                 $email->assigned_user_id = $user;
1747                 $email->status = 'unread';
1748
1749                 $email->save();
1750         }
1751         return true;
1752 }
1753
1754 function getAssignedEmailsCountForUsers($userIds) {
1755         $counts = array();
1756         foreach($userIds as $id) {
1757                 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '$id' AND status = 'unread'");
1758                 $a = $this->db->fetchByAssoc($r);
1759                 $counts[$id] = $a['c'];
1760         } // foreach
1761         return $counts;
1762 } // fn
1763
1764 function getLastRobin($ie) {
1765         $lastRobin = "";
1766         if($this->validCacheFileExists($ie->id, 'folders', "robin.cache.php")) {
1767                 $lastRobin = $this->getCacheValue($ie->id, 'folders', "robin.cache.php", 'robin');
1768         } // if
1769         return $lastRobin;
1770 } // fn
1771
1772 function setLastRobin($ie, $lastRobin) {
1773     global $sugar_config;
1774     $cacheFolderPath = sugar_cached("modules/Emails/{$ie->id}/folders");
1775     if (!file_exists($cacheFolderPath)) {
1776         mkdir_recursive($cacheFolderPath);
1777     }
1778         $this->writeCacheFile('robin', $lastRobin, $ie->id, 'folders', "robin.cache.php");
1779 } // fn
1780
1781         /**
1782          * returns the metadata defining a single email message for display.  Uses cache file if it exists
1783          * @return array
1784          */
1785 function getSingleMessage($ie) {
1786
1787                 global $timedate;
1788                 global $app_strings,$mod_strings;
1789                 $ie->retrieve($_REQUEST['ieId']);
1790                 $noCache = true;
1791
1792                 $ie->mailbox = $_REQUEST['mbox'];
1793                 $filename = $_REQUEST['mbox'].$_REQUEST['uid'].".php";
1794                 $md5uidl = "";
1795                 if ($ie->isPop3Protocol()) {
1796                         $md5uidl = md5($_REQUEST['uid']);
1797                         $filename = $_REQUEST['mbox'].$md5uidl.".php";
1798                 } // if
1799
1800                 if($this->validCacheFileExists($_REQUEST['ieId'], 'messages', $filename)) {
1801                         $out = $this->getCacheValue($_REQUEST['ieId'], 'messages', $filename, 'out');
1802                         $noCache = false;
1803
1804                         // something fubar'd the cache?
1805                         if(empty($out['meta']['email']['name']) && empty($out['meta']['email']['description'])) {
1806                                 $noCache = true;
1807                         } else {
1808                                 // When sending data from cache, convert date into users preffered format
1809                                 $dateTimeInGMTFormat = $out['meta']['email']['date_start'];
1810                                 $out['meta']['email']['date_start'] = $timedate->to_display_date_time($dateTimeInGMTFormat);
1811                         } // else
1812                 }
1813
1814                 if($noCache) {
1815                         $writeToCacheFile = true;
1816                         if ($ie->isPop3Protocol()) {
1817                                 $status = $ie->setEmailForDisplay($_REQUEST['uid'], true, true, true);
1818                         } else {
1819                                 $status = $ie->setEmailForDisplay($_REQUEST['uid'], false, true, true);
1820                         }
1821                         $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
1822                         // modify the out object to store date in GMT format on the local cache file
1823                         $dateTimeInUserFormat = $out['meta']['email']['date_start'];
1824                         $out['meta']['email']['date_start'] = $timedate->to_db($dateTimeInUserFormat);
1825                         if ($status == 'error') {
1826                                 $writeToCacheFile = false;
1827                         }
1828                         if ($writeToCacheFile) {
1829                                 if ($ie->isPop3Protocol()) {
1830                                         $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$md5uidl}.php");
1831                                 } else {
1832                                         $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$_REQUEST['uid']}.php");
1833                                 } // else
1834                         // restore date in the users preferred format to be send on to UI for diaply
1835                         $out['meta']['email']['date_start'] = $dateTimeInUserFormat;
1836                         } // if
1837                 }
1838                 $out['meta']['email']['toaddrs'] = $this->generateExpandableAddrs($out['meta']['email']['toaddrs']);
1839                 if(!empty($out['meta']['email']['cc_addrs'])) {
1840             $ccs = $this->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
1841                     $out['meta']['cc'] = <<<eoq
1842                                 <tr>
1843                                         <td NOWRAP valign="top" class="displayEmailLabel">
1844                                                 {$app_strings['LBL_EMAIL_CC']}:
1845                                         </td>
1846                                         <td class="displayEmailValue">
1847                                                 {$ccs}
1848                                         </td>
1849                                 </tr>
1850 eoq;
1851                 }
1852
1853                  if(empty($out['meta']['email']['description']))
1854                 $out['meta']['email']['description'] = $mod_strings['LBL_EMPTY_EMAIL_BODY'];
1855
1856                 if($noCache) {
1857                         $GLOBALS['log']->debug("EMAILUI: getSingleMessage() NOT using cache file");
1858                 } else {
1859                         $GLOBALS['log']->debug("EMAILUI: getSingleMessage() using cache file [ ".$_REQUEST['mbox'].$_REQUEST['uid'].".php ]");
1860                 }
1861
1862                 $this->setReadFlag($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['uid']);
1863                 return $out;
1864         }
1865
1866
1867         /**
1868          * Returns the HTML for a list of emails in a given folder
1869          * @param GUID $ieId GUID to InboundEmail instance
1870          * @param string $mbox Mailbox path name in dot notation
1871          * @param int $folderListCacheOffset Seconds for valid cache file
1872          * @return string HTML render of list.
1873          */
1874         function getListEmails($ieId, $mbox, $folderListCacheOffset, $forceRefresh='false') {
1875                 global $sugar_config;
1876
1877
1878                 $ie = new InboundEmail();
1879                 $ie->retrieve($ieId);
1880                 $list = $ie->displayFolderContents($mbox, $forceRefresh);
1881
1882                 return $list;
1883         }
1884
1885         /**
1886          * Returns the templatized compose screen.  Used by reply, forwards and draft status messages.
1887          * @param object email Email bean in focus
1888          */
1889         function displayComposeEmail($email) {
1890                 global $locale;
1891                 global $current_user;
1892
1893
1894                 $ea = new SugarEmailAddress();
1895
1896                 if(!empty($email)) {
1897                     $email->cids2Links();
1898                         $description = (empty($email->description_html)) ? $email->description : $email->description_html;
1899                 }
1900
1901                 //Get the most complete address list availible for this email
1902                 $addresses = array('toAddresses' => 'to', 'ccAddresses' => 'cc', 'bccAddresses' => 'bcc');
1903                 foreach($addresses as $var => $type)
1904                 {
1905                         $$var = "";
1906                         foreach (array("{$type}_addrs_names", "{$type}addrs", "{$type}_addrs") as $emailVar)
1907                         {
1908                                 if (!empty($email->$emailVar)) {
1909                                         $$var = $email->$emailVar;
1910                                         break;
1911                                 }
1912                         }
1913                 }
1914
1915                 $ret = array();
1916                 $ret['type'] = $email->type;
1917                 $ret['name'] = $email->name;
1918                 $ret['description'] = $description;
1919                 $ret['from'] = (isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'forward') ? "" : $email->from_addr;
1920                 $ret['to'] = from_html($toAddresses);
1921                 $ret['uid'] = $email->id;
1922                 $ret['parent_name'] = $email->parent_name;
1923                 $ret['parent_type'] = $email->parent_type;
1924                 $ret['parent_id'] = $email->parent_id;
1925
1926                 // reply all
1927                 if(isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'replyAll') {
1928                     $ret['cc'] = from_html($ccAddresses);
1929                     $ret['bcc'] = $bccAddresses;
1930
1931                         $userEmails = array();
1932                         $userEmailsMeta = $ea->getAddressesByGUID($current_user->id, 'Users');
1933                         foreach($userEmailsMeta as $emailMeta) {
1934                                 $userEmails[] = from_html(strtolower(trim($emailMeta['email_address'])));
1935                         }
1936                         $userEmails[] = from_html(strtolower(trim($email->from_addr)));
1937
1938                         $ret['cc'] = from_html($email->cc_addrs);
1939                         $toAddresses = from_html($toAddresses);
1940                         $to = str_replace($this->addressSeparators, "::", $toAddresses);
1941                         $exTo = explode("::", $to);
1942
1943                         if(is_array($exTo)) {
1944                                 foreach($exTo as $addr) {
1945                                         $addr = strtolower(trim($addr));
1946                                         if(!in_array($addr, $userEmails)) {
1947                                                 if(!empty($ret['cc'])) {
1948                                                         $ret['cc'] = $ret['cc'].", ";
1949                                                 }
1950                                                 $ret['cc'] = $ret['cc'].trim($addr);
1951                                         }
1952                                 }
1953                         } elseif(!empty($exTo)) {
1954                                 $exTo = trim($exTo);
1955                                 if(!in_array($exTo, $userEmails)) {
1956                                         $ret['cc'] = $ret['cc'].", ".$exTo;
1957                                 }
1958                         }
1959                 }
1960                 return $ret;
1961         }
1962         /**
1963          * Formats email body on reply/forward
1964          * @param object email Email object in focus
1965          * @param string type
1966          * @return object email
1967          */
1968         function handleReplyType($email, $type) {
1969                 global $mod_strings;
1970                  $GLOBALS['log']->debug("****At Handle Reply Type: $type");
1971                 switch($type) {
1972                         case "reply":
1973                         case "replyAll":
1974                                 $header = $email->getReplyHeader();
1975                 if(!preg_match('/^(re:)+/i', $email->name)) {
1976                     $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
1977                 }
1978                                 if ($type == "reply") {
1979                                         $email->cc_addrs = "";
1980                                         if (!empty($email->reply_to_addr)) {
1981                                                 $email->from_addr = $email->reply_to_addr;
1982                                         } // if
1983                                 } else {
1984                                         if (!empty($email->reply_to_addr)) {
1985                                                 $email->to_addrs = $email->to_addrs . "," . $email->reply_to_addr;
1986                                         } // if
1987                                 } // else
1988                         break;
1989
1990                         case "forward":
1991                                 $header = $email->getForwardHeader();
1992                                 if(!preg_match('/^(fw:)+/i', $email->name)) {
1993                     $email->name = "{$mod_strings['LBL_FW']} {$email->name}";
1994                 }
1995                                 $email->cc_addrs = "";
1996                         break;
1997
1998                         case "replyCase":
1999                                 $GLOBALS['log']->debug("EMAILUI: At reply case");
2000                                 $header = $email->getReplyHeader();
2001
2002                 $myCase = new aCase();
2003                 $myCase->retrieve($email->parent_id);
2004                 $myCaseMacro = $myCase->getEmailSubjectMacro();
2005                 $email->parent_name = $myCase->name;
2006                 $GLOBALS['log']->debug("****Case # : {$myCase->case_number} macro: $myCaseMacro");
2007                                 if(!strpos($email->name, str_replace('%1',$myCase->case_number,$myCaseMacro))) {
2008                                 $GLOBALS['log']->debug("Replacing");
2009                             $email->name = str_replace('%1',$myCase->case_number,$myCaseMacro) . ' '. $email->name;
2010                         }
2011                 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
2012             break;
2013                 }
2014
2015                 $html = trim($email->description_html);
2016                 $plain = trim($email->description);
2017
2018                 $desc = (!empty($html)) ? $html : $plain;
2019
2020                 $email->description = $header.$email->quoteHtmlEmailForNewEmailUI($desc);
2021                 return $email;
2022
2023         }
2024
2025         ///////////////////////////////////////////////////////////////////////////
2026         ////    PRIVATE HELPERS
2027         /**
2028          * Generates a UNION query to get one list of users, contacts, leads, and
2029          * prospects; used specifically for the addressBook
2030          */
2031         function _getPeopleUnionQuery($whereArr , $person) {
2032                 global $current_user , $app_strings;
2033                 global $db;
2034                 if(!isset($person) || $person === 'LBL_DROPDOWN_LIST_ALL'){
2035                         $peopleTables = array("users",
2036                                               "contacts",
2037                                               "leads",
2038                                               "prospects",
2039                                               "accounts"
2040                                              );
2041                 }else{
2042                         $peopleTables = array($person);
2043                 }
2044                 $q = '';
2045
2046                 $whereAdd = "";
2047
2048                 foreach($whereArr as $column => $clause) {
2049                         if(!empty($whereAdd)) {
2050                                 $whereAdd .= " AND ";
2051                         }
2052                         $clause = $current_user->db->quote($clause);
2053                         $whereAdd .= "{$column} LIKE '{$clause}%'";
2054                 }
2055
2056
2057                 foreach($peopleTables as $table) {
2058                         $module = ucfirst($table);
2059             $class = substr($module, 0, strlen($module) - 1);
2060             require_once("modules/{$module}/{$class}.php");
2061             $person = new $class();
2062                         if (!$person->ACLAccess('list')) {
2063                                 continue;
2064                         } // if
2065                         $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id <> '{$current_user->id}')";
2066
2067             if (ACLController::requireOwner($module, 'list')) {
2068                 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2069             } // if
2070                         if(!empty($whereAdd)) {
2071                                 $where .= " AND ({$whereAdd})";
2072                         }
2073
2074                         if ($person === 'accounts') {
2075                                 $t = "SELECT {$table}.id, '' first_name, {$table}.name, eabr.primary_address, ea.email_address, '{$module}' module ";
2076                         } else {
2077                                 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2078                         }
2079                         $t .= "FROM {$table} ";
2080                         $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2081                         $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2082                         $t .= " WHERE {$where}";
2083
2084                         if(!empty($q)) {
2085                                 $q .= "\n UNION ALL \n";
2086                         }
2087
2088                         $q .= "({$t})";
2089                 }
2090                 $countq = "SELECT count(people.id) c from ($q) people";
2091                 $q .= "ORDER BY last_name";
2092
2093                 return array('query' => $q, 'countQuery' => $countq);
2094     }
2095
2096     /**
2097      * get emails of related bean for a given bean id
2098      * @param $beanType
2099      * @param $condition array of conditions inclued bean id
2100      * @return array('query' => $q, 'countQuery' => $countq);
2101      */
2102     function getRelatedEmail($beanType, $whereArr, $relatedBeanInfoArr = ''){
2103         global $beanList, $current_user, $app_strings, $db;
2104         $finalQuery = '';
2105                 $searchBeans = null;
2106                 if($beanType === 'LBL_DROPDOWN_LIST_ALL')
2107                         $searchBeans = array("users",
2108                                              "contacts",
2109                                              "leads",
2110                                              "prospects",
2111                                              "accounts"
2112                                             );
2113
2114         if ($relatedBeanInfoArr == '' || empty($relatedBeanInfoArr['related_bean_type']) )
2115         {
2116                         if ($searchBeans != null)
2117                         {
2118                                 $q = array();
2119                                 foreach ($searchBeans as $searchBean)
2120                                 {
2121                                     $searchq = $this->findEmailFromBeanIds('', $searchBean, $whereArr);
2122                                     if(!empty($searchq)) {
2123                                             $q[] = "($searchq)";
2124                                     }
2125                                 }
2126                                 if (!empty($q))
2127                             $finalQuery .= implode("\n UNION ALL \n", $q);
2128                         }
2129                         else
2130                                 $finalQuery = $this->findEmailFromBeanIds('', $beanType, $whereArr);
2131         }
2132         else
2133         {
2134             $class = $beanList[$relatedBeanInfoArr['related_bean_type']];
2135             $focus = new $class();
2136             $focus->retrieve($relatedBeanInfoArr['related_bean_id']);
2137             if ($searchBeans != null)
2138             {
2139                 $q = array();
2140                 foreach ($searchBeans as $searchBean)
2141                 {
2142                     if ($focus->load_relationship($searchBean))
2143                     {
2144                         $data = $focus->$searchBean->get();
2145                         if (count($data) != 0)
2146                         $q[] = '('.$this->findEmailFromBeanIds($data, $searchBean, $whereArr).')';
2147                     }
2148                 }
2149                 if (!empty($q))
2150                 $finalQuery .= implode("\n UNION ALL \n", $q);
2151             }
2152             else
2153             {
2154                 if ($focus->load_relationship($beanType))
2155                 {
2156                     $data = $focus->$beanType->get();
2157                     if (count($data) != 0)
2158                     $finalQuery = $this->findEmailFromBeanIds($data, $beanType, $whereArr);
2159                 }
2160             }
2161         }
2162         $countq = "SELECT count(people.id) c from ($finalQuery) people";
2163                 return array('query' => $finalQuery, 'countQuery' => $countq);
2164     }
2165
2166     function findEmailFromBeanIds($beanIds, $beanType, $whereArr) {
2167         global $current_user;
2168                 $q = '';
2169                 $whereAdd = "";
2170                 $relatedIDs = '';
2171                 if ($beanIds != '') {
2172                         foreach ($beanIds as $key => $value) {
2173                                 $beanIds[$key] = '\''.$value.'\'';
2174                         }
2175                         $relatedIDs = implode(',', $beanIds);
2176                 }
2177
2178                 if ($beanType == 'accounts') {
2179                         if (isset($whereArr['first_name'])) {
2180                                 $whereArr['name'] = $whereArr['first_name'];
2181                         }
2182                         unset($whereArr['last_name']);
2183                         unset($whereArr['first_name']);
2184                 }
2185
2186                 foreach($whereArr as $column => $clause) {
2187                         if(!empty($whereAdd)) {
2188                                 $whereAdd .= " OR ";
2189                         }
2190                         $clause = $current_user->db->quote($clause);
2191                         $whereAdd .= "{$column} LIKE '{$clause}%'";
2192                 }
2193                 $table = $beanType;
2194                 $module = ucfirst($table);
2195             $class = substr($module, 0, strlen($module) - 1);
2196             require_once("modules/{$module}/{$class}.php");
2197             $person = new $class();
2198                 if ($person->ACLAccess('list')) {
2199                         if ($relatedIDs != '') {
2200                                 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id in ($relatedIDs))";
2201                         } else {
2202                                 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1)";
2203                         }
2204
2205                         if (ACLController::requireOwner($module, 'list')) {
2206                                 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2207                         } // if
2208                         if(!empty($whereAdd)) {
2209                                 $where .= " AND ({$whereAdd})";
2210                         }
2211
2212                         if ($beanType === 'accounts') {
2213                                 $t = "SELECT {$table}.id, '' first_name, {$table}.name last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2214                         } else {
2215                                 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2216                         }
2217
2218                         $t .= "FROM {$table} ";
2219                         $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2220                         $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2221                         $t .= " WHERE {$where}";
2222                 } // if
2223                 return $t;
2224     }
2225
2226         /**
2227          * Cleans UID lists
2228          * @param mixed $uids
2229          * @param bool $returnString False will return an array
2230          * @return mixed
2231          */
2232         function _cleanUIDList($uids, $returnString=false) {
2233                 global $app_strings;
2234                 $GLOBALS['log']->debug("_cleanUIDList: before - [ {$uids} ]");
2235
2236                 if(!is_array($uids)) {
2237                         $returnString = true;
2238
2239                         $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
2240                         $uids = $exUids;
2241                 }
2242
2243                 $cleanUids = array();
2244                 foreach($uids as $uid) {
2245                         $cleanUids[$uid] = $uid;
2246                 }
2247
2248                 sort($cleanUids);
2249
2250                 if($returnString) {
2251                         $cleanImplode = implode($app_strings['LBL_EMAIL_DELIMITER'], $cleanUids);
2252                         $GLOBALS['log']->debug("_cleanUIDList: after - [ {$cleanImplode} ]");
2253                         return $cleanImplode;
2254                 }
2255
2256                 return $cleanUids;
2257         }
2258
2259         /**
2260          * Creates defaults for the User
2261          * @param object $user User in focus
2262          */
2263         function preflightUser(&$user) {
2264                 global $mod_strings;
2265
2266                 $goodToGo = $user->getPreference("email2Preflight", "Emails");
2267                         $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
2268                         $r = $user->db->query($q);
2269                         $a = $user->db->fetchByAssoc($r);
2270
2271                         if($a['count'] < 1) {
2272                                 require_once("include/SugarFolders/SugarFolders.php");
2273                                 // My Emails
2274                                 $folder = new SugarFolder();
2275                                 $folder->new_with_id = true;
2276                                 $folder->id = create_guid();
2277                                 $folder->name = $mod_strings['LNK_MY_INBOX'];
2278                                 $folder->has_child = 1;
2279                                 $folder->created_by = $user->id;
2280                                 $folder->modified_by = $user->id;
2281                                 $folder->is_dynamic = 1;
2282                                 $folder->folder_type = "inbound";
2283                                 $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
2284                                 $folder->save();
2285
2286                                 // My Drafts
2287                                 $drafts = new SugarFolder();
2288                                 $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
2289                                 $drafts->has_child = 0;
2290                                 $drafts->parent_folder = $folder->id;
2291                                 $drafts->created_by = $user->id;
2292                                 $drafts->modified_by = $user->id;
2293                                 $drafts->is_dynamic = 1;
2294                                 $drafts->folder_type = "draft";
2295                                 $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
2296                                 $drafts->save();
2297
2298
2299                                 // Sent Emails
2300                                 $archived = new SugarFolder();
2301                                 $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
2302                                 $archived->has_child = 0;
2303                                 $archived->parent_folder = $folder->id;
2304                                 $archived->created_by = $user->id;
2305                                 $archived->modified_by = $user->id;
2306                                 $archived->is_dynamic = 1;
2307                                 $archived->folder_type = "sent";
2308                                 $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
2309                                 $archived->save();
2310
2311                                 // Archived Emails
2312                                 $archived = new SugarFolder();
2313                                 $archived->name = $mod_strings['LBL_LIST_TITLE_MY_ARCHIVES'];
2314                                 $archived->has_child = 0;
2315                                 $archived->parent_folder = $folder->id;
2316                                 $archived->created_by = $user->id;
2317                                 $archived->modified_by = $user->id;
2318                                 $archived->is_dynamic = 1;
2319                                 $archived->folder_type = "archived";
2320                                 $archived->dynamic_query = '';
2321                                 $archived->save();
2322
2323                                 // set flag to show that this was run
2324                         $user->setPreference("email2Preflight", true, 1, "Emails");
2325                 }
2326         }
2327
2328         /**
2329          * Parses the core dynamic folder query
2330          * @param string $type 'inbound', 'draft', etc.
2331          * @param string $userId
2332          * @return string
2333          */
2334         function generateDynamicFolderQuery($type, $userId) {
2335                 $q = $this->coreDynamicFolderQuery;
2336
2337                 $status = $type;
2338
2339                 if($type == "sent") {
2340                         $type = "out";
2341                 }
2342
2343                 $replacee = array("::TYPE::", "::STATUS::", "::USER_ID::");
2344                 $replacer = array($type, $status, $userId);
2345
2346                 $ret = str_replace($replacee, $replacer, $q);
2347
2348                 if($type == 'inbound') {
2349                         $ret .= " AND status NOT IN ('sent', 'archived', 'draft') AND type NOT IN ('out', 'archived', 'draft')";
2350                 } else {
2351                         $ret .= " AND status NOT IN ('archived') AND type NOT IN ('archived')";
2352                 }
2353
2354                 return $ret;
2355         }
2356
2357         /**
2358          * Preps the User's cache dir
2359          */
2360         function preflightUserCache() {
2361                 $path = clean_path($this->userCacheDir);
2362                 if(!file_exists($this->userCacheDir))
2363                         mkdir_recursive($path);
2364
2365                 $files = findAllFiles($path, array());
2366
2367                 foreach($files as $file) {
2368                         unlink($file);
2369                 }
2370         }
2371
2372         function clearInboundAccountCache($ieId) {
2373                 global $sugar_config;
2374                 $cacheRoot = sugar_cached("modules/Emails/{$ieId}");
2375                 $files = findAllFiles($cacheRoot."/messages/", array());
2376                 foreach($files as $file) {
2377                         unlink($file);
2378                 } // fn
2379                 $files = findAllFiles($cacheRoot."/attachments/", array());
2380                 foreach($files as $file) {
2381                         unlink($file);
2382                 } // for
2383         } // fn
2384
2385         /**
2386          * returns an array of EmailTemplates that the user has access to for the compose email screen
2387          * @return array
2388          */
2389         function getEmailTemplatesArray() {
2390
2391                 global $app_strings;
2392
2393                 if(ACLController::checkAccess('EmailTemplates', 'list', true) && ACLController::checkAccess('EmailTemplates', 'view', true)) {
2394                         $et = new EmailTemplate();
2395             $etResult = $et->db->query($et->create_new_list_query('',"(type IS NULL OR type='' OR type='email')",array(),array(),''));
2396                         $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2397                         while($etA = $et->db->fetchByAssoc($etResult)) {
2398                                 $email_templates_arr[$etA['id']] = $etA['name'];
2399                         }
2400                 } else {
2401                         $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2402                 }
2403
2404                 return $email_templates_arr;
2405         }
2406
2407         function getFromAccountsArray($ie) {
2408         global $current_user;
2409         global $app_strings;
2410
2411         $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2412         $ieAccountsFrom= array();
2413
2414         $oe = new OutboundEmail();
2415         $system = $oe->getSystemMailerSettings();
2416         $ret = $current_user->getUsersNameAndEmail();
2417                 $ret['name'] = from_html($ret['name']);
2418                 $useMyAccountString = true;
2419
2420         if(empty($ret['email'])) {
2421                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2422                 $ret['email'] = $systemReturn['email'];
2423                 $ret['name'] = from_html($systemReturn['name']);
2424                 $useMyAccountString = false;
2425                 } // if
2426
2427                 $myAccountString = '';
2428                 if ($useMyAccountString) {
2429                         $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2430                 } // if
2431
2432                 //Check to make sure that the user has set the associated inbound email account -> outbound account is active.
2433                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2434         $sf = new SugarFolder();
2435         $groupSubs = $sf->getSubscriptions($current_user);
2436
2437         foreach($ieAccountsFull as $k => $v)
2438         {
2439             $personalSelected = (!empty($showFolders) && in_array($v->id, $showFolders));
2440
2441             $allowOutboundGroupUsage = $v->get_stored_options('allow_outbound_group_usage',FALSE);
2442             $groupSelected = ( in_array($v->groupfolder_id, $groupSubs)  && $allowOutboundGroupUsage);
2443             $selected = ( $personalSelected || $groupSelected );
2444
2445             if(!$selected)
2446             {
2447                 $GLOBALS['log']->debug("Inbound Email {$v->name}, not selected and will not be available for selection within compose UI.");
2448                 continue;
2449             }
2450
2451                 $name = $v->get_stored_options('from_name');
2452                 $addr = $v->get_stored_options('from_addr');
2453                 if ($name != null && $addr != null) {
2454                         $name = from_html($name);
2455                         if (!$v->is_personal) {
2456                         $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2457                         } else {
2458                         $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr})");
2459                         } // else
2460                 } // if
2461         } // foreach
2462
2463
2464         $userSystemOverride = $oe->getUsersMailerForSystemOverride($current_user->id);
2465         //Substitute in the users system override if its available.
2466         if($userSystemOverride != null)
2467                     $system = $userSystemOverride;
2468
2469         if( !empty($system->mail_smtpserver) )
2470         {
2471             $admin = new Administration();
2472             $admin->retrieveSettings(); //retrieve all admin settings.
2473             $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2474                 "{$ret['name']} ({$ret['email']}){$myAccountString}");
2475         }
2476
2477         return $ieAccountsFrom;
2478     } // fn
2479
2480     /**
2481      * This function will return all the accounts this user has access to based on the
2482      * match of the emailId passed in as a parameter
2483      *
2484      * @param unknown_type $ie
2485      * @return unknown
2486      */
2487         function getFromAllAccountsArray($ie, $ret) {
2488         global $current_user;
2489         global $app_strings;
2490
2491         $ret['fromAccounts'] = array();
2492         if (!isset($ret['to']) && !empty($ret['from'])) {
2493                 $ret['fromAccounts']['status'] = false;
2494                 return $ret;
2495         }
2496         $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2497                 $foundInPersonalAccounts = false;
2498                 $foundInGroupAccounts = false;
2499                 $foundInSystemAccounts = false;
2500
2501                 //$toArray = array();
2502                 if ($ret['type'] == "draft") {
2503                         $toArray = explode(",", $ret['from']);
2504                 } else {
2505                         $toArray = $ie->email->email2ParseAddressesForAddressesOnly($ret['to']);
2506                 } // else
2507         foreach($ieAccountsFull as $k => $v) {
2508                 $storedOptions = unserialize(base64_decode($v->stored_options));
2509                         if (  array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2510                         if ($v->is_personal) {
2511                                         $foundInPersonalAccounts = true;
2512                                         break;
2513                                 } else  {
2514                                         $foundInGroupAccounts = true;
2515                                 } // else
2516                         } // if
2517         } // foreach
2518
2519             $oe = new OutboundEmail();
2520         $system = $oe->getSystemMailerSettings();
2521
2522         $return = $current_user->getUsersNameAndEmail();
2523                 $return['name'] = from_html($return['name']);
2524                 $useMyAccountString = true;
2525
2526         if(empty($return['email'])) {
2527                 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2528                 $return['email'] = $systemReturn['email'];
2529                 $return['name'] = from_html($systemReturn['name']);
2530                 $useMyAccountString = false;
2531                 } // if
2532
2533                 $myAccountString = '';
2534                 if ($useMyAccountString) {
2535                         $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2536                 } // if
2537
2538         if(!empty($system->id)) {
2539
2540             $admin = new Administration();
2541             $admin->retrieveSettings(); //retrieve all admin settings.
2542             if (in_array(trim($return['email']), $toArray)) {
2543                 $foundInSystemAccounts = true;
2544             } // if
2545         } // if
2546
2547         if (!$foundInPersonalAccounts && !$foundInGroupAccounts && !$foundInSystemAccounts) {
2548                 $ret['fromAccounts']['status'] = false;
2549                 return $ret;
2550         } // if
2551
2552         $ieAccountsFrom= array();
2553         foreach($ieAccountsFull as $k => $v) {
2554                 $storedOptions = unserialize(base64_decode($v->stored_options));
2555                 $storedOptionsName = from_html($storedOptions['from_name']);
2556
2557                 $selected = false;
2558                         if (array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2559                 //if ($ret['to'] == $storedOptions['from_addr']) {
2560                         $selected = true;
2561                         } // if
2562                 if ($foundInPersonalAccounts) {
2563                         if ($v->is_personal) {
2564                         $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']})");
2565                         } // if
2566                 } else {
2567                 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2568                 } // else
2569         } // foreach
2570
2571         if(!empty($system->id)) {
2572             if (!$foundInPersonalAccounts && !$foundInGroupAccounts && $foundInSystemAccounts) {
2573             $ieAccountsFrom[] = array("value" => $system->id, "selected" => true, "text" =>
2574                 "{$return['name']} ({$return['email']}){$myAccountString}");
2575             } else {
2576             $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2577                 "{$return['name']} ({$return['email']}){$myAccountString}");
2578             } // else
2579         } // if
2580
2581         $ret['fromAccounts']['status'] = ($foundInPersonalAccounts || $foundInGroupAccounts || $foundInSystemAccounts) ? true : false;
2582                 $ret['fromAccounts']['data'] = $ieAccountsFrom;
2583         return $ret;
2584     } // fn
2585
2586
2587         /**
2588          * takes an array and creates XML
2589          * @param array Array to convert
2590          * @param string Name to wrap highest level items in array
2591          * @return string XML
2592          */
2593         function arrayToXML($a, $paramName) {
2594                 if(!is_array($a))
2595                         return '';
2596
2597                 $bad = array("<",">","'",'"',"&");
2598                 $good = array("&lt;", "&gt;", "&#39;", "&quot;","&amp;");
2599
2600                 $ret = "";
2601
2602                 for($i=0; $i<count($a); $i++) {
2603                         $email = $a[$i];
2604                         $ret .= "\n<{$paramName}>";
2605
2606                         foreach($email as $k => $v) {
2607                                 $ret .= "\n\t<{$k}>".str_replace($bad, $good, $v)."</{$k}>";
2608                         }
2609                         $ret .= "\n</{$paramName}>";
2610                 }
2611                 return $ret;
2612         }
2613
2614         /**
2615          * Re-used option getter for Show Accounts multiselect pane
2616          */
2617         function getShowAccountsOptions(&$ie) {
2618                 global $current_user;
2619                 global $app_strings;
2620                 global $mod_strings;
2621
2622                 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2623                 $ieAccountsShowOptionsMeta = array();
2624                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2625
2626                 $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
2627
2628                 foreach($ieAccountsFull as $k => $v) {
2629                         $selected = (!empty($showFolders) && in_array($v->id, $showFolders)) ? true : false;
2630                         $default = ($defaultIEAccount == $v->id) ? TRUE : FALSE;
2631                         $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
2632                         $type = ($v->is_personal) ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
2633
2634                         $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected,
2635                                                                                                         'server_url' => $v->server_url, 'is_group' => !$v->is_personal,'group_id' => $v->group_id,
2636                                                                                                         'is_default' => $default, 'has_groupfolder' => $has_groupfolder,'type' => $type );
2637                 }
2638
2639                 //Retrieve the grou folders
2640                 $f = new SugarFolder();
2641                 $groupFolders = $f->getGroupFoldersForSettings($current_user);
2642
2643                 foreach ($groupFolders as $singleGroup)
2644                 {
2645                     //Retrieve the related IE accounts.
2646             $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
2647
2648             if(count($relatedIEAccounts) == 0)
2649                 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
2650             else if(count($relatedIEAccounts) == 1)
2651             {
2652                 if($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce')
2653                     continue;
2654
2655                 $server_url = $relatedIEAccounts[0]->server_url;
2656             }
2657             else
2658                 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
2659
2660             $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
2661                     $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'],
2662                                                                                                         'server_url' => $server_url, 'is_group' => true,'group_id' => $singleGroup['id'],
2663                                                                                                         'is_default' => FALSE, 'has_groupfolder' => true,'type' => $type);
2664                 }
2665
2666
2667                 return $ieAccountsShowOptionsMeta;
2668         }
2669
2670         function getShowAccountsOptionsForSearch(&$ie) {
2671                 global $current_user;
2672                 global $app_strings;
2673
2674                 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2675                 //$ieAccountsShowOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
2676                 $ieAccountsShowOptionsMeta = array();
2677                 $ieAccountsShowOptionsMeta[] = array("value" => "", "text" => $app_strings['LBL_NONE'], 'selected' => '');
2678                 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2679
2680                 foreach($ieAccountsFull as $k => $v) {
2681                         if(!in_array($v->id, $showFolders)) {
2682                                 continue;
2683                         }
2684                         $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
2685                         $ieAccountsShowOptionsMeta[] = array("value" => $v->id, "text" => $group.$v->name, 'protocol' => $v->protocol);
2686                 }
2687
2688                 return $ieAccountsShowOptionsMeta;
2689         }
2690         /**
2691          * Formats a display message on successful async call
2692          * @param string $type Type of message to display
2693          */
2694         function displaySuccessMessage($type) {
2695                 global $app_strings;
2696
2697                 switch($type) {
2698                         case "delete":
2699                                 $message = $app_strings['LBL_EMAIL_DELETE_SUCCESS'];
2700                         break;
2701
2702                         default:
2703                                 $message = "NOOP: invalid type";
2704                         break;
2705                 }
2706
2707                 $this->smarty->assign('app_strings', $app_strings);
2708                 $this->smarty->assign('message', $message);
2709                 echo $this->smarty->fetch("modules/Emails/templates/successMessage.tpl");
2710         }
2711
2712         /**
2713          * Validates existence and expiration of a cache file
2714          * @param string $ieId
2715          * @param string $type Type of cache file: folders, messages, etc.
2716          * @param string $file The cachefile name
2717          * @param int refreshOffset Refresh time in secs.
2718          * @return mixed.
2719          */
2720         function validCacheFileExists($ieId, $type, $file, $refreshOffset=-1) {
2721                 global $sugar_config;
2722
2723                 if($refreshOffset == -1) {
2724                         $refreshOffset = $this->cacheTimeouts[$type]; // use defaults
2725                 }
2726
2727                 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2728                 if(file_exists($cacheFilePath)) {
2729                         return true;
2730                 }
2731
2732                 return false;
2733         }
2734
2735         /**
2736          * retrieves the cached value
2737          * @param string $ieId
2738          * @param string $type Type of cache file: folders, messages, etc.
2739          * @param string $file The cachefile name
2740          * @param string $key name of cache value
2741          * @return mixed
2742          */
2743         function getCacheValue($ieId, $type, $file, $key) {
2744                 global $sugar_config;
2745
2746                 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2747                 $cacheFile = array();
2748
2749                 if(file_exists($cacheFilePath)) {
2750                         include($cacheFilePath); // provides $cacheFile
2751
2752                         if(isset($cacheFile[$key])) {
2753                                 $ret = unserialize($cacheFile[$key]);
2754                                 return $ret;
2755                         }
2756                 } else {
2757                         $GLOBALS['log']->debug("EMAILUI: cache file not found [ {$cacheFilePath} ] - creating blank cache file");
2758                         $this->writeCacheFile('retArr', array(), $ieId, $type, $file);
2759                 }
2760
2761                 return null;
2762         }
2763
2764         /**
2765          * retrieves the cache file last touched time
2766          * @param string $ieId
2767          * @param string $type Type of cache file: folders, messages, etc.
2768          * @param string $file The cachefile name
2769          * @return string
2770          */
2771         function getCacheTimestamp($ieId, $type, $file) {
2772                 global $sugar_config;
2773
2774                 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2775                 $cacheFile = array();
2776
2777                 if(file_exists($cacheFilePath)) {
2778                         include($cacheFilePath); // provides $cacheFile['timestamp']
2779
2780                         if(isset($cacheFile['timestamp'])) {
2781                                 $GLOBALS['log']->debug("EMAILUI: found timestamp [ {$cacheFile['timestamp']} ]");
2782                                 return $cacheFile['timestamp'];
2783                         }
2784                 }
2785
2786                 return '';
2787         }
2788
2789         /**
2790          * Updates the timestamp for a cache file - usually to mark a "check email"
2791          * process
2792          * @param string $ieId
2793          * @param string $type Type of cache file: folders, messages, etc.
2794          * @param string $file The cachefile name
2795          */
2796         function setCacheTimestamp($ieId, $type, $file) {
2797                 global $sugar_config;
2798
2799                 $cacheFilePath = sugar_cached("modules/Emails/{$ieId}/{$type}/{$file}");
2800                 $cacheFile = array();
2801
2802                 if(file_exists($cacheFilePath)) {
2803                         include($cacheFilePath); // provides $cacheFile['timestamp']
2804
2805                         if(isset($cacheFile['timestamp'])) {
2806                                 $cacheFile['timestamp'] = strtotime('now');
2807                                 $GLOBALS['log']->debug("EMAILUI: setting updated timestamp [ {$cacheFile['timestamp']} ]");
2808                                 return $this->_writeCacheFile($cacheFile, $cacheFilePath);
2809                         }
2810                 }
2811         }
2812
2813
2814         /**
2815          * Writes caches to flat file in cache dir.
2816          * @param string $key Key to the main cache entry (not timestamp)
2817          * @param mixed $var Variable to be cached
2818          * @param string $ieId I-E focus ID
2819          * @param string $type Folder in cache
2820          * @param string $file Cache file name
2821          */
2822         function writeCacheFile($key, $var, $ieId, $type, $file) {
2823                 global $sugar_config;
2824
2825                 $the_file = sugar_cached("/modules/Emails/{$ieId}/{$type}/{$file}");
2826                 $timestamp = strtotime('now');
2827                 $array = array();
2828                 $array['timestamp'] = $timestamp;
2829                 $array[$key] = serialize($var); // serialized since varexport_helper() can't handle PHP objects
2830
2831                 return $this->_writeCacheFile($array, $the_file);
2832         }
2833
2834         /**
2835          * Performs the actual file write.  Abstracted from writeCacheFile() for
2836          * flexibility
2837          * @param array $array The array to write to the cache
2838          * @param string $file Full path (relative) with cache file name
2839          * @return bool
2840          */
2841         function _writeCacheFile($array, $file) {
2842                 global $sugar_config;
2843
2844                 $arrayString = var_export_helper($array);
2845
2846                 $date = date("r");
2847             $the_string =<<<eoq
2848 <?php // created: {$date}
2849         \$cacheFile = {$arrayString};
2850 ?>
2851 eoq;
2852             if($fh = @sugar_fopen($file, "w")) {
2853                 fputs($fh, $the_string);
2854                 fclose($fh);
2855                 return true;
2856             } else {
2857                 $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]");
2858                 return false;
2859             }
2860         }
2861
2862         /**
2863          * Generate JSON encoded data to be consumed by yui datatable.
2864          *
2865          * @param array $data
2866          * @param string $resultsParam The resultsList name
2867          * @return string
2868          */
2869         function jsonOuput($data, $resultsParam, $count=0, $fromCache=true, $unread=-1) {
2870             global $app_strings;
2871
2872                 $count = ($count > 0) ? $count : 0;
2873
2874                 if(isset($a['fromCache']))
2875                         $cached = ($a['fromCache'] == 1) ? 1 : 0;
2876                 else
2877                         $cached = ($fromCache) ? 1 : 0;
2878
2879                 if($data['mbox'] == 'undefined' || empty($data['mbox']))
2880                         $data['mbox'] = $app_strings['LBL_NONE'];
2881
2882                 $jsonOut = array('TotalCount' => $count, 'FromCache' => $cached, 'UnreadCount' => $unread, $resultsParam => $data['out']);
2883
2884                 return json_encode($jsonOut);
2885         }
2886         /**
2887          * generates XML output from an array
2888          * @param array
2889          * @param string master list Item
2890          * @return string
2891          */
2892         function xmlOutput($a, $paramName, $count=0, $fromCache=true, $unread=-1) {
2893                 global $app_strings;
2894                 $count = ($count > 0) ? $count : 0;
2895
2896                 if(isset($a['fromCache'])) {
2897                         $cached = ($a['fromCache'] == 1) ? 1 : 0;
2898                 } else {
2899                         $cached = ($fromCache) ? 1 : 0;
2900                 }
2901
2902                 if($a['mbox'] == 'undefined' || empty($a['mbox'])) {
2903                         $a['mbox'] = $app_strings['LBL_NONE'];
2904                 }
2905
2906                 $xml = $this->arrayToXML($a['out'], $paramName);
2907
2908                 $ret =<<<eoq
2909 <?xml version="1.0" encoding="UTF-8"?>
2910 <EmailPage>
2911 <TotalCount>{$count}</TotalCount>
2912 <UnreadCount>{$unread}</UnreadCount>
2913 <FromCache> {$cached} </FromCache>
2914 <{$paramName}s>
2915 {$xml}
2916 </{$paramName}s>
2917 </EmailPage>
2918 eoq;
2919                 return $ret;
2920         }
2921
2922     /**
2923      * Generate to/cc addresses string in email detailview.
2924      *
2925      * @param string $str
2926      * @param string $target values: to, cc
2927      * @param int $defaultNum
2928      * @return string $str
2929      */
2930         function generateExpandableAddrs($str) {
2931             global $mod_strings;
2932             $tempStr = $str.',';
2933         $tempStr = html_entity_decode($tempStr);
2934             $tempStr = $this->unifyEmailString($tempStr);
2935         $defaultNum = 2;
2936         $pattern = '/@.*,/U';
2937         preg_match_all($pattern, $tempStr, $matchs);
2938         $totalCount = count($matchs[0]);
2939
2940         if(!empty($matchs[0]) && $totalCount > $defaultNum) {
2941             $position = strpos($tempStr, $matchs[0][$defaultNum]);
2942             $hiddenCount = $totalCount - $defaultNum;
2943             $frontStr = substr($tempStr, 0, $position);
2944             $backStr = substr($tempStr, $position, -1);
2945             $str = htmlentities($frontStr) . '<a class="utilsLink" onclick="javascript: SUGAR.email2.detailView.displayAllAddrs(this);">...['.$mod_strings['LBL_EMAIL_DETAIL_VIEW_SHOW'].$hiddenCount.$mod_strings['LBL_EMAIL_DETAIL_VIEW_MORE'].']</a><span style="display: none;">' .htmlentities($backStr).'</span>';
2946         }
2947
2948         return $str;
2949     }
2950
2951     /**
2952      * Unify the seperator as ,
2953      *
2954      * @param String $str email address string
2955      * @return String converted string
2956      */
2957     function unifyEmailString($str) {
2958         preg_match_all('/@.*;/U', $str, $matches);
2959         if(!empty($matches[0])) {
2960             foreach($matches[0] as $key => $value) {
2961                 $new[] = str_replace(";",",",$value);
2962             }
2963             return str_replace($matches[0], $new, $str);
2964         }
2965         return $str;
2966     }
2967 } // end class def