2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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 and &, <, >
383 // but not double quotes since json would escape them
384 foreach ($composePackage as $key => $singleCompose)
386 if (is_string($singleCompose))
387 $composePackage[$key] = str_replace(" ", " ", from_html($singleCompose));
390 $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
392 $j_quickComposeOptions = JSON::encode($quickComposeOptions, false ,true);
395 return $j_quickComposeOptions;
399 * Generate the config data needed for the Full Compose UI and the Quick Compose UI. The set of config data
400 * returned is the minimum set needed by the quick compose UI.
402 * @param String $type Drives which tinyMCE options will be included.
404 function _generateComposeConfigData($type = "email_compose_light" )
406 global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
409 $parent_types = $app_list_strings['record_type_display'];
410 $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
412 foreach($disabled_parent_types as $disabled_parent_type) {
413 unset($parent_types[$disabled_parent_type]);
415 asort($parent_types);
416 $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
419 require_once("include/SugarTinyMCE.php");
420 $tiny = new SugarTinyMCE();
421 $tinyConf = $tiny->getConfig($type);
423 //Generate Language Packs
424 $lang = "var app_strings = new Object();\n";
425 foreach($app_strings as $k => $v) {
426 if(strpos($k, 'LBL_EMAIL_') !== false) {
427 $lang .= "app_strings.{$k} = '{$v}';\n";
430 //Get the email mod strings but don't use the global variable as this may be overridden by
431 //other modules when the quick create is rendered.
432 $email_mod_strings = return_module_language($current_language,'Emails');
433 $modStrings = "var mod_strings = new Object();\n";
434 foreach($email_mod_strings as $k => $v) {
435 $v = str_replace("'", "\'", $v);
436 $modStrings .= "mod_strings.{$k} = '{$v}';\n";
438 $lang .= "\n\n{$modStrings}\n";
440 //Grab the Inboundemail language pack
441 $ieModStrings = "var ie_mod_strings = new Object();\n";
442 $ie_mod_strings = return_module_language($current_language,'InboundEmail');
443 foreach($ie_mod_strings as $k => $v) {
444 $v = str_replace("'", "\'", $v);
445 $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
447 $lang .= "\n\n{$ieModStrings}\n";
449 $this->smarty->assign('linkBeans', $linkBeans);
450 $this->smarty->assign('linkBeansOptions', $parent_types);
451 $this->smarty->assign('tinyMCE', $tinyConf);
452 $this->smarty->assign('lang', $lang);
453 $this->smarty->assign('app_strings', $app_strings);
454 $this->smarty->assign('mod_strings', $email_mod_strings);
455 $ie1 = new InboundEmail();
458 $defsigID = $current_user->getPreference('signature_default');
459 $defaultSignature = $current_user->getDefaultSignature();
460 $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
461 $this->smarty->assign('defaultSignature', $sigJson);
462 $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
464 $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
466 //Get the users default outbound id
467 $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
468 $this->smarty->assign('defaultOutID', $defaultOutID);
471 $charsets = json_encode($locale->getCharsetSelect());
472 $this->smarty->assign('emailCharsets', $charsets);
474 //Relateable List of People for address book search
476 $peopleTables = array("users",
481 $filterPeopleTables = array();
482 global $app_list_strings, $app_strings;
483 $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
484 foreach($peopleTables as $table) {
485 $module = ucfirst($table);
486 $class = substr($module, 0, strlen($module) - 1);
487 require_once("modules/{$module}/{$class}.php");
488 $person = new $class();
490 if (!$person->ACLAccess('list')) continue;
491 $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
493 $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
500 ///////////////////////////////////////////////////////////////////////////
502 ///////////////////////////////////////////////////////////////////////////
505 * Retrieves all relationship metadata for a user's address book
508 function getContacts() {
509 global $current_user;
511 $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
512 $r = $this->db->query($q);
516 while($a = $this->db->fetchByAssoc($r)) {
517 $ret[$a['bean_id']] = array(
518 'id' => $a['bean_id'],
519 'module' => $a['bean'],
527 * Saves changes to a user's address book
528 * @param array contacts
530 function setContacts($contacts) {
531 global $current_user;
533 $oldContacts = $this->getContacts();
535 foreach($contacts as $cid => $contact) {
536 if(!in_array($contact['id'], $oldContacts)) {
537 $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
538 $r = $this->db->query($q, true);
544 * Removes contacts from the user's address book
547 function removeContacts($ids) {
548 global $current_user;
552 foreach($ids as $id) {
556 $concat .= "'{$id}'";
559 $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
560 $r = $this->db->query($q);
564 * saves editted Contact info
565 * @param string $str JSON serialized object
567 function saveContactEdit($str) {
569 $json = getJSONobj();
571 $str = from_html($str);
572 $obj = $json->decode($str);
574 $contact = new Contact();
575 $contact->retrieve($obj['contact_id']);
576 $contact->first_name = $obj['contact_first_name'];
577 $contact->last_name = $obj['contact_last_name'];
580 // handle email address changes
581 $addresses = array();
583 foreach($obj as $k => $req) {
584 if(strpos($k, 'emailAddress') !== false) {
585 $addresses[$k] = $req;
589 // prefill some REQUEST vars for emailAddress save
590 $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
591 $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
592 $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
596 * Prepares the Edit Contact mini-form via template assignment
597 * @param string id ID of contact in question
598 * @param string module Module in focus
601 function getEditContact($id, $module) {
605 if(!class_exists("Contact")) {
609 $contact = new Contact();
610 $contact->retrieve($_REQUEST['id']);
613 if($contact->ACLAccess('edit')) {
614 $contactMeta = array();
615 $contactMeta['id'] = $contact->id;
616 $contactMeta['module'] = $contact->module_dir;
617 $contactMeta['first_name'] = $contact->first_name;
618 $contactMeta['last_name'] = $contact->last_name;
620 $this->smarty->assign("app_strings", $app_strings);
621 $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
622 $this->smarty->assign("contact", $contactMeta);
624 $ea = new SugarEmailAddress();
625 $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
626 $this->smarty->assign("emailWidget", $newEmail['html']);
628 $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
629 $ret['prefillData'] = $newEmail['prefillData'];
632 $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
633 $ret['prefillData'] = '{}';
637 $ret['contactName'] = $contact->full_name;
644 * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
646 * @param array $contacts Array of contact types -> IDs
647 * @param object $user User in focus
650 function getUserContacts($contacts, $user=null) {
652 global $current_user;
656 $user = $current_user;
659 $emailAddress = new SugarEmailAddress();
665 foreach($contacts as $contact) {
666 if(!isset($modules[$contact['module']])) {
667 $modules[$contact['module']] = array();
669 $modules[$contact['module']][] = $contact;
672 foreach($modules as $module => $contacts) {
674 $union .= " UNION ALL ";
677 $table = strtolower($module);
680 foreach($contacts as $contact) {
681 if(!empty($idsSerial)) {
684 $idsSerial .= "'{$contact['id']}'";
687 $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
690 $union .= " ORDER BY last_name";
693 $r = $user->db->query($union);
697 while($a = $user->db->fetchByAssoc($r)) {
700 $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
702 $c['module'] = $a['module'];
703 $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
709 //// END ADDRESS BOOK
710 ///////////////////////////////////////////////////////////////////////////
713 ///////////////////////////////////////////////////////////////////////////
714 //// EMAIL 2.0 Preferences
715 function getUserPrefsJS() {
716 global $current_user;
719 // sort order per mailbox view
720 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
721 $sortArray = array();
722 if(!empty($sortSerial)) {
723 $sortArray = unserialize($sortSerial);
726 // treeview collapsed/open states
727 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
728 $folderStates = array();
729 if(!empty($folderStateSerial)) {
730 $folderStates = unserialize($folderStateSerial);
733 // subscribed accounts
734 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
737 $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
739 if(empty($emailSettings)) {
740 $emailSettings = array();
741 $emailSettings['emailCheckInterval'] = -1;
742 $emailSettings['autoImport'] = '';
743 $emailSettings['alwaysSaveOutbound'] = '1';
744 $emailSettings['sendPlainText'] = '';
745 $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
746 $emailSettings['showNumInList'] = 20;
750 $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
751 $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
754 $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
756 $listViewSort = array(
758 "sortDirection" => 'DESC',
762 $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
763 $signatureDefault = $current_user->getPreference('signature_default');
765 'signature_prepend' => $signaturePrepend,
766 'signature_default' => $signatureDefault
772 'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
773 'full_name' => from_html($current_user->full_name),
776 $userPreferences = array();
777 $userPreferences['sort'] = $sortArray;
778 $userPreferences['folderStates'] = $folderStates;
779 $userPreferences['showFolders'] = $showFolders;
780 $userPreferences['emailSettings'] = $emailSettings;
781 $userPreferences['focusFolder'] = $focusFolder;
782 $userPreferences['showUnreadOnly'] = $showUnreadOnly;
783 $userPreferences['listViewSort'] = $listViewSort;
784 $userPreferences['signatures'] = $signatures;
785 $userPreferences['current_user'] = $user;
786 return $userPreferences;
791 ///////////////////////////////////////////////////////////////////////////
792 //// FOLDER FUNCTIONS
795 * Creates a new Sugar folder
796 * @param string $nodeLabel New sugar folder name
797 * @param string $parentLabel Parent folder name
799 function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
800 global $current_user;
802 $this->folder->name = $nodeLabel;
803 $this->folder->is_group = $isGroup;
804 $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
805 $this->folder->has_child = 0;
806 $this->folder->created_by = $current_user->id;
807 $this->folder->modified_by = $current_user->id;
808 $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
810 $this->folder->save();
812 'action' => 'newFolderSave',
813 'id' => $this->folder->id,
814 'name' => $this->folder->name,
815 'is_group' => $this->folder->is_group,
816 'is_dynamic' => $this->folder->is_dynamic
821 * Saves user sort prefernces
823 function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
824 global $current_user;
826 $sortArray = array();
828 $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
829 if(!empty($sortSerial)) {
830 $sortArray = unserialize($sortSerial);
833 $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
834 $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
835 $sortSerial = serialize($sortArray);
836 $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
840 * Stickies folder collapse/open state
842 function saveFolderOpenState($focusFolder, $focusFolderOpen) {
843 global $current_user;
845 $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
846 $folderStates = array();
848 if(!empty($folderStateSerial)) {
849 $folderStates = unserialize($folderStateSerial);
852 $folderStates[$focusFolder] = $focusFolderOpen;
853 $newFolderStateSerial = serialize($folderStates);
854 $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
858 * saves a folder's view state
860 function saveListView($ieId, $folder) {
861 global $current_user;
863 $saveState = array();
864 $saveState['ieId'] = $ieId;
865 $saveState['folder'] = $folder;
866 $saveStateSerial = serialize($saveState);
867 $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
871 * Generates cache folder structure
873 function preflightEmailCache($cacheRoot) {
875 if(!file_exists($cacheRoot))
876 mkdir_recursive(clean_path($cacheRoot));
879 if(!file_exists($cacheRoot."/folders"))
880 mkdir_recursive(clean_path("{$cacheRoot}/folders"));
883 if(!file_exists($cacheRoot."/messages"))
884 mkdir_recursive(clean_path("{$cacheRoot}/messages"));
887 if(!file_exists($cacheRoot."/attachments"))
888 mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
891 function deleteEmailCacheForFolders($cacheRoot) {
892 $filePath = $cacheRoot."/folders/folders.php";
893 if (file_exists($filePath)) {
897 ///////////////////////////////////////////////////////////////////////////
900 * Identifies subscribed mailboxes and empties the trash
901 * @param object $ie InboundEmail
903 function emptyTrash(&$ie) {
904 global $current_user;
906 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
908 if(is_array($showFolders)) {
909 foreach($showFolders as $ieId) {
911 $ie->retrieve($ieId);
919 * returns an array of nodes that correspond to IMAP mailboxes.
920 * @param bool $forceRefresh
921 * @return object TreeView object
923 function getMailboxNodes() {
924 global $sugar_config;
925 global $current_user;
928 $tree = new Tree("frameFolders");
929 $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
932 $ie = new InboundEmail();
933 $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins. this will be set via user prefs
935 $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
936 $rootNode->dynamicloadfunction = '';
937 $rootNode->expanded = true;
938 $rootNode->dynamic_load = true;
939 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
941 if(empty($showFolders)) {
942 $showFolders = array();
946 if($current_user->hasPersonalEmail()) {
947 $personals = $ie->retrieveByGroupId($current_user->id);
949 foreach($personals as $k => $personalAccount) {
950 if(in_array($personalAccount->id, $showFolders)) {
951 // check for cache value
952 $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$personalAccount->id}";
953 $this->preflightEmailCache($cacheRoot);
955 if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
956 $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
958 $mailboxes = $personalAccount->getMailboxes();
961 $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
962 $acctNode->dynamicloadfunction = '';
963 $acctNode->expanded = false;
964 $acctNode->set_property('cls', 'ieFolder');
965 $acctNode->set_property('ieId', $personalAccount->id);
966 $acctNode->set_property('protocol', $personalAccount->protocol);
968 if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
969 if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
970 $acctNode->expanded = true;
973 $acctNode->dynamic_load = true;
975 $nodePath = $acctNode->_properties['id'];
977 foreach($mailboxes as $k => $mbox) {
978 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
979 $nodePath, false, $personalAccount));
982 $rootNode->add_node($acctNode);
988 $beans = $ie->retrieveAllByGroupId($current_user->id, false);
989 foreach($beans as $k => $groupAccount) {
990 if(in_array($groupAccount->id, $showFolders)) {
991 // check for cache value
992 $cacheRoot = "{$sugar_config['cache_dir']}modules/Emails/{$groupAccount->id}";
993 $this->preflightEmailCache($cacheRoot);
994 //$groupAccount->connectMailserver();
996 if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
997 $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
999 $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
1002 $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
1003 $acctNode->dynamicloadfunction = '';
1004 $acctNode->expanded = false;
1005 $acctNode->set_property('isGroup', 'true');
1006 $acctNode->set_property('ieId', $groupAccount->id);
1007 $acctNode->set_property('protocol', $groupAccount->protocol);
1009 if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
1010 if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
1011 $acctNode->expanded = true;
1014 $acctNode->dynamic_load = true;
1015 $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
1017 foreach($mailboxes as $k => $mbox) {
1018 $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
1019 $nodePath, true, $groupAccount));
1022 $rootNode->add_node($acctNode);
1026 // SugarFolder nodes
1027 /* SugarFolders are built at onload when the UI renders */
1029 $tree->add_node($rootNode);
1033 function getMailBoxesFromCacheValue($mailAccount) {
1034 $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
1035 $mailboxes = $foldersCache['mailboxes'];
1036 $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
1037 $mailAccount->saveMailBoxFolders($mailboxesArray);
1038 $this->deleteEmailCacheForFolders($cacheRoot);
1043 * Builds up a TreeView Node object
1047 * @param string ID of InboundEmail instance
1048 * @param string nodePath Serialized path from root node to current node
1049 * @param bool isGroup
1050 * @param bool forceRefresh
1053 function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
1054 global $sugar_config;
1056 // get unread counts
1057 $exMbox = explode("::", $nodePath);
1059 $GLOBALS['log']->debug("$key --- $nodePath::$label");
1061 if(count($exMbox) >= 2) {
1063 for($i=2; $i<count($exMbox); $i++) {
1064 if($mailbox != "") {
1067 $mailbox .= "{$exMbox[$i]}";
1070 $mailbox = substr($key, strpos($key, '.'));
1072 $unseen = $this->getUnreadCount($ie, $mailbox);
1075 //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
1079 $nodePath = $nodePath."::".$label;
1080 $node = new ExtNode($nodePath, $label);
1081 $node->dynamicloadfunction = '';
1082 $node->expanded = false;
1083 $node->set_property('labelStyle', "remoteFolder");
1086 if(array_key_exists($nodePath, $this->folderStates)) {
1087 if($this->folderStates[$nodePath] == 'open') {
1088 $node->expanded = true;
1092 $group = ($isGroup) ? 'true' : 'false';
1093 $node->dynamic_load = true;
1094 //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
1095 $node->set_property('isGroup', $group);
1096 $node->set_property('isDynamic', 'false');
1097 $node->set_property('ieId', $ieId);
1098 $node->set_property('mbox', $key);
1099 $node->set_property('unseen', $unseen);
1100 $node->set_property('cls', 'ieFolder');
1102 if(is_array($mbox)) {
1103 foreach($mbox as $k => $v) {
1104 $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
1112 * Totals the unread emails
1114 function getUnreadCount(&$ie, $mailbox) {
1115 global $sugar_config;
1119 return $ie->getCacheUnreadCount($mailbox);
1122 ///////////////////////////////////////////////////////////////////////////
1125 * Used exclusively by draft code. Returns Notes and Documents as attachments.
1129 function getDraftAttachments($ret) {
1132 // $ret['uid'] is the draft Email object's GUID
1133 $ret['attachments'] = array();
1135 $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
1136 $r = $db->query($q);
1138 while($a = $db->fetchByAssoc($r)) {
1139 $ret['attachments'][$a['id']] = array(
1141 'filename' => $a['filename'],
1148 function createCopyOfInboundAttachment($ie, $ret, $uid) {
1149 global $sugar_config;
1150 if ($ie->isPop3Protocol()) {
1151 // get the UIDL from database;
1152 $cachedUIDL = md5($uid);
1153 $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php";
1155 $cache = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php";
1157 if(file_exists($cache)) {
1158 include($cache); // profides $cacheFile
1159 $metaOut = unserialize($cacheFile['out']);
1160 $meta = $metaOut['meta']['email'];
1161 if (isset($meta['attachments'])) {
1162 $attachmentHtmlData = $meta['attachments'];
1163 $actualAttachmentInfo = array();
1164 $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
1165 if (sizeof($actualAttachmentInfo) > 0) {
1166 foreach($actualAttachmentInfo as $key => $value) {
1169 $datasplit = explode("&", $value);
1170 $attachmentIdArray = explode("=", $datasplit[0]);
1171 $attachmentid = $attachmentIdArray[1];
1173 $fileNameArray = explode("=", $datasplit[4]);
1174 $fileName = $fileNameArray[1];
1175 $guid = create_guid();
1176 //$destination = clean_path("{$this->userCacheDir}/{$guid}{$fileName}");
1177 $destination = clean_path("{$this->userCacheDir}/{$guid}");
1179 $attachmentFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/attachments/{$attachmentid}";
1180 copy($attachmentFilePath, $destination);
1181 $ret['attachments'][$guid] = array();
1182 $ret['attachments'][$guid]['id'] = $guid . $fileName;
1183 $ret['attachments'][$guid]['filename'] = $fileName;
1193 function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
1194 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1195 while ($downLoadPHP) {
1196 $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
1197 $final = strpos($attachmentHtmlData, "\">");
1198 $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
1199 $attachmentHtmlData = substr($attachmentHtmlData, $final);
1200 $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
1204 * Renders the QuickCreate form from Smarty and returns HTML
1205 * @param array $vars request variable global
1206 * @param object $email Fetched email object
1207 * @param bool $addToAddressBook
1210 function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
1211 require_once("include/EditView/EditView2.php");
1212 global $app_strings;
1213 global $mod_strings;
1214 global $current_user;
1217 global $current_language;
1219 //Setup the current module languge
1220 $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
1222 $bean = $beanList[$_REQUEST['qc_module']];
1223 $class = $beanFiles[$bean];
1224 require_once($class);
1226 $focus = new $bean();
1232 $emailAddress = array();
1235 if(in_array($bean, $people)) {
1237 $focus->lead_source = 'Email';
1238 $focus->lead_source_description = trim($email->name);
1240 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
1242 if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
1243 $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr_name;
1246 $name = explode(" ", trim($from));
1248 $address = trim(array_pop($name));
1249 $address = str_replace(array("<",">","<",">"), "", $address);
1251 $emailAddress[] = array(
1252 'email_address' => $address,
1253 'primary_address' => 1,
1254 'invalid_email' => 0,
1256 'reply_to_address' => 1
1259 $focus->email1 = $address;
1262 $focus->last_name = trim(array_pop($name));
1264 foreach($name as $first) {
1265 if(!empty($focus->first_name)) {
1266 $focus->first_name .= " ";
1268 $focus->first_name .= trim($first);
1272 // bugs, cases, tasks
1273 $focus->name = trim($email->name);
1276 $focus->description = trim(strip_tags($email->description));
1277 $focus->assigned_user_id = $current_user->id;
1280 $EditView = new EditView();
1281 $EditView->ss = new Sugar_Smarty();
1282 //MFH BUG#20283 - checks for custom quickcreate fields
1283 $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
1284 $EditView->process();
1285 $EditView->render();
1287 $EditView->defs['templateMeta']['form']['buttons'] = array(
1288 'email2save' => array(
1289 'id' => 'e2AjaxSave',
1290 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_SAVE_BUTTON_LABEL']
1291 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
1293 'email2saveandreply' => array(
1294 'id' => 'e2SaveAndReply',
1295 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
1296 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
1298 'email2cancel' => array(
1300 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_CANCEL']
1301 . ' " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
1306 if($addToAddressBookButton) {
1307 $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
1308 'id' => 'e2addToAddressBook',
1309 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
1310 . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
1314 //Get the module language for javascript
1315 if(!is_file($GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/' . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
1316 require_once('include/language/jsLanguage.php');
1317 jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
1319 $jsLanguage = '<script type="text/javascript" src="' . $GLOBALS['sugar_config']['cache_dir'] . 'jsLanguage/'
1320 . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js?s=' . $GLOBALS['sugar_version'] . '&c='
1321 . $GLOBALS['sugar_config']['js_custom_version'] . '&j=' . $GLOBALS['sugar_config']['js_lang_version'] . '"></script>';
1325 $EditView->view = 'EmailQCView';
1326 $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
1327 $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
1329 $meta['html'] = $jsLanguage . $EditView->display(false, true);
1330 $meta['html'] = str_replace("src='include/SugarEmailAddress/SugarEmailAddress.js?s={$GLOBALS['js_version_key']}&c={$GLOBALS['sugar_config']['js_custom_version']}'", '', $meta['html']);
1331 $meta['emailAddress'] = $emailAddress;
1333 $mod_strings = return_module_language($current_language, 'Emails');
1339 * Renders the Import form from Smarty and returns HTML
1340 * @param array $vars request variable global
1341 * @param object $email Fetched email object
1342 * @param bool $addToAddressBook
1345 function getImportForm($vars, $email, $formName = 'ImportEditView') {
1346 require_once("include/EditView/EditView2.php");
1347 require_once("include/TemplateHandler/TemplateHandler.php");
1348 require_once('include/QuickSearchDefaults.php');
1349 $qsd = new QuickSearchDefaults();
1350 $qsd->setFormName($formName);
1352 global $app_strings;
1353 global $current_user;
1354 global $app_list_strings;
1355 $sqs_objects = array(
1356 "{$formName}_parent_name" => $qsd->getQSParent(),
1358 $smarty = new Sugar_Smarty();
1359 $smarty->assign("APP",$app_strings);
1360 $smarty->assign('formName',$formName);
1361 $showAssignTo = false;
1362 if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
1363 $showAssignTo = true;
1365 if ($showAssignTo) {
1366 if(empty($email->assigned_user_id) && empty($email->id))
1367 $email->assigned_user_id = $current_user->id;
1368 if(empty($email->assigned_name) && empty($email->id))
1369 $email->assigned_user_name = $current_user->user_name;
1370 $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
1372 $smarty->assign("showAssignedTo",$showAssignTo);
1374 $showDelete = false;
1375 if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
1378 $smarty->assign("showDelete",$showDelete);
1380 $smarty->assign("userId",$email->assigned_user_id);
1381 $smarty->assign("userName",$email->assigned_user_name);
1382 $parent_types = $app_list_strings['record_type_display'];
1383 $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
1385 $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
1386 $smarty->assign('SQS', $quicksearch_js);
1389 $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
1394 * This function returns the detail view for email in new 2.0 interface
1397 function getDetailViewForEmail2($emailId) {
1399 require_once('include/DetailView/DetailView.php');
1400 global $app_strings, $app_list_strings;
1401 global $mod_strings;
1403 $smarty = new Sugar_Smarty();
1406 $focus = new Email();
1407 $focus->retrieve($emailId);
1408 $detailView->ss = new Sugar_Smarty();
1409 $detailView = new DetailView();
1412 if($focus->type == 'out') {
1413 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name), true);
1414 } elseif ($focus->type == 'draft') {
1415 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_LIST_FORM_DRAFTS_TITLE'],$focus->name), true);
1416 } elseif($focus->type == 'inbound') {
1417 $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_INBOUND_TITLE'],$focus->name), true);
1419 $smarty->assign("emailTitle", $title);
1421 // DEFAULT TO TEXT IF NO HTML CONTENT:
1422 $html = trim(from_html($focus->description_html));
1424 $smarty->assign('SHOW_PLAINTEXT', 'true');
1425 $description = nl2br($focus->description);
1427 $smarty->assign('SHOW_PLAINTEXT', 'false');
1428 $description = from_html($focus->description_html);
1431 //if not empty or set to test (from test campaigns)
1432 if (!empty($focus->parent_type) && $focus->parent_type !='test') {
1433 $smarty->assign('PARENT_MODULE', $focus->parent_type);
1434 $smarty->assign('PARENT_TYPE', $app_list_strings['record_type_display'][$focus->parent_type] . ":");
1438 $smarty->assign('MOD', $mod_strings);
1439 $smarty->assign('APP', $app_strings);
1440 $smarty->assign('GRIDLINE', $gridline);
1441 $smarty->assign('PRINT_URL', 'index.php?'.$GLOBALS['request_string']);
1442 $smarty->assign('ID', $focus->id);
1443 $smarty->assign('TYPE', $focus->type);
1444 $smarty->assign('PARENT_NAME', $focus->parent_name);
1445 $smarty->assign('PARENT_ID', $focus->parent_id);
1446 $smarty->assign('NAME', $focus->name);
1447 $smarty->assign('ASSIGNED_TO', $focus->assigned_user_name);
1448 $smarty->assign('DATE_MODIFIED', $focus->date_modified);
1449 $smarty->assign('DATE_ENTERED', $focus->date_entered);
1450 $smarty->assign('DATE_START', $focus->date_start);
1451 $smarty->assign('TIME_START', $focus->time_start);
1452 $smarty->assign('FROM', $focus->from_addr);
1453 $smarty->assign('TO', nl2br($focus->to_addrs));
1454 $smarty->assign('CC', nl2br($focus->cc_addrs));
1455 $smarty->assign('BCC', nl2br($focus->bcc_addrs));
1456 $smarty->assign('CREATED_BY', $focus->created_by_name);
1457 $smarty->assign('MODIFIED_BY', $focus->modified_by_name);
1458 $smarty->assign('DESCRIPTION', nl2br($focus->description));
1459 $smarty->assign('DESCRIPTION_HTML', from_html($focus->description_html));
1460 $smarty->assign('DATE_SENT', $focus->date_entered);
1461 $smarty->assign('EMAIL_NAME', 'RE: '.$focus->name);
1462 $smarty->assign("TAG", $focus->listviewACLHelper());
1463 $smarty->assign("SUGAR_VERSION", $GLOBALS['sugar_version']);
1464 $smarty->assign("JS_CUSTOM_VERSION", $GLOBALS['sugar_config']['js_custom_version']);
1465 if(!empty($focus->reply_to_email)) {
1468 <td class=\"tabDetailViewDL\"><slot>".$mod_strings['LBL_REPLY_TO_NAME']."</slot></td>
1469 <td colspan=3 class=\"tabDetailViewDF\"><slot>".$focus->reply_to_addr."</slot></td>
1471 $smarty->assign("REPLY_TO", $replyTo);
1473 ///////////////////////////////////////////////////////////////////////////////
1474 //// JAVASCRIPT VARS
1476 $jsVars .= "var showRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL']}';";
1477 $jsVars .= "var hideRaw = '{$mod_strings['LBL_BUTTON_RAW_LABEL_HIDE']}';";
1478 $smarty->assign("JS_VARS", $jsVars);
1479 ///////////////////////////////////////////////////////////////////////////////
1480 //// NOTES (attachements, etc.)
1481 ///////////////////////////////////////////////////////////////////////////////
1484 $where = "notes.parent_id='{$focus->id}'";
1485 //take in account if this is from campaign and the template id is stored in the macros.
1487 if(isset($macro_values) && isset($macro_values['email_template_id'])){
1488 $where = "notes.parent_id='{$macro_values['email_template_id']}'";
1490 $notes_list = $note->get_full_list("notes.name", $where, true);
1492 if(! isset($notes_list)) {
1493 $notes_list = array();
1497 for($i=0; $i<count($notes_list); $i++) {
1498 $the_note = $notes_list[$i];
1499 //$attachments .= "<a href=\"".UploadFile::get_url($the_note->filename,$the_note->id)."\" target=\"_blank\">".$the_note->name.$the_note->description ."</a><br>";
1500 $attachments .= "<a href=\"index.php?entryPoint=download&id=".$the_note->id."&type=Notes\">".$the_note->name."</a><br />";
1502 $smarty->assign("ATTACHMENTS", $attachments);
1503 ///////////////////////////////////////////////////////////////////////////////
1505 ///////////////////////////////////////////////////////////////////////////////
1506 $show_subpanels = true;
1507 if ($show_subpanels) {
1508 require_once('include/SubPanel/SubPanelTiles.php');
1509 $subpanel = new SubPanelTiles($focus, 'Emails');
1510 $smarty->assign("SUBPANEL", $subpanel->display());
1512 $meta['html'] = $smarty->fetch("modules/Emails/templates/emailDetailView.tpl");
1518 * Sets the "read" flag in the overview cache
1520 function setReadFlag($ieId, $mbox, $uid) {
1521 $this->markEmails('read', $ieId, $mbox, $uid);
1525 * Marks emails with the passed flag type. This will be applied to local
1526 * cache files as well as remote emails.
1527 * @param string $type Flag type
1528 * @param string $ieId
1529 * @param string $folder IMAP folder structure or SugarFolder GUID
1530 * @param string $uids Comma sep list of UIDs or GUIDs
1532 function markEmails($type, $ieId, $folder, $uids) {
1534 global $app_strings;
1535 $uids = $this->_cleanUIDList($uids);
1536 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1538 if(strpos($folder, 'sugar::') !== false) {
1539 // dealing with a sugar email object, uids are GUIDs
1540 foreach($exUids as $id) {
1541 $email = new Email();
1542 $email->retrieve($id);
1546 $email->status = 'unread';
1551 $email->status = 'read';
1560 $email->flagged = 1;
1565 $email->flagged = 0;
1572 /* dealing with IMAP email, uids are IMAP uids */
1573 global $ie; // provided by EmailUIAjax.php
1576 $ie = new InboundEmail();
1578 $ie->retrieve($ieId);
1579 $ie->mailbox = $folder;
1580 $ie->connectMailserver();
1582 if($type == 'deleted') {
1583 $ie->deleteMessageOnMailServer($uids);
1584 $ie->deleteMessageFromCache($uids);
1586 $overviews = $ie->getCacheValueForUIDs($ie->mailbox, $exUids);
1587 $manipulated = array();
1589 foreach($overviews['retArr'] as $k => $overview) {
1590 if(in_array($overview->uid, $exUids)) {
1593 $overview->seen = 0;
1597 $overview->seen = 1;
1601 $overview->flagged = 1;
1605 $overview->flagged = 0;
1608 $manipulated[] = $overview;
1612 if(!empty($manipulated)) {
1613 $ie->setCacheValue($ie->mailbox, array(), $manipulated);
1614 /* now mark emails on email server */
1615 $ie->markEmails(implode(",", explode($app_strings['LBL_EMAIL_DELIMITER'], $uids)), $type);
1617 } // end not type == deleted
1621 function doAssignment($distributeMethod, $ieid, $folder, $uids, $users) {
1622 global $app_strings;
1623 $users = explode(",", $users);
1624 $emailIds = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1626 if($folder != 'sugar::Emails') {
1627 $emailIds = array();
1628 $uids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
1629 $ie = new InboundEmail();
1630 $ie->retrieve($ieid);
1632 // dealing with an inbound email data so we need to import an email and then
1633 foreach($uids as $uid) {
1634 $ie->mailbox = $folder;
1635 $ie->connectMailserver();
1637 if (!$ie->isPop3Protocol()) {
1638 $msgNo = imap_msgno($ie->conn, $uid);
1640 $msgNo = $ie->getCorrectMessageNoForPop3($uid);
1643 if(!empty($msgNo)) {
1644 if ($ie->importOneEmail($msgNo, $uid)) {
1645 $emailIds[] = $ie->email->id;
1646 $ie->deleteMessageOnMailServer($uid);
1647 //$ie->retrieve($ieid);
1648 //$ie->connectMailserver();
1649 $ie->mailbox = $folder;
1650 $ie->deleteMessageFromCache(($uids[] = $uid));
1652 $out = $out . "Message No : " . $messageIndex . " failed. Reason : Message already imported \r\n";
1659 if (count($emailIds) > 0) {
1660 $this->doDistributionWithMethod($users, $emailIds, $distributeMethod);
1666 * get team id and team set id from request
1669 function getTeams() {
1672 function doDistributionWithMethod($users, $emailIds, $distributionMethod) {
1673 // we have users and the items to distribute
1674 if($distributionMethod == 'roundRobin') {
1675 $this->distRoundRobin($users, $emailIds);
1676 } elseif($distributionMethod == 'leastBusy') {
1677 $this->distLeastBusy($users, $emailIds);
1678 } elseif($distributionMethod == 'direct') {
1679 if(count($users) > 1) {
1680 // only 1 user allowed in direct assignment
1684 $this->distDirect($user, $emailIds);
1691 * distributes emails to users on Round Robin basis
1692 * @param $userIds array of users to dist to
1693 * @param $mailIds array of email ids to push on those users
1694 * @return boolean true on success
1696 function distRoundRobin($userIds, $mailIds) {
1697 // check if we have a 'lastRobin'
1698 $lastRobin = $userIds[0];
1699 foreach($mailIds as $k => $mailId) {
1700 $userIdsKeys = array_flip($userIds); // now keys are values
1701 $thisRobinKey = $userIdsKeys[$lastRobin] + 1;
1702 if(!empty($userIds[$thisRobinKey])) {
1703 $thisRobin = $userIds[$thisRobinKey];
1704 $lastRobin = $userIds[$thisRobinKey];
1706 $thisRobin = $userIds[0];
1707 $lastRobin = $userIds[0];
1710 $email = new Email();
1711 $email->retrieve($mailId);
1712 $email->assigned_user_id = $thisRobin;
1713 $email->status = 'unread';
1721 * distributes emails to users on Least Busy basis
1722 * @param $userIds array of users to dist to
1723 * @param $mailIds array of email ids to push on those users
1724 * @return boolean true on success
1726 function distLeastBusy($userIds, $mailIds) {
1727 foreach($mailIds as $k => $mailId) {
1728 $email = new Email();
1729 $email->retrieve($mailId);
1730 foreach($userIds as $k => $id) {
1731 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '.$id.' AND status = 'unread'");
1732 $a = $this->db->fetchByAssoc($r);
1733 $counts[$id] = $a['c'];
1735 asort($counts); // lowest to highest
1736 $countsKeys = array_flip($counts); // keys now the 'count of items'
1737 $leastBusy = array_shift($countsKeys); // user id of lowest item count
1738 $email->assigned_user_id = $leastBusy;
1739 $email->status = 'unread';
1746 * distributes emails to 1 user
1747 * @param $user users to dist to
1748 * @param $mailIds array of email ids to push
1749 * @return boolean true on success
1751 function distDirect($user, $mailIds) {
1752 foreach($mailIds as $k => $mailId) {
1753 $email = new Email();
1754 $email->retrieve($mailId);
1755 $email->assigned_user_id = $user;
1756 $email->status = 'unread';
1763 function getAssignedEmailsCountForUsers($userIds) {
1765 foreach($userIds as $id) {
1766 $r = $this->db->query("SELECT count(*) AS c FROM emails WHERE assigned_user_id = '$id' AND status = 'unread'");
1767 $a = $this->db->fetchByAssoc($r);
1768 $counts[$id] = $a['c'];
1773 function getLastRobin($ie) {
1775 if($this->validCacheFileExists($ie->id, 'folders', "robin.cache.php")) {
1776 $lastRobin = $this->getCacheValue($ie->id, 'folders', "robin.cache.php", 'robin');
1781 function setLastRobin($ie, $lastRobin) {
1782 global $sugar_config;
1783 $cacheFolderPath = clean_path("{$sugar_config['cache_dir']}modules/Emails/{$ie->id}/folders");
1784 if (!file_exists($cacheFolderPath)) {
1785 mkdir_recursive($cacheFolderPath);
1787 $this->writeCacheFile('robin', $lastRobin, $ie->id, 'folders', "robin.cache.php");
1791 * returns the metadata defining a single email message for display. Uses cache file if it exists
1794 function getSingleMessage($ie) {
1797 global $app_strings,$mod_strings;
1798 $ie->retrieve($_REQUEST['ieId']);
1801 $ie->mailbox = $_REQUEST['mbox'];
1802 $filename = $_REQUEST['mbox'].$_REQUEST['uid'].".php";
1804 if ($ie->isPop3Protocol()) {
1805 $md5uidl = md5($_REQUEST['uid']);
1806 $filename = $_REQUEST['mbox'].$md5uidl.".php";
1809 if($this->validCacheFileExists($_REQUEST['ieId'], 'messages', $filename)) {
1810 $out = $this->getCacheValue($_REQUEST['ieId'], 'messages', $filename, 'out');
1813 // something fubar'd the cache?
1814 if(empty($out['meta']['email']['name']) && empty($out['meta']['email']['description'])) {
1817 // When sending data from cache, convert date into users preffered format
1818 $dateTimeInGMTFormat = $out['meta']['email']['date_start'];
1819 $out['meta']['email']['date_start'] = $timedate->to_display_date_time($dateTimeInGMTFormat);
1824 $writeToCacheFile = true;
1825 if ($ie->isPop3Protocol()) {
1826 $status = $ie->setEmailForDisplay($_REQUEST['uid'], true, true, true);
1828 $status = $ie->setEmailForDisplay($_REQUEST['uid'], false, true, true);
1830 $out = $ie->displayOneEmail($_REQUEST['uid'], $_REQUEST['mbox']);
1831 // modify the out object to store date in GMT format on the local cache file
1832 $dateTimeInUserFormat = $out['meta']['email']['date_start'];
1833 $out['meta']['email']['date_start'] = $timedate->to_db($dateTimeInUserFormat);
1834 if ($status == 'error') {
1835 $writeToCacheFile = false;
1837 if ($writeToCacheFile) {
1838 if ($ie->isPop3Protocol()) {
1839 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$md5uidl}.php");
1841 $this->writeCacheFile('out', $out, $_REQUEST['ieId'], 'messages', "{$_REQUEST['mbox']}{$_REQUEST['uid']}.php");
1843 // restore date in the users preferred format to be send on to UI for diaply
1844 $out['meta']['email']['date_start'] = $dateTimeInUserFormat;
1847 $out['meta']['email']['toaddrs'] = $this->generateExpandableAddrs($out['meta']['email']['toaddrs']);
1848 if(!empty($out['meta']['email']['cc_addrs'])) {
1849 $ccs = $this->generateExpandableAddrs($out['meta']['email']['cc_addrs']);
1850 $out['meta']['cc'] = <<<eoq
1852 <td NOWRAP valign="top" class="displayEmailLabel">
1853 {$app_strings['LBL_EMAIL_CC']}:
1855 <td class="displayEmailValue">
1862 if(empty($out['meta']['email']['description']))
1863 $out['meta']['email']['description'] = $mod_strings['LBL_EMPTY_EMAIL_BODY'];
1866 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() NOT using cache file");
1868 $GLOBALS['log']->debug("EMAILUI: getSingleMessage() using cache file [ ".$_REQUEST['mbox'].$_REQUEST['uid'].".php ]");
1871 $this->setReadFlag($_REQUEST['ieId'], $_REQUEST['mbox'], $_REQUEST['uid']);
1877 * Returns the HTML for a list of emails in a given folder
1878 * @param GUID $ieId GUID to InboundEmail instance
1879 * @param string $mbox Mailbox path name in dot notation
1880 * @param int $folderListCacheOffset Seconds for valid cache file
1881 * @return string HTML render of list.
1883 function getListEmails($ieId, $mbox, $folderListCacheOffset, $forceRefresh='false') {
1884 global $sugar_config;
1887 $ie = new InboundEmail();
1888 $ie->retrieve($ieId);
1889 $list = $ie->displayFolderContents($mbox, $forceRefresh);
1895 * Returns the templatized compose screen. Used by reply, forwards and draft status messages.
1896 * @param object email Email bean in focus
1898 function displayComposeEmail($email) {
1900 global $current_user;
1903 $ea = new SugarEmailAddress();
1905 if(!empty($email)) {
1906 $description = (empty($email->description_html)) ? $email->description : $email->description_html;
1909 //Get the most complete address list availible for this email
1910 $addresses = array('toAddresses' => 'to', 'ccAddresses' => 'cc', 'bccAddresses' => 'bcc');
1911 foreach($addresses as $var => $type)
1914 foreach (array("{$type}_addrs_names", "{$type}addrs", "{$type}_addrs") as $emailVar)
1916 if (!empty($email->$emailVar)) {
1917 $$var = $email->$emailVar;
1924 $ret['type'] = $email->type;
1925 $ret['name'] = $email->name;
1926 $ret['description'] = $description;
1927 $ret['from'] = (isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'forward') ? "" : $email->from_addr;
1928 $ret['to'] = from_html($toAddresses);
1929 $ret['uid'] = $email->id;
1930 $ret['parent_name'] = $email->parent_name;
1931 $ret['parent_type'] = $email->parent_type;
1932 $ret['parent_id'] = $email->parent_id;
1935 if(isset($_REQUEST['composeType']) && $_REQUEST['composeType'] == 'replyAll') {
1936 $ret['cc'] = from_html($ccAddresses);
1937 $ret['bcc'] = $bccAddresses;
1939 $userEmails = array();
1940 $userEmailsMeta = $ea->getAddressesByGUID($current_user->id, 'Users');
1941 foreach($userEmailsMeta as $emailMeta) {
1942 $userEmails[] = from_html(strtolower(trim($emailMeta['email_address'])));
1944 $userEmails[] = from_html(strtolower(trim($email->from_addr)));
1946 $ret['cc'] = from_html($email->cc_addrs);
1947 $toAddresses = from_html($toAddresses);
1948 $to = str_replace($this->addressSeparators, "::", $toAddresses);
1949 $exTo = explode("::", $to);
1951 if(is_array($exTo)) {
1952 foreach($exTo as $addr) {
1953 $addr = strtolower(trim($addr));
1954 if(!in_array($addr, $userEmails)) {
1955 if(!empty($ret['cc'])) {
1956 $ret['cc'] = $ret['cc'].", ";
1958 $ret['cc'] = $ret['cc'].trim($addr);
1961 } elseif(!empty($exTo)) {
1962 $exTo = trim($exTo);
1963 if(!in_array($exTo, $userEmails)) {
1964 $ret['cc'] = $ret['cc'].", ".$exTo;
1971 * Formats email body on reply/forward
1972 * @param object email Email object in focus
1973 * @param string type
1974 * @return object email
1976 function handleReplyType($email, $type) {
1977 global $mod_strings;
1978 $GLOBALS['log']->debug("****At Handle Reply Type: $type");
1982 $header = $email->getReplyHeader();
1983 if(!preg_match('/^(re:)+/i', $email->name)) {
1984 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
1986 if ($type == "reply") {
1987 $email->cc_addrs = "";
1988 if (!empty($email->reply_to_addr)) {
1989 $email->from_addr = $email->reply_to_addr;
1992 if (!empty($email->reply_to_addr)) {
1993 $email->to_addrs = $email->to_addrs . "," . $email->reply_to_addr;
1999 $header = $email->getForwardHeader();
2000 if(!preg_match('/^(fw:)+/i', $email->name)) {
2001 $email->name = "{$mod_strings['LBL_FW']} {$email->name}";
2003 $email->cc_addrs = "";
2007 $GLOBALS['log']->debug("EMAILUI: At reply case");
2008 $header = $email->getReplyHeader();
2010 $myCase = new aCase();
2011 $myCase->retrieve($email->parent_id);
2012 $myCaseMacro = $myCase->getEmailSubjectMacro();
2013 $email->parent_name = $myCase->name;
2014 $GLOBALS['log']->debug("****Case # : {$myCase->case_number} macro: $myCaseMacro");
2015 if(!strpos($email->name, str_replace('%1',$myCase->case_number,$myCaseMacro))) {
2016 $GLOBALS['log']->debug("Replacing");
2017 $email->name = str_replace('%1',$myCase->case_number,$myCaseMacro) . ' '. $email->name;
2019 $email->name = "{$mod_strings['LBL_RE']} {$email->name}";
2023 $html = trim($email->description_html);
2024 $plain = trim($email->description);
2026 $desc = (!empty($html)) ? $html : $plain;
2028 $email->description = $header.$email->quoteHtmlEmailForNewEmailUI($desc);
2033 ///////////////////////////////////////////////////////////////////////////
2034 //// PRIVATE HELPERS
2036 * Generates a UNION query to get one list of users, contacts, leads, and
2037 * prospects; used specifically for the addressBook
2039 function _getPeopleUnionQuery($whereArr , $person) {
2040 global $current_user , $app_strings;
2042 if(!isset($person) || $person === 'LBL_DROPDOWN_LIST_ALL'){
2043 $peopleTables = array("users",
2050 $peopleTables = array($person);
2056 foreach($whereArr as $column => $clause) {
2057 if(!empty($whereAdd)) {
2058 $whereAdd .= " AND ";
2060 $clause = $current_user->db->helper->escape_quote($clause);
2061 $whereAdd .= "{$column} LIKE '{$clause}%'";
2065 foreach($peopleTables as $table) {
2066 $module = ucfirst($table);
2067 $class = substr($module, 0, strlen($module) - 1);
2068 require_once("modules/{$module}/{$class}.php");
2069 $person = new $class();
2070 if (!$person->ACLAccess('list')) {
2073 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id <> '{$current_user->id}')";
2075 if (ACLController::requireOwner($module, 'list')) {
2076 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2078 if(!empty($whereAdd)) {
2079 $where .= " AND ({$whereAdd})";
2082 if ($person === 'accounts') {
2083 $t = "SELECT {$table}.id, '' first_name, {$table}.name, eabr.primary_address, ea.email_address, '{$module}' module ";
2085 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2087 $t .= "FROM {$table} ";
2088 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2089 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2090 $t .= " WHERE {$where}";
2093 $q .= "\n UNION ALL \n";
2098 $countq = "SELECT count(people.id) c from ($q) people";
2099 $q .= "ORDER BY last_name";
2101 return array('query' => $q, 'countQuery' => $countq);
2105 * get emails of related bean for a given bean id
2107 * @param $condition array of conditions inclued bean id
2108 * @return array('query' => $q, 'countQuery' => $countq);
2110 function getRelatedEmail($beanType, $whereArr, $relatedBeanInfoArr = ''){
2111 global $beanList, $current_user, $app_strings, $db;
2113 $searchBeans = null;
2114 if($beanType === 'LBL_DROPDOWN_LIST_ALL')
2115 $searchBeans = array("users",
2122 if ($relatedBeanInfoArr == '' || empty($relatedBeanInfoArr['related_bean_type']) )
2124 if ($searchBeans != null)
2127 foreach ($searchBeans as $searchBean)
2129 $searchq = $this->findEmailFromBeanIds('', $searchBean, $whereArr);
2130 if(!empty($searchq)) {
2131 $q[] = "($searchq)";
2135 $finalQuery .= implode("\n UNION ALL \n", $q);
2138 $finalQuery = $this->findEmailFromBeanIds('', $beanType, $whereArr);
2142 $class = $beanList[$relatedBeanInfoArr['related_bean_type']];
2143 $focus = new $class();
2144 $focus->retrieve($relatedBeanInfoArr['related_bean_id']);
2145 if ($searchBeans != null)
2148 foreach ($searchBeans as $searchBean)
2150 if ($focus->load_relationship($searchBean))
2152 $data = $focus->$searchBean->get();
2153 if (count($data) != 0)
2154 $q[] = '('.$this->findEmailFromBeanIds($data, $searchBean, $whereArr).')';
2158 $finalQuery .= implode("\n UNION ALL \n", $q);
2162 if ($focus->load_relationship($beanType))
2164 $data = $focus->$beanType->get();
2165 if (count($data) != 0)
2166 $finalQuery = $this->findEmailFromBeanIds($data, $beanType, $whereArr);
2170 $countq = "SELECT count(people.id) c from ($finalQuery) people";
2171 return array('query' => $finalQuery, 'countQuery' => $countq);
2174 function findEmailFromBeanIds($beanIds, $beanType, $whereArr) {
2175 global $current_user;
2179 if ($beanIds != '') {
2180 foreach ($beanIds as $key => $value) {
2181 $beanIds[$key] = '\''.$value.'\'';
2183 $relatedIDs = implode(',', $beanIds);
2186 if ($beanType == 'accounts') {
2187 if (isset($whereArr['first_name'])) {
2188 $whereArr['name'] = $whereArr['first_name'];
2190 unset($whereArr['last_name']);
2191 unset($whereArr['first_name']);
2194 foreach($whereArr as $column => $clause) {
2195 if(!empty($whereAdd)) {
2196 $whereAdd .= " OR ";
2198 $clause = $current_user->db->helper->escape_quote($clause);
2199 $whereAdd .= "{$column} LIKE '{$clause}%'";
2202 $module = ucfirst($table);
2203 $class = substr($module, 0, strlen($module) - 1);
2204 require_once("modules/{$module}/{$class}.php");
2205 $person = new $class();
2206 if ($person->ACLAccess('list')) {
2207 if ($relatedIDs != '') {
2208 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1 AND {$table}.id in ($relatedIDs))";
2210 $where = "({$table}.deleted = 0 AND eabr.primary_address = 1)";
2213 if (ACLController::requireOwner($module, 'list')) {
2214 $where = $where . " AND ({$table}.assigned_user_id = '{$current_user->id}')";
2216 if(!empty($whereAdd)) {
2217 $where .= " AND ({$whereAdd})";
2220 if ($beanType === 'accounts') {
2221 $t = "SELECT {$table}.id, '' first_name, {$table}.name last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2223 $t = "SELECT {$table}.id, {$table}.first_name, {$table}.last_name, eabr.primary_address, ea.email_address, '{$module}' module ";
2226 $t .= "FROM {$table} ";
2227 $t .= "JOIN email_addr_bean_rel eabr ON ({$table}.id = eabr.bean_id and eabr.deleted=0) ";
2228 $t .= "JOIN email_addresses ea ON (eabr.email_address_id = ea.id) ";
2229 $t .= " WHERE {$where}";
2236 * @param mixed $uids
2237 * @param bool $returnString False will return an array
2240 function _cleanUIDList($uids, $returnString=false) {
2241 global $app_strings;
2242 $GLOBALS['log']->debug("_cleanUIDList: before - [ {$uids} ]");
2244 if(!is_array($uids)) {
2245 $returnString = true;
2247 $exUids = explode($app_strings['LBL_EMAIL_DELIMITER'], $uids);
2251 $cleanUids = array();
2252 foreach($uids as $uid) {
2253 $cleanUids[$uid] = $uid;
2259 $cleanImplode = implode($app_strings['LBL_EMAIL_DELIMITER'], $cleanUids);
2260 $GLOBALS['log']->debug("_cleanUIDList: after - [ {$cleanImplode} ]");
2261 return $cleanImplode;
2268 * Creates defaults for the User
2269 * @param object $user User in focus
2271 function preflightUser(&$user) {
2272 global $mod_strings;
2274 $goodToGo = $user->getPreference("email2Preflight", "Emails");
2275 $q = "SELECT count(*) count FROM folders f where f.created_by = '{$user->id}' AND f.folder_type = 'inbound' AND f.deleted = 0";
2276 $r = $user->db->query($q);
2277 $a = $user->db->fetchByAssoc($r);
2279 if($a['count'] < 1) {
2280 require_once("include/SugarFolders/SugarFolders.php");
2282 $folder = new SugarFolder();
2283 $folder->new_with_id = true;
2284 $folder->id = create_guid();
2285 $folder->name = $mod_strings['LNK_MY_INBOX'];
2286 $folder->has_child = 1;
2287 $folder->created_by = $user->id;
2288 $folder->modified_by = $user->id;
2289 $folder->is_dynamic = 1;
2290 $folder->folder_type = "inbound";
2291 $folder->dynamic_query = $this->generateDynamicFolderQuery('inbound', $user->id);
2295 $drafts = new SugarFolder();
2296 $drafts->name = $mod_strings['LNK_MY_DRAFTS'];
2297 $drafts->has_child = 0;
2298 $drafts->parent_folder = $folder->id;
2299 $drafts->created_by = $user->id;
2300 $drafts->modified_by = $user->id;
2301 $drafts->is_dynamic = 1;
2302 $drafts->folder_type = "draft";
2303 $drafts->dynamic_query = $this->generateDynamicFolderQuery('draft', $user->id);
2308 $archived = new SugarFolder();
2309 $archived->name = $mod_strings['LNK_SENT_EMAIL_LIST'];
2310 $archived->has_child = 0;
2311 $archived->parent_folder = $folder->id;
2312 $archived->created_by = $user->id;
2313 $archived->modified_by = $user->id;
2314 $archived->is_dynamic = 1;
2315 $archived->folder_type = "sent";
2316 $archived->dynamic_query = $this->generateDynamicFolderQuery('sent', $user->id);
2319 // set flag to show that this was run
2320 $user->setPreference("email2Preflight", true, 1, "Emails");
2325 * Parses the core dynamic folder query
2326 * @param string $type 'inbound', 'draft', etc.
2327 * @param string $userId
2330 function generateDynamicFolderQuery($type, $userId) {
2331 $q = $this->coreDynamicFolderQuery;
2335 if($type == "sent") {
2339 $replacee = array("::TYPE::", "::STATUS::", "::USER_ID::");
2340 $replacer = array($type, $status, $userId);
2342 $ret = str_replace($replacee, $replacer, $q);
2344 if($type == 'inbound') {
2345 $ret .= " AND status NOT IN ('sent', 'archived', 'draft') AND type NOT IN ('out', 'archived', 'draft')";
2347 $ret .= " AND status NOT IN ('archived') AND type NOT IN ('archived')";
2354 * Preps the User's cache dir
2356 function preflightUserCache() {
2357 $path = clean_path($this->userCacheDir);
2358 if(!file_exists($this->userCacheDir))
2359 mkdir_recursive($path);
2361 $files = findAllFiles($path, array());
2363 foreach($files as $file) {
2368 function clearInboundAccountCache($ieId) {
2369 global $sugar_config;
2370 $cacheRoot = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}";
2371 $files = findAllFiles($cacheRoot."/messages/", array());
2372 foreach($files as $file) {
2375 $files = findAllFiles($cacheRoot."/attachments/", array());
2376 foreach($files as $file) {
2382 * returns an array of EmailTemplates that the user has access to for the compose email screen
2385 function getEmailTemplatesArray() {
2387 global $app_strings;
2389 if(ACLController::checkAccess('EmailTemplates', 'list', true) && ACLController::checkAccess('EmailTemplates', 'view', true)) {
2390 $et = new EmailTemplate();
2391 $etResult = $et->db->query($et->create_new_list_query('','',array(),array(),''));
2392 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2393 while($etA = $et->db->fetchByAssoc($etResult)) {
2394 $email_templates_arr[$etA['id']] = $etA['name'];
2397 $email_templates_arr = array('' => $app_strings['LBL_NONE']);
2400 return $email_templates_arr;
2403 function getFromAccountsArray($ie) {
2404 global $current_user;
2405 global $app_strings;
2407 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2408 $ieAccountsFrom= array();
2410 $oe = new OutboundEmail();
2411 $system = $oe->getSystemMailerSettings();
2412 $ret = $current_user->getUsersNameAndEmail();
2413 $ret['name'] = from_html($ret['name']);
2414 $useMyAccountString = true;
2416 if(empty($ret['email'])) {
2417 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2418 $ret['email'] = $systemReturn['email'];
2419 $ret['name'] = from_html($systemReturn['name']);
2420 $useMyAccountString = false;
2423 $myAccountString = '';
2424 if ($useMyAccountString) {
2425 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2428 //Check to make sure that the user has set the associated inbound email acount -> outbound acount is active.
2429 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2430 $sf = new SugarFolder();
2431 $groupSubs = $sf->getSubscriptions($current_user);
2433 foreach($ieAccountsFull as $k => $v)
2435 $personalSelected = (!empty($showFolders) && in_array($v->id, $showFolders));
2437 $allowOutboundGroupUsage = $v->get_stored_options('allow_outbound_group_usage',FALSE);
2438 $groupSelected = ( in_array($v->groupfolder_id, $groupSubs) && $allowOutboundGroupUsage);
2439 $selected = ( $personalSelected || $groupSelected );
2443 $GLOBALS['log']->debug("Inbound Email {$v->name}, not selected and will not be available for selection within compose UI.");
2447 $name = $v->get_stored_options('from_name');
2448 $addr = $v->get_stored_options('from_addr');
2449 if ($name != null && $addr != null) {
2450 $name = from_html($name);
2451 if (!$v->is_personal) {
2452 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2454 $ieAccountsFrom[] = array("value" => $v->id, "text" => "{$name} ({$addr})");
2460 $userSystemOverride = $oe->getUsersMailerForSystemOverride($current_user->id);
2461 //Substitute in the users system override if its available.
2462 if($userSystemOverride != null)
2463 $system = $userSystemOverride;
2465 if( !empty($system->mail_smtpserver) )
2467 $admin = new Administration();
2468 $admin->retrieveSettings(); //retrieve all admin settings.
2469 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2470 "{$ret['name']} ({$ret['email']}){$myAccountString}");
2473 return $ieAccountsFrom;
2477 * This function will return all the accounts this user has access to based on the
2478 * match of the emailId passed in as a parameter
2480 * @param unknown_type $ie
2483 function getFromAllAccountsArray($ie, $ret) {
2484 global $current_user;
2485 global $app_strings;
2487 $ret['fromAccounts'] = array();
2488 if (!isset($ret['to']) && !empty($ret['from'])) {
2489 $ret['fromAccounts']['status'] = false;
2492 $ieAccountsFull = $ie->retrieveAllByGroupIdWithGroupAccounts($current_user->id);
2493 $foundInPersonalAccounts = false;
2494 $foundInGroupAccounts = false;
2495 $foundInSystemAccounts = false;
2497 //$toArray = array();
2498 if ($ret['type'] == "draft") {
2499 $toArray = explode(",", $ret['from']);
2501 $toArray = $ie->email->email2ParseAddressesForAddressesOnly($ret['to']);
2503 foreach($ieAccountsFull as $k => $v) {
2504 $storedOptions = unserialize(base64_decode($v->stored_options));
2505 if ( array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2506 if ($v->is_personal) {
2507 $foundInPersonalAccounts = true;
2510 $foundInGroupAccounts = true;
2515 $oe = new OutboundEmail();
2516 $system = $oe->getSystemMailerSettings();
2518 $return = $current_user->getUsersNameAndEmail();
2519 $return['name'] = from_html($return['name']);
2520 $useMyAccountString = true;
2522 if(empty($return['email'])) {
2523 $systemReturn = $current_user->getSystemDefaultNameAndEmail();
2524 $return['email'] = $systemReturn['email'];
2525 $return['name'] = from_html($systemReturn['name']);
2526 $useMyAccountString = false;
2529 $myAccountString = '';
2530 if ($useMyAccountString) {
2531 $myAccountString = " - {$app_strings['LBL_MY_ACCOUNT']}";
2534 if(!empty($system->id)) {
2536 $admin = new Administration();
2537 $admin->retrieveSettings(); //retrieve all admin settings.
2538 if (in_array(trim($return['email']), $toArray)) {
2539 $foundInSystemAccounts = true;
2543 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && !$foundInSystemAccounts) {
2544 $ret['fromAccounts']['status'] = false;
2548 $ieAccountsFrom= array();
2549 foreach($ieAccountsFull as $k => $v) {
2550 $storedOptions = unserialize(base64_decode($v->stored_options));
2551 $storedOptionsName = from_html($storedOptions['from_name']);
2554 if (array_search_insensitive($storedOptions['from_addr'], $toArray)) {
2555 //if ($ret['to'] == $storedOptions['from_addr']) {
2558 if ($foundInPersonalAccounts) {
2559 if ($v->is_personal) {
2560 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']})");
2563 $ieAccountsFrom[] = array("value" => $v->id, "selected" => $selected, "text" => "{$storedOptionsName} ({$storedOptions['from_addr']}) - {$app_strings['LBL_EMAIL_UPPER_CASE_GROUP']}");
2567 if(!empty($system->id)) {
2568 if (!$foundInPersonalAccounts && !$foundInGroupAccounts && $foundInSystemAccounts) {
2569 $ieAccountsFrom[] = array("value" => $system->id, "selected" => true, "text" =>
2570 "{$return['name']} ({$return['email']}){$myAccountString}");
2572 $ieAccountsFrom[] = array("value" => $system->id, "text" =>
2573 "{$return['name']} ({$return['email']}){$myAccountString}");
2577 $ret['fromAccounts']['status'] = ($foundInPersonalAccounts || $foundInGroupAccounts || $foundInSystemAccounts) ? true : false;
2578 $ret['fromAccounts']['data'] = $ieAccountsFrom;
2584 * takes an array and creates XML
2585 * @param array Array to convert
2586 * @param string Name to wrap highest level items in array
2587 * @return string XML
2589 function arrayToXML($a, $paramName) {
2593 $bad = array("<",">","'",'"',"&");
2594 $good = array("<", ">", "'", ""","&");
2598 for($i=0; $i<count($a); $i++) {
2600 $ret .= "\n<{$paramName}>";
2602 foreach($email as $k => $v) {
2603 $ret .= "\n\t<{$k}>".str_replace($bad, $good, $v)."</{$k}>";
2605 $ret .= "\n</{$paramName}>";
2611 * Re-used option getter for Show Accounts multiselect pane
2613 function getShowAccountsOptions(&$ie) {
2614 global $current_user;
2615 global $app_strings;
2616 global $mod_strings;
2618 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2619 $ieAccountsShowOptionsMeta = array();
2620 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2622 $defaultIEAccount = $ie->getUsersDefaultOutboundServerId($current_user);
2624 foreach($ieAccountsFull as $k => $v) {
2625 $selected = (!empty($showFolders) && in_array($v->id, $showFolders)) ? true : false;
2626 $default = ($defaultIEAccount == $v->id) ? TRUE : FALSE;
2627 $has_groupfolder = !empty($v->groupfolder_id) ? TRUE : FALSE;
2628 $type = ($v->is_personal) ? $mod_strings['LBL_MAILBOX_TYPE_PERSONAL'] : $mod_strings['LBL_MAILBOX_TYPE_GROUP'];
2630 $ieAccountsShowOptionsMeta[] = array("id" => $v->id, "name" => $v->name, 'is_active' => $selected,
2631 'server_url' => $v->server_url, 'is_group' => !$v->is_personal,'group_id' => $v->group_id,
2632 'is_default' => $default, 'has_groupfolder' => $has_groupfolder,'type' => $type );
2635 //Retrieve the grou folders
2636 $f = new SugarFolder();
2637 $groupFolders = $f->getGroupFoldersForSettings($current_user);
2639 foreach ($groupFolders as $singleGroup)
2641 //Retrieve the related IE accounts.
2642 $relatedIEAccounts = $ie->retrieveByGroupFolderId($singleGroup['id']);
2644 if(count($relatedIEAccounts) == 0)
2645 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS_EMPTY'];
2646 else if(count($relatedIEAccounts) == 1)
2648 if($relatedIEAccounts[0]->status != 'Active' || $relatedIEAccounts[0]->mailbox_type == 'bounce')
2651 $server_url = $relatedIEAccounts[0]->server_url;
2654 $server_url = $app_strings['LBL_EMAIL_MULT_GROUP_FOLDER_ACCOUNTS'];
2656 $type = $mod_strings['LBL_MAILBOX_TYPE_GROUP_FOLDER'];
2657 $ieAccountsShowOptionsMeta[] = array("id" => $singleGroup['id'], "name" => $singleGroup['origName'], 'is_active' => $singleGroup['selected'],
2658 'server_url' => $server_url, 'is_group' => true,'group_id' => $singleGroup['id'],
2659 'is_default' => FALSE, 'has_groupfolder' => true,'type' => $type);
2663 return $ieAccountsShowOptionsMeta;
2666 function getShowAccountsOptionsForSearch(&$ie) {
2667 global $current_user;
2668 global $app_strings;
2670 $ieAccountsFull = $ie->retrieveAllByGroupId($current_user->id);
2671 //$ieAccountsShowOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
2672 $ieAccountsShowOptionsMeta = array();
2673 $ieAccountsShowOptionsMeta[] = array("value" => "", "text" => $app_strings['LBL_NONE'], 'selected' => '');
2674 $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
2676 foreach($ieAccountsFull as $k => $v) {
2677 if(!in_array($v->id, $showFolders)) {
2680 $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
2681 $ieAccountsShowOptionsMeta[] = array("value" => $v->id, "text" => $group.$v->name, 'protocol' => $v->protocol);
2684 return $ieAccountsShowOptionsMeta;
2687 * Formats a display message on successful async call
2688 * @param string $type Type of message to display
2690 function displaySuccessMessage($type) {
2691 global $app_strings;
2695 $message = $app_strings['LBL_EMAIL_DELETE_SUCCESS'];
2699 $message = "NOOP: invalid type";
2703 $this->smarty->assign('app_strings', $app_strings);
2704 $this->smarty->assign('message', $message);
2705 echo $this->smarty->fetch("modules/Emails/templates/successMessage.tpl");
2709 * Validates existence and expiration of a cache file
2710 * @param string $ieId
2711 * @param string $type Type of cache file: folders, messages, etc.
2712 * @param string $file The cachefile name
2713 * @param int refreshOffset Refresh time in secs.
2716 function validCacheFileExists($ieId, $type, $file, $refreshOffset=-1) {
2717 global $sugar_config;
2719 if($refreshOffset == -1) {
2720 $refreshOffset = $this->cacheTimeouts[$type]; // use defaults
2723 $cacheFilePath = getcwd()."/{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2724 if(file_exists($cacheFilePath)) {
2732 * retrieves the cached value
2733 * @param string $ieId
2734 * @param string $type Type of cache file: folders, messages, etc.
2735 * @param string $file The cachefile name
2736 * @param string $key name of cache value
2739 function getCacheValue($ieId, $type, $file, $key) {
2740 global $sugar_config;
2742 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2743 $cacheFile = array();
2745 if(file_exists($cacheFilePath)) {
2746 include($cacheFilePath); // provides $cacheFile
2748 if(isset($cacheFile[$key])) {
2749 $ret = unserialize($cacheFile[$key]);
2753 $GLOBALS['log']->debug("EMAILUI: cache file not found [ {$cacheFilePath} ] - creating blank cache file");
2754 $this->writeCacheFile('retArr', array(), $ieId, $type, $file);
2761 * retrieves the cache file last touched time
2762 * @param string $ieId
2763 * @param string $type Type of cache file: folders, messages, etc.
2764 * @param string $file The cachefile name
2767 function getCacheTimestamp($ieId, $type, $file) {
2768 global $sugar_config;
2770 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2771 $cacheFile = array();
2773 if(file_exists($cacheFilePath)) {
2774 include($cacheFilePath); // provides $cacheFile['timestamp']
2776 if(isset($cacheFile['timestamp'])) {
2777 $GLOBALS['log']->debug("EMAILUI: found timestamp [ {$cacheFile['timestamp']} ]");
2778 return $cacheFile['timestamp'];
2786 * Updates the timestamp for a cache file - usually to mark a "check email"
2788 * @param string $ieId
2789 * @param string $type Type of cache file: folders, messages, etc.
2790 * @param string $file The cachefile name
2792 function setCacheTimestamp($ieId, $type, $file) {
2793 global $sugar_config;
2795 $cacheFilePath = "{$sugar_config['cache_dir']}modules/Emails/{$ieId}/{$type}/{$file}";
2796 $cacheFile = array();
2798 if(file_exists($cacheFilePath)) {
2799 include($cacheFilePath); // provides $cacheFile['timestamp']
2801 if(isset($cacheFile['timestamp'])) {
2802 $cacheFile['timestamp'] = strtotime('now');
2803 $GLOBALS['log']->debug("EMAILUI: setting updated timestamp [ {$cacheFile['timestamp']} ]");
2804 return $this->_writeCacheFile($cacheFile, $cacheFilePath);
2811 * Writes caches to flat file in cache dir.
2812 * @param string $key Key to the main cache entry (not timestamp)
2813 * @param mixed $var Variable to be cached
2814 * @param string $ieId I-E focus ID
2815 * @param string $type Folder in cache
2816 * @param string $file Cache file name
2818 function writeCacheFile($key, $var, $ieId, $type, $file) {
2819 global $sugar_config;
2821 $the_file = clean_path("{$sugar_config['cache_dir']}/modules/Emails/{$ieId}/{$type}/{$file}");
2822 $timestamp = strtotime('now');
2824 $array['timestamp'] = $timestamp;
2825 $array[$key] = serialize($var); // serialized since varexport_helper() can't handle PHP objects
2827 return $this->_writeCacheFile($array, $the_file);
2831 * Performs the actual file write. Abstracted from writeCacheFile() for
2833 * @param array $array The array to write to the cache
2834 * @param string $file Full path (relative) with cache file name
2837 function _writeCacheFile($array, $file) {
2838 global $sugar_config;
2840 $arrayString = var_export_helper($array);
2844 <?php // created: {$date}
2845 \$cacheFile = {$arrayString};
2848 if($fh = @sugar_fopen($file, "w")) {
2849 fputs($fh, $the_string);
2853 $GLOBALS['log']->debug("EMAILUI: Could not write cache file [ {$file} ]");
2859 * Generate JSON encoded data to be consumed by yui datatable.
2861 * @param array $data
2862 * @param string $resultsParam The resultsList name
2865 function jsonOuput($data, $resultsParam, $count=0, $fromCache=true, $unread=-1) {
2866 global $app_strings;
2868 $count = ($count > 0) ? $count : 0;
2870 if(isset($a['fromCache']))
2871 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2873 $cached = ($fromCache) ? 1 : 0;
2875 if($data['mbox'] == 'undefined' || empty($data['mbox']))
2876 $data['mbox'] = $app_strings['LBL_NONE'];
2878 $jsonOut = array('TotalCount' => $count, 'FromCache' => $cached, 'UnreadCount' => $unread, $resultsParam => $data['out']);
2880 return json_encode($jsonOut);
2883 * generates XML output from an array
2885 * @param string master list Item
2888 function xmlOutput($a, $paramName, $count=0, $fromCache=true, $unread=-1) {
2889 global $app_strings;
2890 $count = ($count > 0) ? $count : 0;
2892 if(isset($a['fromCache'])) {
2893 $cached = ($a['fromCache'] == 1) ? 1 : 0;
2895 $cached = ($fromCache) ? 1 : 0;
2898 if($a['mbox'] == 'undefined' || empty($a['mbox'])) {
2899 $a['mbox'] = $app_strings['LBL_NONE'];
2902 $xml = $this->arrayToXML($a['out'], $paramName);
2905 <?xml version="1.0" encoding="UTF-8"?>
2907 <TotalCount>{$count}</TotalCount>
2908 <UnreadCount>{$unread}</UnreadCount>
2909 <FromCache> {$cached} </FromCache>
2919 * Generate to/cc addresses string in email detailview.
2921 * @param string $str
2922 * @param string $target values: to, cc
2923 * @param int $defaultNum
2924 * @return string $str
2926 function generateExpandableAddrs($str) {
2927 global $mod_strings;
2928 $tempStr = $str.',';
2929 $tempStr = html_entity_decode($tempStr);
2930 $tempStr = $this->unifyEmailString($tempStr);
2932 $pattern = '/@.*,/U';
2933 preg_match_all($pattern, $tempStr, $matchs);
2934 $totalCount = count($matchs[0]);
2936 if(!empty($matchs[0]) && $totalCount > $defaultNum) {
2937 $position = strpos($tempStr, $matchs[0][$defaultNum]);
2938 $hiddenCount = $totalCount - $defaultNum;
2939 $frontStr = substr($tempStr, 0, $position);
2940 $backStr = substr($tempStr, $position, -1);
2941 $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>';
2948 * Unify the seperator as ,
2950 * @param String $str email address string
2951 * @return String converted string
2953 function unifyEmailString($str) {
2954 preg_match_all('/@.*;/U', $str, $matches);
2955 if(!empty($matches[0])) {
2956 foreach($matches[0] as $key => $value) {
2957 $new[] = str_replace(";",",",$value);
2959 return str_replace($matches[0], $new, $str);