PageRenderTime 3118ms CodeModel.GetById 45ms RepoModel.GetById 6ms app.codeStats 1ms

/modules/Emails/EmailUI.php

https://bitbucket.org/cviolette/sugarcrm
PHP | 2989 lines | 2546 code | 203 blank | 240 comment | 72 complexity | bf9d7d8e7db8e0cb6ed638eb5c42ca8c MD5 | raw file
Possible License(s): LGPL-2.1, MPL-2.0-no-copyleft-exception, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  1. <?php
  2. if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
  3. /*********************************************************************************
  4. * SugarCRM Community Edition is a customer relationship management program developed by
  5. * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
  6. *
  7. * This program is free software; you can redistribute it and/or modify it under
  8. * the terms of the GNU Affero General Public License version 3 as published by the
  9. * Free Software Foundation with the addition of the following permission added
  10. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  11. * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  12. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  13. *
  14. * This program is distributed in the hope that it will be useful, but WITHOUT
  15. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  16. * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  17. * details.
  18. *
  19. * You should have received a copy of the GNU Affero General Public License along with
  20. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  21. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  22. * 02110-1301 USA.
  23. *
  24. * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  25. * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  26. *
  27. * The interactive user interfaces in modified source and object code versions
  28. * of this program must display Appropriate Legal Notices, as required under
  29. * Section 5 of the GNU Affero General Public License version 3.
  30. *
  31. * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  32. * these Appropriate Legal Notices must retain the display of the "Powered by
  33. * SugarCRM" logo. If the display of the logo is not reasonably feasible for
  34. * technical reasons, the Appropriate Legal Notices must display the words
  35. * "Powered by SugarCRM".
  36. ********************************************************************************/
  37. /*********************************************************************************
  38. * Description:
  39. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc. All Rights
  40. * Reserved. Contributor(s): ______________________________________..
  41. *********************************************************************************/
  42. require_once("include/ytree/Tree.php");
  43. require_once("include/ytree/ExtNode.php");
  44. require_once("include/SugarFolders/SugarFolders.php");
  45. class EmailUI {
  46. var $db;
  47. var $folder; // place holder for SugarFolder object
  48. var $folderStates = array(); // array of folderPath names and their states (1/0)
  49. var $smarty;
  50. var $addressSeparators = array(";", ",");
  51. 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";
  52. var $groupCss = "<span class='groupInbox'>";
  53. var $cacheTimeouts = array(
  54. 'messages' => 86400, // 24 hours
  55. 'folders' => 300, // 5 mins
  56. 'attachments' => 86400, // 24 hours
  57. );
  58. var $userCacheDir = '';
  59. var $coreDynamicFolderQuery = "SELECT emails.id polymorphic_id, 'Emails' polymorphic_module FROM emails
  60. JOIN emails_text on emails.id = emails_text.email_id
  61. WHERE (type = '::TYPE::' OR status = '::STATUS::') AND assigned_user_id = '::USER_ID::' AND emails.deleted = '0'";
  62. /**
  63. * Sole constructor
  64. */
  65. function EmailUI() {
  66. global $sugar_config;
  67. global $current_user;
  68. $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
  69. if(!empty($folderStateSerial)) {
  70. $this->folderStates = unserialize($folderStateSerial);
  71. }
  72. $this->smarty = new Sugar_Smarty();
  73. $this->folder = new SugarFolder();
  74. $this->userCacheDir = sugar_cached("modules/Emails/{$current_user->id}");
  75. $this->db = DBManagerFactory::getInstance();
  76. }
  77. ///////////////////////////////////////////////////////////////////////////
  78. //// CORE
  79. /**
  80. * Renders the frame for emails
  81. */
  82. function displayEmailFrame() {
  83. require_once("include/OutboundEmail/OutboundEmail.php");
  84. global $app_strings, $app_list_strings;
  85. global $mod_strings;
  86. global $sugar_config;
  87. global $current_user;
  88. global $locale;
  89. global $timedate;
  90. global $theme;
  91. global $sugar_version;
  92. global $sugar_flavor;
  93. global $current_language;
  94. global $server_unique_key;
  95. $this->preflightUserCache();
  96. $ie = new InboundEmail();
  97. // focus listView
  98. $list = array(
  99. 'mbox' => 'Home',
  100. 'ieId' => '',
  101. 'name' => 'Home',
  102. 'unreadChecked' => 0,
  103. 'out' => array(),
  104. );
  105. $this->_generateComposeConfigData('email_compose');
  106. //Check quick create module access
  107. $QCAvailableModules = $this->_loadQuickCreateModules();
  108. //Get the quickSearch js needed for assigned user id on Search Tab
  109. require_once('include/QuickSearchDefaults.php');
  110. $qsd = QuickSearchDefaults::getQuickSearchDefaults();
  111. $qsd->setFormName('advancedSearchForm');
  112. $quicksearchAssignedUser = "if(typeof sqs_objects == 'undefined'){var sqs_objects = new Array;}";
  113. $quicksearchAssignedUser .= "sqs_objects['advancedSearchForm_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
  114. $qsd->setFormName('Distribute');
  115. $quicksearchAssignedUser .= "sqs_objects['Distribute_assigned_user_name']=" . json_encode($qsd->getQSUser()) . ";";
  116. $this->smarty->assign('quickSearchForAssignedUser', $quicksearchAssignedUser);
  117. ///////////////////////////////////////////////////////////////////////
  118. //// BASIC ASSIGNS
  119. $this->smarty->assign("currentUserId",$current_user->id);
  120. $this->smarty->assign("CURRENT_USER_EMAIL",$current_user->email1);
  121. $this->smarty->assign("currentUserName",$current_user->name);
  122. $this->smarty->assign('yuiPath', 'modules/Emails/javascript/yui-ext/');
  123. $this->smarty->assign('app_strings', $app_strings);
  124. $this->smarty->assign('mod_strings', $mod_strings);
  125. $this->smarty->assign('theme', $theme);
  126. $this->smarty->assign('sugar_config', $sugar_config);
  127. $this->smarty->assign('is_admin', $current_user->is_admin);
  128. $this->smarty->assign('sugar_version', $sugar_version);
  129. $this->smarty->assign('sugar_flavor', $sugar_flavor);
  130. $this->smarty->assign('current_language', $current_language);
  131. $this->smarty->assign('server_unique_key', $server_unique_key);
  132. $this->smarty->assign('qcModules', json_encode($QCAvailableModules));
  133. $extAllDebugValue = "ext-all.js";
  134. $this->smarty->assign('extFileName', $extAllDebugValue);
  135. // settings: general
  136. $e2UserPreferences = $this->getUserPrefsJS();
  137. $emailSettings = $e2UserPreferences['emailSettings'];
  138. ///////////////////////////////////////////////////////////////////////
  139. //// USER SETTINGS
  140. // settings: accounts
  141. $cuDatePref = $current_user->getUserDateTimePreferences();
  142. $this->smarty->assign('dateFormat', $cuDatePref['date']);
  143. $this->smarty->assign('dateFormatExample', str_replace(array("Y", "m", "d"), array("yyyy", "mm", "dd"), $cuDatePref['date']));
  144. $this->smarty->assign('calFormat', $timedate->get_cal_date_format());
  145. $this->smarty->assign('TIME_FORMAT', $timedate->get_user_time_format());
  146. $ieAccounts = $ie->retrieveByGroupId($current_user->id);
  147. $ieAccountsOptions = "<option value=''>{$app_strings['LBL_NONE']}</option>\n";
  148. foreach($ieAccounts as $k => $v) {
  149. $disabled = (!$v->is_personal) ? "DISABLED" : "";
  150. $group = (!$v->is_personal) ? $app_strings['LBL_EMAIL_GROUP']."." : "";
  151. $ieAccountsOptions .= "<option value='{$v->id}' $disabled>{$group}{$v->name}</option>\n";
  152. }
  153. $this->smarty->assign('ieAccounts', $ieAccountsOptions);
  154. $this->smarty->assign('rollover', $this->rolloverStyle);
  155. $protocol = filterInboundEmailPopSelection($app_list_strings['dom_email_server_type']);
  156. $this->smarty->assign('PROTOCOL', get_select_options_with_id($protocol, ''));
  157. $this->smarty->assign('MAIL_SSL_OPTIONS', get_select_options_with_id($app_list_strings['email_settings_for_ssl'], ''));
  158. $this->smarty->assign('ie_mod_strings', return_module_language($current_language, 'InboundEmail'));
  159. $charsetSelectedValue = isset($emailSettings['defaultOutboundCharset']) ? $emailSettings['defaultOutboundCharset'] : false;
  160. if (!$charsetSelectedValue) {
  161. $charsetSelectedValue = $current_user->getPreference('default_export_charset', 'global');
  162. if (!$charsetSelectedValue) {
  163. $charsetSelectedValue = $locale->getPrecedentPreference('default_email_charset');
  164. }
  165. }
  166. $charset = array(
  167. 'options' => $locale->getCharsetSelect(),
  168. 'selected' => $charsetSelectedValue,
  169. );
  170. $this->smarty->assign('charset', $charset);
  171. $emailCheckInterval = array('options' => $app_strings['LBL_EMAIL_CHECK_INTERVAL_DOM'], 'selected' => $emailSettings['emailCheckInterval']);
  172. $this->smarty->assign('emailCheckInterval', $emailCheckInterval);
  173. $this->smarty->assign('attachmentsSearchOptions', $app_list_strings['checkbox_dom']);
  174. $this->smarty->assign('sendPlainTextChecked', ($emailSettings['sendPlainText'] == 1) ? 'CHECKED' : '');
  175. $this->smarty->assign('showNumInList', get_select_options_with_id($app_list_strings['email_settings_num_dom'], $emailSettings['showNumInList']));
  176. //// END USER SETTINGS
  177. ///////////////////////////////////////////////////////////////////////
  178. ///////////////////////////////////////////////////////////////////////
  179. //// SIGNATURES
  180. $prependSignature = ($current_user->getPreference('signature_prepend')) ? 'true' : 'false';
  181. $defsigID = $current_user->getPreference('signature_default');
  182. $this->smarty->assign('signatures', $current_user->getSignatures(false, $defsigID));
  183. $this->smarty->assign('signaturesSettings', $current_user->getSignatures(false, $defsigID, false));
  184. $signatureButtons = $current_user->getSignatureButtons('SUGAR.email2.settings.createSignature', !empty($defsigID));
  185. if (!empty($defsigID)) {
  186. $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:inherit;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
  187. </span>';
  188. } else {
  189. $signatureButtons = $signatureButtons . '<span name="delete_sig" id="delete_sig" style="visibility:hidden;"><input class="button" onclick="javascript:SUGAR.email2.settings.deleteSignature();" value="'.$app_strings['LBL_EMAIL_DELETE'].'" type="button" tabindex="392">&nbsp;
  190. </span>';
  191. }
  192. $this->smarty->assign('signatureButtons', $signatureButtons);
  193. $this->smarty->assign('signaturePrepend', $prependSignature == 'true' ? 'CHECKED' : '');
  194. //// END SIGNATURES
  195. ///////////////////////////////////////////////////////////////////////
  196. ///////////////////////////////////////////////////////////////////////
  197. //// EMAIL TEMPLATES
  198. $email_templates_arr = $this->getEmailTemplatesArray();
  199. natcasesort($email_templates_arr);
  200. $this->smarty->assign('EMAIL_TEMPLATE_OPTIONS', get_select_options_with_id($email_templates_arr, ''));
  201. //// END EMAIL TEMPLATES
  202. ///////////////////////////////////////////////////////////////////////
  203. ///////////////////////////////////////////////////////////////////////
  204. //// FOLDERS & TreeView
  205. $this->smarty->assign('groupUserOptions', $ie->getGroupsWithSelectOptions(array('' => $app_strings['LBL_EMAIL_CREATE_NEW'])));
  206. $tree = $this->getMailboxNodes();
  207. // preloaded folder
  208. $preloadFolder = 'lazyLoadFolder = ';
  209. $focusFolderSerial = $current_user->getPreference('focusFolder', 'Emails');
  210. if(!empty($focusFolderSerial)) {
  211. $focusFolder = unserialize($focusFolderSerial);
  212. //$focusFolder['ieId'], $focusFolder['folder']
  213. $preloadFolder .= json_encode($focusFolder).";";
  214. } else {
  215. $preloadFolder .= "new Object();";
  216. }
  217. //// END FOLDERS
  218. ///////////////////////////////////////////////////////////////////////
  219. $out = "";
  220. $out .= $this->smarty->fetch("modules/Emails/templates/_baseEmail.tpl");
  221. $out .= $tree->generate_header();
  222. $out .= $tree->generateNodesNoInit(true, 'email2treeinit');
  223. $out .=<<<eoq
  224. <script type="text/javascript" language="javascript">
  225. var loader = new YAHOO.util.YUILoader({
  226. require : [
  227. "layout", "element", "tabview", "menu",
  228. "cookie", "sugarwidgets"
  229. ],
  230. loadOptional: true,
  231. skin: { base: 'blank', defaultSkin: '' },
  232. onSuccess: email2init,
  233. allowRollup: true,
  234. base: "include/javascript/yui/build/"
  235. });
  236. loader.addModule({
  237. name :"sugarwidgets",
  238. type : "js",
  239. fullpath: "include/javascript/sugarwidgets/SugarYUIWidgets.js",
  240. varName: "YAHOO.SUGAR",
  241. requires: ["datatable", "dragdrop", "treeview", "tabview", "calendar"]
  242. });
  243. loader.insert();
  244. {$preloadFolder};
  245. </script>
  246. eoq;
  247. return $out;
  248. }
  249. /**
  250. * Generate the frame needed for the quick compose email UI. This frame is loaded dynamically
  251. * by an ajax call.
  252. *
  253. * @return JSON An object containing html markup and js script variables.
  254. */
  255. function displayQuickComposeEmailFrame()
  256. {
  257. $this->preflightUserCache();
  258. $this->_generateComposeConfigData('email_compose_light');
  259. $javascriptOut = $this->smarty->fetch("modules/Emails/templates/_baseConfigData.tpl");
  260. $divOut = $this->smarty->fetch("modules/Emails/templates/overlay.tpl");
  261. $divOut .= $this->smarty->fetch("modules/Emails/templates/addressSearchContent.tpl");
  262. $outData = array('jsData' => $javascriptOut,'divData'=> $divOut);
  263. $out = json_encode($outData);
  264. return $out;
  265. }
  266. /**
  267. * Load the modules from the metadata file and include in a custom one if it exists
  268. *
  269. * @return array
  270. */
  271. protected function _loadQuickCreateModules()
  272. {
  273. $QCAvailableModules = array();
  274. $QCModules = array();
  275. include('modules/Emails/metadata/qcmodulesdefs.php');
  276. if (file_exists('custom/modules/Emails/metadata/qcmodulesdefs.php')) {
  277. include('custom/modules/Emails/metadata/qcmodulesdefs.php');
  278. }
  279. foreach($QCModules as $module) {
  280. $seed = SugarModule::get($module)->loadBean();
  281. if ( ( $seed instanceOf SugarBean ) && $seed->ACLAccess('edit') ) {
  282. $QCAvailableModules[] = $module;
  283. }
  284. }
  285. return $QCAvailableModules;
  286. }
  287. /**
  288. * Given an email link url (eg. index.php?action=Compose&parent_type=Contacts...) break up the
  289. * request components and create a compose package that can be used by the quick compose UI. The
  290. * result is typically passed into the js call SUGAR.quickCompose.init which initalizes the quick compose
  291. * UI.
  292. *
  293. * @param String $emailLinkUrl
  294. * @return JSON Object containing the composePackage and full link url
  295. */
  296. function generateComposePackageForQuickCreateFromComposeUrl($emailLinkUrl, $lazyLoad=false)
  297. {
  298. $composeData = explode("&",$emailLinkUrl);
  299. $a_composeData = array();
  300. foreach ($composeData as $singleRequest)
  301. {
  302. $tmp = explode("=",$singleRequest);
  303. $a_composeData[$tmp[0]] = urldecode($tmp[1]);
  304. }
  305. return $this->generateComposePackageForQuickCreate($a_composeData,$emailLinkUrl, $lazyLoad);
  306. }
  307. /**
  308. * Generate the composePackage for the quick compose email UI. The package contains
  309. * key/value pairs generated by the Compose.php file which are then set into the
  310. * quick compose email UI (eg. to addr, parent id, parent type, etc)
  311. *
  312. * @param Array $composeData Associative array read and processed by generateComposeDataPackage.
  313. * @param String $fullLinkUrl A link that contains all pertinant information so the user can be
  314. * directed to the full compose screen if needed
  315. * @param SugarBean $bean Optional - the parent object bean with data
  316. * @return JSON Object containg composePackage and fullLinkUrl
  317. */
  318. function generateComposePackageForQuickCreate($composeData,$fullLinkUrl, $lazyLoad=false, $bean = null)
  319. {
  320. $_REQUEST['forQuickCreate'] = true;
  321. if(!$lazyLoad){
  322. require_once('modules/Emails/Compose.php');
  323. $composePackage = generateComposeDataPackage($composeData,FALSE, $bean);
  324. }else{
  325. $composePackage = $composeData;
  326. }
  327. // JSON object is passed into the function defined within the a href onclick event
  328. // which is delimeted by '. Need to escape all single quotes and &, <, >
  329. // but not double quotes since json would escape them
  330. foreach ($composePackage as $key => $singleCompose)
  331. {
  332. if (is_string($singleCompose))
  333. $composePackage[$key] = str_replace("&nbsp;", " ", from_html($singleCompose));
  334. }
  335. $quickComposeOptions = array('fullComposeUrl' => $fullLinkUrl,'composePackage' => $composePackage);
  336. $j_quickComposeOptions = JSON::encode($quickComposeOptions, false ,true);
  337. return $j_quickComposeOptions;
  338. }
  339. /**
  340. * Generate the config data needed for the Full Compose UI and the Quick Compose UI. The set of config data
  341. * returned is the minimum set needed by the quick compose UI.
  342. *
  343. * @param String $type Drives which tinyMCE options will be included.
  344. */
  345. function _generateComposeConfigData($type = "email_compose_light" )
  346. {
  347. global $app_list_strings,$current_user, $app_strings, $mod_strings,$current_language,$locale;
  348. //Link drop-downs
  349. $parent_types = $app_list_strings['record_type_display'];
  350. $disabled_parent_types = ACLController::disabledModuleList($parent_types, false, 'list');
  351. foreach($disabled_parent_types as $disabled_parent_type) {
  352. unset($parent_types[$disabled_parent_type]);
  353. }
  354. asort($parent_types);
  355. $linkBeans = json_encode(get_select_options_with_id($parent_types, ''));
  356. //TinyMCE Config
  357. require_once("include/SugarTinyMCE.php");
  358. $tiny = new SugarTinyMCE();
  359. $tinyConf = $tiny->getConfig($type);
  360. //Generate Language Packs
  361. $lang = "var app_strings = new Object();\n";
  362. foreach($app_strings as $k => $v) {
  363. if(strpos($k, 'LBL_EMAIL_') !== false) {
  364. $lang .= "app_strings.{$k} = '{$v}';\n";
  365. }
  366. }
  367. //Get the email mod strings but don't use the global variable as this may be overridden by
  368. //other modules when the quick create is rendered.
  369. $email_mod_strings = return_module_language($current_language,'Emails');
  370. $modStrings = "var mod_strings = new Object();\n";
  371. foreach($email_mod_strings as $k => $v) {
  372. $v = str_replace("'", "\'", $v);
  373. $modStrings .= "mod_strings.{$k} = '{$v}';\n";
  374. }
  375. $lang .= "\n\n{$modStrings}\n";
  376. //Grab the Inboundemail language pack
  377. $ieModStrings = "var ie_mod_strings = new Object();\n";
  378. $ie_mod_strings = return_module_language($current_language,'InboundEmail');
  379. foreach($ie_mod_strings as $k => $v) {
  380. $v = str_replace("'", "\'", $v);
  381. $ieModStrings .= "ie_mod_strings.{$k} = '{$v}';\n";
  382. }
  383. $lang .= "\n\n{$ieModStrings}\n";
  384. $this->smarty->assign('linkBeans', $linkBeans);
  385. $this->smarty->assign('linkBeansOptions', $parent_types);
  386. $this->smarty->assign('tinyMCE', $tinyConf);
  387. $this->smarty->assign('lang', $lang);
  388. $this->smarty->assign('app_strings', $app_strings);
  389. $this->smarty->assign('mod_strings', $email_mod_strings);
  390. $ie1 = new InboundEmail();
  391. //Signatures
  392. $defsigID = $current_user->getPreference('signature_default');
  393. $defaultSignature = $current_user->getDefaultSignature();
  394. $sigJson = !empty($defaultSignature) ? json_encode(array($defaultSignature['id'] => from_html($defaultSignature['signature_html']))) : "new Object()";
  395. $this->smarty->assign('defaultSignature', $sigJson);
  396. $this->smarty->assign('signatureDefaultId', (isset($defaultSignature['id'])) ? $defaultSignature['id'] : "");
  397. //User Preferences
  398. $this->smarty->assign('userPrefs', json_encode($this->getUserPrefsJS()));
  399. //Get the users default outbound id
  400. $defaultOutID = $ie1->getUsersDefaultOutboundServerId($current_user);
  401. $this->smarty->assign('defaultOutID', $defaultOutID);
  402. //Character Set
  403. $charsets = json_encode($locale->getCharsetSelect());
  404. $this->smarty->assign('emailCharsets', $charsets);
  405. //Relateable List of People for address book search
  406. //#20776 jchi
  407. $peopleTables = array("users",
  408. "contacts",
  409. "leads",
  410. "prospects",
  411. "accounts");
  412. $filterPeopleTables = array();
  413. global $app_list_strings, $app_strings;
  414. $filterPeopleTables['LBL_DROPDOWN_LIST_ALL'] = $app_strings['LBL_DROPDOWN_LIST_ALL'];
  415. foreach($peopleTables as $table) {
  416. $module = ucfirst($table);
  417. $class = substr($module, 0, strlen($module) - 1);
  418. require_once("modules/{$module}/{$class}.php");
  419. $person = new $class();
  420. if (!$person->ACLAccess('list')) continue;
  421. $filterPeopleTables[$person->table_name] = $app_list_strings['moduleList'][$person->module_dir];
  422. }
  423. $this->smarty->assign('listOfPersons' , get_select_options_with_id($filterPeopleTables,''));
  424. }
  425. //// END CORE
  426. ///////////////////////////////////////////////////////////////////////////
  427. ///////////////////////////////////////////////////////////////////////////
  428. //// ADDRESS BOOK
  429. /**
  430. * Retrieves all relationship metadata for a user's address book
  431. * @return array
  432. */
  433. function getContacts() {
  434. global $current_user;
  435. $q = "SELECT * FROM address_book WHERE assigned_user_id = '{$current_user->id}' ORDER BY bean DESC";
  436. $r = $this->db->query($q);
  437. $ret = array();
  438. while($a = $this->db->fetchByAssoc($r)) {
  439. $ret[$a['bean_id']] = array(
  440. 'id' => $a['bean_id'],
  441. 'module' => $a['bean'],
  442. );
  443. }
  444. return $ret;
  445. }
  446. /**
  447. * Saves changes to a user's address book
  448. * @param array contacts
  449. */
  450. function setContacts($contacts) {
  451. global $current_user;
  452. $oldContacts = $this->getContacts();
  453. foreach($contacts as $cid => $contact) {
  454. if(!in_array($contact['id'], $oldContacts)) {
  455. $q = "INSERT INTO address_book (assigned_user_id, bean, bean_id) VALUES ('{$current_user->id}', '{$contact['module']}', '{$contact['id']}')";
  456. $r = $this->db->query($q, true);
  457. }
  458. }
  459. }
  460. /**
  461. * Removes contacts from the user's address book
  462. * @param array ids
  463. */
  464. function removeContacts($ids) {
  465. global $current_user;
  466. $concat = "";
  467. foreach($ids as $id) {
  468. if(!empty($concat))
  469. $concat .= ", ";
  470. $concat .= "'{$id}'";
  471. }
  472. $q = "DELETE FROM address_book WHERE assigned_user_id = '{$current_user->id}' AND bean_id IN ({$concat})";
  473. $r = $this->db->query($q);
  474. }
  475. /**
  476. * saves editted Contact info
  477. * @param string $str JSON serialized object
  478. */
  479. function saveContactEdit($str) {
  480. $json = getJSONobj();
  481. $str = from_html($str);
  482. $obj = $json->decode($str);
  483. $contact = new Contact();
  484. $contact->retrieve($obj['contact_id']);
  485. $contact->first_name = $obj['contact_first_name'];
  486. $contact->last_name = $obj['contact_last_name'];
  487. $contact->save();
  488. // handle email address changes
  489. $addresses = array();
  490. foreach($obj as $k => $req) {
  491. if(strpos($k, 'emailAddress') !== false) {
  492. $addresses[$k] = $req;
  493. }
  494. }
  495. // prefill some REQUEST vars for emailAddress save
  496. $_REQUEST['emailAddressOptOutFlag'] = $obj['optOut'];
  497. $_REQUEST['emailAddressInvalidFlag'] = $obj['invalid'];
  498. $contact->emailAddress->save($obj['contact_id'], 'Contacts', $addresses, $obj['primary'], '');
  499. }
  500. /**
  501. * Prepares the Edit Contact mini-form via template assignment
  502. * @param string id ID of contact in question
  503. * @param string module Module in focus
  504. * @return array
  505. */
  506. function getEditContact($id, $module) {
  507. global $app_strings;
  508. if(!class_exists("Contact")) {
  509. }
  510. $contact = new Contact();
  511. $contact->retrieve($_REQUEST['id']);
  512. $ret = array();
  513. if($contact->ACLAccess('edit')) {
  514. $contactMeta = array();
  515. $contactMeta['id'] = $contact->id;
  516. $contactMeta['module'] = $contact->module_dir;
  517. $contactMeta['first_name'] = $contact->first_name;
  518. $contactMeta['last_name'] = $contact->last_name;
  519. $this->smarty->assign("app_strings", $app_strings);
  520. $this->smarty->assign("contact_strings", return_module_language($_SESSION['authenticated_user_language'], 'Contacts'));
  521. $this->smarty->assign("contact", $contactMeta);
  522. $ea = new SugarEmailAddress();
  523. $newEmail = $ea->getEmailAddressWidgetEditView($id, $module, true);
  524. $this->smarty->assign("emailWidget", $newEmail['html']);
  525. $ret['form'] = $this->smarty->fetch("modules/Emails/templates/editContact.tpl");
  526. $ret['prefillData'] = $newEmail['prefillData'];
  527. } else {
  528. $id = "";
  529. $ret['form'] = $app_strings['LBL_EMAIL_ERROR_NO_ACCESS'];
  530. $ret['prefillData'] = '{}';
  531. }
  532. $ret['id'] = $id;
  533. $ret['contactName'] = $contact->full_name;
  534. return $ret;
  535. }
  536. /**
  537. * Retrieves a concatenated list of contacts, those with assigned_user_id = user's id and those in the address_book
  538. * table
  539. * @param array $contacts Array of contact types -> IDs
  540. * @param object $user User in focus
  541. * @return array
  542. */
  543. function getUserContacts($contacts, $user=null) {
  544. global $current_user;
  545. global $locale;
  546. if(empty($user)) {
  547. $user = $current_user;
  548. }
  549. $emailAddress = new SugarEmailAddress();
  550. $ret = array();
  551. $union = '';
  552. $modules = array();
  553. foreach($contacts as $contact) {
  554. if(!isset($modules[$contact['module']])) {
  555. $modules[$contact['module']] = array();
  556. }
  557. $modules[$contact['module']][] = $contact;
  558. }
  559. foreach($modules as $module => $contacts) {
  560. if(!empty($union)) {
  561. $union .= " UNION ALL ";
  562. }
  563. $table = strtolower($module);
  564. $idsSerial = '';
  565. foreach($contacts as $contact) {
  566. if(!empty($idsSerial)) {
  567. $idsSerial .= ",";
  568. }
  569. $idsSerial .= "'{$contact['id']}'";
  570. }
  571. $union .= "(SELECT id, first_name, last_name, title, '{$module}' module FROM {$table} WHERE id IN({$idsSerial}) AND deleted = 0 )";
  572. }
  573. if(!empty($union)) {
  574. $union .= " ORDER BY last_name";
  575. }
  576. $r = $user->db->query($union);
  577. //_pp($union);
  578. while($a = $user->db->fetchByAssoc($r)) {
  579. $c = array();
  580. $c['name'] = $locale->getLocaleFormattedName($a['first_name'], "<b>{$a['last_name']}</b>", '', $a['title'], '', $user);
  581. $c['id'] = $a['id'];
  582. $c['module'] = $a['module'];
  583. $c['email'] = $emailAddress->getAddressesByGUID($a['id'], $a['module']);
  584. $ret[$a['id']] = $c;
  585. }
  586. return $ret;
  587. }
  588. //// END ADDRESS BOOK
  589. ///////////////////////////////////////////////////////////////////////////
  590. ///////////////////////////////////////////////////////////////////////////
  591. //// EMAIL 2.0 Preferences
  592. function getUserPrefsJS() {
  593. global $current_user;
  594. global $locale;
  595. // sort order per mailbox view
  596. $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
  597. $sortArray = array();
  598. if(!empty($sortSerial)) {
  599. $sortArray = unserialize($sortSerial);
  600. }
  601. // treeview collapsed/open states
  602. $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
  603. $folderStates = array();
  604. if(!empty($folderStateSerial)) {
  605. $folderStates = unserialize($folderStateSerial);
  606. }
  607. // subscribed accounts
  608. $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
  609. // general settings
  610. $emailSettings = $current_user->getPreference('emailSettings', 'Emails');
  611. if(empty($emailSettings)) {
  612. $emailSettings = array();
  613. $emailSettings['emailCheckInterval'] = -1;
  614. $emailSettings['autoImport'] = '';
  615. $emailSettings['alwaysSaveOutbound'] = '1';
  616. $emailSettings['sendPlainText'] = '';
  617. $emailSettings['defaultOutboundCharset'] = $GLOBALS['sugar_config']['default_email_charset'];
  618. $emailSettings['showNumInList'] = 20;
  619. }
  620. // focus folder
  621. $focusFolder = $current_user->getPreference('focusFolder', 'Emails');
  622. $focusFolder = !empty($focusFolder) ? unserialize($focusFolder) : array();
  623. // unread only flag
  624. $showUnreadOnly = $current_user->getPreference('showUnreadOnly', 'Emails');
  625. $listViewSort = array(
  626. "sortBy" => 'date',
  627. "sortDirection" => 'DESC',
  628. );
  629. // signature prefs
  630. $signaturePrepend = $current_user->getPreference('signature_prepend') ? 'true' : 'false';
  631. $signatureDefault = $current_user->getPreference('signature_default');
  632. $signatures = array(
  633. 'signature_prepend' => $signaturePrepend,
  634. 'signature_default' => $signatureDefault
  635. );
  636. // current_user
  637. $user = array(
  638. 'emailAddresses' => $current_user->emailAddress->getAddressesByGUID($current_user->id, 'Users'),
  639. 'full_name' => from_html($current_user->full_name),
  640. );
  641. $userPreferences = array();
  642. $userPreferences['sort'] = $sortArray;
  643. $userPreferences['folderStates'] = $folderStates;
  644. $userPreferences['showFolders'] = $showFolders;
  645. $userPreferences['emailSettings'] = $emailSettings;
  646. $userPreferences['focusFolder'] = $focusFolder;
  647. $userPreferences['showUnreadOnly'] = $showUnreadOnly;
  648. $userPreferences['listViewSort'] = $listViewSort;
  649. $userPreferences['signatures'] = $signatures;
  650. $userPreferences['current_user'] = $user;
  651. return $userPreferences;
  652. }
  653. ///////////////////////////////////////////////////////////////////////////
  654. //// FOLDER FUNCTIONS
  655. /**
  656. * Creates a new Sugar folder
  657. * @param string $nodeLabel New sugar folder name
  658. * @param string $parentLabel Parent folder name
  659. */
  660. function saveNewFolder($nodeLabel, $parentId, $isGroup=0) {
  661. global $current_user;
  662. $this->folder->name = $nodeLabel;
  663. $this->folder->is_group = $isGroup;
  664. $this->folder->parent_folder = ($parentId == 'Home') ? "" : $parentId;
  665. $this->folder->has_child = 0;
  666. $this->folder->created_by = $current_user->id;
  667. $this->folder->modified_by = $current_user->id;
  668. $this->folder->date_modified = $this->folder->date_created = TimeDate::getInstance()->nowDb();
  669. $this->folder->save();
  670. return array(
  671. 'action' => 'newFolderSave',
  672. 'id' => $this->folder->id,
  673. 'name' => $this->folder->name,
  674. 'is_group' => $this->folder->is_group,
  675. 'is_dynamic' => $this->folder->is_dynamic
  676. );
  677. }
  678. /**
  679. * Saves user sort prefernces
  680. */
  681. function saveListViewSortOrder($ieId, $focusFolder, $sortBy, $sortDir) {
  682. global $current_user;
  683. $sortArray = array();
  684. $sortSerial = $current_user->getPreference('folderSortOrder', 'Emails');
  685. if(!empty($sortSerial)) {
  686. $sortArray = unserialize($sortSerial);
  687. }
  688. $sortArray[$ieId][$focusFolder]['current']['sort'] = $sortBy;
  689. $sortArray[$ieId][$focusFolder]['current']['direction'] = $sortDir;
  690. $sortSerial = serialize($sortArray);
  691. $current_user->setPreference('folderSortOrder', $sortSerial, '', 'Emails');
  692. }
  693. /**
  694. * Stickies folder collapse/open state
  695. */
  696. function saveFolderOpenState($focusFolder, $focusFolderOpen) {
  697. global $current_user;
  698. $folderStateSerial = $current_user->getPreference('folderOpenState', 'Emails');
  699. $folderStates = array();
  700. if(!empty($folderStateSerial)) {
  701. $folderStates = unserialize($folderStateSerial);
  702. }
  703. $folderStates[$focusFolder] = $focusFolderOpen;
  704. $newFolderStateSerial = serialize($folderStates);
  705. $current_user->setPreference('folderOpenState', $newFolderStateSerial, '', 'Emails');
  706. }
  707. /**
  708. * saves a folder's view state
  709. */
  710. function saveListView($ieId, $folder) {
  711. global $current_user;
  712. $saveState = array();
  713. $saveState['ieId'] = $ieId;
  714. $saveState['folder'] = $folder;
  715. $saveStateSerial = serialize($saveState);
  716. $current_user->setPreference('focusFolder', $saveStateSerial, '', 'Emails');
  717. }
  718. /**
  719. * Generates cache folder structure
  720. */
  721. function preflightEmailCache($cacheRoot) {
  722. // base
  723. if(!file_exists($cacheRoot))
  724. mkdir_recursive(clean_path($cacheRoot));
  725. // folders
  726. if(!file_exists($cacheRoot."/folders"))
  727. mkdir_recursive(clean_path("{$cacheRoot}/folders"));
  728. // messages
  729. if(!file_exists($cacheRoot."/messages"))
  730. mkdir_recursive(clean_path("{$cacheRoot}/messages"));
  731. // attachments
  732. if(!file_exists($cacheRoot."/attachments"))
  733. mkdir_recursive(clean_path("{$cacheRoot}/attachments"));
  734. }
  735. function deleteEmailCacheForFolders($cacheRoot) {
  736. $filePath = $cacheRoot."/folders/folders.php";
  737. if (file_exists($filePath)) {
  738. unlink($filePath);
  739. }
  740. }
  741. ///////////////////////////////////////////////////////////////////////////
  742. //// IMAP FUNCTIONS
  743. /**
  744. * Identifies subscribed mailboxes and empties the trash
  745. * @param object $ie InboundEmail
  746. */
  747. function emptyTrash(&$ie) {
  748. global $current_user;
  749. $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
  750. if(is_array($showFolders)) {
  751. foreach($showFolders as $ieId) {
  752. if(!empty($ieId)) {
  753. $ie->retrieve($ieId);
  754. $ie->emptyTrash();
  755. }
  756. }
  757. }
  758. }
  759. /**
  760. * returns an array of nodes that correspond to IMAP mailboxes.
  761. * @param bool $forceRefresh
  762. * @return object TreeView object
  763. */
  764. function getMailboxNodes() {
  765. global $sugar_config;
  766. global $current_user;
  767. global $app_strings;
  768. $tree = new Tree("frameFolders");
  769. $tree->tree_style= 'include/ytree/TreeView/css/check/tree.css';
  770. $nodes = array();
  771. $ie = new InboundEmail();
  772. $refreshOffset = $this->cacheTimeouts['folders']; // 5 mins. this will be set via user prefs
  773. $rootNode = new ExtNode($app_strings['LBL_EMAIL_HOME_FOLDER'], $app_strings['LBL_EMAIL_HOME_FOLDER']);
  774. $rootNode->dynamicloadfunction = '';
  775. $rootNode->expanded = true;
  776. $rootNode->dynamic_load = true;
  777. $showFolders = unserialize(base64_decode($current_user->getPreference('showFolders', 'Emails')));
  778. if(empty($showFolders)) {
  779. $showFolders = array();
  780. }
  781. // INBOX NODES
  782. if($current_user->hasPersonalEmail()) {
  783. $personals = $ie->retrieveByGroupId($current_user->id);
  784. foreach($personals as $k => $personalAccount) {
  785. if(in_array($personalAccount->id, $showFolders)) {
  786. // check for cache value
  787. $cacheRoot = sugar_cached("modules/Emails/{$personalAccount->id}");
  788. $this->preflightEmailCache($cacheRoot);
  789. if($this->validCacheFileExists($personalAccount->id, 'folders', "folders.php")) {
  790. $mailboxes = $this->getMailBoxesFromCacheValue($personalAccount);
  791. } else {
  792. $mailboxes = $personalAccount->getMailboxes();
  793. }
  794. $acctNode = new ExtNode('Home::' . $personalAccount->name, $personalAccount->name);
  795. $acctNode->dynamicloadfunction = '';
  796. $acctNode->expanded = false;
  797. $acctNode->set_property('cls', 'ieFolder');
  798. $acctNode->set_property('ieId', $personalAccount->id);
  799. $acctNode->set_property('protocol', $personalAccount->protocol);
  800. if(array_key_exists('Home::'.$personalAccount->name, $this->folderStates)) {
  801. if($this->folderStates['Home::'.$personalAccount->name] == 'open') {
  802. $acctNode->expanded = true;
  803. }
  804. }
  805. $acctNode->dynamic_load = true;
  806. $nodePath = $acctNode->_properties['id'];
  807. foreach($mailboxes as $k => $mbox) {
  808. $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $personalAccount->id,
  809. $nodePath, false, $personalAccount));
  810. }
  811. $rootNode->add_node($acctNode);
  812. }
  813. }
  814. }
  815. // GROUP INBOX NODES
  816. $beans = $ie->retrieveAllByGroupId($current_user->id, false);
  817. foreach($beans as $k => $groupAccount) {
  818. if(in_array($groupAccount->id, $showFolders)) {
  819. // check for cache value
  820. $cacheRoot = sugar_cached("modules/Emails/{$groupAccount->id}");
  821. $this->preflightEmailCache($cacheRoot);
  822. //$groupAccount->connectMailserver();
  823. if($this->validCacheFileExists($groupAccount->id, 'folders', "folders.php")) {
  824. $mailboxes = $this->getMailBoxesFromCacheValue($groupAccount);
  825. } else {
  826. $mailboxes = $groupAccount->getMailBoxesForGroupAccount();
  827. }
  828. $acctNode = new ExtNode($groupAccount->name, "group.{$groupAccount->name}");
  829. $acctNode->dynamicloadfunction = '';
  830. $acctNode->expanded = false;
  831. $acctNode->set_property('isGroup', 'true');
  832. $acctNode->set_property('ieId', $groupAccount->id);
  833. $acctNode->set_property('protocol', $groupAccount->protocol);
  834. if(array_key_exists('Home::'.$groupAccount->name, $this->folderStates)) {
  835. if($this->folderStates['Home::'.$groupAccount->name] == 'open') {
  836. $acctNode->expanded = true;
  837. }
  838. }
  839. $acctNode->dynamic_load = true;
  840. $nodePath = $rootNode->_properties['id']."::".$acctNode->_properties['id'];
  841. foreach($mailboxes as $k => $mbox) {
  842. $acctNode->add_node($this->buildTreeNode($k, $k, $mbox, $groupAccount->id,
  843. $nodePath, true, $groupAccount));
  844. }
  845. $rootNode->add_node($acctNode);
  846. }
  847. }
  848. // SugarFolder nodes
  849. /* SugarFolders are built at onload when the UI renders */
  850. $tree->add_node($rootNode);
  851. return $tree;
  852. }
  853. function getMailBoxesFromCacheValue($mailAccount) {
  854. $foldersCache = $this->getCacheValue($mailAccount->id, 'folders', "folders.php", 'foldersCache');
  855. $mailboxes = $foldersCache['mailboxes'];
  856. $mailboxesArray = $mailAccount->generateFlatArrayFromMultiDimArray($mailboxes, $mailAccount->retrieveDelimiter());
  857. $mailAccount->saveMailBoxFolders($mailboxesArray);
  858. $this->deleteEmailCacheForFolders($cacheRoot);
  859. return $mailboxes;
  860. } // fn
  861. /**
  862. * Builds up a TreeView Node object
  863. * @param mixed
  864. * @param mixed
  865. * @param string
  866. * @param string ID of InboundEmail instance
  867. * @param string nodePath Serialized path from root node to current node
  868. * @param bool isGroup
  869. * @param bool forceRefresh
  870. * @return mixed
  871. */
  872. function buildTreeNode($key, $label, $mbox, $ieId, $nodePath, $isGroup, $ie) {
  873. global $sugar_config;
  874. // get unread counts
  875. $exMbox = explode("::", $nodePath);
  876. $unseen = 0;
  877. $GLOBALS['log']->debug("$key --- $nodePath::$label");
  878. if(count($exMbox) >= 2) {
  879. $mailbox = "";
  880. for($i=2; $i<count($exMbox); $i++) {
  881. if($mailbox != "") {
  882. $mailbox .= ".";
  883. }
  884. $mailbox .= "{$exMbox[$i]}";
  885. }
  886. $mailbox = substr($key, strpos($key, '.'));
  887. $unseen = $this->getUnreadCount($ie, $mailbox);
  888. if($unseen > 0) {
  889. //$label = " <span id='span{$ie->id}{$ie->mailbox}' style='font-weight:bold'>{$label} (<span id='span{$ie->id}{$ie->mailbox}nums'>{$unseen}</span>)</span>";
  890. }
  891. }
  892. $nodePath = $nodePath."::".$label;
  893. $node = new ExtNode($nodePath, $label);
  894. $node->dynamicloadfunction = '';
  895. $node->expanded = false;
  896. $node->set_property('labelStyle', "remoteFolder");
  897. if(array_key_exists($nodePath, $this->folderStates)) {
  898. if($this->folderStates[$nodePath] == 'open') {
  899. $node->expanded = true;
  900. }
  901. }
  902. $group = ($isGroup) ? 'true' : 'false';
  903. $node->dynamic_load = true;
  904. //$node->set_property('href', " SUGAR.email2.listView.populateListFrame(YAHOO.namespace('frameFolders').selectednode, '{$ieId}', 'false');");
  905. $node->set_property('isGroup', $group);
  906. $node->set_property('isDynamic', 'false');
  907. $node->set_property('ieId', $ieId);
  908. $node->set_property('mbox', $key);
  909. $node->set_property('unseen', $unseen);
  910. $node->set_property('cls', 'ieFolder');
  911. if(is_array($mbox)) {
  912. foreach($mbox as $k => $v) {
  913. $node->add_node($this->buildTreeNode("$key.$k", $k, $v, $ieId, $nodePath, $isGroup, $ie));
  914. }
  915. }
  916. return $node;
  917. }
  918. /**
  919. * Totals the unread emails
  920. */
  921. function getUnreadCount(&$ie, $mailbox) {
  922. global $sugar_config;
  923. $unseen = 0;
  924. // use cache
  925. return $ie->getCacheUnreadCount($mailbox);
  926. }
  927. ///////////////////////////////////////////////////////////////////////////
  928. //// DISPLAY CODE
  929. /**
  930. * Used exclusively by draft code. Returns Notes and Documents as attachments.
  931. * @param array $ret
  932. * @return array
  933. */
  934. function getDraftAttachments($ret) {
  935. global $db;
  936. // $ret['uid'] is the draft Email object's GUID
  937. $ret['attachments'] = array();
  938. $q = "SELECT id, filename FROM notes WHERE parent_id = '{$ret['uid']}' AND deleted = 0";
  939. $r = $db->query($q);
  940. while($a = $db->fetchByAssoc($r)) {
  941. $ret['attachments'][$a['id']] = array(
  942. 'id' => $a['id'],
  943. 'filename' => $a['filename'],
  944. );
  945. }
  946. return $ret;
  947. }
  948. function createCopyOfInboundAttachment($ie, $ret, $uid) {
  949. global $sugar_config;
  950. if ($ie->isPop3Protocol()) {
  951. // get the UIDL from database;
  952. $cachedUIDL = md5($uid);
  953. $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$cachedUIDL}.php");
  954. } else {
  955. $cache = sugar_cached("modules/Emails/{$ie->id}/messages/{$ie->mailbox}{$uid}.php");
  956. }
  957. if(file_exists($cache)) {
  958. include($cache); // profides $cacheFile
  959. $metaOut = unserialize($cacheFile['out']);
  960. $meta = $metaOut['meta']['email'];
  961. if (isset($meta['attachments'])) {
  962. $attachmentHtmlData = $meta['attachments'];
  963. $actualAttachmentInfo = array();
  964. $this->parseAttachmentInfo($actualAttachmentInfo, $attachmentHtmlData);
  965. if (sizeof($actualAttachmentInfo) > 0) {
  966. foreach($actualAttachmentInfo as $key => $value) {
  967. $info_vars = array();
  968. parse_str($value, $info_vars);
  969. $fileName = $info_vars['tempName'];
  970. $attachmentid = $info_vars['id'];
  971. $guid = create_guid();
  972. $destination = clean_path("{$this->userCacheDir}/{$guid}");
  973. $attachmentFilePath = sugar_cached("modules/Emails/{$ie->id}/attachments/{$attachmentid}");
  974. copy($attachmentFilePath, $destination);
  975. $ret['attachments'][$guid] = array();
  976. $ret['attachments'][$guid]['id'] = $guid . $fileName;
  977. $ret['attachments'][$guid]['filename'] = $fileName;
  978. } // for
  979. } // if
  980. } // if
  981. } // if
  982. return $ret;
  983. } // fn
  984. function parseAttachmentInfo(&$actualAttachmentInfo, $attachmentHtmlData) {
  985. $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
  986. while ($downLoadPHP) {
  987. $attachmentHtmlData = substr($attachmentHtmlData, $downLoadPHP+30);
  988. $final = strpos($attachmentHtmlData, "\">");
  989. $actualAttachmentInfo[] = substr($attachmentHtmlData, 0, $final);
  990. $attachmentHtmlData = substr($attachmentHtmlData, $final);
  991. $downLoadPHP = strpos($attachmentHtmlData, "index.php?entryPoint=download&");
  992. } // while
  993. }
  994. /**
  995. * Renders the QuickCreate form from Smarty and returns HTML
  996. * @param array $vars request variable global
  997. * @param object $email Fetched email object
  998. * @param bool $addToAddressBook
  999. * @return array
  1000. */
  1001. function getQuickCreateForm($vars, $email, $addToAddressBookButton=false) {
  1002. require_once("include/EditView/EditView2.php");
  1003. global $app_strings;
  1004. global $mod_strings;
  1005. global $current_user;
  1006. global $beanList;
  1007. global $beanFiles;
  1008. global $current_language;
  1009. //Setup the current module languge
  1010. $mod_strings = return_module_language($current_language, $_REQUEST['qc_module']);
  1011. $bean = $beanList[$_REQUEST['qc_module']];
  1012. $class = $beanFiles[$bean];
  1013. require_once($class);
  1014. $focus = new $bean();
  1015. $people = array(
  1016. 'Contact'
  1017. ,'Lead'
  1018. );
  1019. $emailAddress = array();
  1020. // people
  1021. if(in_array($bean, $people)) {
  1022. // lead specific
  1023. $focus->lead_source = 'Email';
  1024. $focus->lead_source_description = trim($email->name);
  1025. $from = (isset($email->from_name) && !empty($email->from_name)) ? $email->from_name : $email->from_addr;
  1026. if(isset($_REQUEST['sugarEmail']) && !empty($_REQUEST['sugarEmail']))
  1027. $from = (isset($email->to_addrs_names) && !empty($email->to_addrs_names)) ? $email->to_addrs_names : $email->to_addrs;
  1028. $name = explode(" ", trim($from));
  1029. $address = trim(array_pop($name));
  1030. $address = str_replace(array("<",">","&lt;","&gt;"), "", $address);
  1031. $emailAddress[] = array(
  1032. 'email_address' => $address,
  1033. 'primary_address' => 1,
  1034. 'invalid_email' => 0,
  1035. 'opt_out' => 0,
  1036. 'reply_to_address' => 1
  1037. );
  1038. $focus->email1 = $address;
  1039. if(!empty($name)) {
  1040. $focus->last_name = trim(array_pop($name));
  1041. foreach($name as $first) {
  1042. if(!empty($focus->first_name)) {
  1043. $focus->first_name .= " ";
  1044. }
  1045. $focus->first_name .= trim($first);
  1046. }
  1047. }
  1048. } else {
  1049. // bugs, cases, tasks
  1050. $focus->name = trim($email->name);
  1051. }
  1052. $focus->description = trim(strip_tags($email->description));
  1053. $focus->assigned_user_id = $current_user->id;
  1054. $EditView = new EditView();
  1055. $EditView->ss = new Sugar_Smarty();
  1056. //MFH BUG#20283 - checks for custom quickcreate fields
  1057. $EditView->setup($_REQUEST['qc_module'], $focus, 'custom/modules/'.$focus->module_dir.'/metadata/editviewdefs.php', 'include/EditView/EditView.tpl');
  1058. $EditView->process();
  1059. $EditView->render();
  1060. $EditView->defs['templateMeta']['form']['buttons'] = array(
  1061. 'email2save' => array(
  1062. 'id' => 'e2AjaxSave',
  1063. 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_SAVE_BUTTON_LABEL']
  1064. . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(false);" />'
  1065. ),
  1066. 'email2saveandreply' => array(
  1067. 'id' => 'e2SaveAndReply',
  1068. 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_SAVE_AND_REPLY']
  1069. . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(\'reply\');" />'
  1070. ),
  1071. 'email2cancel' => array(
  1072. 'id' => 'e2cancel',
  1073. 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_CANCEL']
  1074. . ' " onclick="SUGAR.email2.detailView.quickCreateDialog.hide();" />'
  1075. )
  1076. );
  1077. if($addToAddressBookButton) {
  1078. $EditView->defs['templateMeta']['form']['buttons']['email2saveAddToAddressBook'] = array(
  1079. 'id' => 'e2addToAddressBook',
  1080. 'customCode' => '<input type="button" class="button" value=" '.$app_strings['LBL_EMAIL_ADDRESS_BOOK_SAVE_AND_ADD']
  1081. . ' " onclick="SUGAR.email2.detailView.saveQuickCreate(true);" />'
  1082. );
  1083. }
  1084. //Get the module language for javascript
  1085. if(!is_file(sugar_cached('jsLanguage/') . $_REQUEST['qc_module'] . '/' . $GLOBALS['current_language'] . '.js')) {
  1086. require_once('include/language/jsLanguage.php');
  1087. jsLanguage::createModuleStringsCache($_REQUEST['qc_module'], $GLOBALS['current_language']);
  1088. }
  1089. $jsLanguage = getVersionedScript("cache/jsLanguage/{$_REQUEST['qc_module']}/{$GLOBALS['current_language']}.js", $GLOBALS['sugar_config']['js_lang_version']);
  1090. $EditView->view = 'EmailQCView';
  1091. $EditView->defs['templateMeta']['form']['headerTpl'] = 'include/EditView/header.tpl';
  1092. $EditView->defs['templateMeta']['form']['footerTpl'] = 'include/EditView/footer.tpl';
  1093. $meta = array();
  1094. $meta['html'] = $jsLanguage . $EditView->display(false, true);
  1095. $meta['html'] = str_replace("src='".getVersionedPath('include/SugarEmailAddress/SugarEmailAddress.js')."'", '', $meta['html']);
  1096. $meta['emailAddress'] = $emailAddress;
  1097. $mod_strings = return_module_language($current_language, 'Emails');
  1098. return $meta;
  1099. }
  1100. /**
  1101. * Renders the Import form from Smarty and returns HTML
  1102. * @param array $vars request variable global
  1103. * @param object $email Fetched email object
  1104. * @param bool $addToAddressBook
  1105. * @return array
  1106. */
  1107. function getImportForm($vars, $email, $formName = 'ImportEditView') {
  1108. require_once("include/EditView/EditView2.php");
  1109. require_once("include/TemplateHandler/TemplateHandler.php");
  1110. require_once('include/QuickSearchDefaults.php');
  1111. $qsd = QuickSearchDefaults::getQuickSearchDefaults();
  1112. $qsd->setFormName($formName);
  1113. global $app_strings;
  1114. global $current_user;
  1115. global $app_list_strings;
  1116. $sqs_objects = array(
  1117. "{$formName}_parent_name" => $qsd->getQSParent(),
  1118. );
  1119. $smarty = new Sugar_Smarty();
  1120. $smarty->assign("APP",$app_strings);
  1121. $smarty->assign('formName',$formName);
  1122. $showAssignTo = false;
  1123. if (!isset($vars['showAssignTo']) || $vars['showAssignTo'] == true) {
  1124. $showAssignTo = true;
  1125. } // if
  1126. if ($showAssignTo) {
  1127. if(empty($email->assigned_user_id) && empty($email->id))
  1128. $email->assigned_user_id = $current_user->id;
  1129. if(empty($email->assigned_name) && empty($email->id))
  1130. $email->assigned_user_name = $current_user->user_name;
  1131. $sqs_objects["{$formName}_assigned_user_name"] = $qsd->getQSUser();
  1132. }
  1133. $smarty->assign("showAssignedTo",$showAssignTo);
  1134. $showDelete = false;
  1135. if (!isset($vars['showDelete']) || $vars['showDelete'] == true) {
  1136. $showDelete = true;
  1137. }
  1138. $smarty->assign("showDelete",$showDelete);
  1139. $smarty->assign("userId",$email->assigned_user_id);
  1140. $smarty->assign("userName",$email->assigned_user_name);
  1141. $parent_types = $app_list_strings['record_type_display'];
  1142. $smarty->assign('parentOptions', get_select_options_with_id($parent_types, $email->parent_type));
  1143. $quicksearch_js = '<script type="text/javascript" language="javascript">sqs_objects = ' . json_encode($sqs_objects) . '</script>';
  1144. $smarty->assign('SQS', $quicksearch_js);
  1145. $meta = array();
  1146. $meta['html'] = $smarty->fetch("modules/Emails/templates/importRelate.tpl");
  1147. return $meta;
  1148. }
  1149. /**
  1150. * This function returns the detail view for email in new 2.0 interface
  1151. *
  1152. */
  1153. function getDetailViewForEmail2($emailId) {
  1154. require_once('include/DetailView/DetailView.php');
  1155. global $app_strings, $app_list_strings;
  1156. global $mod_strings;
  1157. $smarty = new Sugar_Smarty();
  1158. // SETTING DEFAULTS
  1159. $focus = new Email();
  1160. $focus->retrieve($emailId);
  1161. $detailView->ss = new Sugar_Smarty();
  1162. $detailView = new DetailView();
  1163. $title = "";
  1164. $offset = 0;
  1165. if($focus->type == 'out') {
  1166. $title = getClassicModuleTitle('Emails', array($mod_strings['LBL_SENT_MODULE_NAME'],$focus->name),

Large files files are truncated, but you can click here to view the full file