PageRenderTime 54ms CodeModel.GetById 1ms RepoModel.GetById 0ms app.codeStats 1ms

/SugarCE-6.5.4/SugarCE-Full-6.5.4/include/utils.php

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