PageRenderTime 73ms CodeModel.GetById 26ms RepoModel.GetById 0ms app.codeStats 1ms

/include/utils.php

https://github.com/vincentamari/SuperSweetAdmin
PHP | 4192 lines | 3577 code | 251 blank | 364 comment | 295 complexity | 1e9d2e6845f607b9386c0f95d3fad748 MD5 | raw file
Possible License(s): MPL-2.0-no-copyleft-exception, AGPL-3.0, LGPL-2.1
  1. <?php
  2. /*********************************************************************************
  3. * SugarCRM is a customer relationship management program developed by
  4. * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
  5. *
  6. * This program is free software; you can redistribute it and/or modify it under
  7. * the terms of the GNU Affero General Public License version 3 as published by the
  8. * Free Software Foundation with the addition of the following permission added
  9. * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  10. * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  11. * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  12. *
  13. * This program is distributed in the hope that it will be useful, but WITHOUT
  14. * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  15. * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
  16. * details.
  17. *
  18. * You should have received a copy of the GNU Affero General Public License along with
  19. * this program; if not, see http://www.gnu.org/licenses or write to the Free
  20. * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  21. * 02110-1301 USA.
  22. *
  23. * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  24. * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  25. *
  26. * The interactive user interfaces in modified source and object code versions
  27. * of this program must display Appropriate Legal Notices, as required under
  28. * Section 5 of the GNU Affero General Public License version 3.
  29. *
  30. * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  31. * these Appropriate Legal Notices must retain the display of the "Powered by
  32. * SugarCRM" logo. If the display of the logo is not reasonably feasible for
  33. * technical reasons, the Appropriate Legal Notices must display the words
  34. * "Powered by SugarCRM".
  35. ********************************************************************************/
  36. /*********************************************************************************
  37. * Description: Includes generic helper functions used throughout the application.
  38. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  39. * All Rights Reserved.
  40. * Contributor(s): ______________________________________..
  41. ********************************************************************************/
  42. require_once('include/SugarObjects/SugarConfig.php');
  43. require_once('include/utils/security_utils.php');
  44. function make_sugar_config(&$sugar_config)
  45. {
  46. /* used to convert non-array config.php file to array format */
  47. global $admin_export_only;
  48. global $cache_dir;
  49. global $calculate_response_time;
  50. global $create_default_user;
  51. global $dateFormats;
  52. global $dbconfig;
  53. global $dbconfigoption;
  54. global $default_action;
  55. global $default_charset;
  56. global $default_currency_name;
  57. global $default_currency_symbol;
  58. global $default_currency_iso4217;
  59. global $defaultDateFormat;
  60. global $default_language;
  61. global $default_module;
  62. global $default_password;
  63. global $default_permission_mode;
  64. global $default_theme;
  65. global $defaultTimeFormat;
  66. global $default_user_is_admin;
  67. global $default_user_name;
  68. global $disable_export;
  69. global $disable_persistent_connections;
  70. global $display_email_template_variable_chooser;
  71. global $display_inbound_email_buttons;
  72. global $history_max_viewed;
  73. global $host_name;
  74. global $import_dir;
  75. global $languages;
  76. global $list_max_entries_per_page;
  77. global $lock_default_user_name;
  78. global $log_memory_usage;
  79. global $requireAccounts;
  80. global $RSS_CACHE_TIME;
  81. global $session_dir;
  82. global $site_URL;
  83. global $site_url;
  84. global $sugar_version;
  85. global $timeFormats;
  86. global $tmp_dir;
  87. global $translation_string_prefix;
  88. global $unique_key;
  89. global $upload_badext;
  90. global $upload_dir;
  91. global $upload_maxsize;
  92. global $import_max_execution_time;
  93. global $list_max_entries_per_subpanel;
  94. global $passwordsetting;
  95. // assumes the following variables must be set:
  96. // $dbconfig, $dbconfigoption, $cache_dir, $import_dir, $session_dir, $site_URL, $tmp_dir, $upload_dir
  97. $sugar_config = array (
  98. 'admin_export_only' => empty($admin_export_only) ? false : $admin_export_only,
  99. 'export_delimiter' => empty($export_delimiter) ? ',' : $export_delimiter,
  100. 'cache_dir' => empty($cache_dir) ? 'cache/' : $cache_dir,
  101. 'calculate_response_time' => empty($calculate_response_time) ? true : $calculate_response_time,
  102. 'create_default_user' => empty($create_default_user) ? false : $create_default_user,
  103. 'chartEngine' => 'Jit',
  104. 'date_formats' => empty($dateFormats) ? array(
  105. 'Y-m-d'=>'2010-12-23',
  106. 'd-m-Y' => '23-12-2010',
  107. 'm-d-Y'=>'12-23-2010',
  108. 'Y/m/d'=>'2010/12/23',
  109. 'd/m/Y' => '23/12/2010',
  110. 'm/d/Y'=>'12/23/2010',
  111. 'Y.m.d' => '2010.12.23',
  112. 'd.m.Y' => '23.12.2010',
  113. 'm.d.Y' => '12.23.2010'
  114. ) : $dateFormats,
  115. 'dbconfig' => $dbconfig, // this must be set!!
  116. 'dbconfigoption' => $dbconfigoption, // this must be set!!
  117. 'default_action' => empty($default_action) ? 'index' : $default_action,
  118. 'default_charset' => empty($default_charset) ? 'UTF-8' : $default_charset,
  119. 'default_currency_name' => empty($default_currency_name) ? 'US Dollar' : $default_currency_name,
  120. 'default_currency_symbol' => empty($default_currency_symbol) ? '$' : $default_currency_symbol,
  121. 'default_currency_iso4217' => empty($default_currency_iso4217) ? '$' : $default_currency_iso4217,
  122. 'default_date_format' => empty($defaultDateFormat) ? 'm/d/Y' : $defaultDateFormat,
  123. 'default_export_charset' => 'UTF-8',
  124. 'default_language' => empty($default_language) ? 'en_us' : $default_language,
  125. 'default_module' => empty($default_module) ? 'Home' : $default_module,
  126. 'default_password' => empty($default_password) ? '' : $default_password,
  127. 'default_permissions' => array (
  128. 'dir_mode' => 02770,
  129. 'file_mode' => 0660,
  130. 'chown' => '',
  131. 'chgrp' => '',
  132. ),
  133. 'default_theme' => empty($default_theme) ? 'Sugar5' : $default_theme,
  134. 'default_time_format' => empty($defaultTimeFormat) ? 'h:ia' : $defaultTimeFormat,
  135. 'default_user_is_admin' => empty($default_user_is_admin) ? false : $default_user_is_admin,
  136. 'default_user_name' => empty($default_user_name) ? '' : $default_user_name,
  137. 'disable_export' => empty($disable_export) ? false : $disable_export,
  138. 'disable_persistent_connections' => empty($disable_persistent_connections) ? false : $disable_persistent_connections,
  139. 'display_email_template_variable_chooser' => empty($display_email_template_variable_chooser) ? false : $display_email_template_variable_chooser,
  140. 'display_inbound_email_buttons' => empty($display_inbound_email_buttons) ? false : $display_inbound_email_buttons,
  141. 'history_max_viewed' => empty($history_max_viewed) ? 50 : $history_max_viewed,
  142. 'host_name' => empty($host_name) ? 'localhost' : $host_name,
  143. 'import_dir' => $import_dir, // this must be set!!
  144. 'import_max_records_per_file' => 100,
  145. 'languages' => empty($languages) ? array('en_us' => 'English (US)') : $languages,
  146. 'list_max_entries_per_page' => empty($list_max_entries_per_page) ? 20 : $list_max_entries_per_page,
  147. 'list_max_entries_per_subpanel' => empty($list_max_entries_per_subpanel) ? 10 : $list_max_entries_per_subpanel,
  148. 'lock_default_user_name' => empty($lock_default_user_name) ? false : $lock_default_user_name,
  149. 'log_memory_usage' => empty($log_memory_usage) ? false : $log_memory_usage,
  150. 'portal_view' => 'single_user',
  151. 'resource_management' => array (
  152. 'special_query_limit' => 50000,
  153. 'special_query_modules' => array('Reports', 'Export', 'Import', 'Administration', 'Sync'),
  154. 'default_limit' => 1000,
  155. ),
  156. 'require_accounts' => empty($requireAccounts) ? true : $requireAccounts,
  157. 'rss_cache_time' => empty($RSS_CACHE_TIME) ? '10800' : $RSS_CACHE_TIME,
  158. 'session_dir' => $session_dir, // this must be set!!
  159. 'site_url' => empty($site_URL) ? $site_url : $site_URL, // this must be set!!
  160. 'showDetailData' => true, // if true, read-only ACL fields will still appear on EditViews as non-editable
  161. 'showThemePicker' => true,
  162. 'sugar_version' => empty($sugar_version) ? 'unknown' : $sugar_version,
  163. 'time_formats' => empty($timeFormats) ? array (
  164. 'H:i'=>'23:00', 'h:ia'=>'11:00 pm', 'h:iA'=>'11:00PM',
  165. 'H.i'=>'23.00', 'h.ia'=>'11.00 pm', 'h.iA'=>'11.00PM' ) : $timeFormats,
  166. 'tmp_dir' => $tmp_dir, // this must be set!!
  167. 'translation_string_prefix' => empty($translation_string_prefix) ? false : $translation_string_prefix,
  168. 'unique_key' => empty($unique_key) ? md5(create_guid()) : $unique_key,
  169. 'upload_badext' => empty($upload_badext) ? array (
  170. 'php', 'php3', 'php4', 'php5', 'pl', 'cgi', 'py',
  171. 'asp', 'cfm', 'js', 'vbs', 'html', 'htm' ) : $upload_badext,
  172. 'upload_dir' => $upload_dir, // this must be set!!
  173. 'upload_maxsize' => empty($upload_maxsize) ? 3000000 : $upload_maxsize,
  174. 'import_max_execution_time' => empty($import_max_execution_time) ? 3600 : $import_max_execution_time,
  175. 'lock_homepage' => false,
  176. 'lock_subpanels' => false,
  177. 'max_dashlets_homepage' => 15,
  178. 'dashlet_display_row_options' => array('1','3','5','10'),
  179. 'default_max_tabs' => empty($max_tabs) ? '7' : $max_tabs,
  180. 'default_subpanel_tabs' => empty($subpanel_tabs) ? true : $subpanel_tabs,
  181. 'default_subpanel_links' => empty($subpanel_links) ? false : $subpanel_links,
  182. 'default_swap_last_viewed' => empty($swap_last_viewed) ? false : $swap_last_viewed,
  183. 'default_swap_shortcuts' => empty($swap_shortcuts) ? false : $swap_shortcuts,
  184. 'default_navigation_paradigm' => empty($navigation_paradigm) ? 'gm' : $navigation_paradigm,
  185. 'default_call_status' => 'Planned',
  186. 'js_lang_version' => 1,
  187. 'passwordsetting' => empty($passwordsetting) ? array (
  188. 'SystemGeneratedPasswordON' => '',
  189. 'generatepasswordtmpl' => '',
  190. 'lostpasswordtmpl' => '',
  191. 'forgotpasswordON' => true,
  192. 'linkexpiration' => '1',
  193. 'linkexpirationtime' => '30',
  194. 'linkexpirationtype' => '1',
  195. 'systexpiration' => '0',
  196. 'systexpirationtime' => '',
  197. 'systexpirationtype' => '0',
  198. 'systexpirationlogin' => '',
  199. ) : $passwordsetting,
  200. );
  201. }
  202. function get_sugar_config_defaults() {
  203. global $locale;
  204. /**
  205. * used for getting base values for array style config.php. used by the
  206. * installer and to fill in new entries on upgrades. see also:
  207. * sugar_config_union
  208. */
  209. $sugar_config_defaults = array (
  210. 'admin_export_only' => false,
  211. 'export_delimiter' => ',',
  212. 'cache_dir' => 'cache/',
  213. 'calculate_response_time' => true,
  214. 'create_default_user' => false,
  215. 'chartEngine' => 'Jit',
  216. 'date_formats' => array (
  217. 'Y-m-d' => '2010-12-23', 'm-d-Y' => '12-23-2010', 'd-m-Y' => '23-12-2010',
  218. 'Y/m/d' => '2010/12/23', 'm/d/Y' => '12/23/2010', 'd/m/Y' => '23/12/2010',
  219. 'Y.m.d' => '2010.12.23', 'd.m.Y' => '23.12.2010', 'm.d.Y' => '12.23.2010',),
  220. 'dbconfigoption' => array (
  221. 'persistent' => true,
  222. 'autofree' => false,
  223. 'debug' => 0,
  224. 'seqname_format' => '%s_seq',
  225. 'portability' => 0,
  226. 'ssl' => false ),
  227. 'default_action' => 'index',
  228. 'default_charset' => return_session_value_or_default('default_charset',
  229. 'UTF-8'),
  230. 'default_currency_name' => return_session_value_or_default('default_currency_name', 'US Dollar'),
  231. 'default_currency_symbol' => return_session_value_or_default('default_currency_symbol', '$'),
  232. 'default_currency_iso4217' => return_session_value_or_default('default_currency_iso4217', 'USD'),
  233. 'default_currency_significant_digits' => return_session_value_or_default('default_currency_significant_digits', 2),
  234. 'default_number_grouping_seperator' => return_session_value_or_default('default_number_grouping_seperator', ','),
  235. 'default_decimal_seperator' => return_session_value_or_default('default_decimal_seperator', '.'),
  236. 'default_date_format' => 'm/d/Y',
  237. 'default_export_charset' => 'UTF-8',
  238. 'default_language' => return_session_value_or_default('default_language',
  239. 'en_us'),
  240. 'default_module' => 'Home',
  241. 'default_password' => '',
  242. 'default_permissions' => array (
  243. 'dir_mode' => 02770,
  244. 'file_mode' => 0660,
  245. 'user' => '',
  246. 'group' => '',
  247. ),
  248. 'default_theme' => return_session_value_or_default('site_default_theme', 'Sugar5'),
  249. 'default_time_format' => 'h:ia',
  250. 'default_user_is_admin' => false,
  251. 'default_user_name' => '',
  252. 'disable_export' => false,
  253. 'disable_persistent_connections' =>
  254. return_session_value_or_default('disable_persistent_connections',
  255. 'false'),
  256. 'display_email_template_variable_chooser' => false,
  257. 'display_inbound_email_buttons' => false,
  258. 'dump_slow_queries' => false,
  259. 'email_default_editor' => 'html',
  260. 'email_default_client' => 'sugar',
  261. 'email_default_delete_attachments' => true,
  262. 'history_max_viewed' => 50,
  263. 'installer_locked' => true,
  264. 'import_max_records_per_file' => 100,
  265. 'languages' => array('en_us' => 'English (US)'),
  266. 'large_scale_test' => false,
  267. 'list_max_entries_per_page' => 20,
  268. 'list_max_entries_per_subpanel' => 10,
  269. 'lock_default_user_name' => false,
  270. 'log_memory_usage' => false,
  271. 'portal_view' => 'single_user',
  272. 'resource_management' => array (
  273. 'special_query_limit' => 50000,
  274. 'special_query_modules' => array('Reports', 'Export', 'Import', 'Administration', 'Sync'),
  275. 'default_limit' => 1000,
  276. ),
  277. 'require_accounts' => true,
  278. 'rss_cache_time' => return_session_value_or_default('rss_cache_time',
  279. '10800'),
  280. 'save_query' => 'all',
  281. 'showDetailData' => true, // if true, read-only ACL fields will still appear on EditViews as non-editable
  282. 'showThemePicker' => true,
  283. 'slow_query_time_msec' => '100',
  284. 'sugarbeet' => true,
  285. 'time_formats' => array (
  286. 'H:i'=>'23:00', 'h:ia'=>'11:00pm', 'h:iA'=>'11:00PM',
  287. 'H.i'=>'23.00', 'h.ia'=>'11.00pm', 'h.iA'=>'11.00PM' ),
  288. 'tracker_max_display_length' => 15,
  289. 'translation_string_prefix' =>
  290. return_session_value_or_default('translation_string_prefix', false),
  291. 'upload_badext' => array (
  292. 'php', 'php3', 'php4', 'php5', 'pl', 'cgi', 'py',
  293. 'asp', 'cfm', 'js', 'vbs', 'html', 'htm' ),
  294. 'upload_maxsize' => 3000000,
  295. 'import_max_execution_time' => 3600,
  296. // 'use_php_code_json' => returnPhpJsonStatus(),
  297. 'verify_client_ip' => true,
  298. 'js_custom_version' => '',
  299. 'js_lang_version' => 1,
  300. 'default_number_grouping_seperator' => ',',
  301. 'default_decimal_seperator' => '.',
  302. 'lock_homepage' => false,
  303. 'lock_subpanels' => false,
  304. 'max_dashlets_homepage' => '15',
  305. 'default_max_tabs' => '7',
  306. 'dashlet_display_row_options' => array('1','3','5','10'),
  307. 'default_subpanel_tabs' => true,
  308. 'default_subpanel_links' => false,
  309. 'default_swap_last_viewed' => false,
  310. 'default_swap_shortcuts' => false,
  311. 'default_navigation_paradigm' => 'gm',
  312. 'admin_access_control' => false,
  313. 'use_common_ml_dir' => false,
  314. 'common_ml_dir' => '',
  315. 'vcal_time' => '2',
  316. 'passwordsetting' => empty($passwordsetting) ? array (
  317. 'SystemGeneratedPasswordON' => '',
  318. 'generatepasswordtmpl' => '',
  319. 'lostpasswordtmpl' => '',
  320. 'forgotpasswordON' => false,
  321. 'linkexpiration' => '1',
  322. 'linkexpirationtime' => '30',
  323. 'linkexpirationtype' => '1',
  324. 'systexpiration' => '0',
  325. 'systexpirationtime' => '',
  326. 'systexpirationtype' => '0',
  327. 'systexpirationlogin' => '',
  328. ) : $passwordsetting,
  329. 'use_real_names' => true,
  330. );
  331. if(!is_object($locale)) {
  332. $locale = new Localization();
  333. }
  334. $sugar_config_defaults['default_currencies'] = $locale->getDefaultCurrencies();
  335. $sugar_config_defaults = sugarArrayMerge($locale->getLocaleConfigDefaults(), $sugar_config_defaults);
  336. return( $sugar_config_defaults );
  337. }
  338. /**
  339. * @deprecated use SugarView::getMenu() instead
  340. */
  341. function load_menu($path){
  342. global $module_menu;
  343. if(file_exists($path . 'Menu.php'))
  344. {
  345. require($path . 'Menu.php');
  346. }
  347. if(file_exists('custom/' . $path . 'Ext/Menus/menu.ext.php'))
  348. {
  349. require('custom/' . $path . 'Ext/Menus/menu.ext.php');
  350. }
  351. if(file_exists('custom/application/Ext/Menus/menu.ext.php'))
  352. {
  353. require('custom/application/Ext/Menus/menu.ext.php');
  354. }
  355. return $module_menu;
  356. }
  357. /**
  358. * get_notify_template_file
  359. * This function will return the location of the email notifications template to use
  360. *
  361. * @return string relative file path to email notifications template file
  362. */
  363. function get_notify_template_file($language){
  364. /*
  365. * Order of operation:
  366. * 1) custom version of specified language
  367. * 2) stock version of specified language
  368. * 3) custom version of en_us template
  369. * 4) stock en_us template
  370. */
  371. // set $file to the base code template so it's set if none of the conditions pass
  372. $file = "include/language/en_us.notify_template.html";
  373. if(file_exists("custom/include/language/{$language}.notify_template.html")){
  374. $file = "custom/include/language/{$language}.notify_template.html";
  375. }
  376. else if(file_exists("include/language/{$language}.notify_template.html")){
  377. $file = "include/language/{$language}.notify_template.html";
  378. }
  379. else if(file_exists("custom/include/language/en_us.notify_template.html")){
  380. $file = "custom/include/language/en_us.notify_template.html";
  381. }
  382. return $file;
  383. }
  384. function sugar_config_union( $default, $override ){
  385. // a little different then array_merge and array_merge_recursive. we want
  386. // the second array to override the first array if the same value exists,
  387. // otherwise merge the unique keys. it handles arrays of arrays recursively
  388. // might be suitable for a generic array_union
  389. if( !is_array( $override ) ){
  390. $override = array();
  391. }
  392. foreach( $default as $key => $value ){
  393. if( !array_key_exists($key, $override) ){
  394. $override[$key] = $value;
  395. }
  396. else if( is_array( $key ) ){
  397. $override[$key] = sugar_config_union( $value, $override[$key] );
  398. }
  399. }
  400. return( $override );
  401. }
  402. function make_not_writable( $file ){
  403. // Returns true if the given file/dir has been made not writable
  404. $ret_val = false;
  405. if( is_file($file) || is_dir($file) ){
  406. if( !is_writable($file) ){
  407. $ret_val = true;
  408. }
  409. else {
  410. $original_fileperms = fileperms($file);
  411. // take away writable permissions
  412. $new_fileperms = $original_fileperms & ~0x0092;
  413. @sugar_chmod($file, $new_fileperms);
  414. if( !is_writable($file) ){
  415. $ret_val = true;
  416. }
  417. }
  418. }
  419. return $ret_val;
  420. }
  421. /** This function returns the name of the person.
  422. * It currently returns "first last". It should not put the space if either name is not available.
  423. * It should not return errors if either name is not available.
  424. * If no names are present, it will return ""
  425. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  426. * All Rights Reserved.
  427. * Contributor(s): ______________________________________..
  428. */
  429. function return_name($row, $first_column, $last_column)
  430. {
  431. $first_name = "";
  432. $last_name = "";
  433. $full_name = "";
  434. if(isset($row[$first_column]))
  435. {
  436. $first_name = stripslashes($row[$first_column]);
  437. }
  438. if(isset($row[$last_column]))
  439. {
  440. $last_name = stripslashes($row[$last_column]);
  441. }
  442. $full_name = $first_name;
  443. // If we have a first name and we have a last name
  444. if($full_name != "" && $last_name != "")
  445. {
  446. // append a space, then the last name
  447. $full_name .= " ".$last_name;
  448. }
  449. // If we have no first name, but we have a last name
  450. else if($last_name != "")
  451. {
  452. // append the last name without the space.
  453. $full_name .= $last_name;
  454. }
  455. return $full_name;
  456. }
  457. function get_languages()
  458. {
  459. global $sugar_config;
  460. $lang = $sugar_config['languages'];
  461. if(!empty($sugar_config['disabled_languages'])){
  462. foreach(explode(',', $sugar_config['disabled_languages']) as $disable) {
  463. unset($lang[$disable]);
  464. }
  465. }
  466. return $lang;
  467. }
  468. function get_all_languages()
  469. {
  470. global $sugar_config;
  471. return $sugar_config['languages'];
  472. }
  473. function get_language_display($key)
  474. {
  475. global $sugar_config;
  476. return $sugar_config['languages'][$key];
  477. }
  478. function get_assigned_user_name($assigned_user_id, $is_group = '') {
  479. static $saved_user_list = null;
  480. if(empty($saved_user_list)) {
  481. $saved_user_list = get_user_array(false, '', '', false, null, $is_group);
  482. }
  483. if(isset($saved_user_list[$assigned_user_id])) {
  484. return $saved_user_list[$assigned_user_id];
  485. }
  486. return '';
  487. }
  488. /**
  489. * retrieves the user_name column value (login)
  490. * @param string id GUID of user
  491. * @return string
  492. */
  493. function get_user_name($id) {
  494. global $db;
  495. if(empty($db))
  496. $db = DBManagerFactory::getInstance();
  497. $q = "SELECT user_name FROM users WHERE id='{$id}'";
  498. $r = $db->query($q);
  499. $a = $db->fetchByAssoc($r);
  500. return (empty($a)) ? '' : $a['user_name'];
  501. }
  502. //TODO Update to use global cache
  503. function get_user_array($add_blank=true, $status="Active", $assigned_user="", $use_real_name=false, $user_name_begins = null, $is_group=' AND portal_only=0 ', $from_cache = true) {
  504. global $locale;
  505. global $sugar_config;
  506. if(empty($locale)) {
  507. $locale = new Localization();
  508. }
  509. if($from_cache)
  510. $user_array = get_register_value('user_array', $add_blank. $status . $assigned_user);
  511. if(!isset($user_array)) {
  512. $db = DBManagerFactory::getInstance();
  513. $temp_result = Array();
  514. // Including deleted users for now.
  515. if (empty($status)) {
  516. $query = "SELECT id, first_name, last_name, user_name from users WHERE 1=1".$is_group;
  517. }
  518. else {
  519. $query = "SELECT id, first_name, last_name, user_name from users WHERE status='$status'".$is_group;
  520. }
  521. if (!empty($user_name_begins)) {
  522. $query .= " AND user_name LIKE '$user_name_begins%' ";
  523. }
  524. if (!empty($assigned_user)) {
  525. $query .= " OR id='$assigned_user'";
  526. }
  527. $query = $query.' ORDER BY user_name ASC';
  528. $GLOBALS['log']->debug("get_user_array query: $query");
  529. $result = $db->query($query, true, "Error filling in user array: ");
  530. if ($add_blank==true) {
  531. // Add in a blank row
  532. $temp_result[''] = '';
  533. }
  534. // Get the id and the name.
  535. while($row = $db->fetchByAssoc($result)) {
  536. if($use_real_name == true || showFullName()) {
  537. if(isset($row['last_name'])) { // cn: we will ALWAYS have both first_name and last_name (empty value if blank in db)
  538. $temp_result[$row['id']] = $locale->getLocaleFormattedName($row['first_name'],$row['last_name']);
  539. } else {
  540. $temp_result[$row['id']] = $row['user_name'];
  541. }
  542. } else {
  543. $temp_result[$row['id']] = $row['user_name'];
  544. }
  545. }
  546. $user_array = $temp_result;
  547. if($from_cache)
  548. set_register_value('user_array', $add_blank. $status . $assigned_user, $temp_result);
  549. }
  550. return $user_array;
  551. }
  552. /**
  553. * uses a different query to return a list of users than get_user_array()
  554. * @param args string where clause entry
  555. * @return array Array of Users' details that match passed criteria
  556. */
  557. function getUserArrayFromFullName($args, $hide_portal_users = false) {
  558. global $locale;
  559. $db = DBManagerFactory::getInstance();
  560. $argArray = array();
  561. if(strpos($args, " ")) {
  562. $argArray = explode(" ", $args);
  563. } else {
  564. $argArray[] = $args;
  565. }
  566. $inClause = '';
  567. foreach($argArray as $arg) {
  568. if(!empty($inClause)) {
  569. $inClause .= ' OR ';
  570. }
  571. if(empty($arg))
  572. continue;
  573. $inClause .= "(first_name LIKE '{$arg}%' OR last_name LIKE '{$arg}%')";
  574. }
  575. $query = "SELECT id, first_name, last_name, user_name FROM users WHERE status='Active' AND deleted=0 AND ";
  576. if ( $hide_portal_users ) {
  577. $query .= " portal_only=0 AND ";
  578. }
  579. $query .= $inClause;
  580. $query .= " ORDER BY last_name ASC";
  581. $r = $db->query($query);
  582. $ret = array();
  583. while($a = $db->fetchByAssoc($r)) {
  584. $ret[$a['id']] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name']);
  585. }
  586. return $ret;
  587. }
  588. /**
  589. *
  590. * based on user pref then system pref
  591. */
  592. function showFullName() {
  593. global $sugar_config;
  594. global $current_user;
  595. static $showFullName = null;
  596. if (is_null($showFullName)) {
  597. $sysPref = (isset($sugar_config['use_real_names']) && $sugar_config['use_real_names'] == true) ? true : false;
  598. $userPref = (is_object($current_user)) ? $current_user->getPreference('use_real_names') : null;
  599. if($userPref != null) {
  600. $bool = ($userPref == 'on') ? true : false;
  601. $showFullName = $bool;
  602. } else {
  603. $showFullName = $sysPref;
  604. }
  605. }
  606. return $showFullName;
  607. }
  608. function clean($string, $maxLength)
  609. {
  610. $string = substr($string, 0, $maxLength);
  611. return escapeshellcmd($string);
  612. }
  613. /**
  614. * Copy the specified request variable to the member variable of the specified object.
  615. * Do no copy if the member variable is already set.
  616. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  617. * All Rights Reserved.
  618. * Contributor(s): ______________________________________..
  619. */
  620. function safe_map($request_var, & $focus, $always_copy = false)
  621. {
  622. safe_map_named($request_var, $focus, $request_var, $always_copy);
  623. }
  624. /**
  625. * Copy the specified request variable to the member variable of the specified object.
  626. * Do no copy if the member variable is already set.
  627. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  628. * All Rights Reserved.
  629. * Contributor(s): ______________________________________..
  630. */
  631. function safe_map_named($request_var, & $focus, $member_var, $always_copy)
  632. {
  633. if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) {
  634. $GLOBALS['log']->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var");
  635. $focus->$member_var = $_REQUEST[$request_var];
  636. }
  637. }
  638. /**
  639. * This function retrieves an application language file and returns the array of strings included in the $app_list_strings var.
  640. *
  641. * @param string $language specific language to load
  642. * @return array lang strings
  643. */
  644. function return_app_list_strings_language($language)
  645. {
  646. global $app_list_strings;
  647. global $sugar_config;
  648. $cache_key = 'app_list_strings.'.$language;
  649. // Check for cached value
  650. $cache_entry = sugar_cache_retrieve($cache_key);
  651. if(!empty($cache_entry))
  652. {
  653. return $cache_entry;
  654. }
  655. $default_language = $sugar_config['default_language'];
  656. $temp_app_list_strings = $app_list_strings;
  657. $langs = array();
  658. if ($language != 'en_us') {
  659. $langs[] = 'en_us';
  660. }
  661. if ($default_language != 'en_us' && $language != $default_language) {
  662. $langs[] = $default_language;
  663. }
  664. $langs[] = $language;
  665. $app_list_strings_array = array();
  666. foreach ( $langs as $lang ) {
  667. $app_list_strings = array();
  668. if(file_exists("include/language/$lang.lang.php")) {
  669. include("include/language/$lang.lang.php");
  670. $GLOBALS['log']->info("Found language file: $lang.lang.php");
  671. }
  672. if(file_exists("include/language/$lang.lang.override.php")) {
  673. include("include/language/$lang.lang.override.php");
  674. $GLOBALS['log']->info("Found override language file: $lang.lang.override.php");
  675. }
  676. if(file_exists("include/language/$lang.lang.php.override")) {
  677. include("include/language/$lang.lang.php.override");
  678. $GLOBALS['log']->info("Found override language file: $lang.lang.php.override");
  679. }
  680. $app_list_strings_array[] = $app_list_strings;
  681. }
  682. $app_list_strings = array();
  683. foreach ( $app_list_strings_array as $app_list_strings_item ) {
  684. $app_list_strings = sugarArrayMerge($app_list_strings, $app_list_strings_item);
  685. }
  686. foreach ( $langs as $lang ) {
  687. if(file_exists("custom/application/Ext/Language/$lang.lang.ext.php")) {
  688. $app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/$lang.lang.ext.php" , $app_list_strings);
  689. $GLOBALS['log']->info("Found extended language file: $lang.lang.ext.php");
  690. }
  691. if(file_exists("custom/include/language/$lang.lang.php")) {
  692. include("custom/include/language/$lang.lang.php");
  693. $GLOBALS['log']->info("Found custom language file: $lang.lang.php");
  694. }
  695. }
  696. if(!isset($app_list_strings)) {
  697. $GLOBALS['log']->fatal("Unable to load the application language file for the selected language ($language) or the default language ($default_language) or the en_us language");
  698. return null;
  699. }
  700. $return_value = $app_list_strings;
  701. $app_list_strings = $temp_app_list_strings;
  702. sugar_cache_put($cache_key, $return_value);
  703. return $return_value;
  704. }
  705. /**
  706. * The dropdown items in custom language files is $app_list_strings['$key']['$second_key'] = $value not
  707. * $GLOBALS['app_list_strings']['$key'] = $value, so we have to delete the original ones in app_list_strings and relace it with the custom ones.
  708. * @param file string the language that you want include,
  709. * @param app_list_strings array the golbal strings
  710. * @return array
  711. */
  712. //jchi 25347
  713. function _mergeCustomAppListStrings($file , $app_list_strings){
  714. $app_list_strings_original = $app_list_strings;
  715. unset($app_list_strings);
  716. include($file);
  717. if(!isset($app_list_strings) || !is_array($app_list_strings)){
  718. return $app_list_strings_original;
  719. }
  720. //Bug 25347: We should not merge custom dropdown fields unless they relate to parent fields or the module list.
  721. foreach($app_list_strings as $key=>$value)
  722. {
  723. $exemptDropdowns = array("moduleList", "parent_type_display", "record_type_display", "record_type_display_notes");
  724. if (!in_array($key, $exemptDropdowns) && array_key_exists($key, $app_list_strings_original))
  725. {
  726. unset($app_list_strings_original["$key"]);
  727. }
  728. }
  729. $app_list_strings = sugarArrayMergeRecursive($app_list_strings_original , $app_list_strings);
  730. return $app_list_strings;
  731. }
  732. /**
  733. * This function retrieves an application language file and returns the array of strings included.
  734. *
  735. * @param string $language specific language to load
  736. * @return array lang strings
  737. */
  738. function return_application_language($language)
  739. {
  740. global $app_strings, $sugar_config;
  741. $cache_key = 'app_strings.'.$language;
  742. // Check for cached value
  743. $cache_entry = sugar_cache_retrieve($cache_key);
  744. if(!empty($cache_entry))
  745. {
  746. return $cache_entry;
  747. }
  748. $temp_app_strings = $app_strings;
  749. $default_language = $sugar_config['default_language'];
  750. $langs = array();
  751. if ($language != 'en_us') {
  752. $langs[] = 'en_us';
  753. }
  754. if ($default_language != 'en_us' && $language != $default_language) {
  755. $langs[] = $default_language;
  756. }
  757. $langs[] = $language;
  758. $app_strings_array = array();
  759. foreach ( $langs as $lang ) {
  760. $app_strings = array();
  761. if(file_exists("include/language/$lang.lang.php")) {
  762. include("include/language/$lang.lang.php");
  763. $GLOBALS['log']->info("Found language file: $lang.lang.php");
  764. }
  765. if(file_exists("include/language/$lang.lang.override.php")) {
  766. include("include/language/$lang.lang.override.php");
  767. $GLOBALS['log']->info("Found override language file: $lang.lang.override.php");
  768. }
  769. if(file_exists("include/language/$lang.lang.php.override")) {
  770. include("include/language/$lang.lang.php.override");
  771. $GLOBALS['log']->info("Found override language file: $lang.lang.php.override");
  772. }
  773. if(file_exists("custom/application/Ext/Language/$lang.lang.ext.php")) {
  774. include("custom/application/Ext/Language/$lang.lang.ext.php");
  775. $GLOBALS['log']->info("Found extended language file: $lang.lang.ext.php");
  776. }
  777. if(file_exists("custom/include/language/$lang.lang.php")) {
  778. include("custom/include/language/$lang.lang.php");
  779. $GLOBALS['log']->info("Found custom language file: $lang.lang.php");
  780. }
  781. $app_strings_array[] = $app_strings;
  782. }
  783. $app_strings = array();
  784. foreach ( $app_strings_array as $app_strings_item ) {
  785. $app_strings = sugarArrayMerge($app_strings, $app_strings_item);
  786. }
  787. if(!isset($app_strings)) {
  788. $GLOBALS['log']->fatal("Unable to load the application language strings");
  789. return null;
  790. }
  791. // If we are in debug mode for translating, turn on the prefix now!
  792. if($sugar_config['translation_string_prefix']) {
  793. foreach($app_strings as $entry_key=>$entry_value) {
  794. $app_strings[$entry_key] = $language.' '.$entry_value;
  795. }
  796. }
  797. if(isset($_SESSION['show_deleted'])) {
  798. $app_strings['LBL_DELETE_BUTTON'] = $app_strings['LBL_UNDELETE_BUTTON'];
  799. $app_strings['LBL_DELETE_BUTTON_LABEL'] = $app_strings['LBL_UNDELETE_BUTTON_LABEL'];
  800. $app_strings['LBL_DELETE_BUTTON_TITLE'] = $app_strings['LBL_UNDELETE_BUTTON_TITLE'];
  801. $app_strings['LBL_DELETE'] = $app_strings['LBL_UNDELETE'];
  802. }
  803. $app_strings['LBL_ALT_HOT_KEY'] = get_alt_hot_key();
  804. $return_value = $app_strings;
  805. $app_strings = $temp_app_strings;
  806. sugar_cache_put($cache_key, $return_value);
  807. return $return_value;
  808. }
  809. /**
  810. * This function retrieves a module's language file and returns the array of strings included.
  811. *
  812. * @param string $language specific language to load
  813. * @param string $module module name to load strings for
  814. * @param bool $refresh optional, true if you want to rebuild the language strings
  815. * @return array lang strings
  816. */
  817. function return_module_language($language, $module, $refresh=false)
  818. {
  819. global $mod_strings;
  820. global $sugar_config;
  821. global $currentModule;
  822. // Jenny - Bug 8119: Need to check if $module is not empty
  823. if (empty($module)) {
  824. $stack = debug_backtrace();
  825. $GLOBALS['log']->warn("Variable module is not in return_module_language ". var_export($stack, true));
  826. return array();
  827. }
  828. $cache_key = "mod_strings_lang.".$language.$module;
  829. // Check for cached value
  830. $cache_entry = sugar_cache_retrieve($cache_key);
  831. if(!empty($cache_entry))
  832. {
  833. return $cache_entry;
  834. }
  835. // Store the current mod strings for later
  836. $temp_mod_strings = $mod_strings;
  837. $loaded_mod_strings = array();
  838. $language_used = $language;
  839. $default_language = $sugar_config['default_language'];
  840. if(empty($language)) {
  841. $language = $default_language;
  842. }
  843. // Bug 21559 - So we can get all the strings defined in the template, refresh
  844. // the vardefs file if the cached language file doesn't exist.
  845. if(!file_exists($GLOBALS['sugar_config']['cache_dir'].'modules/'. $module . '/language/'.$language.'.lang.php')
  846. && !empty($GLOBALS['beanList'][$module])){
  847. $object = $GLOBALS['beanList'][$module];
  848. if ($object == 'aCase') {
  849. $object = 'Case';
  850. }
  851. VardefManager::refreshVardefs($module,$object);
  852. }
  853. $loaded_mod_strings = LanguageManager::loadModuleLanguage($module, $language,$refresh);
  854. // cn: bug 6048 - merge en_us with requested language
  855. if($language != $sugar_config['default_language'])
  856. $loaded_mod_strings = sugarArrayMerge(
  857. LanguageManager::loadModuleLanguage($module, $sugar_config['default_language'],$refresh),
  858. $loaded_mod_strings
  859. );
  860. // Load in en_us strings by default
  861. if($language != 'en_us' && $sugar_config['default_language'] != 'en_us')
  862. $loaded_mod_strings = sugarArrayMerge(
  863. LanguageManager::loadModuleLanguage($module, 'en_us', $refresh),
  864. $loaded_mod_strings
  865. );
  866. // If we are in debug mode for translating, turn on the prefix now!
  867. if($sugar_config['translation_string_prefix']) {
  868. foreach($loaded_mod_strings as $entry_key=>$entry_value) {
  869. $loaded_mod_strings[$entry_key] = $language_used.' '.$entry_value;
  870. }
  871. }
  872. $return_value = $loaded_mod_strings;
  873. if(!isset($mod_strings)){
  874. $mod_strings = $return_value;
  875. }
  876. else
  877. $mod_strings = $temp_mod_strings;
  878. sugar_cache_put($cache_key, $return_value);
  879. return $return_value;
  880. }
  881. /** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var.
  882. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  883. * All Rights Reserved.
  884. * Contributor(s): ______________________________________..
  885. * If you are using the current language, do not call this function unless you are loading it for the first time */
  886. function return_mod_list_strings_language($language,$module) {
  887. global $mod_list_strings;
  888. global $sugar_config;
  889. global $currentModule;
  890. $cache_key = "mod_list_str_lang.".$language.$module;
  891. // Check for cached value
  892. $cache_entry = sugar_cache_retrieve($cache_key);
  893. if(!empty($cache_entry))
  894. {
  895. return $cache_entry;
  896. }
  897. $language_used = $language;
  898. $temp_mod_list_strings = $mod_list_strings;
  899. $default_language = $sugar_config['default_language'];
  900. if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) {
  901. return $mod_list_strings;
  902. }
  903. // cn: bug 6351 - include en_us if file langpack not available
  904. // cn: bug 6048 - merge en_us with requested language
  905. include("modules/$module/language/en_us.lang.php");
  906. $en_mod_list_strings = array();
  907. if($language_used != $default_language)
  908. $en_mod_list_strings = $mod_list_strings;
  909. if(file_exists("modules/$module/language/$language.lang.php")) {
  910. include("modules/$module/language/$language.lang.php");
  911. }
  912. if(file_exists("modules/$module/language/$language.lang.override.php")){
  913. include("modules/$module/language/$language.lang.override.php");
  914. }
  915. if(file_exists("modules/$module/language/$language.lang.php.override")){
  916. echo 'Please Change:<br>' . "modules/$module/language/$language.lang.php.override" . '<br>to<br>' . 'Please Change:<br>' . "modules/$module/language/$language.lang.override.php";
  917. include("modules/$module/language/$language.lang.php.override");
  918. }
  919. // cn: bug 6048 - merge en_us with requested language
  920. $mod_list_strings = sugarArrayMerge($en_mod_list_strings, $mod_list_strings);
  921. // if we still don't have a language pack, then log an error
  922. if(!isset($mod_list_strings)) {
  923. $GLOBALS['log']->fatal("Unable to load the application list language file for the selected language($language) or the default language($default_language) for module({$module})");
  924. return null;
  925. }
  926. $return_value = $mod_list_strings;
  927. $mod_list_strings = $temp_mod_list_strings;
  928. sugar_cache_put($cache_key, $return_value);
  929. return $return_value;
  930. }
  931. /** This function retrieves a theme's language file and returns the array of strings included.
  932. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  933. * All Rights Reserved.
  934. * Contributor(s): ______________________________________..
  935. */
  936. function return_theme_language($language, $theme)
  937. {
  938. global $mod_strings, $sugar_config, $currentModule;
  939. $language_used = $language;
  940. $default_language = $sugar_config['default_language'];
  941. include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php");
  942. if(file_exists(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.override.php")){
  943. include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.override.php");
  944. }
  945. if(file_exists(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php.override")){
  946. echo 'Please Change:<br>' . SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php.override" . '<br>to<br>' . 'Please Change:<br>' . SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.override.php";
  947. include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php.override");
  948. }
  949. if(!isset($theme_strings))
  950. {
  951. $GLOBALS['log']->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme);
  952. require(SugarThemeRegistry::get($theme)->getFilePath()."/language/$default_language.lang.php");
  953. $language_used = $default_language;
  954. }
  955. if(!isset($theme_strings))
  956. {
  957. $GLOBALS['log']->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)");
  958. return null;
  959. }
  960. // If we are in debug mode for translating, turn on the prefix now!
  961. if($sugar_config['translation_string_prefix'])
  962. {
  963. foreach($theme_strings as $entry_key=>$entry_value)
  964. {
  965. $theme_strings[$entry_key] = $language_used.' '.$entry_value;
  966. }
  967. }
  968. return $theme_strings;
  969. }
  970. /** If the session variable is defined and is not equal to "" then return it. Otherwise, return the default value.
  971. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  972. * All Rights Reserved.
  973. * Contributor(s): ______________________________________..
  974. */
  975. function return_session_value_or_default($varname, $default)
  976. {
  977. if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "")
  978. {
  979. return $_SESSION[$varname];
  980. }
  981. return $default;
  982. }
  983. /**
  984. * Creates an array of where restrictions. These are used to construct a where SQL statement on the query
  985. * It looks for the variable in the $_REQUEST array. If it is set and is not "" it will create a where clause out of it.
  986. * @param &$where_clauses - The array to append the clause to
  987. * @param $variable_name - The name of the variable to look for an add to the where clause if found
  988. * @param $SQL_name - [Optional] If specified, this is the SQL column name that is used. If not specified, the $variable_name is used as the SQL_name.
  989. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  990. * All Rights Reserved.
  991. * Contributor(s): ______________________________________..
  992. */
  993. function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null)
  994. {
  995. if($SQL_name == null)
  996. {
  997. $SQL_name = $variable_name;
  998. }
  999. if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "")
  1000. {
  1001. array_push($where_clauses, "$SQL_name like '".$GLOBALS['db']->quote($_REQUEST[$variable_name])."%'");
  1002. }
  1003. }
  1004. /**
  1005. * Generate the appropriate SQL based on the where clauses.
  1006. * @param $where_clauses - An Array of individual where clauses stored as strings
  1007. * @returns string where_clause - The final SQL where clause to be executed.
  1008. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1009. * All Rights Reserved.
  1010. * Contributor(s): ______________________________________..
  1011. */
  1012. function generate_where_statement($where_clauses)
  1013. {
  1014. $where = "";
  1015. foreach($where_clauses as $clause)
  1016. {
  1017. if($where != "")
  1018. $where .= " and ";
  1019. $where .= $clause;
  1020. }
  1021. $GLOBALS['log']->info("Here is the where clause for the list view: $where");
  1022. return $where;
  1023. }
  1024. /**
  1025. * determines if a passed string matches the criteria for a Sugar GUID
  1026. * @param string $guid
  1027. * @return bool False on failure
  1028. */
  1029. function is_guid($guid) {
  1030. if(strlen($guid) != 36) {
  1031. return false;
  1032. }
  1033. if(preg_match("/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i", $guid)) {
  1034. return true;
  1035. }
  1036. return true;;
  1037. }
  1038. /**
  1039. * A temporary method of generating GUIDs of the correct format for our DB.
  1040. * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
  1041. *
  1042. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1043. * All Rights Reserved.
  1044. * Contributor(s): ______________________________________..
  1045. */
  1046. function create_guid()
  1047. {
  1048. $microTime = microtime();
  1049. list($a_dec, $a_sec) = explode(" ", $microTime);
  1050. $dec_hex = dechex($a_dec* 1000000);
  1051. $sec_hex = dechex($a_sec);
  1052. ensure_length($dec_hex, 5);
  1053. ensure_length($sec_hex, 6);
  1054. $guid = "";
  1055. $guid .= $dec_hex;
  1056. $guid .= create_guid_section(3);
  1057. $guid .= '-';
  1058. $guid .= create_guid_section(4);
  1059. $guid .= '-';
  1060. $guid .= create_guid_section(4);
  1061. $guid .= '-';
  1062. $guid .= create_guid_section(4);
  1063. $guid .= '-';
  1064. $guid .= $sec_hex;
  1065. $guid .= create_guid_section(6);
  1066. return $guid;
  1067. }
  1068. function create_guid_section($characters)
  1069. {
  1070. $return = "";
  1071. for($i=0; $i<$characters; $i++)
  1072. {
  1073. $return .= dechex(mt_rand(0,15));
  1074. }
  1075. return $return;
  1076. }
  1077. function ensure_length(&$string, $length)
  1078. {
  1079. $strlen = strlen($string);
  1080. if($strlen < $length)
  1081. {
  1082. $string = str_pad($string,$length,"0");
  1083. }
  1084. else if($strlen > $length)
  1085. {
  1086. $string = substr($string, 0, $length);
  1087. }
  1088. }
  1089. function microtime_diff($a, $b) {
  1090. list($a_dec, $a_sec) = explode(" ", $a);
  1091. list($b_dec, $b_sec) = explode(" ", $b);
  1092. return $b_sec - $a_sec + $b_dec - $a_dec;
  1093. }
  1094. // check if Studio is displayed.
  1095. function displayStudioForCurrentUser()
  1096. {
  1097. if ( is_admin($GLOBALS['current_user']) ) {
  1098. return true;
  1099. }
  1100. return true;
  1101. }
  1102. function displayWorkflowForCurrentUser()
  1103. {
  1104. $_SESSION['display_workflow_for_user'] = false;
  1105. return false;
  1106. }
  1107. // return an array with all modules where the user is an admin.
  1108. function get_admin_modules_for_user($user) {
  1109. global $beanList;
  1110. $admin_modules = array();
  1111. return ($admin_modules);
  1112. }
  1113. function get_workflow_admin_modules_for_user($user){
  1114. if (isset($_SESSION['get_workflow_admin_modules_for_user'])) {
  1115. return $_SESSION['get_workflow_admin_modules_for_user'];
  1116. }
  1117. global $moduleList;
  1118. $workflow_mod_list = array();
  1119. foreach($moduleList as $module){
  1120. $workflow_mod_list[$module] = $module;
  1121. }
  1122. // This list is taken from teh previous version of workflow_utils.php
  1123. $workflow_mod_list['Tasks'] = "Tasks";
  1124. $workflow_mod_list['Calls'] = "Calls";
  1125. $workflow_mod_list['Meetings'] = "Meetings";
  1126. $workflow_mod_list['Notes'] = "Notes";
  1127. $workflow_mod_list['ProjectTask'] = "Project Tasks";
  1128. $workflow_mod_list['Leads'] = "Leads";
  1129. $workflow_mod_list['Opportunities'] = "Opportunities";
  1130. // End of list
  1131. $workflow_admin_modules = array();
  1132. if(empty($user)) {
  1133. return $workflow_admin_modules;
  1134. }
  1135. $actions = ACLAction::getUserActions($user->id);
  1136. //check for ForecastSchedule because it doesn't exist in $workflow_mod_list
  1137. if (isset($actions['ForecastSchedule']['module']['admin']['aclaccess']) && ($actions['ForecastSchedule']['module']['admin']['aclaccess']==ACL_ALLOW_DEV ||
  1138. $actions['ForecastSchedule']['module']['admin']['aclaccess']==ACL_ALLOW_ADMIN_DEV)) {
  1139. $workflow_admin_modules['Forecasts'] = 'Forecasts';
  1140. }
  1141. foreach ($workflow_mod_list as $key=>$val) {
  1142. if(!in_array($val, $workflow_admin_modules) && ($val!='iFrames' && $val!='Feeds' && $val!='Home' && $val!='Dashboard'
  1143. && $val!='Calendar' && $val!='Activities' && $val!='Reports') &&
  1144. (is_admin_for_module($user,$key))) {
  1145. $workflow_admin_modules[$key] = $val;
  1146. }
  1147. }
  1148. $_SESSION['get_workflow_admin_modules_for_user'] = $workflow_admin_modules;
  1149. return ($workflow_admin_modules);
  1150. }
  1151. // Check if user is admin for at least one module.
  1152. function is_admin_for_any_module($user) {
  1153. return false;
  1154. }
  1155. // Check if user is admin for a specific module.
  1156. function is_admin_for_module($user,$module) {
  1157. return false;
  1158. }
  1159. /**
  1160. * Check if user id belongs to a system admin.
  1161. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1162. * All Rights Reserved.
  1163. * Contributor(s): ______________________________________..
  1164. */
  1165. function is_admin($user) {
  1166. if(!empty($user) && ($user->is_admin == '1' || $user->is_admin === 'on')){
  1167. return true;
  1168. }
  1169. return false;
  1170. }
  1171. /**
  1172. * Return the display name for a theme if it exists.
  1173. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1174. * All Rights Reserved.
  1175. * Contributor(s): ______________________________________..
  1176. *
  1177. * @deprecated use SugarThemeRegistry::get($theme)->name instead
  1178. */
  1179. function get_theme_display($theme)
  1180. {
  1181. return SugarThemeRegistry::get($theme)->name;
  1182. }
  1183. /**
  1184. * Return an array of directory names.
  1185. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1186. * All Rights Reserved.
  1187. * Contributor(s): ______________________________________..
  1188. *
  1189. * @deprecated use SugarThemeRegistry::availableThemes() instead.
  1190. */
  1191. function get_themes()
  1192. {
  1193. return SugarThemeRegistry::availableThemes();
  1194. }
  1195. /**
  1196. * THIS FUNCTION IS DEPRECATED AND SHOULD NOT BE USED; USE get_select_options_with_id()
  1197. * Create HTML to display select options in a dropdown list. To be used inside
  1198. * of a select statement in a form.
  1199. * param $option_list - the array of strings to that contains the option list
  1200. * param $selected - the string which contains the default value
  1201. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1202. * All Rights Reserved.
  1203. * Contributor(s): ______________________________________..
  1204. */
  1205. function get_select_options ($option_list, $selected) {
  1206. return get_select_options_with_id($option_list, $selected);
  1207. }
  1208. /**
  1209. * Create HTML to display select options in a dropdown list. To be used inside
  1210. * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The values are the display strings.
  1211. * param $option_list - the array of strings to that contains the option list
  1212. * param $selected - the string which contains the default value
  1213. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1214. * All Rights Reserved.
  1215. * Contributor(s): ______________________________________..
  1216. */
  1217. function get_select_options_with_id ($option_list, $selected_key) {
  1218. return get_select_options_with_id_separate_key($option_list, $option_list, $selected_key);
  1219. }
  1220. /**
  1221. * Create HTML to display select options in a dropdown list. To be used inside
  1222. * of a select statement in a form. This method expects the option list to have keys and values. The keys are the ids. The values are the display strings.
  1223. * param $label_list - the array of strings to that contains the option list
  1224. * param $key_list - the array of strings to that contains the values list
  1225. * param $selected - the string which contains the default value
  1226. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1227. * All Rights Reserved.
  1228. * Contributor(s): ______________________________________..
  1229. */
  1230. function get_select_options_with_id_separate_key ($label_list, $key_list, $selected_key, $massupdate=false) {
  1231. global $app_strings;
  1232. $select_options = "";
  1233. //for setting null selection values to human readable --None--
  1234. $pattern = "/'0?'></";
  1235. $replacement = "''>".$app_strings['LBL_NONE']."<";
  1236. if (empty($key_list)) $key_list = array();
  1237. //create the type dropdown domain and set the selected value if $opp value already exists
  1238. foreach ($key_list as $option_key=>$option_value) {
  1239. $selected_string = '';
  1240. // the system is evaluating $selected_key == 0 || '' to true. Be very careful when changing this. Test all cases.
  1241. // The bug was only happening with one of the users in the drop down. It was being replaced by none.
  1242. if (($option_key != '' && $selected_key == $option_key) || ($selected_key == '' && $option_key == '' && !$massupdate) || (is_array($selected_key) && in_array($option_key, $selected_key)))
  1243. {
  1244. $selected_string = 'selected ';
  1245. }
  1246. $html_value = $option_key;
  1247. $select_options .= "\n<OPTION ".$selected_string."value='$html_value'>$label_list[$option_key]</OPTION>";
  1248. }
  1249. $select_options = preg_replace($pattern, $replacement, $select_options);
  1250. return $select_options;
  1251. }
  1252. /**
  1253. * Call this method instead of die().
  1254. * Then we call the die method with the error message that is passed in.
  1255. */
  1256. function sugar_die($error_message)
  1257. {
  1258. global $focus;
  1259. sugar_cleanup();
  1260. die($error_message);
  1261. }
  1262. /**
  1263. * Create javascript to clear values of all elements in a form.
  1264. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1265. * All Rights Reserved.
  1266. * Contributor(s): ______________________________________..
  1267. */
  1268. function get_clear_form_js () {
  1269. $the_script = <<<EOQ
  1270. <script type="text/javascript" language="JavaScript">
  1271. function clear_form(form) {
  1272. var newLoc = 'index.php?action=' + form.action.value + '&module=' + form.module.value + '&query=true&clear_query=true';
  1273. if(typeof(form.advanced) != 'undefined'){
  1274. newLoc += '&advanced=' + form.advanced.value;
  1275. }
  1276. document.location.href= newLoc;
  1277. }
  1278. </script>
  1279. EOQ;
  1280. return $the_script;
  1281. }
  1282. /**
  1283. * Create javascript to set the cursor focus to specific field in a form
  1284. * when the screen is rendered. The field name is currently hardcoded into the
  1285. * the function.
  1286. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1287. * All Rights Reserved.
  1288. * Contributor(s): ______________________________________..
  1289. */
  1290. function get_set_focus_js () {
  1291. //TODO Clint 5/20 - Make this function more generic so that it can take in the target form and field names as variables
  1292. $the_script = <<<EOQ
  1293. <script type="text/javascript" language="JavaScript">
  1294. <!-- Begin
  1295. function set_focus() {
  1296. if (document.forms.length > 0) {
  1297. for (i = 0; i < document.forms.length; i++) {
  1298. for (j = 0; j < document.forms[i].elements.length; j++) {
  1299. var field = document.forms[i].elements[j];
  1300. if ((field.type == "text" || field.type == "textarea" || field.type == "password") &&
  1301. !field.disabled && (field.name == "first_name" || field.name == "name" || field.name == "user_name" || field.name=="document_name")) {
  1302. field.focus();
  1303. if (field.type == "text") {
  1304. field.select();
  1305. }
  1306. break;
  1307. }
  1308. }
  1309. }
  1310. }
  1311. }
  1312. // End -->
  1313. </script>
  1314. EOQ;
  1315. return $the_script;
  1316. }
  1317. /**
  1318. * Very cool algorithm for sorting multi-dimensional arrays. Found at http://us2.php.net/manual/en/function.array-multisort.php
  1319. * Syntax: $new_array = array_csort($array [, 'col1' [, SORT_FLAG [, SORT_FLAG]]]...);
  1320. * Explanation: $array is the array you want to sort, 'col1' is the name of the column
  1321. * you want to sort, SORT_FLAGS are : SORT_ASC, SORT_DESC, SORT_REGULAR, SORT_NUMERIC, SORT_STRING
  1322. * you can repeat the 'col',FLAG,FLAG, as often you want, the highest prioritiy is given to
  1323. * the first - so the array is sorted by the last given column first, then the one before ...
  1324. * Example: $array = array_csort($array,'town','age',SORT_DESC,'name');
  1325. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1326. * All Rights Reserved.
  1327. * Contributor(s): ______________________________________..
  1328. */
  1329. function array_csort() {
  1330. $args = func_get_args();
  1331. $marray = array_shift($args);
  1332. $i = 0;
  1333. $msortline = "return(array_multisort(";
  1334. foreach ($args as $arg) {
  1335. $i++;
  1336. if (is_string($arg)) {
  1337. foreach ($marray as $row) {
  1338. $sortarr[$i][] = $row[$arg];
  1339. }
  1340. } else {
  1341. $sortarr[$i] = $arg;
  1342. }
  1343. $msortline .= "\$sortarr[".$i."],";
  1344. }
  1345. $msortline .= "\$marray));";
  1346. eval($msortline);
  1347. return $marray;
  1348. }
  1349. /**
  1350. * Converts localized date format string to jscalendar format
  1351. * Example: $array = array_csort($array,'town','age',SORT_DESC,'name');
  1352. * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  1353. * All Rights Reserved.
  1354. * Contributor(s): ______________________________________..
  1355. */
  1356. function parse_calendardate($local_format) {
  1357. preg_match('/\(?([^-]{1})[^-]*-([^-]{1})[^-]*-([^-]{1})[^-]*\)/', $local_format, $matches);
  1358. $calendar_format = "%" . $matches[1] . "-%" . $matches[2] . "-%" . $matches[3];
  1359. return str_replace(array("y", "ᅣ1�7", "a", "j"), array("Y", "Y", "Y", "d"), $calendar_format);
  1360. }
  1361. function translate($string, $mod='', $selectedValue=''){
  1362. //$test_start = microtime();
  1363. //static $mod_strings_results = array();
  1364. if(!empty($mod)){
  1365. global $current_language;
  1366. //Bug 31275
  1367. if(isset($_REQUEST['login_language'])){
  1368. $current_language = ($_REQUEST['login_language'] == $current_language)? $current_language : $_REQUEST['login_language'];
  1369. }
  1370. $mod_strings = return_module_language($current_language, $mod);
  1371. }else{
  1372. global $mod_strings;
  1373. }
  1374. $returnValue = '';
  1375. global $app_strings, $app_list_strings;
  1376. if(isset($mod_strings[$string]))
  1377. $returnValue = $mod_strings[$string];
  1378. else if(isset($app_strings[$string]))
  1379. $returnValue = $app_strings[$string];
  1380. else if(isset($app_list_strings[$string]))
  1381. $returnValue = $app_list_strings[$string];
  1382. else if(isset($app_list_strings['moduleList']) && isset($app_list_strings['moduleList'][$string]))
  1383. $returnValue = $app_list_strings['moduleList'][$string];
  1384. //$test_end = microtime();
  1385. //
  1386. // $mod_strings_results[$mod] = microtime_diff($test_start,$test_end);
  1387. //
  1388. // echo("translate results:");
  1389. // $total_time = 0;
  1390. // $total_strings = 0;
  1391. // foreach($mod_strings_results as $key=>$value)
  1392. // {
  1393. // echo("Module $key \t\t time $value \t\t<br>");
  1394. // $total_time += $value;
  1395. // }
  1396. //
  1397. // echo("Total time: $total_time<br>");
  1398. if(empty($returnValue)){
  1399. return $string;
  1400. }
  1401. if(is_array($returnValue) && ! empty($selectedValue) && isset($returnValue[$selectedValue]) ){
  1402. return $returnValue[$selectedValue];
  1403. }
  1404. return $returnValue;
  1405. }
  1406. function unTranslateNum($num) {
  1407. static $dec_sep;
  1408. static $num_grp_sep;
  1409. global $current_user, $sugar_config;
  1410. if($dec_sep == null) {
  1411. $user_dec_sep = $current_user->getPreference('dec_sep');
  1412. $dec_sep = (empty($user_dec_sep) ? $sugar_config['default_decimal_seperator'] : $user_dec_sep);
  1413. }
  1414. if($num_grp_sep == null) {
  1415. $user_num_grp_sep = $current_user->getPreference('num_grp_sep');
  1416. $num_grp_sep = (empty($user_num_grp_sep) ? $sugar_config['default_number_grouping_seperator'] : $user_num_grp_sep);
  1417. }
  1418. $num = preg_replace("'" . preg_quote($num_grp_sep) . "'", '', $num);
  1419. $num = preg_replace("'" . preg_quote($dec_sep) . "'", '.', $num);
  1420. return $num;
  1421. }
  1422. function add_http($url) {
  1423. if(!preg_match("@://@i", $url)) {
  1424. $scheme = "http";
  1425. if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') {
  1426. $scheme = 'https';
  1427. }
  1428. return "{$scheme}://{$url}";
  1429. }
  1430. return $url;
  1431. }
  1432. /**
  1433. * returns a default array of XSS tags to clean
  1434. * @return array
  1435. */
  1436. function getDefaultXssTags() {
  1437. $tmp = array(
  1438. "applet" => "applet",
  1439. "base" => "base",
  1440. "embed" => "embed",
  1441. "form" => "form",
  1442. "frame" => "frame",
  1443. "frameset" => "frameset",
  1444. "iframe" => "iframe",
  1445. "import" => "\?import",
  1446. "layer" => "layer",
  1447. "link" => "link",
  1448. "object" => "object",
  1449. "script" => "script",
  1450. "xmp" => "xmp",
  1451. );
  1452. $ret = base64_encode(serialize($tmp));
  1453. return $ret;
  1454. }
  1455. /**
  1456. * Remove potential xss vectors from strings
  1457. * @param string str String to search for XSS attack vectors
  1458. * @param bool cleanImg Flag to allow <img> tags to survive - only used by InboundEmail for inline images.
  1459. * @return string
  1460. */
  1461. function remove_xss($str, $cleanImg=true)
  1462. {
  1463. $potentials = clean_xss($str, $cleanImg);
  1464. if(is_array($potentials) && !empty($potentials)) {
  1465. foreach($potentials as $bad) {
  1466. $str = str_replace($bad, "", $str);
  1467. }
  1468. }
  1469. return $str;
  1470. }
  1471. /**
  1472. * Detects typical XSS attack patterns
  1473. * @param string str String to search for XSS attack vectors
  1474. * @param bool cleanImg Flag to allow <img> tags to survive - only used by InboundEmail for inline images.
  1475. * @return array Array of matches, empty on clean string
  1476. */
  1477. function clean_xss($str, $cleanImg=true) {
  1478. global $sugar_config;
  1479. if(empty($sugar_config['email_xss']))
  1480. $sugar_config['email_xss'] = getDefaultXssTags();
  1481. $arr = unserialize(base64_decode($sugar_config['email_xss']));
  1482. $regex = '';
  1483. foreach($arr as $v) {
  1484. if(!empty($regex)) {
  1485. $regex .= "|";
  1486. }
  1487. $regex .= $v;
  1488. }
  1489. $tag_regex = "#<({$regex})[^>]*>?#sim";
  1490. // cn: bug 13079 - "on\w" matched too many non-events (cONTact, strONG, etc.)
  1491. $jsEvents = "onblur|onfocus|oncontextmenu|onresize|onscroll|onunload|ondblclick|onclick|";
  1492. $jsEvents .= "onmouseup|onmouseover|onmousedown|onmouseenter|onmouseleave|onmousemove|onload|onchange|";
  1493. $jsEvents .= "onreset|onselect|onsubmit|onkeydown|onkeypress|onkeyup|onabort|onerror|ondragdrop";
  1494. $attribute_regex = "#<[^/>][^>]+({$jsEvents})[^=>]*=[^>]*>#sim";
  1495. $javascript_regex = '@<[^/>][^>]+(expression\(|j\W*a\W*v\W*a|v\W*b\W*s\W*c\W*r|&#|/\*|\*/)[^>]*>@sim';
  1496. $imgsrc_regex = '#<[^>]+src[^=]*=([^>]*?http://[^>]*)>#sim';
  1497. $css_url = '#url\(.*\.\w+\)#';
  1498. $str = str_replace("\t", "", $str);
  1499. $matches = array_merge(
  1500. xss_check_pattern($tag_regex, $str),
  1501. xss_check_pattern($javascript_regex, $str),
  1502. xss_check_pattern($attribute_regex, $str)
  1503. );
  1504. if($cleanImg) {
  1505. $matches = array_merge($matches,
  1506. xss_check_pattern($imgsrc_regex, $str)
  1507. );
  1508. }
  1509. // cn: bug 13498 - custom white-list of allowed domains that vet remote images
  1510. preg_match_all($css_url, $str, $cssUrlMatches, PREG_PATTERN_ORDER);
  1511. if(isset($sugar_config['security_trusted_domains']) && !empty($sugar_config['security_trusted_domains']) && is_array($sugar_config['security_trusted_domains'])) {
  1512. if(is_array($cssUrlMatches) && count($cssUrlMatches) > 0) {
  1513. // normalize whitelist
  1514. foreach($sugar_config['security_trusted_domains'] as $k => $v) {
  1515. $sugar_config['security_trusted_domains'][$k] = strtolower($v);
  1516. }
  1517. foreach($cssUrlMatches[0] as $match) {
  1518. $domain = strtolower(substr(strstr($match, "://"), 3));
  1519. $baseUrl = substr($domain, 0, strpos($domain, "/"));
  1520. if(!in_array($baseUrl, $sugar_config['security_trusted_domains'])) {
  1521. $matches[] = $match;
  1522. }
  1523. }
  1524. }
  1525. } else {
  1526. $matches = array_merge($matches, $cssUrlMatches[0]);
  1527. }
  1528. return $matches;
  1529. }
  1530. /**
  1531. * Helper function used by clean_xss() to parse for known-bad vectors
  1532. * @param string pattern Regex pattern to use
  1533. * @param string str String to parse for badness
  1534. * @return array
  1535. */
  1536. function xss_check_pattern($pattern, $str) {
  1537. preg_match_all($pattern, $str, $matches, PREG_PATTERN_ORDER);
  1538. return $matches[1];
  1539. }
  1540. // Designed to take a string passed in the URL as a parameter and clean all "bad" data from it
  1541. // The second argument is a string, "filter," which corresponds to a regular expression
  1542. function clean_string($str, $filter = "STANDARD") {
  1543. global $sugar_config;
  1544. $filters = Array(
  1545. "STANDARD" => '#[^A-Z0-9\-_\.\@]#i',
  1546. "STANDARDSPACE" => '#[^A-Z0-9\-_\.\@\ ]#i',
  1547. "FILE" => '#[^A-Z0-9\-_\.]#i',
  1548. "NUMBER" => '#[^0-9\-]#i',
  1549. "SQL_COLUMN_LIST" => '#[^A-Z0-9,_\.]#i',
  1550. "PATH_NO_URL" => '#://#i',
  1551. "SAFED_GET" => '#[^A-Z0-9\@\=\&\?\.\/\-_~]#i', /* range of allowed characters in a GET string */
  1552. "UNIFIED_SEARCH" => "#[\\x00]#", /* cn: bug 3356 & 9236 - MBCS search strings */
  1553. "AUTO_INCREMENT" => '#[^0-9\-,\ ]#i',
  1554. "ALPHANUM" => '#[^A-Z0-9\-]#i',
  1555. );
  1556. if (preg_match($filters[$filter], $str)) {
  1557. if (isset($GLOBALS['log']) && is_object($GLOBALS['log'])) {
  1558. $GLOBALS['log']->fatal("SECURITY: bad data passed in; string: {$str}");
  1559. }
  1560. die("Bad data passed in; <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
  1561. }
  1562. else {
  1563. return $str;
  1564. }
  1565. }
  1566. function clean_special_arguments() {
  1567. if(isset($_SERVER['PHP_SELF'])) {
  1568. if (!empty($_SERVER['PHP_SELF'])) clean_string($_SERVER['PHP_SELF'], 'SAFED_GET');
  1569. }
  1570. if (!empty($_REQUEST) && !empty($_REQUEST['login_theme'])) clean_string($_REQUEST['login_theme'], "STANDARD");
  1571. if (!empty($_REQUEST) && !empty($_REQUEST['login_module'])) clean_string($_REQUEST['login_module'], "STANDARD");
  1572. if (!empty($_REQUEST) && !empty($_REQUEST['login_action'])) clean_string($_REQUEST['login_action'], "STANDARD");
  1573. if (!empty($_REQUEST) && !empty($_REQUEST['ck_login_theme_20'])) clean_string($_REQUEST['ck_login_theme_20'], "STANDARD");
  1574. if (!empty($_SESSION) && !empty($_SESSION['authenticated_user_theme'])) clean_string($_SESSION['authenticated_user_theme'], "STANDARD");
  1575. if (!empty($_REQUEST) && !empty($_REQUEST['module_name'])) clean_string($_REQUEST['module_name'], "STANDARD");
  1576. if (!empty($_REQUEST) && !empty($_REQUEST['module'])) clean_string($_REQUEST['module'], "STANDARD");
  1577. if (!empty($_POST) && !empty($_POST['parent_type'])) clean_string($_POST['parent_type'], "STANDARD");
  1578. if (!empty($_REQUEST) && !empty($_REQUEST['mod_lang'])) clean_string($_REQUEST['mod_lang'], "STANDARD");
  1579. if (!empty($_SESSION) && !empty($_SESSION['authenticated_user_language'])) clean_string($_SESSION['authenticated_user_language'], "STANDARD");
  1580. if (!empty($_SESSION) && !empty($_SESSION['dyn_layout_file'])) clean_string($_SESSION['dyn_layout_file'], "PATH_NO_URL");
  1581. if (!empty($_GET) && !empty($_GET['from'])) clean_string($_GET['from']);
  1582. if (!empty($_GET) && !empty($_GET['gmto'])) clean_string($_GET['gmto'], "NUMBER");
  1583. if (!empty($_GET) && !empty($_GET['case_number'])) clean_string($_GET['case_number'], "AUTO_INCREMENT");
  1584. if (!empty($_GET) && !empty($_GET['bug_number'])) clean_string($_GET['bug_number'], "AUTO_INCREMENT");
  1585. if (!empty($_GET) && !empty($_GET['quote_num'])) clean_string($_GET['quote_num'], "AUTO_INCREMENT");
  1586. clean_superglobals('stamp', 'ALPHANUM'); // for vcr controls
  1587. clean_superglobals('offset', 'ALPHANUM');
  1588. clean_superglobals('return_action');
  1589. clean_superglobals('return_module');
  1590. return TRUE;
  1591. }
  1592. /**
  1593. * cleans the given key in superglobals $_GET, $_POST, $_REQUEST
  1594. */
  1595. function clean_superglobals($key, $filter = 'STANDARD') {
  1596. if(isset($_GET[$key])) clean_string($_GET[$key], $filter);
  1597. if(isset($_POST[$key])) clean_string($_POST[$key], $filter);
  1598. if(isset($_REQUEST[$key])) clean_string($_REQUEST[$key], $filter);
  1599. }
  1600. function set_superglobals($key, $val){
  1601. $_GET[$key] = $val;
  1602. $_POST[$key] = $val;
  1603. $_REQUEST[$key] = $val;
  1604. }
  1605. // Works in conjunction with clean_string() to defeat SQL injection, file inclusion attacks, and XSS
  1606. function clean_incoming_data() {
  1607. global $sugar_config;
  1608. if (get_magic_quotes_gpc() == 1) {
  1609. $req = array_map("preprocess_param", $_REQUEST);
  1610. $post = array_map("preprocess_param", $_POST);
  1611. $get = array_map("preprocess_param", $_GET);
  1612. } else {
  1613. $req = array_map("securexss", $_REQUEST);
  1614. $post = array_map("securexss", $_POST);
  1615. $get = array_map("securexss", $_GET);
  1616. }
  1617. // PHP cannot stomp out superglobals reliably
  1618. foreach($post as $k => $v) { $_POST[$k] = $v; }
  1619. foreach($get as $k => $v) { $_GET[$k] = $v; }
  1620. foreach($req as $k => $v) {
  1621. $_REQUEST[$k] = $v;
  1622. //ensure the keys are safe as well
  1623. securexsskey($k);
  1624. }
  1625. // Any additional variables that need to be cleaned should be added here
  1626. if (isset($_REQUEST['login_theme'])) clean_string($_REQUEST['login_theme']);
  1627. if (isset($_REQUEST['login_module'])) clean_string($_REQUEST['login_module']);
  1628. if (isset($_REQUEST['login_action'])) clean_string($_REQUEST['login_action']);
  1629. if (isset($_REQUEST['login_language'])) clean_string($_REQUEST['login_language']);
  1630. if (isset($_REQUEST['action'])) clean_string($_REQUEST['action']);
  1631. if (isset($_REQUEST['module'])) clean_string($_REQUEST['module']);
  1632. if (isset($_REQUEST['record'])) clean_string($_REQUEST['record'], 'STANDARDSPACE');
  1633. if (isset($_SESSION['authenticated_user_theme'])) clean_string($_SESSION['authenticated_user_theme']);
  1634. if (isset($_SESSION['authenticated_user_language'])) clean_string($_SESSION['authenticated_user_language']);
  1635. if (isset($_REQUEST['language'])) clean_string($_REQUEST['language']);
  1636. if (isset($sugar_config['default_theme'])) clean_string($sugar_config['default_theme']);
  1637. if (isset($_REQUEST['offset'])) clean_string($_REQUEST['offset']);
  1638. if (isset($_REQUEST['stamp'])) clean_string($_REQUEST['stamp']);
  1639. if(isset($_REQUEST['lvso'])){
  1640. set_superglobals('lvso', (strtolower($_REQUEST['lvso']) === 'desc')?'desc':'asc');
  1641. }
  1642. // Clean "offset" and "order_by" parameters in URL
  1643. foreach ($_REQUEST as $key => $val) {
  1644. if (str_end($key, "_offset")) {
  1645. clean_string($_REQUEST[$key], "ALPHANUM"); // keep this ALPHANUM for disable_count_query
  1646. set_superglobals($key, $_REQUEST[$key]);
  1647. }
  1648. elseif (str_end($key, "_ORDER_BY")) {
  1649. clean_string($_REQUEST[$key], "SQL_COLUMN_LIST");
  1650. set_superglobals($key, $_REQUEST[$key]);
  1651. }
  1652. }
  1653. return 0;
  1654. }
  1655. // Returns TRUE if $str begins with $begin
  1656. function str_begin($str, $begin) {
  1657. return (substr($str, 0, strlen($begin)) == $begin);
  1658. }
  1659. // Returns TRUE if $str ends with $end
  1660. function str_end($str, $end) {
  1661. return (substr($str, strlen($str) - strlen($end)) == $end);
  1662. }
  1663. function securexss($value) {
  1664. if(is_array($value)){
  1665. $new = array();
  1666. foreach($value as $key=>$val){
  1667. $new[$key] = securexss($val);
  1668. }
  1669. return $new;
  1670. }
  1671. static $xss_cleanup= array('"' =>'&quot;', "'" => '&#039;' , '<' =>'&lt;' , '>'=>'&gt;');
  1672. $value = preg_replace(array('/javascript:/i', '/\0/'), array('java script:', ''), $value);
  1673. $value = preg_replace('/javascript:/i', 'java script:', $value);
  1674. return str_replace(array_keys($xss_cleanup), array_values($xss_cleanup), $value);
  1675. }
  1676. function securexsskey($value, $die=true){
  1677. global $sugar_config;
  1678. $matches = array();
  1679. preg_match("/[\'\"\<\>]/", $value, $matches);
  1680. if(!empty($matches)){
  1681. if($die){
  1682. die("Bad data passed in; <a href=\"{$sugar_config['site_url']}\">Return to Home</a>");
  1683. }else{
  1684. unset($_REQUEST[$value]);
  1685. unset($_POST[$value]);
  1686. unset($_GET[$value]);
  1687. }
  1688. }
  1689. }
  1690. function preprocess_param($value){
  1691. if(is_string($value)){
  1692. if(get_magic_quotes_gpc() == 1){
  1693. $value = stripslashes($value);
  1694. }
  1695. $value = securexss($value);
  1696. }
  1697. return $value;
  1698. }
  1699. function set_register_value($category, $name, $value){
  1700. return sugar_cache_put("{$category}:{$name}", $value);
  1701. }
  1702. function get_register_value($category,$name){
  1703. return sugar_cache_retrieve("{$category}:{$name}");
  1704. }
  1705. // this function cleans id's when being imported
  1706. function convert_id($string)
  1707. {
  1708. return preg_replace_callback( '|[^A-Za-z0-9\-]|',
  1709. create_function(
  1710. // single quotes are essential here,
  1711. // or alternative escape all $ as \$
  1712. '$matches',
  1713. 'return ord($matches[0]);'
  1714. ) ,$string);
  1715. }
  1716. /**
  1717. * @deprecated use SugarTheme::getImage()
  1718. */
  1719. function get_image($image,$other_attributes,$width="",$height="")
  1720. {
  1721. return SugarThemeRegistry::current()->getImage(basename($image),
  1722. $other_attributes,
  1723. empty($width) ? null : $width,
  1724. empty($height) ? null : $height
  1725. );
  1726. }
  1727. /**
  1728. * @deprecated use SugarTheme::getImageURL()
  1729. */
  1730. function getImagePath($image_name)
  1731. {
  1732. return SugarThemeRegistry::current()->getImageURL($image_name);
  1733. }
  1734. function getWebPath($relative_path){
  1735. //if it has a :// then it isn't a relative path
  1736. if(substr_count($relative_path, '://') > 0) return $relative_path;
  1737. if(defined('TEMPLATE_URL'))$relative_path = SugarTemplateUtilities::getWebPath($relative_path);
  1738. return $relative_path;
  1739. }
  1740. function getJSPath($relative_path, $additional_attrs=''){
  1741. if(defined('TEMPLATE_URL'))$relative_path = SugarTemplateUtilities::getWebPath($relative_path);
  1742. if(empty($GLOBALS['sugar_config']['js_custom_version']))$GLOBALS['sugar_config']['js_custom_version'] = 1;
  1743. $js_version_key = isset($GLOBALS['js_version_key'])?$GLOBALS['js_version_key']:'';
  1744. $path = $relative_path . '?s=' . $js_version_key . '&c=' . $GLOBALS['sugar_config']['js_custom_version'] ;
  1745. if ( inDeveloperMode() ) $path .= '&developerMode='.mt_rand();
  1746. if(!empty($additonal_attrs)) $path .= '&' . $additional_attrs;
  1747. return $path;
  1748. }
  1749. function getSWFPath($relative_path, $additional_params=''){
  1750. $path = $relative_path;
  1751. if (!empty($additional_params)){
  1752. $path .= '?' . $additional_params;
  1753. }
  1754. if (defined('TEMPLATE_URL')){
  1755. $path = TEMPLATE_URL . '/' . $path;
  1756. }
  1757. return $path;
  1758. }
  1759. function getSQLDate($date_str)
  1760. {
  1761. if (preg_match('/^(\d{1,2})-(\d{1,2})-(\d{4})$/',$date_str,$match))
  1762. {
  1763. if ( strlen($match[2]) == 1)
  1764. {
  1765. $match[2] = "0".$match[2];
  1766. }
  1767. if ( strlen($match[1]) == 1)
  1768. {
  1769. $match[1] = "0".$match[1];
  1770. }
  1771. return "{$match[3]}-{$match[1]}-{$match[2]}";
  1772. }
  1773. else if (preg_match('/^(\d{1,2})\/(\d{1,2})\/(\d{4})$/',$date_str,$match))
  1774. {
  1775. if ( strlen($match[2]) == 1)
  1776. {
  1777. $match[2] = "0".$match[2];
  1778. }
  1779. if ( strlen($match[1]) == 1)
  1780. {
  1781. $match[1] = "0".$match[1];
  1782. }
  1783. return "{$match[3]}-{$match[1]}-{$match[2]}";
  1784. }
  1785. else
  1786. {
  1787. return "";
  1788. }
  1789. }
  1790. function clone_history(&$db, $from_id,$to_id, $to_type)
  1791. {
  1792. global $timedate;
  1793. $old_note_id=null;
  1794. $old_filename=null;
  1795. require_once('include/upload_file.php');
  1796. $tables = array('calls'=>'Call', 'meetings'=>'Meeting', 'notes'=>'Note', 'tasks'=>'Task');
  1797. $location=array('Email'=>"modules/Emails/Email.php",
  1798. 'Call'=>"modules/Calls/Call.php",
  1799. 'Meeting'=>"modules/Meetings/Meeting.php",
  1800. 'Note'=>"modules/Notes/Note.php",
  1801. 'Tasks'=>"modules/Tasks/Task.php",
  1802. );
  1803. foreach($tables as $table=>$bean_class)
  1804. {
  1805. if (!class_exists($bean_class))
  1806. {
  1807. require_once($location[$bean_class]);
  1808. }
  1809. $bProcessingNotes=false;
  1810. if ($table=='notes')
  1811. {
  1812. $bProcessingNotes=true;
  1813. }
  1814. $query = "SELECT id FROM $table WHERE parent_id='$from_id'";
  1815. $results = $db->query($query);
  1816. while($row = $db->fetchByAssoc($results))
  1817. {
  1818. //retrieve existing record.
  1819. $bean= new $bean_class();
  1820. $bean->retrieve($row['id']);
  1821. //process for new instance.
  1822. if ($bProcessingNotes)
  1823. {
  1824. $old_note_id=$row['id'];
  1825. $old_filename=$bean->filename;
  1826. }
  1827. $bean->id=null;
  1828. $bean->parent_id=$to_id;
  1829. $bean->parent_type=$to_type;
  1830. if ($to_type=='Contacts' and in_array('contact_id',$bean->column_fields))
  1831. {
  1832. $bean->contact_id=$to_id;
  1833. }
  1834. $bean->update_date_modified = false;
  1835. $bean->update_modified_by = false;
  1836. if(isset($bean->date_modified))
  1837. $bean->date_modified = $timedate->to_db($bean->date_modified);
  1838. if(isset($bean->date_entered))
  1839. $bean->date_entered = $timedate->to_db($bean->date_entered);
  1840. //save
  1841. $new_id=$bean->save();
  1842. //duplicate the file now. for notes.
  1843. if ($bProcessingNotes && !empty($old_filename))
  1844. {
  1845. UploadFile::duplicate_file($old_note_id,$new_id,$old_filename);
  1846. }
  1847. //reset the values needed for attachment duplication.
  1848. $old_note_id=null;
  1849. $old_filename=null;
  1850. }
  1851. }
  1852. }
  1853. function values_to_keys($array)
  1854. {
  1855. $new_array = array();
  1856. if(!is_array($array))
  1857. {
  1858. return $new_array;
  1859. }
  1860. foreach($array as $arr){
  1861. $new_array[$arr] = $arr;
  1862. }
  1863. return $new_array;
  1864. }
  1865. function clone_relationship(&$db, $tables = array(), $from_column, $from_id, $to_id)
  1866. {
  1867. foreach($tables as $table)
  1868. {
  1869. if ($table == 'emails_beans') {
  1870. $query = "SELECT * FROM $table WHERE $from_column='$from_id' and bean_module='Leads'";
  1871. } else {
  1872. $query = "SELECT * FROM $table WHERE $from_column='$from_id'";
  1873. }
  1874. $results = $db->query($query);
  1875. while($row = $db->fetchByAssoc($results))
  1876. {
  1877. $query = "INSERT INTO $table ";
  1878. $names = '';
  1879. $values = '';
  1880. $row[$from_column] = $to_id;
  1881. $row['id'] = create_guid();
  1882. if ($table=='emails_beans') {
  1883. $row['bean_module'] =='Contacts';
  1884. }
  1885. foreach($row as $name=>$value)
  1886. {
  1887. if(empty($names))
  1888. {
  1889. $names .= $name;
  1890. $values .= "'$value'";
  1891. } else
  1892. {
  1893. $names .= ', '. $name;
  1894. $values .= ", '$value'";
  1895. }
  1896. }
  1897. $query .= "($names) VALUES ($values)";
  1898. $db->query($query);
  1899. }
  1900. }
  1901. }
  1902. function get_unlinked_email_query($type, $bean) {
  1903. global $current_user;
  1904. $return_array['select']='SELECT emails.id ';
  1905. $return_array['from']='FROM emails ';
  1906. $return_array['where']="";
  1907. $return_array['join'] = " JOIN (select distinct email_id from emails_email_addr_rel eear
  1908. join email_addr_bean_rel eabr on eabr.bean_id ='$bean->id' and eabr.bean_module = '$bean->module_dir' and
  1909. eabr.email_address_id = eear.email_address_id and eabr.deleted=0
  1910. where eear.deleted=0 and eear.email_id not in
  1911. (select eb.email_id from emails_beans eb where eb.bean_module ='$bean->module_dir' and eb.bean_id = '$bean->id')
  1912. ) derivedemails on derivedemails.email_id = emails.id";
  1913. $return_array['join_tables'][0] = '';
  1914. if (isset($type) and isset($type['return_as_array']) and $type['return_as_array']==true) {
  1915. return $return_array;
  1916. }
  1917. return $return_array['select'] . $return_array['from'] . $return_array['where'];
  1918. } // fn
  1919. /**
  1920. * Check to see if the number is empty or non-zero
  1921. * @param $value
  1922. * @return boolean
  1923. **/
  1924. function number_empty($value)
  1925. {
  1926. return empty($value) && $value != '0';
  1927. }
  1928. function get_bean_select_array($add_blank=true, $bean_name, $display_columns, $where='', $order_by='', $blank_is_none=false)
  1929. {
  1930. global $beanFiles;
  1931. require_once($beanFiles[$bean_name]);
  1932. $focus = new $bean_name();
  1933. $user_array = array();
  1934. $user_array = get_register_value('select_array',$bean_name. $display_columns. $where . $order_by);
  1935. if(!$user_array)
  1936. {
  1937. $db = DBManagerFactory::getInstance();
  1938. $temp_result = Array();
  1939. $query = "SELECT id, {$display_columns} as display from {$focus->table_name} ";
  1940. $query .= "where ";
  1941. if ( $where != '')
  1942. {
  1943. $query .= $where." AND ";
  1944. }
  1945. $query .= " deleted=0";
  1946. if ( $order_by != '')
  1947. {
  1948. $query .= ' order by '.$order_by;
  1949. }
  1950. $GLOBALS['log']->debug("get_user_array query: $query");
  1951. $result = $db->query($query, true, "Error filling in user array: ");
  1952. if ($add_blank==true){
  1953. // Add in a blank row
  1954. if($blank_is_none == true) { // set 'blank row' to "--None--"
  1955. global $app_strings;
  1956. $temp_result[''] = $app_strings['LBL_NONE'];
  1957. } else {
  1958. $temp_result[''] = '';
  1959. }
  1960. }
  1961. // Get the id and the name.
  1962. while($row = $db->fetchByAssoc($result))
  1963. {
  1964. $temp_result[$row['id']] = $row['display'];
  1965. }
  1966. $user_array = $temp_result;
  1967. set_register_value('select_array',$bean_name. $display_columns. $where . $order_by,$temp_result);
  1968. }
  1969. return $user_array;
  1970. }
  1971. /**
  1972. *
  1973. *
  1974. * @param unknown_type $listArray
  1975. */
  1976. // function parse_list_modules
  1977. // searches a list for items in a user's allowed tabs and returns an array that removes unallowed tabs from list
  1978. function parse_list_modules(&$listArray)
  1979. {
  1980. global $modListHeader;
  1981. $returnArray = array();
  1982. foreach($listArray as $optionName => $optionVal)
  1983. {
  1984. if(array_key_exists($optionName, $modListHeader))
  1985. {
  1986. $returnArray[$optionName] = $optionVal;
  1987. }
  1988. // special case for projects
  1989. if(array_key_exists('Project', $modListHeader))
  1990. {
  1991. $returnArray['ProjectTask'] = $listArray['ProjectTask'];
  1992. }
  1993. }
  1994. $acldenied = ACLController::disabledModuleList($listArray,false);
  1995. foreach($acldenied as $denied){
  1996. unset($returnArray[$denied]);
  1997. }
  1998. asort($returnArray);
  1999. return $returnArray;
  2000. }
  2001. function display_notice($msg = false){
  2002. global $error_notice;
  2003. //no error notice - lets just display the error to the user
  2004. if(!isset($error_notice)){
  2005. echo '<br>'.$msg . '<br>';
  2006. }else{
  2007. $error_notice .= $msg . '<br>';
  2008. }
  2009. }
  2010. /* checks if it is a number that atleast has the plus at the beggining
  2011. */
  2012. function skype_formatted($number){
  2013. //kbrill - BUG #15375
  2014. if(isset($_REQUEST['action']) && $_REQUEST['action']=="Popup") {
  2015. return false;
  2016. } else {
  2017. return substr($number, 0, 1) == '+' || substr($number, 0, 2) == '00' || substr($number, 0, 3) == '011';
  2018. }
  2019. // return substr($number, 0, 1) == '+' || substr($number, 0, 2) == '00' || substr($number, 0, 2) == '011';
  2020. }
  2021. function format_skype($number) {
  2022. return preg_replace('/[^\+0-9]/','',$number);
  2023. }
  2024. function insert_charset_header() {
  2025. header('Content-Type: text/html; charset=UTF-8');
  2026. }
  2027. function getCurrentURL()
  2028. {
  2029. $href = "http:";
  2030. if(!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on')
  2031. {
  2032. $href = 'https:';
  2033. }
  2034. $href.= "//".$_SERVER['HTTP_HOST'].$_SERVER['SCRIPT_NAME'].'?'.$_SERVER['QUERY_STRING'];
  2035. return $href;
  2036. }
  2037. function javascript_escape($str) {
  2038. $new_str = '';
  2039. for($i = 0; $i < strlen($str); $i++) {
  2040. if(ord(substr($str, $i, 1))==10){
  2041. $new_str .= '\n';
  2042. }elseif(ord(substr($str, $i, 1))==13){
  2043. $new_str .= '\r';
  2044. }
  2045. else {
  2046. $new_str .= $str{$i};
  2047. }
  2048. }
  2049. $new_str = str_replace("'", "\\'", $new_str);
  2050. return $new_str;
  2051. }
  2052. function js_escape($str, $keep=true){
  2053. $str = html_entity_decode(str_replace("\\", "", $str), ENT_QUOTES);
  2054. if($keep){
  2055. $str = javascript_escape($str);
  2056. }
  2057. else {
  2058. $str = str_replace("'", " ", $str);
  2059. $str = str_replace('"', " ", $str);
  2060. }
  2061. return $str;
  2062. //end function js_escape
  2063. }
  2064. function br2nl($str) {
  2065. $regex = "#<[^>]+br.+?>#i";
  2066. preg_match_all($regex, $str, $matches);
  2067. foreach($matches[0] as $match) {
  2068. $str = str_replace($match, "<br>", $str);
  2069. }
  2070. $brs = array('<br>','<br/>', '<br />');
  2071. $str = str_replace("\r\n", "\n", $str); // make from windows-returns, *nix-returns
  2072. $str = str_replace("\n\r", "\n", $str); // make from windows-returns, *nix-returns
  2073. $str = str_replace("\r", "\n", $str); // make from windows-returns, *nix-returns
  2074. $str = str_ireplace($brs, "\n", $str); // to retrieve it
  2075. return $str;
  2076. }
  2077. /**
  2078. * Private helper function for displaying the contents of a given variable.
  2079. * This function is only intended to be used for SugarCRM internal development.
  2080. * The ppd stands for Pre Print Die.
  2081. */
  2082. function _ppd($mixed)
  2083. {
  2084. }
  2085. /**
  2086. * Private helper function for displaying the contents of a given variable in
  2087. * the Logger. This function is only intended to be used for SugarCRM internal
  2088. * development. The pp stands for Pre Print.
  2089. * @param $mixed var to print_r()
  2090. * @param $die boolean end script flow
  2091. * @param $displayStackTrace also show stack trace
  2092. */
  2093. function _ppl($mixed, $die=false, $displayStackTrace=false, $loglevel="fatal") {
  2094. }
  2095. /**
  2096. * private helper function to quickly show the major, direct, field attributes of a given bean.
  2097. * The ppf stands for Pre[formatted] Print Focus [object]
  2098. * @param object bean The focus bean
  2099. */
  2100. function _ppf($bean, $die=false) {
  2101. }
  2102. /**
  2103. * Private helper function for displaying the contents of a given variable.
  2104. * This function is only intended to be used for SugarCRM internal development.
  2105. * The pp stands for Pre Print.
  2106. */
  2107. function _pp($mixed)
  2108. {
  2109. }
  2110. /**
  2111. * Private helper function for displaying the contents of a given variable.
  2112. * This function is only intended to be used for SugarCRM internal development.
  2113. * The pp stands for Pre Print.
  2114. */
  2115. function _pstack_trace($mixed=NULL)
  2116. {
  2117. }
  2118. /**
  2119. * Private helper function for displaying the contents of a given variable.
  2120. * This function is only intended to be used for SugarCRM internal development.
  2121. * The pp stands for Pre Print Trace.
  2122. */
  2123. function _ppt($mixed, $textOnly=false)
  2124. {
  2125. }
  2126. /**
  2127. * Private helper function for displaying the contents of a given variable.
  2128. * This function is only intended to be used for SugarCRM internal development.
  2129. * The pp stands for Pre Print Trace Die.
  2130. */
  2131. function _pptd($mixed)
  2132. {
  2133. }
  2134. /**
  2135. * Private helper function for decoding javascript UTF8
  2136. * This function is only intended to be used for SugarCRM internal development.
  2137. */
  2138. function decodeJavascriptUTF8($str) {
  2139. }
  2140. /**
  2141. * Will check if a given PHP version string is supported (tested on this ver),
  2142. * unsupported (results unknown), or invalid (something will break on this
  2143. * ver). Do not pass in any pararameter to default to a check against the
  2144. * current environment's PHP version.
  2145. *
  2146. * @return 1 implies supported, 0 implies unsupported, -1 implies invalid
  2147. */
  2148. function check_php_version($sys_php_version = '') {
  2149. $sys_php_version = empty($sys_php_version) ? constant('PHP_VERSION') : $sys_php_version;
  2150. // versions below $min_considered_php_version considered invalid by default,
  2151. // versions equal to or above this ver will be considered depending
  2152. // on the rules that follow
  2153. $min_considered_php_version = '5.2.1';
  2154. // only the supported versions,
  2155. // should be mutually exclusive with $invalid_php_versions
  2156. $supported_php_versions = array (
  2157. '5.2.1', '5.2.2', '5.2.3', '5.2.4', '5.2.5', '5.2.6', '5.2.8', '5.3.0'
  2158. );
  2159. //Find out what Database the system is using.
  2160. global $sugar_config;
  2161. $dbType = '';
  2162. if (isset($_REQUEST['setup_db_type'])) {
  2163. $dbType = $_REQUEST['setup_db_type'];
  2164. } else if (isset ($sugar_config['dbconfig']) && isset ($sugar_config['dbconfig']['db_type'])) {
  2165. $dbType = $sugar_config['dbconfig']['db_type'];
  2166. }
  2167. // invalid versions above the $min_considered_php_version,
  2168. // should be mutually exclusive with $supported_php_versions
  2169. // SugarCRM prohibits install on PHP 5.2.7 on all platforms
  2170. $invalid_php_versions = array('5.2.7');
  2171. // default unsupported
  2172. $retval = 0;
  2173. // versions below $min_considered_php_version are invalid
  2174. if(1 == version_compare($sys_php_version, $min_considered_php_version, '<')) {
  2175. $retval = -1;
  2176. }
  2177. // supported version check overrides default unsupported
  2178. foreach($supported_php_versions as $ver) {
  2179. if(1 == version_compare($sys_php_version, $ver, 'eq') || strpos($sys_php_version,$ver) !== false) {
  2180. $retval = 1;
  2181. break;
  2182. }
  2183. }
  2184. // invalid version check overrides default unsupported
  2185. foreach($invalid_php_versions as $ver) {
  2186. if(1 == version_compare($sys_php_version, $ver, 'eq') && strpos($sys_php_version,$ver) !== false) {
  2187. $retval = -1;
  2188. break;
  2189. }
  2190. }
  2191. //allow a redhat distro to install, regardless of version. We are assuming the redhat naming convention is followed
  2192. //and the php version contains 'rh' characters
  2193. if(strpos($sys_php_version, 'rh') !== false) {
  2194. $retval = 1;
  2195. }
  2196. return $retval;
  2197. }
  2198. /**
  2199. * Will check if a given IIS version string is supported (tested on this ver),
  2200. * unsupported (results unknown), or invalid (something will break on this
  2201. * ver).
  2202. *
  2203. * @return 1 implies supported, 0 implies unsupported, -1 implies invalid
  2204. */
  2205. function check_iis_version($sys_iis_version = '') {
  2206. $server_software = $_SERVER["SERVER_SOFTWARE"];
  2207. $iis_version = '';
  2208. if(strpos($server_software,'Microsoft-IIS') !== false && preg_match_all("/^.*\/(\d+\.?\d*)$/", $server_software, $out))
  2209. $iis_version = $out[1][0];
  2210. $sys_iis_version = empty($sys_iis_version) ? $iis_version : $sys_iis_version;
  2211. // versions below $min_considered_iis_version considered invalid by default,
  2212. // versions equal to or above this ver will be considered depending
  2213. // on the rules that follow
  2214. $min_considered_iis_version = '6.0';
  2215. // only the supported versions,
  2216. // should be mutually exclusive with $invalid_iis_versions
  2217. $supported_iis_versions = array ('6.0', '7.0',);
  2218. $unsupported_iis_versions = array();
  2219. $invalid_iis_versions = array('5.0',);
  2220. // default unsupported
  2221. $retval = 0;
  2222. // versions below $min_considered_iis_version are invalid
  2223. if(1 == version_compare($sys_iis_version, $min_considered_iis_version, '<')) {
  2224. $retval = -1;
  2225. }
  2226. // supported version check overrides default unsupported
  2227. foreach($supported_iis_versions as $ver) {
  2228. if(1 == version_compare($sys_iis_version, $ver, 'eq') || strpos($sys_iis_version,$ver) !== false) {
  2229. $retval = 1;
  2230. break;
  2231. }
  2232. }
  2233. // unsupported version check overrides default unsupported
  2234. foreach($unsupported_iis_versions as $ver) {
  2235. if(1 == version_compare($sys_iis_version, $ver, 'eq') && strpos($sys_iis_version,$ver) !== false) {
  2236. $retval = 0;
  2237. break;
  2238. }
  2239. }
  2240. // invalid version check overrides default unsupported
  2241. foreach($invalid_iis_versions as $ver) {
  2242. if(1 == version_compare($sys_iis_version, $ver, 'eq') && strpos($sys_iis_version,$ver) !== false) {
  2243. $retval = -1;
  2244. break;
  2245. }
  2246. }
  2247. return $retval;
  2248. }
  2249. function pre_login_check(){
  2250. global $action, $login_error;
  2251. if(!empty($action)&& $action == 'Login'){
  2252. if(!empty($login_error)){
  2253. $login_error = htmlentities($login_error);
  2254. $login_error = str_replace(array("&lt;pre&gt;","&lt;/pre&gt;","\r\n", "\n"), "<br>", $login_error);
  2255. $_SESSION['login_error'] = $login_error;
  2256. echo '<script>
  2257. function set_focus() {}
  2258. if(document.getElementById("post_error")) {
  2259. document.getElementById("post_error").innerHTML="'. $login_error. '";
  2260. document.getElementById("cant_login").value=1;
  2261. document.getElementById("login_button").disabled = true;
  2262. document.getElementById("user_name").disabled = true;
  2263. //document.getElementById("user_password").disabled = true;
  2264. }
  2265. </script>';
  2266. }
  2267. }
  2268. }
  2269. function sugar_cleanup($exit = false) {
  2270. static $called = false;
  2271. if($called)return;
  2272. $called = true;
  2273. set_include_path(realpath(dirname(__FILE__) . '/..') . PATH_SEPARATOR . get_include_path());
  2274. chdir(realpath(dirname(__FILE__) . '/..'));
  2275. global $sugar_config;
  2276. require_once('include/utils/LogicHook.php');
  2277. LogicHook::initialize();
  2278. $GLOBALS['logic_hook']->call_custom_logic('', 'server_round_trip');
  2279. //added this check to avoid errors during install.
  2280. if (empty($sugar_config['dbconfig'])) {
  2281. if ($exit) exit; else return;
  2282. }
  2283. if (!class_exists('Tracker', true)) {
  2284. require_once 'modules/Trackers/Tracker.php';
  2285. }
  2286. Tracker::logPage();
  2287. // Now write the cached tracker_queries
  2288. if(!empty($GLOBALS['savePreferencesToDB']) && $GLOBALS['savePreferencesToDB']) {
  2289. if ( isset($GLOBALS['current_user']) && $GLOBALS['current_user'] instanceOf User )
  2290. $GLOBALS['current_user']->savePreferencesToDB();
  2291. }
  2292. //check to see if this is not an ajax call AND the user preference error flag is set
  2293. if(
  2294. (isset($_SESSION['USER_PREFRENCE_ERRORS']) && $_SESSION['USER_PREFRENCE_ERRORS'])
  2295. && ($_REQUEST['action']!='modulelistmenu' && $_REQUEST['action']!='DynamicAction')
  2296. && (empty($_REQUEST['to_pdf']) || !$_REQUEST['to_pdf'] )
  2297. && (empty($_REQUEST['sugar_body_only']) || !$_REQUEST['sugar_body_only'] )
  2298. ){
  2299. global $app_strings;
  2300. //this is not an ajax call and the user preference error flag is set, so reset the flag and print js to flash message
  2301. $err_mess = $app_strings['ERROR_USER_PREFS'];
  2302. $_SESSION['USER_PREFRENCE_ERRORS'] = false;
  2303. echo "
  2304. <script>
  2305. ajaxStatus.flashStatus('$err_mess',7000);
  2306. </script>";
  2307. }
  2308. pre_login_check();
  2309. if(class_exists('DBManagerFactory')) {
  2310. $db = DBManagerFactory::getInstance();
  2311. $db->disconnect();
  2312. if($exit) {
  2313. exit;
  2314. }
  2315. }
  2316. }
  2317. register_shutdown_function('sugar_cleanup');
  2318. /*
  2319. check_logic_hook - checks to see if your custom logic is in the logic file
  2320. if not, it will add it. If the file isn't built yet, it will create the file
  2321. */
  2322. function check_logic_hook_file($module_name, $event, $action_array){
  2323. require_once('include/utils/logic_utils.php');
  2324. $add_logic = false;
  2325. if(file_exists("custom/modules/$module_name/logic_hooks.php")){
  2326. $hook_array = get_hook_array($module_name);
  2327. if(check_existing_element($hook_array, $event, $action_array)==true){
  2328. //the hook at hand is present, so do nothing
  2329. } else {
  2330. $add_logic = true;
  2331. $logic_count = count($hook_array[$event]);
  2332. if($action_array[0]==""){
  2333. $action_array[0] = $logic_count + 1;
  2334. }
  2335. $hook_array[$event][] = $action_array;
  2336. }
  2337. //end if the file exists already
  2338. } else {
  2339. $add_logic = true;
  2340. if($action_array[0]==""){
  2341. $action_array[0] = 1;
  2342. }
  2343. $hook_array = array();
  2344. $hook_array[$event][] = $action_array;
  2345. //end if else file exists already
  2346. }
  2347. if($add_logic == true){
  2348. //reorder array by element[0]
  2349. //$hook_array = reorder_array($hook_array, $event);
  2350. //!!!Finish this above TODO
  2351. $new_contents = replace_or_add_logic_type($hook_array);
  2352. write_logic_file($module_name, $new_contents);
  2353. //end if add_element is true
  2354. }
  2355. //end function check_logic_hook_file
  2356. }
  2357. function remove_logic_hook($module_name, $event, $action_array) {
  2358. require_once('include/utils/logic_utils.php');
  2359. $add_logic = false;
  2360. if(file_exists("custom/modules/".$module_name."/logic_hooks.php")){
  2361. // The file exists, let's make sure the hook is there
  2362. $hook_array = get_hook_array($module_name);
  2363. if(check_existing_element($hook_array, $event, $action_array)==true){
  2364. // The hook is there, time to take it out.
  2365. foreach ( $hook_array[$event] as $i => $hook ) {
  2366. // We don't do a full comparison below just in case the filename changes
  2367. if ( $hook[0] == $action_array[0]
  2368. && $hook[1] == $action_array[1]
  2369. && $hook[3] == $action_array[3]
  2370. && $hook[4] == $action_array[4] ) {
  2371. unset($hook_array[$event][$i]);
  2372. }
  2373. }
  2374. $new_contents = replace_or_add_logic_type($hook_array);
  2375. write_logic_file($module_name, $new_contents);
  2376. }
  2377. }
  2378. }
  2379. function display_stack_trace($textOnly=false){
  2380. $stack = debug_backtrace();
  2381. echo "\n\n display_stack_trace caller, file: " . $stack[0]['file']. ' line#: ' .$stack[0]['line'];
  2382. if(!$textOnly)
  2383. echo '<br>';
  2384. $first = true;
  2385. $out = '';
  2386. foreach($stack as $item) {
  2387. $file = '';
  2388. $class = '';
  2389. $line = '';
  2390. $function = '';
  2391. if(isset($item['file']))
  2392. $file = $item['file'];
  2393. if(isset($item['class']))
  2394. $class = $item['class'];
  2395. if(isset($item['line']))
  2396. $line = $item['line'];
  2397. if(isset($item['function']))
  2398. $function = $item['function'];
  2399. if(!$first) {
  2400. if(!$textOnly) {
  2401. $out .= '<font color="black"><b>';
  2402. }
  2403. $out .= $file;
  2404. if(!$textOnly) {
  2405. $out .= '</b></font><font color="blue">';
  2406. }
  2407. $out .= "[L:{$line}]";
  2408. if(!$textOnly) {
  2409. $out .= '</font><font color="red">';
  2410. }
  2411. $out .= "({$class}:{$function})";
  2412. if(!$textOnly) {
  2413. $out .= '</font><br>';
  2414. } else {
  2415. $out .= "\n";
  2416. }
  2417. } else {
  2418. $first = false;
  2419. }
  2420. }
  2421. echo $out;
  2422. }
  2423. function StackTraceErrorHandler($errno, $errstr, $errfile,$errline, $errcontext) {
  2424. $error_msg = " $errstr occured in <b>$errfile</b> on line $errline [" . date("Y-m-d H:i:s") . ']';
  2425. $halt_script = true;
  2426. switch($errno){
  2427. case 2048: return; //depricated we have lots of these ignore them
  2428. case E_USER_NOTICE:
  2429. case E_NOTICE:
  2430. if ( error_reporting() & E_NOTICE ) {
  2431. $halt_script = false;
  2432. $type = 'Notice';
  2433. }
  2434. else
  2435. return;
  2436. break;
  2437. case E_USER_WARNING:
  2438. case E_COMPILE_WARNING:
  2439. case E_CORE_WARNING:
  2440. case E_WARNING:
  2441. $halt_script = false;
  2442. $type = "Warning";
  2443. break;
  2444. case E_USER_ERROR:
  2445. case E_COMPILE_ERROR:
  2446. case E_CORE_ERROR:
  2447. case E_ERROR:
  2448. $type = "Fatal Error";
  2449. break;
  2450. case E_PARSE:
  2451. $type = "Parse Error";
  2452. break;
  2453. default:
  2454. //don't know what it is might not be so bad
  2455. $halt_script = false;
  2456. $type = "Unknown Error ($errno)";
  2457. break;
  2458. }
  2459. $error_msg = '<b>'.$type.'</b>:' . $error_msg;
  2460. echo $error_msg;
  2461. display_stack_trace();
  2462. if($halt_script){
  2463. exit -1;
  2464. }
  2465. }
  2466. if(isset($sugar_config['stack_trace_errors']) && $sugar_config['stack_trace_errors']){
  2467. set_error_handler('StackTraceErrorHandler');
  2468. }
  2469. function get_sub_cookies($name){
  2470. $cookies = array();
  2471. if(isset($_COOKIE[$name])){
  2472. $subs = explode('#', $_COOKIE[$name]);
  2473. foreach($subs as $cookie){
  2474. if(!empty($cookie)){
  2475. $cookie = explode('=', $cookie);
  2476. $cookies[$cookie[0]] = $cookie[1];
  2477. }
  2478. }
  2479. }
  2480. return $cookies;
  2481. }
  2482. function mark_delete_components($sub_object_array, $run_second_level=false, $sub_sub_array=""){
  2483. if(!empty($sub_object_array)){
  2484. foreach($sub_object_array as $sub_object){
  2485. //run_second level is set to true if you need to remove sub-sub components
  2486. if($run_second_level==true){
  2487. mark_delete_components($sub_object->get_linked_beans($sub_sub_array['rel_field'],$sub_sub_array['rel_module']));
  2488. //end if run_second_level is true
  2489. }
  2490. $sub_object->mark_deleted($sub_object->id);
  2491. //end foreach sub component
  2492. }
  2493. //end if this is not empty
  2494. }
  2495. //end function mark_delete_components
  2496. }
  2497. /**
  2498. * For translating the php.ini memory values into bytes. e.g. input value of '8M' will return 8388608.
  2499. */
  2500. function return_bytes($val)
  2501. {
  2502. $val = trim($val);
  2503. $last = strtolower($val{strlen($val)-1});
  2504. switch($last)
  2505. {
  2506. // The 'G' modifier is available since PHP 5.1.0
  2507. case 'g':
  2508. $val *= 1024;
  2509. case 'm':
  2510. $val *= 1024;
  2511. case 'k':
  2512. $val *= 1024;
  2513. }
  2514. return $val;
  2515. }
  2516. /**
  2517. * Adds the href HTML tags around any URL in the $string
  2518. */
  2519. function url2html($string) {
  2520. //
  2521. $return_string = preg_replace('/(\w+:\/\/)(\S+)/', ' <a href="\\1\\2" target="_new" style="font-weight: normal;">\\1\\2</a>', $string);
  2522. return $return_string;
  2523. }
  2524. // End customization by Julian
  2525. /**
  2526. * tries to determine whether the Host machine is a Windows machine
  2527. */
  2528. function is_windows() {
  2529. static $is_windows = null;
  2530. if (!isset($is_windows)) {
  2531. $is_windows = strtoupper(substr(PHP_OS, 0, 3)) == 'WIN';
  2532. }
  2533. return $is_windows;
  2534. }
  2535. /**
  2536. * equivalent for windows filesystem for PHP's is_writable()
  2537. * @param string file Full path to the file/dir
  2538. * @return bool true if writable
  2539. */
  2540. function is_writable_windows($file) {
  2541. if($file{strlen($file)-1}=='/') {
  2542. return is_writable_windows($file.uniqid(mt_rand()).'.tmp');
  2543. }
  2544. // the assumption here is that Windows has an inherited permissions scheme
  2545. // any file that is a descendant of an unwritable directory will inherit
  2546. // that property and will trigger a failure below.
  2547. if(is_dir($file)) {
  2548. return true;
  2549. }
  2550. $file = str_replace("/", '\\', $file);
  2551. if(file_exists($file)) {
  2552. if (!($f = @sugar_fopen($file, 'r+')))
  2553. return false;
  2554. fclose($f);
  2555. return true;
  2556. }
  2557. if(!($f = @sugar_fopen($file, 'w')))
  2558. return false;
  2559. fclose($f);
  2560. unlink($file);
  2561. return true;
  2562. }
  2563. /**
  2564. * best guesses Timezone based on webserver's TZ settings
  2565. */
  2566. function lookupTimezone($userOffset = 0)
  2567. {
  2568. return TimeDate::guessTimezone($userOffset);
  2569. }
  2570. function convert_module_to_singular($module_array){
  2571. global $beanList;
  2572. foreach($module_array as $key => $value){
  2573. if(!empty($beanList[$value])) $module_array[$key] = $beanList[$value];
  2574. if($value=="Cases") {
  2575. $module_array[$key] = "Case";
  2576. }
  2577. if($key=="projecttask"){
  2578. $module_array['ProjectTask'] = "Project Task";
  2579. unset($module_array[$key]);
  2580. }
  2581. }
  2582. return $module_array;
  2583. //end function convert_module_to_singular
  2584. }
  2585. /*
  2586. * Given the bean_name which may be plural or singular return the singular
  2587. * bean_name. This is important when you need to include files.
  2588. */
  2589. function get_singular_bean_name($bean_name){
  2590. global $beanFiles, $beanList;
  2591. if(array_key_exists($bean_name, $beanList)){
  2592. return $beanList[$bean_name];
  2593. }
  2594. else{
  2595. return $bean_name;
  2596. }
  2597. }
  2598. function get_label($label_tag, $temp_module_strings){
  2599. global $app_strings;
  2600. if(!empty($temp_module_strings[$label_tag])){
  2601. $label_name = $temp_module_strings[$label_tag];
  2602. } else {
  2603. if(!empty($app_strings[$label_tag])){
  2604. $label_name = $app_strings[$label_tag];
  2605. } else {
  2606. $label_name = $label_tag;
  2607. }
  2608. }
  2609. return $label_name;
  2610. //end function get_label
  2611. }
  2612. function search_filter_rel_info(& $focus, $tar_rel_module, $relationship_name){
  2613. $rel_list = array();
  2614. foreach($focus->relationship_fields as $rel_key => $rel_value){
  2615. if($rel_value == $relationship_name){
  2616. $temp_bean = get_module_info($tar_rel_module);
  2617. // echo $focus->$rel_key;
  2618. $temp_bean->retrieve($focus->$rel_key);
  2619. if($temp_bean->id!=""){
  2620. $rel_list[] = $temp_bean;
  2621. return $rel_list;
  2622. }
  2623. }
  2624. }
  2625. foreach($focus->field_defs as $field_name => $field_def){
  2626. //Check if the relationship_name matches a "relate" field
  2627. if(!empty($field_def['type']) && $field_def['type'] == 'relate'
  2628. && !empty($field_def['id_name']) && !empty($focus->field_defs[$field_def['id_name']])
  2629. && !empty($focus->field_defs[$field_def['id_name']]['relationship'])
  2630. && $focus->field_defs[$field_def['id_name']]['relationship'] == $relationship_name)
  2631. {
  2632. $temp_bean = get_module_info($tar_rel_module);
  2633. // echo $focus->$field_def['id_name'];
  2634. $temp_bean->retrieve($focus->$field_def['id_name']);
  2635. if($temp_bean->id!=""){
  2636. $rel_list[] = $temp_bean;
  2637. return $rel_list;
  2638. }
  2639. //Check if the relationship_name matches a "link" in a relate field
  2640. } else if(!empty($rel_value['link']) && !empty($rel_value['id_name']) && $rel_value['link'] == $relationship_name){
  2641. $temp_bean = get_module_info($tar_rel_module);
  2642. // echo $focus->$rel_value['id_name'];
  2643. $temp_bean->retrieve($focus->$rel_value['id_name']);
  2644. if($temp_bean->id!=""){
  2645. $rel_list[] = $temp_bean;
  2646. return $rel_list;
  2647. }
  2648. }
  2649. }
  2650. // special case for unlisted parent-type relationships
  2651. if($focus->parent_type == $tar_rel_module && !empty($focus->parent_id)) {
  2652. $temp_bean = get_module_info($tar_rel_module);
  2653. $temp_bean->retrieve($focus->parent_id);
  2654. if($temp_bean->id!=""){
  2655. $rel_list[] = $temp_bean;
  2656. return $rel_list;
  2657. }
  2658. }
  2659. return $rel_list;
  2660. //end function search_filter_rel_info
  2661. }
  2662. function get_module_info($module_name){
  2663. global $beanList;
  2664. global $dictionary;
  2665. //Get dictionary and focus data for module
  2666. $vardef_name = $beanList[$module_name];
  2667. if($vardef_name=="aCase"){
  2668. $class_name = "Case";
  2669. } else {
  2670. $class_name = $vardef_name;
  2671. }
  2672. if(!file_exists('modules/'. $module_name . '/'.$class_name.'.php')){
  2673. return;
  2674. }
  2675. include_once('modules/'. $module_name . '/'.$class_name.'.php');
  2676. $module_bean = new $vardef_name();
  2677. return $module_bean;
  2678. //end function get_module_table
  2679. }
  2680. /**
  2681. * In order to have one place to obtain the proper object name. aCase for example causes issues throughout the application.
  2682. *
  2683. * @param string $moduleName
  2684. */
  2685. function get_valid_bean_name($module_name){
  2686. global $beanList;
  2687. $vardef_name = $beanList[$module_name];
  2688. if($vardef_name=="aCase"){
  2689. $bean_name = "Case";
  2690. } else {
  2691. $bean_name = $vardef_name;
  2692. }
  2693. return $bean_name;
  2694. }
  2695. function checkAuthUserStatus(){
  2696. //authUserStatus();
  2697. }
  2698. /**
  2699. * This function returns an array of phpinfo() results that can be parsed and
  2700. * used to figure out what version we run, what modules are compiled in, etc.
  2701. * @param $level int info level constant (1,2,4,8...64);
  2702. * @return $returnInfo array array of info about the PHP environment
  2703. * @author original by "code at adspeed dot com" Fron php.net
  2704. * @author customized for Sugar by Chris N.
  2705. */
  2706. function getPhpInfo($level=-1) {
  2707. /** Name (constant) Value Description
  2708. INFO_GENERAL 1 The configuration line, php.ini location, build date, Web Server, System and more.
  2709. INFO_CREDITS 2 PHP Credits. See also phpcredits().
  2710. INFO_CONFIGURATION 4 Current Local and Master values for PHP directives. See also ini_get().
  2711. INFO_MODULES 8 Loaded modules and their respective settings. See also get_loaded_extensions().
  2712. INFO_ENVIRONMENT 16 Environment Variable information that's also available in $_ENV.
  2713. INFO_VARIABLES 32 Shows all predefined variables from EGPCS (Environment, GET, POST, Cookie, Server).
  2714. INFO_LICENSE 64 PHP License information. See also the license FAQ.
  2715. INFO_ALL -1 Shows all of the above. This is the default value.
  2716. */
  2717. ob_start();
  2718. phpinfo($level);
  2719. $phpinfo = ob_get_contents();
  2720. ob_end_clean();
  2721. $phpinfo = strip_tags($phpinfo,'<h1><h2><th><td>');
  2722. $phpinfo = preg_replace('/<th[^>]*>([^<]+)<\/th>/',"<info>\\1</info>",$phpinfo);
  2723. $phpinfo = preg_replace('/<td[^>]*>([^<]+)<\/td>/',"<info>\\1</info>",$phpinfo);
  2724. $parsedInfo = preg_split('/(<h.?>[^<]+<\/h.>)/', $phpinfo, -1, PREG_SPLIT_DELIM_CAPTURE);
  2725. $match = '';
  2726. $version = '';
  2727. $returnInfo = array();
  2728. if(preg_match('/<h1 class\=\"p\">PHP Version ([^<]+)<\/h1>/', $phpinfo, $version)) {
  2729. $returnInfo['PHP Version'] = $version[1];
  2730. }
  2731. for ($i=1; $i<count($parsedInfo); $i++) {
  2732. if (preg_match('/<h.>([^<]+)<\/h.>/', $parsedInfo[$i], $match)) {
  2733. $vName = trim($match[1]);
  2734. $parsedInfo2 = explode("\n",$parsedInfo[$i+1]);
  2735. foreach ($parsedInfo2 AS $vOne) {
  2736. $vPat = '<info>([^<]+)<\/info>';
  2737. $vPat3 = "/$vPat\s*$vPat\s*$vPat/";
  2738. $vPat2 = "/$vPat\s*$vPat/";
  2739. if (preg_match($vPat3,$vOne,$match)) { // 3cols
  2740. $returnInfo[$vName][trim($match[1])] = array(trim($match[2]),trim($match[3]));
  2741. } elseif (preg_match($vPat2,$vOne,$match)) { // 2cols
  2742. $returnInfo[$vName][trim($match[1])] = trim($match[2]);
  2743. }
  2744. }
  2745. } elseif(true) {
  2746. }
  2747. }
  2748. return $returnInfo;
  2749. }
  2750. /**
  2751. * This function will take a string that has tokens like {0}, {1} and will replace
  2752. * those tokens with the args provided
  2753. * @param $format string to format
  2754. * @param $args args to replace
  2755. * @return $result a formatted string
  2756. */
  2757. function string_format($format, $args){
  2758. $result = $format;
  2759. for($i = 0; $i < count($args); $i++){
  2760. $result = str_replace('{'.$i.'}', $args[$i], $result);
  2761. }
  2762. return $result;
  2763. }
  2764. /**
  2765. * Generate a string for displaying a unique identifier that is composed
  2766. * of a system_id and number. This is use to allow us to generate quote
  2767. * numbers using a DB auto-increment key from offline clients and still
  2768. * have the number be unique (since it is modified by the system_id.
  2769. *
  2770. * @param $num of bean
  2771. * @param $system_id from system
  2772. * @return $result a formatted string
  2773. */
  2774. function format_number_display($num, $system_id){
  2775. global $sugar_config;
  2776. if(isset($num) && !empty($num)){
  2777. $num=unformat_number($num);
  2778. if(isset($system_id) && $system_id == 1){
  2779. return sprintf("%d", $num);
  2780. }
  2781. else{
  2782. return sprintf("%d-%d", $num, $system_id);
  2783. }
  2784. }
  2785. }
  2786. function checkLoginUserStatus(){
  2787. }
  2788. /**
  2789. * This function will take a number and system_id and format
  2790. * @param $url URL containing host to append port
  2791. * @param $port the port number - if '' is passed, no change to url
  2792. * @return $resulturl the new URL with the port appended to the host
  2793. */
  2794. function appendPortToHost($url, $port)
  2795. {
  2796. $resulturl = $url;
  2797. // if no port, don't change the url
  2798. if($port != '')
  2799. {
  2800. $split = explode("/", $url);
  2801. //check if it starts with http, in case they didn't include that in url
  2802. if(str_begin($url, 'http'))
  2803. {
  2804. //third index ($split[2]) will be the host
  2805. $split[2] .= ":".$port;
  2806. }
  2807. else // otherwise assumed to start with host name
  2808. {
  2809. //first index ($split[0]) will be the host
  2810. $split[0] .= ":".$port;
  2811. }
  2812. $resulturl = implode("/", $split);
  2813. }
  2814. return $resulturl;
  2815. }
  2816. /**
  2817. * Singleton to return JSON object
  2818. * @return JSON object
  2819. */
  2820. function getJSONobj() {
  2821. static $json = null;
  2822. if(!isset($json)) {
  2823. require_once('include/JSON.php');
  2824. $json = new JSON(JSON_LOOSE_TYPE);
  2825. }
  2826. return $json;
  2827. }
  2828. require_once('include/utils/db_utils.php');
  2829. //check to see if custom utils exists
  2830. if(file_exists('custom/include/custom_utils.php')){
  2831. include_once('custom/include/custom_utils.php');
  2832. }
  2833. /**
  2834. * Set default php.ini settings for entry points
  2835. */
  2836. function setPhpIniSettings() {
  2837. // zlib module
  2838. // Bug 37579 - Comment out force enabling zlib.output_compression, since it can cause problems on certain hosts
  2839. /*
  2840. if(function_exists('gzclose') && headers_sent() == false) {
  2841. ini_set('zlib.output_compression', 1);
  2842. }
  2843. */
  2844. // mbstring module
  2845. //nsingh: breaks zip/unzip functionality. Commenting out 4/23/08
  2846. /*if(function_exists('mb_strlen')) {
  2847. ini_set('mbstring.func_overload', 7);
  2848. ini_set('mbstring.internal_encoding', 'UTF-8');
  2849. }*/
  2850. // http://us3.php.net/manual/en/ref.pcre.php#ini.pcre.backtrack-limit
  2851. // starting with 5.2.0, backtrack_limit breaks JSON decoding
  2852. $backtrack_limit = ini_get('pcre.backtrack_limit');
  2853. if(!empty($backtrack_limit)) {
  2854. ini_set('pcre.backtrack_limit', '-1');
  2855. }
  2856. // mssql only
  2857. if(ini_get("mssql.charset")) {
  2858. ini_set('mssql.charset', "UTF-8");
  2859. }
  2860. }
  2861. /**
  2862. * like array_merge() but will handle array elements that are themselves arrays;
  2863. * PHP's version just overwrites the element with the new one.
  2864. *
  2865. * @internal Note that this function deviates from the internal array_merge()
  2866. * functions in that it does does not treat numeric keys differently
  2867. * than string keys. Additionally, it deviates from
  2868. * array_merge_recursive() by not creating an array when like values
  2869. * found.
  2870. *
  2871. * @param array gimp the array whose values will be overloaded
  2872. * @param array dom the array whose values will pwn the gimp's
  2873. * @return array beaten gimp
  2874. */
  2875. function sugarArrayMerge($gimp, $dom) {
  2876. if(is_array($gimp) && is_array($dom)) {
  2877. foreach($dom as $domKey => $domVal) {
  2878. if(array_key_exists($domKey, $gimp)) {
  2879. if(is_array($domVal)) {
  2880. $tempArr = array();
  2881. foreach ( $domVal as $domArrKey => $domArrVal )
  2882. $tempArr[$domArrKey] = $domArrVal;
  2883. foreach ( $gimp[$domKey] as $gimpArrKey => $gimpArrVal )
  2884. if ( !array_key_exists($gimpArrKey, $tempArr) )
  2885. $tempArr[$gimpArrKey] = $gimpArrVal;
  2886. $gimp[$domKey] = $tempArr;
  2887. } else {
  2888. $gimp[$domKey] = $domVal;
  2889. }
  2890. } else {
  2891. $gimp[$domKey] = $domVal;
  2892. }
  2893. }
  2894. }
  2895. // if the passed value for gimp isn't an array, then return the $dom
  2896. elseif(is_array($dom))
  2897. return $dom;
  2898. return $gimp;
  2899. }
  2900. /**
  2901. * Similiar to sugarArrayMerge except arrays of N depth are merged.
  2902. *
  2903. * @param array gimp the array whose values will be overloaded
  2904. * @param array dom the array whose values will pwn the gimp's
  2905. * @return array beaten gimp
  2906. */
  2907. function sugarArrayMergeRecursive($gimp, $dom) {
  2908. if(is_array($gimp) && is_array($dom)) {
  2909. foreach($dom as $domKey => $domVal) {
  2910. if(array_key_exists($domKey, $gimp)) {
  2911. if(is_array($domVal) && is_array($gimp[$domKey])) {
  2912. $gimp[$domKey] = sugarArrayMergeRecursive($gimp[$domKey], $domVal);
  2913. } else {
  2914. $gimp[$domKey] = $domVal;
  2915. }
  2916. } else {
  2917. $gimp[$domKey] = $domVal;
  2918. }
  2919. }
  2920. }
  2921. // if the passed value for gimp isn't an array, then return the $dom
  2922. elseif(is_array($dom))
  2923. return $dom;
  2924. return $gimp;
  2925. }
  2926. /**
  2927. * finds the correctly working versions of PHP-JSON
  2928. * @return bool True if NOT found or WRONG version
  2929. */
  2930. function returnPhpJsonStatus() {
  2931. if(function_exists('json_encode')) {
  2932. $phpInfo = getPhpInfo(8);
  2933. return version_compare($phpInfo['json']['json version'], '1.1.1', '<');
  2934. }
  2935. return true; // not found
  2936. }
  2937. /**
  2938. * getTrackerSubstring
  2939. *
  2940. * Returns a [number]-char or less string for the Tracker to display in the header
  2941. * based on the tracker_max_display_length setting in config.php. If not set,
  2942. * or invalid length, then defaults to 15 for COM editions, 30 for others.
  2943. *
  2944. * @param string name field for a given Object
  2945. * @return string [number]-char formatted string if length of string exceeds the max allowed
  2946. */
  2947. function getTrackerSubstring($name) {
  2948. static $max_tracker_item_length;
  2949. //Trim the name
  2950. $name = html_entity_decode($name, ENT_QUOTES, 'UTF-8');
  2951. $strlen = function_exists('mb_strlen') ? mb_strlen($name) : strlen($name);
  2952. global $sugar_config;
  2953. if(!isset($max_tracker_item_length)) {
  2954. if(isset($sugar_config['tracker_max_display_length'])) {
  2955. $max_tracker_item_length = (is_int($sugar_config['tracker_max_display_length']) && $sugar_config['tracker_max_display_length'] > 0 && $sugar_config['tracker_max_display_length'] < 50) ? $sugar_config['tracker_max_display_length'] : 15;
  2956. } else {
  2957. $max_tracker_item_length = 15;
  2958. }
  2959. }
  2960. if($strlen > $max_tracker_item_length) {
  2961. $chopped = function_exists('mb_substr') ? mb_substr($name, 0, $max_tracker_item_length, "UTF-8") : substr($name, 0, $max_tracker_item_length, "UTF-8");
  2962. } else {
  2963. $chopped = $name;
  2964. }
  2965. return $chopped;
  2966. }
  2967. function generate_search_where ($field_list=array(),$values=array(),&$bean,$add_custom_fields=false,$module='') {
  2968. $where_clauses= array();
  2969. $like_char='%';
  2970. $table_name=$bean->object_name;
  2971. foreach ($field_list[$module] as $field=>$parms) {
  2972. if(isset($values[$field]) && $values[$field] != "") {
  2973. $operator='like';
  2974. if (!empty($parms['operator'])) {
  2975. $operator=$parms['operator'];
  2976. }
  2977. if (is_array($values[$field])) {
  2978. $operator='in';
  2979. $field_value='';
  2980. foreach ($values[$field] as $key => $val) {
  2981. if ($val != ' ' and $val != '') {
  2982. if (!empty($field_value)) {
  2983. $field_value.=',';
  2984. }
  2985. $field_value .= "'".$GLOBALS['db']->quote($val)."'";
  2986. }
  2987. }
  2988. } else {
  2989. $field_value=$GLOBALS['db']->quote($values[$field]);
  2990. }
  2991. //set db_fields array.
  2992. if (!isset($parms['db_field']) ) {
  2993. $parms['db_field'] = array($field);
  2994. }
  2995. if (isset($parms['my_items']) and $parms['my_items'] == true) {
  2996. global $current_user;
  2997. $field_value = $GLOBALS['db']->quote($current_user->id);
  2998. $operator='=';
  2999. }
  3000. $where='';
  3001. $itr=0;
  3002. if ($field_value != '') {
  3003. foreach ($parms['db_field'] as $db_field) {
  3004. if (strstr($db_field,'.')===false) {
  3005. $db_field=$bean->table_name.".".$db_field;
  3006. }
  3007. if ($GLOBALS['db']->dbType=='oci8' && isset($parms['query_type']) && $parms['query_type']=='case_insensitive') {
  3008. $db_field='upper('.$db_field.")";
  3009. $field_value=strtoupper($field_value);
  3010. }
  3011. $itr++;
  3012. if (!empty($where)) {
  3013. $where .= " OR ";
  3014. }
  3015. switch (strtolower($operator)) {
  3016. case 'like' :
  3017. $where .= $db_field . " like '".$field_value.$like_char."'";
  3018. break;
  3019. case 'in':
  3020. $where .= $db_field . " in (".$field_value.')';
  3021. break;
  3022. case '=':
  3023. $where .= $db_field . " = '".$field_value ."'";
  3024. break;
  3025. }
  3026. }
  3027. }
  3028. if (!empty($where)) {
  3029. if ($itr>1) {
  3030. array_push($where_clauses, '( '.$where.' )');
  3031. } else {
  3032. array_push($where_clauses, $where);
  3033. }
  3034. }
  3035. }
  3036. }
  3037. if ($add_custom_fields) {
  3038. require_once('modules/DynamicFields/DynamicField.php');
  3039. $bean->setupCustomFields($module);
  3040. $bean->custom_fields->setWhereClauses($where_clauses);
  3041. }
  3042. return $where_clauses;
  3043. }
  3044. function add_quotes($str) {
  3045. return "'{$str}'";
  3046. }
  3047. /**
  3048. * This function will rebuild the config file
  3049. * @param $sugar_config
  3050. * @param $sugar_version
  3051. * @return bool true if successful
  3052. */
  3053. function rebuildConfigFile($sugar_config, $sugar_version) {
  3054. // add defaults to missing values of in-memory sugar_config
  3055. $sugar_config = sugarArrayMerge(get_sugar_config_defaults(), $sugar_config );
  3056. // need to override version with default no matter what
  3057. $sugar_config['sugar_version'] = $sugar_version;
  3058. ksort( $sugar_config );
  3059. if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
  3060. return true;
  3061. }
  3062. else {
  3063. return false;
  3064. }
  3065. }
  3066. /**
  3067. * getJavascriptSiteURL
  3068. * This function returns a URL for the client javascript calls to access
  3069. * the site. It uses $_SERVER['HTTP_REFERER'] in the event that Proxy servers
  3070. * are used to access the site. Thus, the hostname in the URL returned may
  3071. * not always match that of $sugar_config['site_url']. Basically, the
  3072. * assumption is that however the user accessed the website is how they
  3073. * will continue to with subsequent javascript requests. If the variable
  3074. * $_SERVER['HTTP_REFERER'] is not found then we default to old algorithm.
  3075. * @return $site_url The url used to refer to the website
  3076. */
  3077. function getJavascriptSiteURL() {
  3078. global $sugar_config;
  3079. if(!empty($_SERVER['HTTP_REFERER'])) {
  3080. $url = parse_url($_SERVER['HTTP_REFERER']);
  3081. $replacement_url = $url['scheme']."://".$url['host'];
  3082. if(!empty($url['port']))
  3083. $replacement_url .= ':'.$url['port'];
  3084. $site_url = preg_replace('/^http[s]?\:\/\/[^\/]+/',$replacement_url,$sugar_config['site_url']);
  3085. } else {
  3086. $site_url = preg_replace('/^http(s)?\:\/\/[^\/]+/',"http$1://".$_SERVER['HTTP_HOST'],$sugar_config['site_url']);
  3087. if(!empty($_SERVER['SERVER_PORT']) &&$_SERVER['SERVER_PORT'] == '443') {
  3088. $site_url = preg_replace('/^http\:/','https:',$site_url);
  3089. }
  3090. }
  3091. $GLOBALS['log']->debug("getJavascriptSiteURL(), site_url=". $site_url);
  3092. return $site_url;
  3093. }
  3094. // works nicely with array_map() -- can be used to wrap single quotes around each element in an array
  3095. function add_squotes($str) {
  3096. return "'" . $str . "'";
  3097. }
  3098. // recursive function to count the number of levels within an array
  3099. function array_depth($array, $depth_count=-1, $depth_array=array()){
  3100. $depth_count++;
  3101. if (is_array($array)){
  3102. foreach ($array as $key => $value){
  3103. $depth_array[] = array_depth($value, $depth_count);
  3104. }
  3105. }
  3106. else{
  3107. return $depth_count;
  3108. }
  3109. foreach ($depth_array as $value){
  3110. $depth_count = $value > $depth_count ? $value : $depth_count;
  3111. }
  3112. return $depth_count;
  3113. }
  3114. /**
  3115. * Creates a new Group User
  3116. * @param string $name Name of Group User
  3117. * @return string GUID of new Group User
  3118. */
  3119. function createGroupUser($name) {
  3120. $group = new User();
  3121. $group->user_name = $name;
  3122. $group->last_name = $name;
  3123. $group->is_group = 1;
  3124. $group->deleted = 0;
  3125. $group->status = 'Active'; // cn: bug 6711
  3126. $group->setPreference('timezone', TimeDate::userTimezone());
  3127. $group->save();
  3128. return $group->id;
  3129. }
  3130. /*
  3131. * Helper function to locate an icon file given only a name
  3132. * Searches through the various paths for the file
  3133. * @param string iconFileName The filename of the icon
  3134. * @return string Relative pathname of the located icon, or '' if not found
  3135. */
  3136. function _getIcon($iconFileName)
  3137. {
  3138. $iconPath = SugarThemeRegistry::current()->getImageURL("icon_{$iconFileName}.gif");
  3139. //First try un-ucfirst-ing the icon name
  3140. if ( empty($iconPath) )
  3141. $iconPath = SugarThemeRegistry::current()->getImageURL(
  3142. "icon_" . strtolower(substr($iconFileName,0,1)).substr($iconFileName,1) . ".gif");
  3143. //Next try removing the icon prefix
  3144. if ( empty($iconPath) )
  3145. $iconPath = SugarThemeRegistry::current()->getImageURL("{$iconFileName}.gif");
  3146. return $iconPath;
  3147. }
  3148. /**
  3149. * Function to grab the correct icon image for Studio
  3150. * @param string $iconFileName Name of the icon file
  3151. * @param string $altfilename Name of a fallback icon file (displayed if the imagefilename doesn't exist)
  3152. * @param string $width Width of image
  3153. * @param string $height Height of image
  3154. * @param string $align Alignment of image
  3155. * @return string $string <img> tag with corresponding image
  3156. */
  3157. function getStudioIcon($iconFileName='', $altFileName='', $width='48', $height='48', $align='baseline' )
  3158. {
  3159. global $app_strings, $theme;
  3160. $iconPath = _getIcon($iconFileName);
  3161. if(empty($iconPath)){
  3162. $iconPath = _getIcon($altFileName);
  3163. if (empty($iconPath))
  3164. {
  3165. return $app_strings['LBL_NO_IMAGE'];
  3166. }
  3167. }
  3168. return '<img border="0" src="'.$iconPath.'" width="'.$width.'" height="'.$height.'" align="'.$align.'">';
  3169. }
  3170. /**
  3171. * Function to grab the correct icon image for Dashlets Dialog
  3172. * @param string $filename Location of the icon file
  3173. * @param string $module Name of the module to fall back onto if file does not exist
  3174. * @param string $width Width of image
  3175. * @param string $height Height of image
  3176. * @param string $align Alignment of image
  3177. * @return string $string <img> tag with corresponding image
  3178. */
  3179. function get_dashlets_dialog_icon($module='', $width='32', $height='32', $align='absmiddle'){
  3180. global $app_strings, $theme;
  3181. $icon_path = _getIcon($module . "_32");
  3182. if (empty($icon_path))
  3183. {
  3184. $icon_path = _getIcon($module);
  3185. }
  3186. if(empty($icon_path)){
  3187. $icon = $app_strings['LBL_NO_IMAGE'];
  3188. }
  3189. else{
  3190. $icon = '<img border="0" src="'.$icon_path.'" width="'.$width.'" height="'.$height.'" align="'.$align.'">';
  3191. }
  3192. return $icon;
  3193. }
  3194. // works nicely to change UTF8 strings that are html entities - good for PDF conversions
  3195. function html_entity_decode_utf8($string)
  3196. {
  3197. static $trans_tbl;
  3198. // replace numeric entities
  3199. //php will have issues with numbers with leading zeros, so do not include them in what we send to code2utf.
  3200. $string = preg_replace('~&#x0*([0-9a-f]+);~ei', 'code2utf(hexdec("\\1"))', $string);
  3201. $string = preg_replace('~&#0*([0-9]+);~e', 'code2utf(\\1)', $string);
  3202. // replace literal entities
  3203. if (!isset($trans_tbl))
  3204. {
  3205. $trans_tbl = array();
  3206. foreach (get_html_translation_table(HTML_ENTITIES) as $val=>$key)
  3207. $trans_tbl[$key] = utf8_encode($val);
  3208. }
  3209. return strtr($string, $trans_tbl);
  3210. }
  3211. // Returns the utf string corresponding to the unicode value
  3212. function code2utf($num)
  3213. {
  3214. if ($num < 128) return chr($num);
  3215. if ($num < 2048) return chr(($num >> 6) + 192) . chr(($num & 63) + 128);
  3216. if ($num < 65536) return chr(($num >> 12) + 224) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3217. if ($num < 2097152) return chr(($num >> 18) + 240) . chr((($num >> 12) & 63) + 128) . chr((($num >> 6) & 63) + 128) . chr(($num & 63) + 128);
  3218. return '';
  3219. }
  3220. function str_split_php4($string, $length = 1) {
  3221. $string_length = strlen($string);
  3222. $return = array();
  3223. $cursor = 0;
  3224. if ($length > $string_length) {
  3225. // use the string_length as the string is shorter than the length
  3226. $length = $string_length;
  3227. }
  3228. for ($cursor = 0; $cursor < $string_length; $cursor = $cursor + $length) {
  3229. $return[] = substr($string, $cursor, $length);
  3230. }
  3231. return $return;
  3232. }
  3233. if (version_compare(phpversion(), '5.0.0', '<')) {
  3234. function str_split($string, $length = 1) {
  3235. return str_split_php4($string, $length);
  3236. }
  3237. }
  3238. /*
  3239. * Invoked when connected to mssql. checks if we have freetds version of mssql library.
  3240. * the response is put into a global variable.
  3241. */
  3242. function is_freetds() {
  3243. $ret=false;
  3244. if (isset($GLOBALS['mssql_library_version'])) {
  3245. if ($GLOBALS['mssql_library_version']=='freetds') {
  3246. $ret=true;
  3247. } else {
  3248. $ret=false;
  3249. }
  3250. } else {
  3251. ob_start();
  3252. phpinfo();
  3253. $info=ob_get_contents();
  3254. ob_end_clean();
  3255. if (strpos($info,'FreeTDS') !== false) {
  3256. $GLOBALS['mssql_library_version']='freetds';
  3257. $ret=true;
  3258. } else {
  3259. $GLOBALS['mssql_library_version']='regular';
  3260. $ret=false;
  3261. }
  3262. }
  3263. return $ret;
  3264. }
  3265. /*
  3266. * stripos - Find position of first occurrence of a case-insensitive string
  3267. *
  3268. * The function is being defined for systems with PHP version < 5.
  3269. *
  3270. */
  3271. if (!function_exists("stripos")){
  3272. function stripos($haystack,$needle,$offset=0){
  3273. return strpos(strtolower($haystack),strtolower($needle),$offset);
  3274. }
  3275. }
  3276. /**
  3277. * Chart dashlet helper function that returns the correct CSS file, dependent on the current theme.
  3278. *
  3279. * @todo this won't work completely right until we impliment css compression and combination
  3280. * for now, we'll just include the last css file found.
  3281. *
  3282. * @return chart.css file to use
  3283. */
  3284. function chartStyle()
  3285. {
  3286. return SugarThemeRegistry::current()->getCSSURL('chart.css');
  3287. }
  3288. /**
  3289. * Chart dashlet helper functions that returns the correct XML color file for charts,
  3290. * dependent on the current theme.
  3291. *
  3292. * @return sugarColors.xml to use
  3293. */
  3294. function chartColors()
  3295. {
  3296. if (SugarThemeRegistry::current()->getCSSURL('sugarColors.xml')=='')
  3297. return SugarThemeRegistry::current()->getImageURL('sugarColors.xml');
  3298. return SugarThemeRegistry::current()->getCSSURL('sugarColors.xml');
  3299. }
  3300. /* End Chart Dashlet helper functions */
  3301. /**
  3302. * This function is designed to set up the php enviroment
  3303. * for AJAX requests.
  3304. */
  3305. function ajaxInit() {
  3306. ini_set('display_errors', 'false');
  3307. }
  3308. /**
  3309. * Returns an absolute path from the given path, determining if it is relative or absolute
  3310. *
  3311. * @param string $path
  3312. * @return string
  3313. */
  3314. function getAbsolutePath(
  3315. $path,
  3316. $currentServer = false
  3317. )
  3318. {
  3319. $path = trim($path);
  3320. // try to match absolute paths like \\server\share, /directory or c:\
  3321. if ( ( substr($path,0,2) == '\\\\' )
  3322. || ( $path[0] == '/' )
  3323. || preg_match('/^[A-z]:/i',$path)
  3324. || $currentServer )
  3325. return $path;
  3326. return getcwd().'/'.$path;
  3327. }
  3328. /**
  3329. * Returns the bean object of the given module
  3330. *
  3331. * @deprecated use SugarModule::loadBean() instead
  3332. * @param string $module
  3333. * @return object
  3334. */
  3335. function loadBean(
  3336. $module
  3337. )
  3338. {
  3339. return SugarModule::get($module)->loadBean();
  3340. }
  3341. /**
  3342. * Returns true if the application is being accessed on a touch screen interface ( like an iPad )
  3343. */
  3344. function isTouchScreen()
  3345. {
  3346. $ua = empty($_SERVER['HTTP_USER_AGENT']) ? "undefined" : strtolower($_SERVER['HTTP_USER_AGENT']);
  3347. // first check if we have forced use of the touch enhanced interface
  3348. if ( isset($_COOKIE['touchscreen']) && $_COOKIE['touchscreen'] == '1' ) {
  3349. return true;
  3350. }
  3351. // next check if we should use the touch interface with our device
  3352. if ( strpos($ua, 'ipad') !== false ) {
  3353. return true;
  3354. }
  3355. return false;
  3356. }
  3357. /**
  3358. * Returns the shortcut keys to access the shortcut links. Shortcut
  3359. * keys vary depending on browser versions and operating systems.
  3360. * @return String value of the shortcut keys
  3361. */
  3362. function get_alt_hot_key() {
  3363. $ua = '';
  3364. if ( isset($_SERVER['HTTP_USER_AGENT']) )
  3365. $ua = strtolower($_SERVER['HTTP_USER_AGENT']);
  3366. $isMac = strpos($ua, 'mac') !== false;
  3367. $isLinux = strpos($ua, 'linux') !== false;
  3368. if(!$isMac && !$isLinux && strpos($ua, 'mozilla') !== false) {
  3369. if(preg_match('/firefox\/(\d)?\./', $ua, $matches)) {
  3370. return $matches[1] < 2 ? 'Alt+' : 'Alt+Shift+';
  3371. }
  3372. }
  3373. return $isMac ? 'Ctrl+' : 'Alt+';
  3374. }
  3375. function can_start_session(){
  3376. if(!empty($_GET['PHPSESSID'])) {
  3377. return true;
  3378. }
  3379. $session_id = session_id();
  3380. return empty($session_id) ? true : false;
  3381. }
  3382. function load_link_class($properties){
  3383. $class = 'Link';
  3384. if(!empty($properties['link_class']) && !empty($properties['link_file'])){
  3385. require_once($properties['link_file']);
  3386. $class = $properties['link_class'];
  3387. }
  3388. return $class;
  3389. }
  3390. function inDeveloperMode()
  3391. {
  3392. return isset($GLOBALS['sugar_config']['developerMode']) && $GLOBALS['sugar_config']['developerMode'];
  3393. }
  3394. /**
  3395. * Filter the protocol list for inbound email accounts.
  3396. *
  3397. * @param array $protocol
  3398. */
  3399. function filterInboundEmailPopSelection($protocol)
  3400. {
  3401. if ( !isset($GLOBALS['sugar_config']['allow_pop_inbound']) || ! $GLOBALS['sugar_config']['allow_pop_inbound'] )
  3402. {
  3403. if( isset($protocol['pop3']) )
  3404. unset($protocol['pop3']);
  3405. }
  3406. else
  3407. $protocol['pop3'] = 'POP3';
  3408. return $protocol;
  3409. }
  3410. /**
  3411. * The function is used because currently we are not supporting mbstring.func_overload
  3412. * For some user using mssql without FreeTDS, they may store multibyte charaters in varchar using latin_general collation. It cannot store so many mutilbyte characters, so we need to use strlen.
  3413. * The varchar in MySQL, Orcale, and nvarchar in FreeTDS, we can store $length mutilbyte charaters in it. we need mb_substr to keep more info.
  3414. * @returns the substred strings.
  3415. */
  3416. function sugar_substr($string, $length, $charset='UTF-8') {
  3417. if($GLOBALS['db']->dbType == 'mssql' && empty($GLOBALS['db']->isFreeTDS)) {
  3418. if(strlen($string) > $length) {
  3419. $string = trim(substr(trim($string),0,$length));
  3420. }
  3421. }
  3422. else {
  3423. if(mb_strlen($string,$charset) > $length) {
  3424. $string = trim(mb_substr(trim($string),0,$length,$charset));
  3425. }
  3426. }
  3427. return $string;
  3428. }
  3429. /**
  3430. * The function is used because on FastCGI enviroment, the ucfirst(Chinese Characters) will produce bad charcters.
  3431. * This will work even without setting the mbstring.*encoding
  3432. */
  3433. function sugar_ucfirst($string, $charset='UTF-8') {
  3434. return mb_strtoupper(mb_substr($string, 0, 1, $charset), $charset) . mb_substr($string, 1, mb_strlen($string), $charset);
  3435. }
  3436. /**
  3437. *
  3438. */
  3439. function unencodeMultienum($string) {
  3440. if (is_array($string))
  3441. {
  3442. return $string;
  3443. }
  3444. if (substr($string, 0 ,1) == "^" && substr($string, -1) == "^") {
  3445. $string = substr(substr($string, 1), 0, strlen($string) -2);
  3446. }
  3447. return explode('^,^', $string);
  3448. }
  3449. function encodeMultienumValue($arr) {
  3450. if (!is_array($arr))
  3451. return $arr;
  3452. if (empty($arr))
  3453. return "";
  3454. $string = "^" . implode('^,^', $arr) . "^";
  3455. return $string;
  3456. }
  3457. /**
  3458. * create_export_query is used for export and massupdate
  3459. * We haven't handle the these fields: $field['type'] == 'relate' && isset($field['link']
  3460. * This function will correct the where clause and output necessary join condition for them
  3461. * @param $module: the module name
  3462. * @param $searchFields: searchFields which is got after $searchForm->populateFromArray()
  3463. * @param $where: where clauses
  3464. * @return $ret_array['where']: corrected where clause
  3465. * @return $ret_array['join']: extra join condition
  3466. */
  3467. function create_export_query_relate_link_patch($module, $searchFields, $where){
  3468. if(file_exists('modules/'.$module.'/SearchForm.html')){
  3469. $ret_array['where'] = $where;
  3470. return $ret_array;
  3471. }
  3472. $seed = loadBean($module);
  3473. foreach($seed->field_defs as $name=>$field)
  3474. {
  3475. if( $field['type'] == 'relate' && isset($field['link']) && !empty($searchFields[$name]['value']) ){
  3476. $seed->load_relationship($field['link']);
  3477. $params = array();
  3478. if(empty($join_type))
  3479. {
  3480. $params['join_type'] = ' LEFT JOIN ';
  3481. }
  3482. else
  3483. {
  3484. $params['join_type'] = $join_type;
  3485. }
  3486. if(isset($data['join_name']))
  3487. {
  3488. $params['join_table_alias'] = $field['join_name'];
  3489. }
  3490. else
  3491. {
  3492. $params['join_table_alias'] = 'join_'.$field['name'];
  3493. }
  3494. if(isset($data['join_link_name']))
  3495. {
  3496. $params['join_table_link_alias'] = $field['join_link_name'];
  3497. }
  3498. else
  3499. {
  3500. $params['join_table_link_alias'] = 'join_link_'.$field['name'];
  3501. }
  3502. $join = $seed->$field['link']->getJoin($params, true);
  3503. $join_table_alias = 'join_'.$field['name'];
  3504. if(isset($field['db_concat_fields'])){
  3505. $db_field = db_concat($join_table_alias, $field['db_concat_fields']);
  3506. $where = preg_replace('/'.$field['name'].'/', $db_field, $where);
  3507. }else{
  3508. $where = preg_replace('/(^|[\s(])' . $field['name'] . '/', '${1}' . $join_table_alias . '.'.$field['rname'], $where);
  3509. }
  3510. }
  3511. }
  3512. $ret_array = array('where'=>$where, 'join'=>$join['join']);
  3513. return $ret_array;
  3514. }
  3515. /**
  3516. * We need to clear all the js cache files, including the js language files in serval places in MB. So I extract them into a util function here.
  3517. * @Depends on QuickRepairAndRebuild.php
  3518. * @Relate bug 30642 ,23177
  3519. */
  3520. function clearAllJsAndJsLangFilesWithoutOutput(){
  3521. global $current_language , $mod_strings;
  3522. $MBmodStrings = $mod_strings;
  3523. $mod_strings = return_module_language ( $current_language, 'Administration' ) ;
  3524. include_once ('modules/Administration/QuickRepairAndRebuild.php') ;
  3525. $repair = new RepairAndClear();
  3526. $repair->module_list = array();
  3527. $repair->show_output = false;
  3528. $repair->clearJsLangFiles();
  3529. $repair->clearJsFiles();
  3530. $mod_strings = $MBmodStrings;
  3531. }
  3532. /**
  3533. * This function will allow you to get a variable value from query string
  3534. */
  3535. function getVariableFromQueryString($variable, $string){
  3536. $matches = array();
  3537. $number = preg_match("/{$variable}=([a-zA-Z0-9_-]+)[&]?/", $string, $matches);
  3538. if($number){
  3539. return $matches[1];
  3540. }
  3541. else{
  3542. return false;
  3543. }
  3544. }
  3545. /**
  3546. * should_hide_iframes
  3547. * This is a helper method to determine whether or not to show iframes (My Sites) related
  3548. * information in the application.
  3549. *
  3550. * @return boolean flag indicating whether or not iframes module should be hidden
  3551. */
  3552. function should_hide_iframes() {
  3553. //Remove the MySites module
  3554. if(file_exists('modules/iFrames/iFrame.php')) {
  3555. if(!class_exists("iFrame")) {
  3556. require_once('modules/iFrames/iFrame.php');
  3557. }
  3558. return false;
  3559. }
  3560. return true;
  3561. }
  3562. /**
  3563. * Given a version such as 5.5.0RC1 return RC. If we have a version such as: 5.5 then return GA
  3564. *
  3565. * @param string $version
  3566. * @return string RC, BETA, GA
  3567. */
  3568. function getVersionStatus($version){
  3569. if(preg_match('/^[\d\.]+?([a-zA-Z]+?)[\d]*?$/si', $version, $matches)) {
  3570. return strtoupper($matches[1]);
  3571. }else{
  3572. return 'GA';
  3573. }
  3574. }
  3575. /**
  3576. * Return the numeric portion of a version. For example if passed 5.5.0RC1 then return 5.5. If given
  3577. * 5.5.1RC1 then return 5.5.1
  3578. *
  3579. * @param string $version
  3580. * @return version
  3581. */
  3582. function getMajorMinorVersion($version){
  3583. if(preg_match('/^([\d\.]+).*$/si', $version, $matches2)){
  3584. $version = $matches2[1];
  3585. $arr = explode('.', $version);
  3586. if(count($arr) > 2){
  3587. if($arr[2] == '0'){
  3588. $version = substr($version, 0, 3);
  3589. }
  3590. }
  3591. }
  3592. return $version;
  3593. }
  3594. /**
  3595. * Return string composed of seconds & microseconds of current time, without dots
  3596. * @return string
  3597. */
  3598. function sugar_microtime()
  3599. {
  3600. $now = explode(' ', microtime());
  3601. $unique_id = $now[1].str_replace('.', '', $now[0]);
  3602. return $unique_id;
  3603. }
  3604. /**
  3605. * Extract urls from a piece of text
  3606. * @param $string
  3607. * @return array of urls found in $string
  3608. */
  3609. function getUrls($string)
  3610. {
  3611. $lines = explode("<br>", trim($string));
  3612. $urls = array();
  3613. foreach($lines as $line){
  3614. $regex = '/http?\:\/\/[^\" ]+/i';
  3615. preg_match_all($regex, $line, $matches);
  3616. foreach($matches[0] as $match){
  3617. $urls[] = $match;
  3618. }
  3619. }
  3620. return $urls;
  3621. }
  3622. ?>