2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 /*********************************************************************************
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
42 * Reserved. Contributor(s): ______________________________________..
43 *********************************************************************************/
45 require_once("include/ytree/Tree.php");
46 require_once("include/ytree/ExtNode.php");
47 require_once("include/SugarFolders/SugarFolders.php");
53 var $folder; // place holder for SugarFolder object
54 var $folderStates = array(); // array of folderPath names and their states (1/0)
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
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'";
76 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
78 if(!empty($folderStateSerial)) {
79 $this->folderStates = unserialize($folderStateSerial);
82 $this->smarty = new Sugar_Smarty();
83 $this->folder = new SugarFolder();
84 $this->userCacheDir = "{$sugar_config['cache_dir']}modules/Emails/{$current_user->id}";
85 $this->db = DBManagerFactory::getInstance();
89 ///////////////////////////////////////////////////////////////////////////
92 * Renders the frame for emails
94 function displayEmailFrame() {
96 require_once("include/OutboundEmail/OutboundEmail.php");
98 global $app_strings, $app_list_strings;
100 global $sugar_config;
101 global $current_user;
105 global $sugar_version;
106 global $sugar_flavor;
107 global $current_language;
108 global $server_unique_key;
110 $this->preflightUserCache();
111 $ie = new InboundEmail();
118 'unreadChecked' => 0,
122 $this->_generateComposeConfigData('email_compose');
125 //Check quick create module access
126 $QCAvailableModules = $this->_loadQuickCreateModules();
128 //Get the quickSearch js needed for assigned user id on Search Tab
129 require_once('include/QuickSearchDefaults.php');
130 $qsd = new QuickSearchDefaults();
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);
139 ///////////////////////////////////////////////////////////////////////
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);
159 $e2UserPreferences = $this->getUserPrefsJS();
160 $emailSettings = $e2UserPreferences['emailSettings'];
162 ///////////////////////////////////////////////////////////////////////
164 // settings: accounts
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());
172 $ieAccounts = $ie->retrieveByGroupId($current_user->id);
173 $ieAccountsOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
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";
181 $this->smarty->assign('ieAccounts', $ieAccountsOptions);
182 $this->smarty->assign('rollover', $this->rolloverStyle);
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'));
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');
197 'options' => $locale->getCharsetSelect(),
198 'selected' => $charsetSelectedValue,
200 $this->smarty->assign('charset', $charset);
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']));
208 //// END USER SETTINGS
209 ///////////////////////////////////////////////////////////////////////
211 ///////////////////////////////////////////////////////////////////////
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">
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">
225 $this->smarty->assign('signatureButtons', $signatureButtons);
226 $this->smarty->assign('signaturePrepend', $prependSignature == 'true' ? 'CHECKED' : '');
228 ///////////////////////////////////////////////////////////////////////
230 ///////////////////////////////////////////////////////////////////////
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 ///////////////////////////////////////////////////////////////////////
238 ///////////////////////////////////////////////////////////////////////
239 //// FOLDERS & TreeView
240 $this->smarty->assign('groupUserOptions', $ie->getGroupsWithSelectOptions(array('' => $app_strings['LBL_EMAIL_CREATE_NEW'])));
242 $tree = $this->getMailboxNodes();
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).";";
252 $preloadFolder .= "new Object();";
255 ///////////////////////////////////////////////////////////////////////
258 $out .= $this->smarty->fetch("modules/Emails/templates/_baseEmail.tpl");
259 $out .= $tree->generate_header();
260 $out .= $tree->generateNodesNoInit(true, 'email2treeinit');
262 <script type="text/javascript" language="javascript">
264 var loader = new YAHOO.util.YUILoader({
266 "layout", "element", "tabview", "menu",
267 "cookie", "sugarwidgets"
270 skin: { base: 'blank', defaultSkin: '' },
271 onSuccess: email2init,
273 base: "include/javascript/yui/build/"
276 name :"sugarwidgets",
278 fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
279 varName: "YAHOO.SUGAR",
280 requires: ["datatable", "dragdrop", "treeview", "tabview", "calendar"]
294 * Generate the frame needed for the quick compose email UI. This frame is loaded dynamically
297 * @return JSON An object containing html markup and js script variables.
299 function displayQuickComposeEmailFrame()
301 $this->preflightUserCache();
303 $this->_generateComposeConfigData('email_compose_light');
304 $javascriptOut = $this->smarty->fetch("modules/Emails/templates/_baseConfigData.tpl");
306 $divOut = $this->smarty->fetch("modules/Emails/templates/overlay.tpl");
307 $divOut .= $this->smarty->fetch("modules/Emails/templates/addressSearchContent.tpl");
309 $outData = array('jsData' => $javascriptOut,'divData'=> $divOut);
310 $out = json_encode($outData);
315 * Load the modules from the metadata file and include in a custom one if it exists
319 protected function _loadQuickCreateModules()
321 $QCAvailableModules = array();
322 $QCModules = array();
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');
329 foreach($QCModules as $module) {
330 $seed = SugarModule::get($module)->loadBean();
331 if ( ( $seed instanceOf SugarBean ) && $seed->ACLAccess('edit') ) {
332 $QCAvailableModules[] = $module;
336 return $QCAvailableModules;
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
345 * @param String $emailLinkUrl
346 * @return JSON Object containing the composePackage and full link url
348 function generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, $lazyLoad=false)
350 $composeData = explode("&",$emailLinkUrl);
351 $a_composeData = array();
352 foreach ($composeData as $singleRequest)
354 $tmp = explode("=",$singleRequest);
355 $a_composeData[$tmp[0]] = urldecode($tmp[1]);
358 return $this->generateComposePackageForQuickCreate($a_composeData,$emailLinkUrl, $lazyLoad);
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)
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 * @return JSON Object containg composePackage and fullLinkUrl
370 function generateComposePackageForQuickCreate($composeData,$fullLinkUrl, $lazyLoad=false)
372 $_REQUEST['forQuickCreate'] = true;
375 require_once('modules/Emails/Compose.php');
376 $composePackage = generateComposeDataPackage($composeData,FALSE);
378 $composePackage = $composeData;
381 //JSON object is passed into the function defined within the a href onclick event
382 //which is delimeted by '. Need to escape all single quotes, every other char is valid.
383 foreach ($composePackage as $key => $singleCompose)
385 if (is_string($singleCompose))
386 $composePackage[$key] = str_replace("'","'",$singleCompose);
389 $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
390 $j_quickComposeOptions = json_encode($quickComposeOptions);
392 return $j_quickComposeOptions;
396 * Generate the config data needed for the Full Compose UI and the Quick Compose UI. The set of config data
397 * returned is the minimum set needed by the quick compose UI.
399 * @param String $type Drives which tinyMCE options will be included.
401 function _generateComposeConfigData($type = "email_compose_light" )
403 global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
406 $parent_types = $app_list_strings['record_type_display'];
407 $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
409 foreach($disabled_parent_types as $disabled_parent_type) {
410 unset($parent_types[$disabled_parent_type]);
412 asort($parent_types);
413 $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
416 require_once("include/SugarTinyMCE.php");
417 $tiny = new SugarTinyMCE();
418 $tinyConf = $tiny->getConfig($type);
420 //Generate Language Packs
421 $lang = "var app_strings = new Object();\n";
422 foreach($app_strings as $k => $v) {
423 if(strpos($k, 'LBL_EMAIL_') !== false) {
424 $lang .= "app_strings.{$k} = '{$v}';\n";
427 //Get the email mod strings but don't use the global variable as this may be overridden by
428 //other modules when the quick create is rendered.
429 $email_mod_strings = return_module_language($current_language,'Emails');
430 $modStrings = "var mod_strings = new Object();\n";
431 foreach($email_mod_strings as $k => $v) {
432 $v = str_replace("'", "\'", $v);
433 $modStrings .= "mod_strings.{$k} = '{$v}';\n";
435 $lang .= "\n\n{$modStrings}\n";
437 //Grab the Inboundemail language pack
438 $ieModStrings = "var ie_mod_strings = new Object();\n";
439 $ie_mod_strings = return_module_language($current_language,'InboundEmail');
440 foreach($ie_mod_strings as $k => $v) {
441 $v = str_replace("'", "\'", $v);
442 $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
444 $lang .= "\n\n{$ieModStrings}\n";
446 $this->smarty->assign('linkBeans', $linkBeans);
447 $this->smarty->assign('linkBeansOptions', $parent_types);
448 $this->smarty->assign('tinyMCE', $tinyConf);
449 $this->smarty->assign('lang', $lang);
450 $this->smarty->assign('app_strings', $app_strings);
451 $this->smarty->assign('mod_strings', $email_mod_strings);
452 $ie1 = new InboundEmail();
455 $defsigID = $current_user->getPreference('signature_default');
456 $defaultSignature = $current_user->getDefaultSignature();
457 $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
458 $this->smarty->assign('defaultSignature', $sigJson);
459 $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
461 $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
463 //Get the users default outbound id
464 $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
465 $this->smarty->assign('defaultOutID', $defaultOutID);
468 $charsets = json_encode($locale->getCharsetSelect());
469 $this->smarty->assign('emailCharsets', $charsets);
471 //Relateable List of People for address book search
473 $peopleTables = array("users",
478 $filterPeopleTables = array();
479 global $app_list_strings, $app_strings;
480 $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
481 foreach($peopleTables as $table) {
482 $module = ucfirst($table);
483 $class = substr($module, 0, strlen($module) - 1);
484 require_once("modules/{$module}/{$class}.php");
485 $person = new $class();
487 if (!$person->ACLAccess('list')) continue;
488 $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
490 $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
497 ///////////////////////////////////////////////////////////////////////////
499 ///////////////////////////////////////////////////////////////////////////
502 * Retrieves all relationship metadata for a user's address book
505 function getContacts() {
506 global $current_user;
508 $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
509 $r = $this->db->query($q);
513 while($a = $this->db->fetchByAssoc($r)) {
514 $ret[$a['bean_id']] = array(
515 'id' => $a['bean_id'],
516 'module' => $a['bean'],
524 * Saves changes to a user's address book
525 * @param array contacts
527 function setContacts($contacts) {
528 global $current_user;
530 $oldContacts = $this->getContacts();
532 foreach($contacts as $cid => $contact) {
533 if(!in_array($contact['id'], $oldContacts)) {
534 $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
535 $r = $this->db->query($q, true);
541 * Removes contacts from the user's address book
544 function removeContacts($ids) {
545 global $current_user;
549 foreach($ids as $id) {
553 $concat .= "'{$id}'";
556 $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
557 $r = $this->db->query($q);
561 * saves editted Contact info
562 * @param string $str JSON serialized object
564 function saveContactEdit($str) {
566 $json = getJSONobj();
568 $str = from_html($str);
569 $obj = $json->decode($str);
571 $contact = new Contact();
572 $contact->retrieve($obj['contact_id']);
573 $contact->first_name = $obj['contact_first_name'];
574 $contact->last_name = $obj['contact_last_name'];
577 // handle email address changes
578 $addresses = array();
580 foreach($obj as $k => $req) {
581 if(strpos($k, 'emailAddress') !== false) {
582 $addresses[$k] = $req;
586 // prefill some REQUEST vars for emailAddress save
587 $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
588 $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
589 $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
593 * Prepares the Edit Contact mini-form via template assignment
594 * @param string id ID of contact in question
595 * @param string module Module in focus
598 function getEditContact($id, $module) {
602 if(!class_exists("Contact")) {
606 $contact = new Contact();
607 $contact->retrieve($_REQUEST['id']);
610 if($contact->ACLAccess('edit')) {
611 $contactMeta = array();
612 $contactMeta['id'] = $contact->id;
613 $contactMeta['module'] = $contact->module_dir;
614 $contactMeta['first_name'] = $contact->first_name;
615 $contactMeta['last_name'] = $contact->last_name;
617 $this->smarty->assign("app_strings", $app_strings);
618 $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
619 $this->smarty->assign("contact", $contactMeta);
621 $ea = new SugarEmailAddress();
622 $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
623 $this->smarty->assign("emailWidget", $newEmail['html']);
625 $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
626 $ret['prefillData'] = $newEmail['prefillData'];
629 $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
630 $ret['prefillData'] = '{}';
634 $ret['contactName'] = $contact->full_name;
641 * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
643 * @param array $contacts Array of contact types -> IDs
644 * @param object $user User in focus
647 function getUserContacts($contacts, $user=null) {
649 global $current_user;
653 $user = $current_user;
656 $emailAddress = new SugarEmailAddress();
662 foreach($contacts as $contact) {
663 if(!isset($modules[$contact['module']])) {
664 $modules[$contact['module']] = array();
666 $modules[$contact['module']][] = $contact;
669 foreach($modules as $module => $contacts) {
671 $union .= " UNION ALL ";
674 $table = strtolower($module);
677 foreach($contacts as $contact) {
678 if(!empty($idsSerial)) {
681 $idsSerial .= "'{$contact['id']}'";
684 $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
687 $union .= " ORDER BY last_name";
690 $r = $user->db->query($union);
694 while($a = $user->db->fetchByAssoc($r)) {
697 $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
699 $c['module'] = $a['module'];
700 $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
706 //// END ADDRESS BOOK
707 ///////////////////////////////////////////////////////////////////////////
710 ///////////////////////////////////////////////////////////////////////////
711 //// EMAIL 2.0 Preferences
712 function getUserPrefsJS() {
713 global $current_user;
716 // sort order per mailbox view
717 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
718 $sortArray = array();
719 if(!empty($sortSerial)) {
720 $sortArray = unserialize($sortSerial);
723 // treeview collapsed/open states
724 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
725 $folderStates = array();
726 if(!empty($folderStateSerial)) {
727 $folderStates = unserialize($folderStateSerial);
730 // subscribed accounts
731 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
734 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
736 if(empty($emailSettings)) {
737 $emailSettings = array();
738 $emailSettings['emailCheckInterval'] = -1;
739 $emailSettings['autoImport'] = '';
740 $emailSettings['alwaysSaveOutbound'] = '1';
741 $emailSettings['sendPlainText'] = '';
742 $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
743 $emailSettings['showNumInList'] = 20;
747 $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
748 $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
751 $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
753 $listViewSort = array(
755 "sortDirection" => 'DESC',
759 $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
760 $signatureDefault = $current_user->getPreference('signature_default');
762 'signature_prepend' => $signaturePrepend,
763 'signature_default' => $signatureDefault
769 'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
770 'full_name' => from_html($current_user->full_name),
773 $userPreferences = array();
774 $userPreferences['sort'] = $sortArray;
775 $userPreferences['folderStates'] = $folderStates;
776 $userPreferences['showFolders'] = $showFolders;
777 $userPreferences['emailSettings'] = $emailSettings;
778 $userPreferences['focusFolder'] = $focusFolder;
779 $userPreferences['showUnreadOnly'] = $showUnreadOnly;
780 $userPreferences['listViewSort'] = $listViewSort;
781 $userPreferences['signatures'] = $signatures;
782 $userPreferences['current_user'] = $user;
783 return $userPreferences;
788 ///////////////////////////////////////////////////////////////////////////
789 //// FOLDER FUNCTIONS
792 * Creates a new Sugar folder
793 * @param string $nodeLabel New sugar folder name
794 * @param string $parentLabel Parent folder name
796 function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
797 global $current_user;
799 $this->folder->name = $nodeLabel;
800 $this->folder->is_group = $isGroup;
801 $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
802 $this->folder->has_child = 0;
803 $this->folder->created_by = $current_user->id;
804 $this->folder->modified_by = $current_user->id;
805 $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
807 $this->folder->save();
809 'action' => 'newFolderSave',
810 'id' => $this->folder->id,
811 'name' => $this->folder->name,
812 'is_group' => $this->folder->is_group,
813 'is_dynamic' => $this->folder->is_dynamic
818 * Saves user sort prefernces
820 function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
821 global $current_user;
823 $sortArray = array();
825 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
826 if(!empty($sortSerial)) {
827 $sortArray = unserialize($sortSerial);
830 $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
831 $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
832 $sortSerial = serialize($sortArray);
833 $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
837 * Stickies folder collapse/open state
839 function saveFolderOpenState($focusFolder, $focusFolderOpen) {
840 global $current_user;
842 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
843 $folderStates = array();
845 if(!empty($folderStateSerial)) {
846 $folderStates = unserialize($folderStateSerial);
849 $folderStates[$focusFolder] = $focusFolderOpen;
850 $newFolderStateSerial = serialize($folderStates);
851 $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
855 * saves a folder's view state
857 function saveListView($ieId, $folder) {
858 global $current_user;
860 $saveState = array();
861 $saveState['ieId'] = $ieId;
862 $saveState['folder'] = $folder;
863 $saveStateSerial = serialize($saveState);
864 $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
868 * Generates cache folder structure
870 function preflightEmailCache($cacheRoot) {
872 if(!file_exists($cacheRoot))
873 mkdir_recursive(clean_path($cacheRoot));
876 if(!file_exists($cacheRoot."/folders"))
877 mkdir_recursive(clean_path("{$cacheRoot}/folders"));
880 if(!file_exists($cacheRoot."/messages"))
881 mkdir_recursive(clean_path("{$cacheRoot}/messages"));
884 if(!file_exists($cacheRoot."/attachments"))
885 mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
888 function deleteEmailCacheForFolders($cacheRoot) {
889 $filePath = $cacheRoot."/folders/folders.php";
890 if (file_exists($filePath)) {
894 ///////////////////////////////////////////////////////////////////////////
897 * Identifies subscribed mailboxes and empties the trash
898 * @param object $ie InboundEmail
900 function emptyTrash(&$ie) {
901 global $current_user;
903 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
905 if(is_array($showFolders)) {
906 foreach($showFolders as $ieId) {
908 $ie->retrieve($ieId);
916 * returns an array of nodes that correspond to IMAP mailboxes.
917 * @param bool $forceRefresh
918 * @return object TreeView object
920 function getMailboxNodes() {
921 global $sugar_config;
922 global $current_user;
925 $tree = new Tree("frameFolders");
926 $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
929 $ie = new InboundEmail();
930 $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins. this will be set via user prefs
932 $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
933 $rootNode->dynamicloadfunction = '';
934 $rootNode->expanded = true;
935 $rootNode->dynamic_load = true;
936 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
938 if(empty($showFolders)) {
939 $showFolders = array();
943 if($current_user->hasPersonalEmail()) {
944 $personals = $ie->retrieveByGroupId($current_user->id);
946 foreach($personals as $k => $personalAccount) {
947 if(in_array($personalAccount->id, $showFolders)) {
948 // check for cache value
949 $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$personalAccount->id}";
950 $this->preflightEmailCache($cacheRoot);
952 if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
953 $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
955 $mailboxes = $personalAccount->getMailboxes();
958 $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
959 $acctNode->dynamicloadfunction = '';
960 $acctNode->expanded = false;
961 $acctNode->set_property('cls', 'ieFolder');
962 $acctNode->set_property('ieId', $personalAccount->id);
963 $acctNode->set_property('protocol', $personalAccount->protocol);
965 if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
966 if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
967 $acctNode->expanded = true;
970 $acctNode->dynamic_load = true;
972 $nodePath = $acctNode->_properties['id'];
974 foreach($mailboxes as $k => $mbox) {
975 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
976 $nodePath, false, $personalAccount));
979 $rootNode->add_node($acctNode);
985 $beans = $ie->retrieveAllByGroupId($current_user->id, false);
986 foreach($beans as $k => $groupAccount) {
987 if(in_array($groupAccount->id, $showFolders)) {
988 // check for cache value
989 $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$groupAccount->id}";
990 $this->preflightEmailCache($cacheRoot);
991 //$groupAccount->connectMailserver();
993 if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
994 $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
996 $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
999 $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
1000 $acctNode->dynamicloadfunction = '';
1001 $acctNode->expanded = false;
1002 $acctNode->set_property('isGroup', 'true');
1003 $acctNode->set_property('ieId', $groupAccount->id);
1004 $acctNode->set_property('protocol', $groupAccount->protocol);
1006 if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
1007 if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
1008 $acctNode->expanded = true;
1011 $acctNode->dynamic_load = true;
1012 $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
1014 foreach($mailboxes as $k => $mbox) {
1015 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
1016 $nodePath, true, $groupAccount));
1019 $rootNode->add_node($acctNode);
1023 // SugarFolder nodes
1024 /* SugarFolders are built at onload when the UI renders */
1026 $tree->add_node($rootNode);
1030 function getMailBoxesFromCacheValue($mailAccount) {
1031 $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
1032 $mailboxes = $foldersCache['mailboxes'];
1033 $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
1034 $mailAccount->saveMailBoxFolders($mailboxesArray);
1035 $this->deleteEmailCacheForFolders($cacheRoot);
1040 * Builds up a TreeView Node object
1044 * @param string ID of InboundEmail instance
1045 * @param string nodePath Serialized path from root node to current node
1046 * @param bool isGroup
1047 * @param bool forceRefresh
1050 function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
1051 global $sugar_config;
1053 // get unread counts
1054 $exMbox = explode("::", $nodePath);
1056 $GLOBALS['log']->debug("$key --- $nodePath::$label");
1058 if(count($exMbox) >= 2) {
1060 for($i=2; $i<count($exMbox); $i++) {
1061 if($mailbox != "") {
1064 $mailbox .= "{$exMbox[$i]}";
1067 $mailbox = substr($key, strpos($key, '.'));
1069 $unseen = $this->getUnreadCount($ie, $mailbox);
1072 //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
1076 $nodePath = $nodePath."::".$label;
1077 $node = new ExtNode($nodePath, $label);
1078 $node->dynamicloadfunction = '';
1079 $node->expanded = false;
1080 $node->set_property('labelStyle', "remoteFolder");
1083 if(array_key_exists($nodePath, $this->folderStates)) {
1084 if($this->folderStates[$nodePath] == 'open') {
1085 $node->expanded = true;
1089 $group = ($isGroup) ? 'true' : 'false';
1090 $node->dynamic_load = true;
1091 //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
1092 $node->set_property('isGroup', $group);
1093 $node->set_property('isDynamic', 'false');
1094 $node->set_property('ieId', $ieId);
1095 $node->set_property('mbox', $key);
1096 $node->set_property('unseen', $unseen);
1097 $node->set_property('cls', 'ieFolder');
1099 if(is_array($mbox)) {
1100 foreach($mbox as $k => $v) {
1101 $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
1109 * Totals the unread emails
1111 function getUnreadCount(&$ie, $mailbox) {
1112 global $sugar_config;
1116 return $ie->getCacheUnreadCount($mailbox);
1119 ///////////////////////////////////////////////////////////////////////////
1122 * Used exclusively by draft code. Returns Notes and Documents as attachments.
1126 function getDraftAttachments($ret) {
1129 // $ret['uid'] is the draft Email object's GUID
1130 $ret['attachments'] = array();
1132 $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
1133 $r = $db->query($q);
1135 while($a = $db->fetchByAssoc($r)) {
1136 $ret['attachments'][$a['id']] = array(
1138 'filename' => $a['filename'],
1145 function createCopyOfInboundAttachment($ie, $ret, $uid) {
1146 global $sugar_config;
1147 if ($ie->isPop3Protocol()) {
1148 // get the UIDL from database;
1149 $cachedUIDL = md5($uid);
1150 $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php";
1152 $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php";
1154 if(file_exists($cache)) {
1155 include($cache); // profides $cacheFile
1156 $metaOut = unserialize($cacheFile['out']);
1157 $meta = $metaOut['meta']['email'];
1158 if (isset($meta['attachments'])) {
1159 $attachmentHtmlData = $meta['attachments'];
1160 $actualAttachmentInfo = array();
1161 $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
1162 if (sizeof($actualAttachmentInfo) > 0) {
1163 foreach($actualAttachmentInfo as $key => $value) {
1166 $datasplit = explode("&", $value);
1167 $attachmentIdArray = explode("=", $datasplit[0]);
1168 $attachmentid = $attachmentIdArray[1];
1170 $fileNameArray = explode("=", $datasplit[4]);
1171 $fileName = $fileNameArray[1];
1172 $guid = create_guid();
1173 //$destination = clean_path("{$this->userCacheDir}/{$guid}{$fileName}");
1174 $destination = clean_path("{$this->userCacheDir}/{$guid}");
1176 $attachmentFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/attachments/{$attachmentid}";
1177 copy($attachmentFilePath, $destination);
1178 $ret['attachments'][$guid] = array();
1179 $ret['attachments'][$guid]['id'] = $guid . $fileName;
1180 $ret['attachments'][$guid]['filename'] = $fileName;
1190 function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
1191 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1192 while ($downLoadPHP) {
1193 $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
1194 $final = strpos($attachmentHtmlData, "\">");
1195 $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
1196 $attachmentHtmlData = substr($attachmentHtmlData, $final);
1197 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1201 * Renders the QuickCreate form from Smarty and returns HTML
1202 * @param array $vars request variable global
1203 * @param object $email Fetched email object
1204 * @param bool $addToAddressBook
1207 function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
1208 require_once("include/EditView/EditView2.php");
1209 global $app_strings;
1210 global $mod_strings;
1211 global $current_user;
1214 global $current_language;
1216 //Setup the current module languge
1217 $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
1219 $bean = $beanList[$_REQUEST['qc_module']];
1220 $class = $beanFiles[$bean];
1221 require_once($class);
1223 $focus = new $bean();
1229 $emailAddress = array();
1232 if(in_array($bean, $people)) {
1234 $focus->lead_source = 'Email';
1235 $focus->lead_source_description = trim($email->name);
1237 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
1239 if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
1240 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr_name;
1243 $name = explode(" ", trim($from));
1245 $address = trim(array_pop($name));
1246 $address = str_replace(array("<",">","<",">"), "", $address);
1248 $emailAddress[] = array(
1249 'email_address' => $address,
1250 'primary_address' => 1,
1251 'invalid_email' => 0,
1253 'reply_to_address' => 1
1256 $focus->email1 = $address;
1259 $focus->last_name = trim(array_pop($name));
1261 foreach($name as $first) {
1262 if(!empty($focus->first_name)) {
1263 $focus->first_name .= " ";
1265 $focus->first_name .= trim($first);
1269 // bugs, cases, tasks
1270 $focus->name = trim($email->name);
1273 $focus->description = trim(strip_tags($email->description));
1274 $focus->assigned_user_id = $current_user->id;
1277 $EditView = new EditView();
1278 $EditView->ss = new Sugar_Smarty();
1279 //MFH BUG#20283 - checks for custom quickcreate fields
1280 $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
1281 $EditView->process();
1282 $EditView->render();
1284 $EditView->defs['templateMeta']['form']['buttons'] = array(
1285 'email2save' => array(
1286 'id' => 'e2AjaxSave',
1287 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_SAVE_BUTTON_LABEL']
1288 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
1290 'email2saveandreply' => array(
1291 'id' => 'e2SaveAndReply',
1292 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
1293 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
1295 'email2cancel' => array(
1297 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_CANCEL']
1298 . ' " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
1303 if($addToAddressBookButton) {
1304 $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
1305 'id' => 'e2addToAddressBook',
1306 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
1307 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
1311 //Get the module language for javascript
1312 if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
1313 require_once('include/language/jsLanguage.php');
1314 jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
1316 $jsLanguage = '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/'
1317 . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c='
1318 . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
1322 $EditView->view = 'EmailQCView';
1323 $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
1324 $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
1326 $meta['html'] = $jsLanguage . $EditView->display(false, true);
1327 $meta['html'] = str_replace("src='include/SugarEmailAddress/SugarEmailAddress.js?s={$GLOBALS['js_version_key']}&c={$GLOBALS['sugar_config']['js_custom_version']}'", '', $meta['html']);
1328 $meta['emailAddress'] = $emailAddress;
1330 $mod_strings = return_module_language($current_language, 'Emails');
1336 * Renders the Import form from Smarty and returns HTML
1337 * @param array $vars request variable global
1338 * @param object $email Fetched email object
1339 * @param bool $addToAddressBook
1342 function getImportForm($vars, $email, $formName = 'ImportEditView') {
1343 require_once("include/EditView/EditView2.php");
1344 require_once("include/TemplateHandler/TemplateHandler.php");
1345 require_once('include/QuickSearchDefaults.php');
1346 $qsd = new QuickSearchDefaults();
1347 $qsd->setFormName($formName);
1349 global $app_strings;
1350 global $current_user;
1351 global $app_list_strings;
1352 $sqs_objects = array(
1353 "{$formName}_parent_name" => $qsd->getQSParent(),
1355 $smarty = new Sugar_Smarty();
1356 $smarty->assign("APP",$app_strings);
1357 $smarty->assign('formName',$formName);
1358 $showAssignTo = false;
1359 if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
1360 $showAssignTo = true;
1362 if ($showAssignTo) {
1363 if(empty($email->assigned_user_id) && empty($email->id))
1364 $email->assigned_user_id = $current_user->id;
1365 if(empty($email->assigned_name) && empty($email->id))
1366 $email->assigned_user_name = $current_user->user_name;
1367 $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
1369 $smarty->assign("showAssignedTo",$showAssignTo);
1371 $showDelete = false;
1372 if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
1375 $smarty->assign("showDelete",$showDelete);
1377 $smarty->assign("userId",$email->assigned_user_id);
1378 $smarty->assign("userName",$email->assigned_user_name);
1379 $parent_types = $app_list_strings['record_type_display'];
1380 $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
1382 $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
1383 $smarty->assign('SQS', $quicksearch_js);
1386 $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
1391 * This function returns the detail view for email in new 2.0 interface
1394 function getDetailViewForEmail2($emailId) {
1396 require_once('include/DetailView/DetailView.php');
1397 global $app_strings, $app_list_strings;
1398 global $mod_strings;
1400 $smarty = new Sugar_Smarty();
1403 $focus = new Email();
1404 $focus->retrieve($emailId);
1405 $detailView->ss = new Sugar_Smarty();
1406 $detailView = new DetailView();
1409 if($focus->type == 'out') {
1410 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name), true);
1411 } elseif ($focus->type == 'draft') {
1412 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_LIST_FORM_DRAFTS_TITLE'],$focus->name), true);
1413 } elseif($focus->type == 'inbound') {
1414 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_INBOUND_TITLE'],$focus->name), true);
1416 $smarty->assign("emailTitle", $title);
1418 // DEFAULT TO TEXT IF NO HTML CONTENT:
1419 $html = trim(from_html($focus->description_html));
1421 $smarty->assign('SHOW_PLAINTEXT', 'true');
1422 $description = nl2br($focus->description);
1424 $smarty->assign('SHOW_PLAINTEXT', 'false');
1425 $description = from_html($focus->description_html);
1428 //if not empty or set to test (from test campaigns)
1429 if (!empty($focus->parent_type) && $focus->parent_type !='test') {
1430 $smarty->assign('PARENT_MODULE', $focus->parent_type);
1431 $smarty->assign('PARENT_TYPE', $app_list_strings['record_type_display'][$focus->parent_type] . ":");
1435 $smarty->assign('MOD', $mod_strings);
1436 $smarty->assign('APP', $app_strings);
1437 $smarty->assign('GRIDLINE', $gridline);
1438 $smarty->assign('PRINT_URL', 'index.php?'.$GLOBALS['request_string']);
1439 $smarty->assign('ID', $focus->id);
1440 $smarty->assign('TYPE', $focus->type);
1441 $smarty->assign('PARENT_NAME', $focus->parent_name);
1442 $smarty->assign('PARENT_ID', $focus->parent_id);
1443 $smarty->assign('NAME', $focus->name);
1444 $smarty->assign('ASSIGNED_TO', $focus->assigned_user_name);
1445 $smarty->assign('DATE_MODIFIED', $focus->date_modified);
1446 $smarty->assign('DATE_ENTERED', $focus->date_entered);
1447 $smarty->assign('DATE_START', $focus->date_start);
1448 $smarty->assign('TIME_START', $focus->time_start);
1449 $smarty->assign('FROM', $focus->from_addr);
1450 $smarty->assign('TO', nl2br($focus->to_addrs));
1451 $smarty->assign('CC', nl2br($focus->cc_addrs));
1452 $smarty->assign('BCC', nl2br($focus->bcc_addrs));
1453 $smarty->assign('CREATED_BY', $focus->created_by_name);
1454 $smarty->assign('MODIFIED_BY', $focus->modified_by_name);
1455 $smarty->assign('DESCRIPTION', nl2br($focus->description));
1456 $smarty->assign('DESCRIPTION_HTML', from_html($focus->description_html));
1457 $smarty->assign('DATE_SENT', $focus->date_entered);
1458 $smarty->assign('EMAIL_NAME', 'RE: '.$focus->name);
1459 $smarty->assign("TAG", $focus->listviewACLHelper());
1460 $smarty->assign("SUGAR_VERSION", $GLOBALS['sugar_version']);
1461 $smarty->assign("JS_CUSTOM_VERSION", $GLOBALS['sugar_config']['js_custom_version']);
1462 if(!empty($focus->reply_to_email)) {
1465 <td class=\"tabDetailViewDL\"><slot>".$mod_strings['LBL_REPLY_TO_NAME']."</slot></td>
1466 <td colspan=3 class=\"tabDetailViewDF\"><slot>".$focus->reply_to_addr."</slot></td>
1468 $smarty->assign("REPLY_TO", $replyTo);
1470 ///////////////////////////////////////////////////////////////////////////////
1471 //// JAVASCRIPT VARS
1473 $jsVars .= "var showRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL']}';";
1474 $jsVars .= "var hideRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL_HIDE']}';";
1475 $smarty->assign("JS_VARS", $jsVars);
1476 ///////////////////////////////////////////////////////////////////////////////
1477 //// NOTES (attachements, etc.)
1478 ///////////////////////////////////////////////////////////////////////////////
1481 $where = "notes.parent_id='{$focus->id}'";
1482 //take in account if this is from campaign and the template id is stored in the macros.
1484 if(isset($macro_values) && isset($macro_values['email_template_id'])){
1485 $where = "notes.parent_id='{$macro_values['email_template_id']}'";
1487 $notes_list = $note->get_full_list("notes.name", $where, true);
1489 if(! isset($notes_list)) {
1490 $notes_list = array();
1494 for($i=0; $i<count($notes_list); $i++) {
1495 $the_note = $notes_list[$i];
1496 //$attachments .= "<a href=\"".UploadFile::get_url($the_note->filename,$the_note->id)."\" target=\"_blank\">".$the_note->name.$the_note->description ."</a><br>";
1497 $attachments .= "<a href=\"index.php?entryPoint=download&id=".$the_note->id."&type=Notes\">".$the_note->name."</a><br />";
1499 $smarty->assign("ATTACHMENTS", $attachments);
1500 ///////////////////////////////////////////////////////////////////////////////
1502 ///////////////////////////////////////////////////////////////////////////////
1503 $show_subpanels = true;
1504 if ($show_subpanels) {
1505 require_once('include/SubPanel/SubPanelTiles.php');
1506 $subpanel = new SubPanelTiles($focus, 'Emails');
1507 $smarty->assign("SUBPANEL", $subpanel->display());
1509 $meta['html'] = $smarty->fetch("modules/Emails/templates/emailDetailView.tpl");
1515 * Sets the "read" flag in the overview cache
1517 function setReadFlag($ieId, $mbox, $uid) {
1518 $this->markEmails('read', $ieId, $mbox, $uid);
1522 * Marks emails with the passed flag type. This will be applied to local
1523 * cache files as well as remote emails.
1524 * @param string $type Flag type
1525 * @param string $ieId
1526 * @param string $folder IMAP folder structure or SugarFolder GUID
1527 * @param string $uids Comma sep list of UIDs or GUIDs
1529 function markEmails($type, $ieId, $folder, $uids) {
1531 global $app_strings;
1532 $uids = $this->_cleanUIDList($uids);
1533 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1535 if(strpos($folder, 'sugar::') !== false) {
1536 // dealing with a sugar email object, uids are GUIDs
1537 foreach($exUids as $id) {
1538 $email = new Email();
1539 $email->retrieve($id);
1543 $email->status = 'unread';
1548 $email->status = 'read';
1557 $email->flagged = 1;
1562 $email->flagged = 0;
1569 /* dealing with IMAP email, uids are IMAP uids */
1570 global $ie; // provided by EmailUIAjax.php
1573 $ie = new InboundEmail();
1575 $ie->retrieve($ieId);
1576 $ie->mailbox = $folder;
1577 $ie->connectMailserver();
1579 if($type == 'deleted') {
1580 $ie->deleteMessageOnMailServer($uids);
1581 $ie->deleteMessageFromCache($uids);
1583 $overviews = $ie->getCacheValueForUIDs($ie->mailbox, $exUids);
1584 $manipulated = array();
1586 foreach($overviews['retArr'] as $k => $overview) {
1587 if(in_array($overview->uid, $exUids)) {
1590 $overview->seen = 0;
1594 $overview->seen = 1;
1598 $overview->flagged = 1;
1602 $overview->flagged = 0;
1605 $manipulated[] = $overview;
1609 if(!empty($manipulated)) {
1610 $ie->setCacheValue($ie->mailbox, array(), $manipulated);
1611 /* now mark emails on email server */
1612 $ie->markEmails(implode(",", explode($app_strings['LBL_EMAIL_DELIMITER'], $uids)), $type);
1614 } // end not type == deleted
1618 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users) {
1619 global $app_strings;
1620 $users = explode(",", $users);
1621 $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1623 if($folder != 'sugar::Emails') {
1624 $emailIds = array();
1625 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1626 $ie = new InboundEmail();
1627 $ie->retrieve($ieid);
1629 // dealing with an inbound email data so we need to import an email and then
1630 foreach($uids as $uid) {
1631 $ie->mailbox = $folder;
1632 $ie->connectMailserver();
1634 if (!$ie->isPop3Protocol()) {
1635 $msgNo = imap_msgno($ie->conn, $uid);
1637 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
1640 if(!empty($msgNo)) {
1641 if ($ie->importOneEmail($msgNo, $uid)) {
1642 $emailIds[] = $ie->email->id;
1643 $ie->deleteMessageOnMailServer($uid);
1644 //$ie->retrieve($ieid);
1645 //$ie->connectMailserver();
1646 $ie->mailbox = $folder;
1647 $ie->deleteMessageFromCache(($uids[] = $uid));
1649 $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
1656 if (count($emailIds) > 0) {
1657 $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
1663 * get team id and team set id from request
1666 function getTeams() {
1669 function doDistributionWithMethod($users, $emailIds, $distributionMethod) {
1670 // we have users and the items to distribute
1671 if($distributionMethod == 'roundRobin') {
1672 $this->distRoundRobin($users, $emailIds);
1673 } elseif($distributionMethod == 'leastBusy') {
1674 $this->distLeastBusy($users, $emailIds);
1675 } elseif($distributionMethod == 'direct') {
1676 if(count($users) > 1) {
1677 // only 1 user allowed in direct assignment
1681 $this->distDirect($user, $emailIds);
1688 * distributes emails to users on Round Robin basis
1689 * @param $userIds array of users to dist to
1690 * @param $mailIds array of email ids to push on those users
1691 * @return boolean true on success
1693 function distRoundRobin($userIds, $mailIds) {
1694 // check if we have a 'lastRobin'
1695 $lastRobin = $userIds[0];
1696 foreach($mailIds as $k => $mailId) {
1697 $userIdsKeys = array_flip($userIds); // now keys are values
1698 $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
1699 if(!empty($userIds[$thisRobinKey])) {
1700 $thisRobin = $userIds[$thisRobinKey];
1701 $lastRobin = $userIds[$thisRobinKey];
1703 $thisRobin = $userIds[0];
1704 $lastRobin = $userIds[0];
1707 $email = new Email();
1708 $email->retrieve($mailId);
1709 $email->assigned_user_id = $thisRobin;
1710 $email->status = 'unread';
1718 * distributes emails to users on Least Busy basis
1719 * @param $userIds array of users to dist to
1720 * @param $mailIds array of email ids to push on those users
1721 * @return boolean true on success
1723 function distLeastBusy($userIds, $mailIds) {
1724 foreach($mailIds as $k => $mailId) {
1725 $email = new Email();
1726 $email->retrieve($mailId);
1727 foreach($userIds as $k => $id) {
1728 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '.$id.' AND status = 'unread'");
1729 $a = $this->db->fetchByAssoc($r);
1730 $counts[$id] = $a['c'];
1732 asort($counts); // lowest to highest
1733 $countsKeys = array_flip($counts); // keys now the 'count of items'
1734 $leastBusy = array_shift($countsKeys); // user id of lowest item count
1735 $email->assigned_user_id = $leastBusy;
1736 $email->status = 'unread';
1743 * distributes emails to 1 user
1744 * @param $user users to dist to
1745 * @param $mailIds array of email ids to push
1746 * @return boolean true on success
1748 function distDirect($user, $mailIds) {
1749 foreach($mailIds as $k => $mailId) {
1750 $email = new Email();
1751 $email->retrieve($mailId);
1752 $email->assigned_user_id = $user;
1753 $email->status = 'unread';
1760 function getAssignedEmailsCountForUsers($userIds) {
1762 foreach($userIds as $id) {
1763 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '$id' AND status = 'unread'");
1764 $a = $this->db->fetchByAssoc($r);
1765 $counts[$id] = $a['c'];
1770 function getLastRobin($ie) {
1772 if($this->validCacheFileExists($ie->id, 'folders', "robin.cache.php")) {
1773 $lastRobin = $this->getCacheValue($ie->id, 'folders', "robin.cache.php", 'robin');
1778 function setLastRobin($ie, $lastRobin) {
1779 global $sugar_config;
1780 $cacheFolderPath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/folders");
1781 if (!file_exists($cacheFolderPath)) {
1782 mkdir_recursive($cacheFolderPath);
1784 $this->writeCacheFile('robin', $lastRobin, $ie->id, 'folders', "robin.cache.php");
1788 * returns the metadata defining a single email message for display. Uses cache file if it exists
1791 function getSingleMessage($ie) {
1794 global $app_strings,$mod_strings;
1795 $ie->retrieve($_REQUEST['ieId']);
1798 $ie->mailbox = $_REQUEST['mbox'];
1799 $filename = $_REQUEST['mbox'].$_REQUEST['uid'].".php";
1801 if ($ie->isPop3Protocol()) {
1802 $md5uidl = md5($_REQUEST['uid']);
1803 $filename = $_REQUEST['mbox'].$md5uidl.".php";
1806 if($this->validCacheFileExists($_REQUEST['ieId'], 'messages', $filename)) {
1807 $out = $this->getCacheValue($_REQUEST['ieId'], 'messages', $filename, 'out');
1810 // something fubar'd the cache?
1811 if(empty($out['meta']['email']['name']) && empty($out['meta']['email']['description'])) {
1814 // When sending data from cache, convert date into users preffered format
1815 $dateTimeInGMTFormat = $out['meta']['email']['date_start'];
1816 $out['meta']['email']['date_start'] = $timedate->to_display_date_time($dateTimeInGMTFormat);
1821 $writeToCacheFile = true;
1822 if ($ie->isPop3Protocol()) {
1823 $status = $ie->setEmailForDisplay($_REQUEST['uid'], true, true, true);
1825 $status = $ie->setEmailForDisplay($_REQUEST['uid'], false, true, true);
1827 $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
1828 // modify the out object to store date in GMT format on the local cache file
1829 $dateTimeInUserFormat = $out['meta']['email']['date_start'];
1830 $out['meta']['email']['date_start'] = $timedate->to_db($dateTimeInUserFormat);
1831 if ($status == 'error') {
1832 $writeToCacheFile = false;
1834 if ($writeToCacheFile) {
1835 if ($ie->isPop3Protocol()) {
1836 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$md5uidl}.php");
1838 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$_REQUEST['uid']}.php");
1840 // restore date in the users preferred format to be send on to UI for diaply
1841 $out['meta']['email']['date_start'] = $dateTimeInUserFormat;
1844 $out['meta']['email']['toaddrs'] = $this->generateExpandableAddrs($out['meta']['email']['toaddrs']);
1845 if(!empty($out['meta']['email']['cc_addrs'])) {
1846 $ccs = $this->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
1847 $out['meta']['cc'] = <<<eoq
1849 <td NOWRAP valign="top" class="displayEmailLabel">
1850 {$app_strings['LBL_EMAIL_CC']}:
1852 <td class="displayEmailValue">
1859 if(empty($out['meta']['email']['description']))
1860 $out['meta']['email']['description'] = $mod_strings['LBL_EMPTY_EMAIL_BODY'];
1863 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() NOT using cache file");
1865 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() using cache file [ ".$_REQUEST['mbox'].$_REQUEST['uid'].".php ]");
1868 $this->setReadFlag($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['uid']);
1874 * Returns the HTML for a list of emails in a given folder
1875 * @param GUID $ieId GUID to InboundEmail instance
1876 * @param string $mbox Mailbox path name in dot notation
1877 * @param int $folderListCacheOffset Seconds for valid cache file
1878 * @return string HTML render of list.
1880 function getListEmails($ieId, $mbox, $folderListCacheOffset, $forceRefresh='false') {
1881 global $sugar_config;
1884 $ie = new InboundEmail();
1885 $ie->retrieve($ieId);
1886 $list = $ie->displayFolderContents($mbox, $forceRefresh);
1892 * Returns the templatized compose screen. Used by reply, forwards and draft status messages.
1893 * @param object email Email bean in focus
1895 function displayComposeEmail($email) {
1897 global $current_user;
1900 $ea = new SugarEmailAddress();
1902 if(!empty($email)) {
1903 $description = (empty($email->description_html)) ? $email->description : $email->description_html;
1906 //Get the most complete address list availible for this email
1907 $addresses = array('toAddresses' => 'to', 'ccAddresses' => 'cc', 'bccAddresses' => 'bcc');
1908 foreach($addresses as $var => $type)
1911 foreach (array("{$type}_addrs_names", "{$type}addrs", "{$type}_addrs") as $emailVar)
1913 if (!empty($email->$emailVar)) {
1914 $$var = $email->$emailVar;
1921 $ret['type'] = $email->type;
1922 $ret['name'] = $email->name;
1923 $ret['description'] = $description;
1924 $ret['from'] = (isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'forward') ? "" : $email->from_addr;
1925 $ret['to'] = from_html($toAddresses);
1926 $ret['uid'] = $email->id;
1927 $ret['parent_name'] = $email->parent_name;
1928 $ret['parent_type'] = $email->parent_type;
1929 $ret['parent_id'] = $email->parent_id;
1932 if(isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'replyAll') {
1933 $ret['cc'] = from_html($ccAddresses);
1934 $ret['bcc'] = $bccAddresses;
1936 $userEmails = array();
1937 $userEmailsMeta = $ea->getAddressesByGUID($current_user->id, 'Users');
1938 foreach($userEmailsMeta as $emailMeta) {
1939 $userEmails[] = from_html(strtolower(trim($emailMeta['email_address'])));
1941 $userEmails[] = from_html(strtolower(trim($email->from_addr)));
1943 $ret['cc'] = from_html($email->cc_addrs);
1944 $toAddresses = from_html($toAddresses);
1945 $to = str_replace($this->addressSeparators, "::", $toAddresses);
1946 $exTo = explode("::", $to);
1948 if(is_array($exTo)) {
1949 foreach($exTo as $addr) {
1950 $addr = strtolower(trim($addr));
1951 if(!in_array($addr, $userEmails)) {
1952 if(!empty($ret['cc'])) {
1953 $ret['cc'] = $ret['cc'].", ";
1955 $ret['cc'] = $ret['cc'].trim($addr);
1958 } elseif(!empty($exTo)) {
1959 $exTo = trim($exTo);
1960 if(!in_array($exTo, $userEmails)) {
1961 $ret['cc'] = $ret['cc'].", ".$exTo;
1968 * Formats email body on reply/forward
1969 * @param object email Email object in focus
1970 * @param string type
1971 * @return object email
1973 function handleReplyType($email, $type) {
1974 global $mod_strings;
1975 $GLOBALS['log']->debug("****At Handle Reply Type: $type");
1979 $header = $email->getReplyHeader();
1980 if(!preg_match('/^(re:)+/i', $email->name)) {
1981 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
1983 if ($type == "reply") {
1984 $email->cc_addrs = "";
1985 if (!empty($email->reply_to_addr)) {
1986 $email->from_addr = $email->reply_to_addr;
1989 if (!empty($email->reply_to_addr)) {
1990 $email->to_addrs = $email->to_addrs . "," . $email->reply_to_addr;
1996 $header = $email->getForwardHeader();
1997 if(!preg_match('/^(fw:)+/i', $email->name)) {
1998 $email->name = "{$mod_strings['LBL_FW']} {$email->name}";
2000 $email->cc_addrs = "";
2004 $GLOBALS['log']->debug("EMAILUI: At reply case");
2005 $header = $email->getReplyHeader();
2007 $myCase = new aCase();
2008 $myCase->retrieve($email->parent_id);
2009 $myCaseMacro = $myCase->getEmailSubjectMacro();
2010 $email->parent_name = $myCase->name;
2011 $GLOBALS['log']->debug("****Case # : {$myCase->case_number} macro: $myCaseMacro");
2012 if(!strpos($email->name, str_replace('%1',$myCase->case_number,$myCaseMacro))) {
2013 $GLOBALS['log']->debug("Replacing");
2014 $email->name = str_replace('%1',$myCase->case_number,$myCaseMacro) . ' '. $email->name;
2016 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
2020 $html = trim($email->description_html);
2021 $plain = trim($email->description);
2023 $desc = (!empty($html)) ? $html : $plain;
2025 $email->description = $header.$email->quoteHtmlEmailForNewEmailUI($desc);
2030 ///////////////////////////////////////////////////////////////////////////
2031 //// PRIVATE HELPERS
2033 * Generates a UNION query to get one list of users, contacts, leads, and
2034 * prospects; used specifically for the addressBook
2036 function _getPeopleUnionQuery($whereArr , $person) {
2037 global $current_user , $app_strings;
2039 if(!isset($person) || $person === 'LBL_DROPDOWN_LIST_ALL'){
2040 $peopleTables = array("users",
2047 $peopleTables = array($person);
2053 foreach($whereArr as $column => $clause) {
2054 if(!empty($whereAdd)) {
2055 $whereAdd .= " AND ";
2057 $clause = $current_user->db->helper->escape_quote($clause);
2058 $whereAdd .= "{$column} LIKE '{$clause}%'";
2062 foreach($peopleTables as $table) {
2063 $module = ucfirst($table);
2064 $class = substr($module, 0, strlen($module) - 1);
2065 require_once("modules/{$module}/{$class}.php");
2066 $person = new $class();
2067 if (!$person->ACLAccess('list')) {
2070 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id <> '{$current_user->id}')";
2072 if (ACLController::requireOwner($module, 'list')) {
2073 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2075 if(!empty($whereAdd)) {
2076 $where .= " AND ({$whereAdd})";
2079 if ($person === 'accounts') {
2080 $t = "SELECT {$table}.id, '' first_name, {$table}.name, eabr.primary_address, ea.email_address, '{$module}' module ";
2082 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2084 $t .= "FROM {$table} ";
2085 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2086 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2087 $t .= " WHERE {$where}";
2090 $q .= "\n UNION ALL \n";
2095 $countq = "SELECT count(people.id) c from ($q) people";
2096 $q .= "ORDER BY last_name";
2098 return array('query' => $q, 'countQuery' => $countq);
2102 * get emails of related bean for a given bean id
2104 * @param $condition array of conditions inclued bean id
2105 * @return array('query' => $q, 'countQuery' => $countq);
2107 function getRelatedEmail($beanType, $whereArr, $relatedBeanInfoArr = ''){
2108 global $beanList, $current_user, $app_strings, $db;
2110 $searchBeans = null;
2111 if($beanType === 'LBL_DROPDOWN_LIST_ALL')
2112 $searchBeans = array("users",
2119 if ($relatedBeanInfoArr == '' || empty($relatedBeanInfoArr['related_bean_type']) )
2121 if ($searchBeans != null)
2124 foreach ($searchBeans as $searchBean)
2126 $searchq = $this->findEmailFromBeanIds('', $searchBean, $whereArr);
2127 if(!empty($searchq)) {
2128 $q[] = "($searchq)";
2132 $finalQuery .= implode("\n UNION ALL \n", $q);
2135 $finalQuery = $this->findEmailFromBeanIds('', $beanType, $whereArr);
2139 $class = $beanList[$relatedBeanInfoArr['related_bean_type']];
2140 $focus = new $class();
2141 $focus->retrieve($relatedBeanInfoArr['related_bean_id']);
2142 if ($searchBeans != null)
2145 foreach ($searchBeans as $searchBean)
2147 if ($focus->load_relationship($searchBean))
2149 $data = $focus->$searchBean->get();
2150 if (count($data) != 0)
2151 $q[] = '('.$this->findEmailFromBeanIds($data, $searchBean, $whereArr).')';
2155 $finalQuery .= implode("\n UNION ALL \n", $q);
2159 if ($focus->load_relationship($beanType))
2161 $data = $focus->$beanType->get();
2162 if (count($data) != 0)
2163 $finalQuery = $this->findEmailFromBeanIds($data, $beanType, $whereArr);
2167 $countq = "SELECT count(people.id) c from ($finalQuery) people";
2168 return array('query' => $finalQuery, 'countQuery' => $countq);
2171 function findEmailFromBeanIds($beanIds, $beanType, $whereArr) {
2172 global $current_user;
2176 if ($beanIds != '') {
2177 foreach ($beanIds as $key => $value) {
2178 $beanIds[$key] = '\''.$value.'\'';
2180 $relatedIDs = implode(',', $beanIds);
2183 if ($beanType == 'accounts') {
2184 if (isset($whereArr['first_name'])) {
2185 $whereArr['name'] = $whereArr['first_name'];
2187 unset($whereArr['last_name']);
2188 unset($whereArr['first_name']);
2191 foreach($whereArr as $column => $clause) {
2192 if(!empty($whereAdd)) {
2193 $whereAdd .= " OR ";
2195 $clause = $current_user->db->helper->escape_quote($clause);
2196 $whereAdd .= "{$column} LIKE '{$clause}%'";
2199 $module = ucfirst($table);
2200 $class = substr($module, 0, strlen($module) - 1);
2201 require_once("modules/{$module}/{$class}.php");
2202 $person = new $class();
2203 if ($person->ACLAccess('list')) {
2204 if ($relatedIDs != '') {
2205 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id in ($relatedIDs))";
2207 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1)";
2210 if (ACLController::requireOwner($module, 'list')) {
2211 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2213 if(!empty($whereAdd)) {
2214 $where .= " AND ({$whereAdd})";
2217 if ($beanType === 'accounts') {
2218 $t = "SELECT {$table}.id, '' first_name, {$table}.name last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2220 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2223 $t .= "FROM {$table} ";
2224 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2225 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2226 $t .= " WHERE {$where}";
2233 * @param mixed $uids
2234 * @param bool $returnString False will return an array
2237 function _cleanUIDList($uids, $returnString=false) {
2238 global $app_strings;
2239 $GLOBALS['log']->debug("_cleanUIDList: before - [ {$uids} ]");
2241 if(!is_array($uids)) {
2242 $returnString = true;
2244 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
2248 $cleanUids = array();
2249 foreach($uids as $uid) {
2250 $cleanUids[$uid] = $uid;
2256 $cleanImplode = implode($app_strings['LBL_EMAIL_DELIMITER'], $cleanUids);
2257 $GLOBALS['log']->debug("_cleanUIDList: after - [ {$cleanImplode} ]");
2258 return $cleanImplode;
2265 * Creates defaults for the User
2266 * @param object $user User in focus
2268 function preflightUser(&$user) {
2269 global $mod_strings;
2271 $goodToGo = $user->getPreference("email2Preflight", "Emails");
2272 $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
2273 $r = $user->db->query($q);
2274 $a = $user->db->fetchByAssoc($r);
2276 if($a['count'] < 1) {
2277 require_once("include/SugarFolders/SugarFolders.php");
2279 $folder = new SugarFolder();
2280 $folder->new_with_id = true;
2281 $folder->id = create_guid();
2282 $folder->name = $mod_strings['LNK_MY_INBOX'];
2283 $folder->has_child = 1;
2284 $folder->created_by = $user->id;
2285 $folder->modified_by = $user->id;
2286 $folder->is_dynamic = 1;
2287 $folder->folder_type = "inbound";
2288 $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
2292 $drafts = new SugarFolder();
2293 $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
2294 $drafts->has_child = 0;
2295 $drafts->parent_folder = $folder->id;
2296 $drafts->created_by = $user->id;
2297 $drafts->modified_by = $user->id;
2298 $drafts->is_dynamic = 1;
2299 $drafts->folder_type = "draft";
2300 $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
2305 $archived = new SugarFolder();
2306 $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
2307 $archived->has_child = 0;
2308 $archived->parent_folder = $folder->id;
2309 $archived->created_by = $user->id;
2310 $archived->modified_by = $user->id;
2311 $archived->is_dynamic = 1;
2312 $archived->folder_type = "sent";
2313 $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
2316 // set flag to show that this was run
2317 $user->setPreference("email2Preflight", true, 1, "Emails");
2322 * Parses the core dynamic folder query
2323 * @param string $type 'inbound', 'draft', etc.
2324 * @param string $userId
2327 function generateDynamicFolderQuery($type, $userId) {
2328 $q = $this->coreDynamicFolderQuery;
2332 if($type == "sent") {
2336 $replacee = array("::TYPE::", "::STATUS::", "::USER_ID::");
2337 $replacer = array($type, $status, $userId);
2339 $ret = str_replace($replacee, $replacer, $q);
2341 if($type == 'inbound') {
2342 $ret .= " AND status NOT IN ('sent', 'archived', 'draft') AND type NOT IN ('out', 'archived', 'draft')";
2344 $ret .= " AND status NOT IN ('archived') AND type NOT IN ('archived')";
2351 * Preps the User's cache dir
2353 function preflightUserCache() {
2354 $path = clean_path($this->userCacheDir);
2355 if(!file_exists($this->userCacheDir))
2356 mkdir_recursive($path);
2358 $files = findAllFiles($path, array());
2360 foreach($files as $file) {
2365 function clearInboundAccountCache($ieId) {
2366 global $sugar_config;
2367 $cacheRoot = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}";
2368 $files = findAllFiles($cacheRoot."/messages/", array());
2369 foreach($files as $file) {
2372 $files = findAllFiles($cacheRoot."/attachments/", array());
2373 foreach($files as $file) {
2379 * returns an array of EmailTemplates that the user has access to for the compose email screen
2382 function getEmailTemplatesArray() {
2384 global $app_strings;
2386 if(ACLController::checkAccess('EmailTemplates', 'list', true) && ACLController::checkAccess('EmailTemplates', 'view', true)) {
2387 $et = new EmailTemplate();
2388 $etResult = $et->db->query($et->create_new_list_query('','',array(),array(),''));
2389 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2390 while($etA = $et->db->fetchByAssoc($etResult)) {
2391 $email_templates_arr[$etA['id']] = $etA['name'];
2394 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2397 return $email_templates_arr;
2400 function getFromAccountsArray($ie) {
2401 global $current_user;
2402 global $app_strings;
2404 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2405 $ieAccountsFrom= array();
2407 $oe = new OutboundEmail();
2408 $system = $oe->getSystemMailerSettings();
2409 $ret = $current_user->getUsersNameAndEmail();
2410 $ret['name'] = from_html($ret['name']);
2411 $useMyAccountString = true;
2413 if(empty($ret['email'])) {
2414 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2415 $ret['email'] = $systemReturn['email'];
2416 $ret['name'] = from_html($systemReturn['name']);
2417 $useMyAccountString = false;
2420 $myAccountString = '';
2421 if ($useMyAccountString) {
2422 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2425 //Check to make sure that the user has set the associated inbound email acount -> outbound acount is active.
2426 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2427 $sf = new SugarFolder();
2428 $groupSubs = $sf->getSubscriptions($current_user);
2430 foreach($ieAccountsFull as $k => $v)
2432 $personalSelected = (!empty($showFolders) && in_array($v->id, $showFolders));
2434 $allowOutboundGroupUsage = $v->get_stored_options('allow_outbound_group_usage',FALSE);
2435 $groupSelected = ( in_array($v->groupfolder_id, $groupSubs) && $allowOutboundGroupUsage);
2436 $selected = ( $personalSelected || $groupSelected );
2440 $GLOBALS['log']->debug("Inbound Email {$v->name}, not selected and will not be available for selection within compose UI.");
2444 $name = $v->get_stored_options('from_name');
2445 $addr = $v->get_stored_options('from_addr');
2446 if ($name != null && $addr != null) {
2447 $name = from_html($name);
2448 if (!$v->is_personal) {
2449 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2451 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr})");
2457 $userSystemOverride = $oe->getUsersMailerForSystemOverride($current_user->id);
2458 //Substitute in the users system override if its available.
2459 if($userSystemOverride != null)
2460 $system = $userSystemOverride;
2462 if( !empty($system->mail_smtpserver) )
2464 $admin = new Administration();
2465 $admin->retrieveSettings(); //retrieve all admin settings.
2466 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2467 "{$ret['name']} ({$ret['email']}){$myAccountString}");
2470 return $ieAccountsFrom;
2474 * This function will return all the accounts this user has access to based on the
2475 * match of the emailId passed in as a parameter
2477 * @param unknown_type $ie
2480 function getFromAllAccountsArray($ie, $ret) {
2481 global $current_user;
2482 global $app_strings;
2484 $ret['fromAccounts'] = array();
2485 if (!isset($ret['to']) && !empty($ret['from'])) {
2486 $ret['fromAccounts']['status'] = false;
2489 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2490 $foundInPersonalAccounts = false;
2491 $foundInGroupAccounts = false;
2492 $foundInSystemAccounts = false;
2494 //$toArray = array();
2495 if ($ret['type'] == "draft") {
2496 $toArray = explode(",", $ret['from']);
2498 $toArray = $ie->email->email2ParseAddressesForAddressesOnly($ret['to']);
2500 foreach($ieAccountsFull as $k => $v) {
2501 $storedOptions = unserialize(base64_decode($v->stored_options));
2502 if ( array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2503 if ($v->is_personal) {
2504 $foundInPersonalAccounts = true;
2507 $foundInGroupAccounts = true;
2512 $oe = new OutboundEmail();
2513 $system = $oe->getSystemMailerSettings();
2515 $return = $current_user->getUsersNameAndEmail();
2516 $return['name'] = from_html($return['name']);
2517 $useMyAccountString = true;
2519 if(empty($return['email'])) {
2520 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2521 $return['email'] = $systemReturn['email'];
2522 $return['name'] = from_html($systemReturn['name']);
2523 $useMyAccountString = false;
2526 $myAccountString = '';
2527 if ($useMyAccountString) {
2528 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2531 if(!empty($system->id)) {
2533 $admin = new Administration();
2534 $admin->retrieveSettings(); //retrieve all admin settings.
2535 if (in_array(trim($return['email']), $toArray)) {
2536 $foundInSystemAccounts = true;
2540 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && !$foundInSystemAccounts) {
2541 $ret['fromAccounts']['status'] = false;
2545 $ieAccountsFrom= array();
2546 foreach($ieAccountsFull as $k => $v) {
2547 $storedOptions = unserialize(base64_decode($v->stored_options));
2548 $storedOptionsName = from_html($storedOptions['from_name']);
2551 if (array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2552 //if ($ret['to'] == $storedOptions['from_addr']) {
2555 if ($foundInPersonalAccounts) {
2556 if ($v->is_personal) {
2557 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']})");
2560 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2564 if(!empty($system->id)) {
2565 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && $foundInSystemAccounts) {
2566 $ieAccountsFrom[] = array("value" => $system->id, "selected" => true, "text" =>
2567 "{$return['name']} ({$return['email']}){$myAccountString}");
2569 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2570 "{$return['name']} ({$return['email']}){$myAccountString}");
2574 $ret['fromAccounts']['status'] = ($foundInPersonalAccounts || $foundInGroupAccounts || $foundInSystemAccounts) ? true : false;
2575 $ret['fromAccounts']['data'] = $ieAccountsFrom;
2581 * takes an array and creates XML
2582 * @param array Array to convert
2583 * @param string Name to wrap highest level items in array
2584 * @return string XML
2586 function arrayToXML($a, $paramName) {
2590 $bad = array("<",">","'",'"',"&");
2591 $good = array("<", ">", "'", ""","&");
2595 for($i=0; $i<count($a); $i++) {
2597 $ret .= "\n<{$paramName}>";
2599 foreach($email as $k => $v) {
2600 $ret .= "\n\t<{$k}>".str_replace($bad, $good, $v)."</{$k}>";
2602 $ret .= "\n</{$paramName}>";
2608 * Re-used option getter for Show Accounts multiselect pane
2610 function getShowAccountsOptions(&$ie) {
2611 global $current_user;
2612 global $app_strings;
2613 global $mod_strings;
2615 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2616 $ieAccountsShowOptionsMeta = array();
2617 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2619 $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
2621 foreach($ieAccountsFull as $k => $v) {
2622 $selected = (!empty($showFolders) && in_array($v->id, $showFolders)) ? true : false;
2623 $default = ($defaultIEAccount == $v->id) ? TRUE : FALSE;
2624 $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
2625 $type = ($v->is_personal) ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
2627 $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected,
2628 'server_url' => $v->server_url, 'is_group' => !$v->is_personal,'group_id' => $v->group_id,
2629 'is_default' => $default, 'has_groupfolder' => $has_groupfolder,'type' => $type );
2632 //Retrieve the grou folders
2633 $f = new SugarFolder();
2634 $groupFolders = $f->getGroupFoldersForSettings($current_user);
2636 foreach ($groupFolders as $singleGroup)
2638 //Retrieve the related IE accounts.
2639 $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
2641 if(count($relatedIEAccounts) == 0)
2642 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
2643 else if(count($relatedIEAccounts) == 1)
2645 if($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce')
2648 $server_url = $relatedIEAccounts[0]->server_url;
2651 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
2653 $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
2654 $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'],
2655 'server_url' => $server_url, 'is_group' => true,'group_id' => $singleGroup['id'],
2656 'is_default' => FALSE, 'has_groupfolder' => true,'type' => $type);
2660 return $ieAccountsShowOptionsMeta;
2663 function getShowAccountsOptionsForSearch(&$ie) {
2664 global $current_user;
2665 global $app_strings;
2667 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2668 //$ieAccountsShowOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
2669 $ieAccountsShowOptionsMeta = array();
2670 $ieAccountsShowOptionsMeta[] = array("value" => "", "text" => $app_strings['LBL_NONE'], 'selected' => '');
2671 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2673 foreach($ieAccountsFull as $k => $v) {
2674 if(!in_array($v->id, $showFolders)) {
2677 $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
2678 $ieAccountsShowOptionsMeta[] = array("value" => $v->id, "text" => $group.$v->name, 'protocol' => $v->protocol);
2681 return $ieAccountsShowOptionsMeta;
2684 * Formats a display message on successful async call
2685 * @param string $type Type of message to display
2687 function displaySuccessMessage($type) {
2688 global $app_strings;
2692 $message = $app_strings['LBL_EMAIL_DELETE_SUCCESS'];
2696 $message = "NOOP: invalid type";
2700 $this->smarty->assign('app_strings', $app_strings);
2701 $this->smarty->assign('message', $message);
2702 echo $this->smarty->fetch("modules/Emails/templates/successMessage.tpl");
2706 * Validates existence and expiration of a cache file
2707 * @param string $ieId
2708 * @param string $type Type of cache file: folders, messages, etc.
2709 * @param string $file The cachefile name
2710 * @param int refreshOffset Refresh time in secs.
2713 function validCacheFileExists($ieId, $type, $file, $refreshOffset=-1) {
2714 global $sugar_config;
2716 if($refreshOffset == -1) {
2717 $refreshOffset = $this->cacheTimeouts[$type]; // use defaults
2720 $cacheFilePath = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2721 if(file_exists($cacheFilePath)) {
2729 * retrieves the cached value
2730 * @param string $ieId
2731 * @param string $type Type of cache file: folders, messages, etc.
2732 * @param string $file The cachefile name
2733 * @param string $key name of cache value
2736 function getCacheValue($ieId, $type, $file, $key) {
2737 global $sugar_config;
2739 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2740 $cacheFile = array();
2742 if(file_exists($cacheFilePath)) {
2743 include($cacheFilePath); // provides $cacheFile
2745 if(isset($cacheFile[$key])) {
2746 $ret = unserialize($cacheFile[$key]);
2750 $GLOBALS['log']->debug("EMAILUI: cache file not found [ {$cacheFilePath} ] - creating blank cache file");
2751 $this->writeCacheFile('retArr', array(), $ieId, $type, $file);
2758 * retrieves the cache file last touched time
2759 * @param string $ieId
2760 * @param string $type Type of cache file: folders, messages, etc.
2761 * @param string $file The cachefile name
2764 function getCacheTimestamp($ieId, $type, $file) {
2765 global $sugar_config;
2767 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2768 $cacheFile = array();
2770 if(file_exists($cacheFilePath)) {
2771 include($cacheFilePath); // provides $cacheFile['timestamp']
2773 if(isset($cacheFile['timestamp'])) {
2774 $GLOBALS['log']->debug("EMAILUI: found timestamp [ {$cacheFile['timestamp']} ]");
2775 return $cacheFile['timestamp'];
2783 * Updates the timestamp for a cache file - usually to mark a "check email"
2785 * @param string $ieId
2786 * @param string $type Type of cache file: folders, messages, etc.
2787 * @param string $file The cachefile name
2789 function setCacheTimestamp($ieId, $type, $file) {
2790 global $sugar_config;
2792 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2793 $cacheFile = array();
2795 if(file_exists($cacheFilePath)) {
2796 include($cacheFilePath); // provides $cacheFile['timestamp']
2798 if(isset($cacheFile['timestamp'])) {
2799 $cacheFile['timestamp'] = strtotime('now');
2800 $GLOBALS['log']->debug("EMAILUI: setting updated timestamp [ {$cacheFile['timestamp']} ]");
2801 return $this->_writeCacheFile($cacheFile, $cacheFilePath);
2808 * Writes caches to flat file in cache dir.
2809 * @param string $key Key to the main cache entry (not timestamp)
2810 * @param mixed $var Variable to be cached
2811 * @param string $ieId I-E focus ID
2812 * @param string $type Folder in cache
2813 * @param string $file Cache file name
2815 function writeCacheFile($key, $var, $ieId, $type, $file) {
2816 global $sugar_config;
2818 $the_file = clean_path("{$sugar_config['cache_dir']}/modules/Emails/{$ieId}/{$type}/{$file}");
2819 $timestamp = strtotime('now');
2821 $array['timestamp'] = $timestamp;
2822 $array[$key] = serialize($var); // serialized since varexport_helper() can't handle PHP objects
2824 return $this->_writeCacheFile($array, $the_file);
2828 * Performs the actual file write. Abstracted from writeCacheFile() for
2830 * @param array $array The array to write to the cache
2831 * @param string $file Full path (relative) with cache file name
2834 function _writeCacheFile($array, $file) {
2835 global $sugar_config;
2837 $arrayString = var_export_helper($array);
2841 <?php // created: {$date}
2842 \$cacheFile = {$arrayString};
2845 if($fh = @sugar_fopen($file, "w")) {
2846 fputs($fh, $the_string);
2850 $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]");
2856 * Generate JSON encoded data to be consumed by yui datatable.
2858 * @param array $data
2859 * @param string $resultsParam The resultsList name
2862 function jsonOuput($data, $resultsParam, $count=0, $fromCache=true, $unread=-1) {
2863 global $app_strings;
2865 $count = ($count > 0) ? $count : 0;
2867 if(isset($a['fromCache']))
2868 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2870 $cached = ($fromCache) ? 1 : 0;
2872 if($data['mbox'] == 'undefined' || empty($data['mbox']))
2873 $data['mbox'] = $app_strings['LBL_NONE'];
2875 $jsonOut = array('TotalCount' => $count, 'FromCache' => $cached, 'UnreadCount' => $unread, $resultsParam => $data['out']);
2877 return json_encode($jsonOut);
2880 * generates XML output from an array
2882 * @param string master list Item
2885 function xmlOutput($a, $paramName, $count=0, $fromCache=true, $unread=-1) {
2886 global $app_strings;
2887 $count = ($count > 0) ? $count : 0;
2889 if(isset($a['fromCache'])) {
2890 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2892 $cached = ($fromCache) ? 1 : 0;
2895 if($a['mbox'] == 'undefined' || empty($a['mbox'])) {
2896 $a['mbox'] = $app_strings['LBL_NONE'];
2899 $xml = $this->arrayToXML($a['out'], $paramName);
2902 <?xml version="1.0" encoding="UTF-8"?>
2904 <TotalCount>{$count}</TotalCount>
2905 <UnreadCount>{$unread}</UnreadCount>
2906 <FromCache> {$cached} </FromCache>
2916 * Generate to/cc addresses string in email detailview.
2918 * @param string $str
2919 * @param string $target values: to, cc
2920 * @param int $defaultNum
2921 * @return string $str
2923 function generateExpandableAddrs($str) {
2924 global $mod_strings;
2925 $tempStr = $str.',';
2926 $tempStr = html_entity_decode($tempStr);
2927 $tempStr = $this->unifyEmailString($tempStr);
2929 $pattern = '/@.*,/U';
2930 preg_match_all($pattern, $tempStr, $matchs);
2931 $totalCount = count($matchs[0]);
2933 if(!empty($matchs[0]) && $totalCount > $defaultNum) {
2934 $position = strpos($tempStr, $matchs[0][$defaultNum]);
2935 $hiddenCount = $totalCount - $defaultNum;
2936 $frontStr = substr($tempStr, 0, $position);
2937 $backStr = substr($tempStr, $position, -1);
2938 $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>';
2945 * Unify the seperator as ,
2947 * @param String $str email address string
2948 * @return String converted string
2950 function unifyEmailString($str) {
2951 preg_match_all('/@.*;/U', $str, $matches);
2952 if(!empty($matches[0])) {
2953 foreach($matches[0] as $key => $value) {
2954 $new[] = str_replace(";",",",$value);
2956 return str_replace($matches[0], $new, $str);