PageRenderTime 10ms CodeModel.GetById 82ms app.highlight 62ms RepoModel.GetById 1ms app.codeStats 2ms

/include/utils.php

https://github.com/Barnetik/SuiteCRM
PHP | 5083 lines | 3452 code | 616 blank | 1015 comment | 735 complexity | 300c757f56f3b674a79ca87e471c9e0f MD5 | raw file

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

   1<?php
   2/*********************************************************************************
   3 * SugarCRM Community Edition is a customer relationship management program developed by
   4 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
   5
   6 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
   7 * Copyright (C) 2011 - 2014 Salesagility Ltd.
   8 *
   9 * This program is free software; you can redistribute it and/or modify it under
  10 * the terms of the GNU Affero General Public License version 3 as published by the
  11 * Free Software Foundation with the addition of the following permission added
  12 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
  13 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
  14 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
  15 *
  16 * This program is distributed in the hope that it will be useful, but WITHOUT
  17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
  18 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
  19 * details.
  20 *
  21 * You should have received a copy of the GNU Affero General Public License along with
  22 * this program; if not, see http://www.gnu.org/licenses or write to the Free
  23 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
  24 * 02110-1301 USA.
  25 *
  26 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
  27 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
  28 *
  29 * The interactive user interfaces in modified source and object code versions
  30 * of this program must display Appropriate Legal Notices, as required under
  31 * Section 5 of the GNU Affero General Public License version 3.
  32 *
  33 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
  34 * these Appropriate Legal Notices must retain the display of the "Powered by
  35 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
  36 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
  37 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
  38 ********************************************************************************/
  39
  40/*********************************************************************************
  41
  42 * Description:  Includes generic helper functions used throughout the application.
  43 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
  44 * All Rights Reserved.
  45 * Contributor(s): ______________________________________..
  46 ********************************************************************************/
  47require_once('include/SugarObjects/SugarConfig.php');
  48require_once('include/utils/security_utils.php');
  49
  50
  51
  52function make_sugar_config(&$sugar_config)
  53{
  54	/* used to convert non-array config.php file to array format */
  55	global $admin_export_only;
  56	global $cache_dir;
  57	global $calculate_response_time;
  58	global $create_default_user;
  59	global $dateFormats;
  60	global $dbconfig;
  61	global $dbconfigoption;
  62	global $default_action;
  63	global $default_charset;
  64	global $default_currency_name;
  65	global $default_currency_symbol;
  66    global $default_currency_iso4217;
  67	global $defaultDateFormat;
  68	global $default_language;
  69	global $default_module;
  70	global $default_password;
  71	global $default_permission_mode;
  72	global $default_theme;
  73	global $defaultTimeFormat;
  74	global $default_user_is_admin;
  75	global $default_user_name;
  76	global $disable_export;
  77	global $disable_persistent_connections;
  78	global $display_email_template_variable_chooser;
  79	global $display_inbound_email_buttons;
  80	global $history_max_viewed;
  81	global $host_name;
  82	global $import_dir;
  83	global $languages;
  84	global $list_max_entries_per_page;
  85	global $lock_default_user_name;
  86	global $log_memory_usage;
  87    global $nameFormats;
  88	global $requireAccounts;
  89	global $RSS_CACHE_TIME;
  90	global $session_dir;
  91	global $site_URL;
  92	global $site_url;
  93	global $sugar_version;
  94	global $timeFormats;
  95	global $tmp_dir;
  96	global $translation_string_prefix;
  97	global $unique_key;
  98	global $upload_badext;
  99	global $upload_dir;
 100	global $upload_maxsize;
 101	global $import_max_execution_time;
 102	global $list_max_entries_per_subpanel;
 103	global $passwordsetting;
 104
 105	// assumes the following variables must be set:
 106	// $dbconfig, $dbconfigoption, $cache_dir,  $session_dir, $site_URL, $upload_dir
 107
 108	$sugar_config = array (
 109	'admin_export_only' => empty($admin_export_only) ? false : $admin_export_only,
 110	'export_delimiter' => empty($export_delimiter) ? ',' : $export_delimiter,
 111	'cache_dir' => empty($cache_dir) ? 'cache/' : $cache_dir,
 112	'calculate_response_time' => empty($calculate_response_time) ? true : $calculate_response_time,
 113	'create_default_user' => empty($create_default_user) ? false : $create_default_user,
 114	'chartEngine' => 'Jit',
 115	'date_formats' => empty($dateFormats) ? array(
 116	'Y-m-d'=>'2010-12-23',
 117	'd-m-Y' => '23-12-2010',
 118	'm-d-Y'=>'12-23-2010',
 119	'Y/m/d'=>'2010/12/23',
 120	'd/m/Y' => '23/12/2010',
 121	'm/d/Y'=>'12/23/2010',
 122	'Y.m.d' => '2010.12.23',
 123	'd.m.Y' => '23.12.2010',
 124	'm.d.Y' => '12.23.2010'
 125		) : $dateFormats,
 126	'dbconfig' => $dbconfig,  // this must be set!!
 127	'dbconfigoption' => $dbconfigoption,  // this must be set!!
 128	'default_action' => empty($default_action) ? 'index' : $default_action,
 129	'default_charset' => empty($default_charset) ? 'UTF-8' : $default_charset,
 130	'default_currency_name' => empty($default_currency_name) ? 'US Dollar' : $default_currency_name,
 131	'default_currency_symbol' => empty($default_currency_symbol) ? '$' : $default_currency_symbol,
 132	'default_currency_iso4217' => empty($default_currency_iso4217) ? '$' : $default_currency_iso4217,
 133	'default_date_format' => empty($defaultDateFormat) ? 'm/d/Y' : $defaultDateFormat,
 134    'default_locale_name_format' => empty($defaultNameFormat) ? 's f l' : $defaultNameFormat,
 135	'default_export_charset' => 'UTF-8',
 136	'default_language' => empty($default_language) ? 'en_us' : $default_language,
 137	'default_module' => empty($default_module) ? 'Home' : $default_module,
 138	'default_password' => empty($default_password) ? '' : $default_password,
 139	'default_permissions' => array (
 140		'dir_mode' => 02770,
 141		'file_mode' => 0660,
 142		'chown' => '',
 143		'chgrp' => '',
 144	),
 145    'default_theme' => empty($default_theme) ? 'Sugar5' : $default_theme,
 146    'default_time_format' => empty($defaultTimeFormat) ? 'h:ia' : $defaultTimeFormat,
 147	'default_user_is_admin' => empty($default_user_is_admin) ? false : $default_user_is_admin,
 148	'default_user_name' => empty($default_user_name) ? '' : $default_user_name,
 149	'disable_export' => empty($disable_export) ? false : $disable_export,
 150    'disable_persistent_connections' => empty($disable_persistent_connections) ? false : $disable_persistent_connections,
 151    'display_email_template_variable_chooser' => empty($display_email_template_variable_chooser) ? false : $display_email_template_variable_chooser,
 152	'display_inbound_email_buttons' => empty($display_inbound_email_buttons) ? false : $display_inbound_email_buttons,
 153	'history_max_viewed' => empty($history_max_viewed) ? 50 : $history_max_viewed,
 154	'host_name' => empty($host_name) ? 'localhost' : $host_name,
 155	'import_dir' => $import_dir,  // this must be set!!
 156	'import_max_records_per_file' => 100,
 157    'import_max_records_total_limit' => '',
 158	'languages' => empty($languages) ? array('en_us' => 'English (US)') : $languages,
 159	'list_max_entries_per_page' => empty($list_max_entries_per_page) ? 20 : $list_max_entries_per_page,
 160	'list_max_entries_per_subpanel' => empty($list_max_entries_per_subpanel) ? 10 : $list_max_entries_per_subpanel,
 161	'lock_default_user_name' => empty($lock_default_user_name) ? false : $lock_default_user_name,
 162	'log_memory_usage' => empty($log_memory_usage) ? false : $log_memory_usage,
 163    'name_formats' => empty($nameFormats) ? array(
 164        's f l' => 's f l', 'f l' => 'f l', 's l' => 's l', 'l, s f' => 'l, s f',
 165        'l, f' => 'l, f', 's l, f' => 's l, f', 'l s f' => 'l s f', 'l f s' => 'l f s'
 166    ) : $nameFormats,
 167    'portal_view' => 'single_user',
 168	'resource_management' => array (
 169	    'special_query_limit' => 50000,
 170	    'special_query_modules' => array('Reports', 'Export', 'Import', 'Administration', 'Sync'),
 171	    'default_limit' => 1000,
 172    ),
 173	'require_accounts' => empty($requireAccounts) ? true : $requireAccounts,
 174	'rss_cache_time' => empty($RSS_CACHE_TIME) ? '10800' : $RSS_CACHE_TIME,
 175	'session_dir' => $session_dir,  // this must be set!!
 176	'site_url' => empty($site_URL) ? $site_url : $site_URL,  // this must be set!!
 177	'showDetailData' => true, // if true, read-only ACL fields will still appear on EditViews as non-editable
 178	'showThemePicker' => true,
 179	'sugar_version' => empty($sugar_version) ? 'unknown' : $sugar_version,
 180	'time_formats' => empty($timeFormats) ? array (
 181	'H:i'=>'23:00', 'h:ia'=>'11:00 pm', 'h:iA'=>'11:00PM',
 182	'H.i'=>'23.00', 'h.ia'=>'11.00 pm', 'h.iA'=>'11.00PM' ) : $timeFormats,
 183	'tmp_dir' => $tmp_dir,  // this must be set!!
 184	'translation_string_prefix' => empty($translation_string_prefix) ? false : $translation_string_prefix,
 185	'unique_key' => empty($unique_key) ? md5(create_guid()) : $unique_key,
 186	'upload_badext' => empty($upload_badext) ? array (
 187	'php', 'php3', 'php4', 'php5', 'pl', 'cgi', 'py',
 188	'asp', 'cfm', 'js', 'vbs', 'html', 'htm' ) : $upload_badext,
 189	'upload_dir' => $upload_dir,  // this must be set!!
 190	'upload_maxsize' => empty($upload_maxsize) ? 30000000 : $upload_maxsize,
 191	'import_max_execution_time' => empty($import_max_execution_time) ? 3600 : $import_max_execution_time,
 192	'lock_homepage' => false,
 193	'lock_subpanels' => false,
 194	'max_dashlets_homepage' => 15,
 195	'dashlet_display_row_options' => array('1','3','5','10'),
 196	'default_max_tabs' => empty($max_tabs) ? '7' : $max_tabs,
 197	'default_subpanel_tabs' =>  empty($subpanel_tabs) ? true : $subpanel_tabs,
 198	'default_subpanel_links' => empty($subpanel_links) ? false : $subpanel_links,
 199	'default_swap_last_viewed' => empty($swap_last_viewed) ? false : $swap_last_viewed,
 200	'default_swap_shortcuts' => empty($swap_shortcuts) ? false : $swap_shortcuts,
 201	'default_navigation_paradigm' => empty($navigation_paradigm) ? 'gm' : $navigation_paradigm,
 202    'default_call_status' => 'Planned',
 203	'js_lang_version' => 1,
 204	'passwordsetting' => empty($passwordsetting) ? array (
 205	    'SystemGeneratedPasswordON' => '',
 206	    'generatepasswordtmpl' => '',
 207	    'lostpasswordtmpl' => '',
 208	    'forgotpasswordON' => true,
 209    	'linkexpiration' => '1',
 210    	'linkexpirationtime' => '30',
 211    	'linkexpirationtype' => '1',
 212	    'systexpiration' => '0',
 213	    'systexpirationtime' => '',
 214	    'systexpirationtype' => '0',
 215	    'systexpirationlogin' => '',
 216		) : $passwordsetting,
 217		'use_sprites' => function_exists('imagecreatetruecolor'),
 218    	'search_wildcard_infront' => false,
 219        'search_wildcard_char' => '%',
 220		'jobs' => array(
 221		    'min_retry_interval' => 60, // minimal job retry delay
 222		    'max_retries' => 5, // how many times to retry the job
 223		    'timeout' => 86400, // how long a job may spend as running before being force-failed
 224		    'soft_lifetime' => 7, // how many days until job record will be soft deleted after completion
 225		    'hard_lifetime' => 21, // how many days until job record will be purged from DB
 226		),
 227		"cron" => array(
 228			'max_cron_jobs' => 10, // max jobs per cron schedule run
 229		    'max_cron_runtime' => 60, // max runtime for cron jobs
 230		    'min_cron_interval' => 30, // minimal interval between cron jobs
 231		),
 232	);
 233}
 234
 235function get_sugar_config_defaults() {
 236	global $locale;
 237	/**
 238	 * used for getting base values for array style config.php.  used by the
 239	 * installer and to fill in new entries on upgrades.  see also:
 240	 * sugar_config_union
 241	 */
 242
 243	$sugar_config_defaults = array (
 244	'admin_export_only' => false,
 245	'export_delimiter' => ',',
 246	'export_excel_compatible' => false,
 247	'cache_dir' => 'cache/',
 248	'calculate_response_time' => true,
 249	'create_default_user' => false,
 250 	'chartEngine' => 'Jit',
 251	'date_formats' => array (
 252	'Y-m-d' => '2010-12-23', 'm-d-Y' => '12-23-2010', 'd-m-Y' => '23-12-2010',
 253	'Y/m/d' => '2010/12/23', 'm/d/Y' => '12/23/2010', 'd/m/Y' => '23/12/2010',
 254	'Y.m.d' => '2010.12.23', 'd.m.Y' => '23.12.2010', 'm.d.Y' => '12.23.2010',),
 255    'name_formats' => array (
 256        's f l' => 's f l', 'f l' => 'f l', 's l' => 's l', 'l, s f' => 'l, s f',
 257        'l, f' => 'l, f', 's l, f' => 's l, f', 'l s f' => 'l s f', 'l f s' => 'l f s'
 258    ),
 259	'dbconfigoption' => array (
 260	'persistent' => true,
 261	'autofree' => false,
 262	'debug' => 0,
 263	'ssl' => false ),
 264	'default_action' => 'index',
 265	'default_charset' => return_session_value_or_default('default_charset',
 266	'UTF-8'),
 267	'default_currency_name' => return_session_value_or_default('default_currency_name', 'US Dollar'),
 268	'default_currency_symbol' => return_session_value_or_default('default_currency_symbol', '$'),
 269	'default_currency_iso4217' => return_session_value_or_default('default_currency_iso4217', 'USD'),
 270	'default_currency_significant_digits' => return_session_value_or_default('default_currency_significant_digits', 2),
 271	'default_number_grouping_seperator' => return_session_value_or_default('default_number_grouping_seperator', ','),
 272	'default_decimal_seperator' => return_session_value_or_default('default_decimal_seperator', '.'),
 273	'default_date_format' => 'm/d/Y',
 274    'default_locale_name_format' => 's f l',
 275	'default_export_charset' => 'UTF-8',
 276	'default_language' => return_session_value_or_default('default_language',
 277	'en_us'),
 278	'default_module' => 'Home',
 279	'default_password' => '',
 280	'default_permissions' => array (
 281		'dir_mode' => 02770,
 282		'file_mode' => 0660,
 283		'user' => '',
 284		'group' => '',
 285	),
 286	'default_theme' => return_session_value_or_default('site_default_theme', 'Sugar5'),
 287	'default_time_format' => 'h:ia',
 288	'default_user_is_admin' => false,
 289	'default_user_name' => '',
 290	'disable_export' => false,
 291	'disable_persistent_connections' =>
 292	return_session_value_or_default('disable_persistent_connections',
 293	'false'),
 294    'display_email_template_variable_chooser' => false,
 295	'display_inbound_email_buttons' => false,
 296	'dump_slow_queries' => false,
 297	'email_address_separator' => ',', // use RFC2368 spec unless we have a noncompliant email client
 298    'email_default_editor' => 'html',
 299	'email_default_client' => 'sugar',
 300	'email_default_delete_attachments' => true,
 301	'history_max_viewed' => 50,
 302	'installer_locked' => true,
 303	'import_max_records_per_file' => 100,
 304    'import_max_records_total_limit' => '',
 305	'languages' => array('en_us' => 'English (US)'),
 306	'large_scale_test' => false,
 307	'list_max_entries_per_page' => 20,
 308	'list_max_entries_per_subpanel' => 10,
 309	'lock_default_user_name' => false,
 310	'log_memory_usage' => false,
 311	'portal_view' => 'single_user',
 312    'resource_management' => array (
 313	    'special_query_limit' => 50000,
 314	    'special_query_modules' => array('Reports', 'Export', 'Import', 'Administration', 'Sync'),
 315	    'default_limit' => 1000,
 316    ),
 317	'require_accounts' => true,
 318	'rss_cache_time' => return_session_value_or_default('rss_cache_time',
 319	'10800'),
 320	'save_query' => 'all',
 321	'showDetailData' => true, // if true, read-only ACL fields will still appear on EditViews as non-editable
 322	'showThemePicker' => true,
 323	'slow_query_time_msec' => '100',
 324    'sugarbeet' => true,
 325    'time_formats' => array (
 326        'H:i'=>'23:00', 'h:ia'=>'11:00pm', 'h:iA'=>'11:00PM', 'h:i a'=>'11:00 pm', 'h:i A'=>'11:00 PM',
 327        'H.i'=>'23.00', 'h.ia'=>'11.00pm', 'h.iA'=>'11.00PM', 'h.i a'=>'11.00 pm', 'h.i A'=>'11.00 PM' ),
 328    'tracker_max_display_length' => 15,
 329	'translation_string_prefix' =>
 330	return_session_value_or_default('translation_string_prefix', false),
 331	'upload_badext' => array (
 332	'php', 'php3', 'php4', 'php5', 'pl', 'cgi', 'py',
 333	'asp', 'cfm', 'js', 'vbs', 'html', 'htm' ),
 334	'upload_maxsize' => 30000000,
 335	'import_max_execution_time' => 3600,
 336//	'use_php_code_json' => returnPhpJsonStatus(),
 337	'verify_client_ip' => true,
 338	'js_custom_version' => '',
 339	'js_lang_version' => 1,
 340        'lead_conv_activity_opt' => 'donothing',
 341	'default_number_grouping_seperator' => ',',
 342	'default_decimal_seperator' => '.',
 343	'lock_homepage' => false,
 344	'lock_subpanels' => false,
 345	'max_dashlets_homepage' => '15',
 346	'default_max_tabs' => '7',
 347	'dashlet_display_row_options' => array('1','3','5','10'),
 348	'default_subpanel_tabs' =>  true,
 349	'default_subpanel_links' => false,
 350	'default_swap_last_viewed' => false,
 351	'default_swap_shortcuts' => false,
 352	'default_navigation_paradigm' => 'gm',
 353	'admin_access_control' => false,
 354  	'use_common_ml_dir'	=> false,
 355  	'common_ml_dir' => '',
 356	'vcal_time' => '2',
 357	'calendar' => array(
 358	  'default_view' => 'week',
 359	  'show_calls_by_default' => true,
 360	  'show_tasks_by_default' => true,
 361	  'show_completed_by_default' => true,
 362	  'editview_width' => 990,
 363	  'editview_height' => 485,
 364	  'day_timestep' => 15,
 365	  'week_timestep' => 30,
 366	  'items_draggable' => true,
 367	  'items_resizable' => true,
 368	  'enable_repeat' => true,
 369	  'max_repeat_count' => 1000,
 370	),
 371	'passwordsetting' => empty($passwordsetting) ? array (
 372	    'SystemGeneratedPasswordON' => '',
 373	    'generatepasswordtmpl' => '',
 374	    'lostpasswordtmpl' => '',
 375	    'forgotpasswordON' => false,
 376    	'linkexpiration' => '1',
 377    	'linkexpirationtime' => '30',
 378    	'linkexpirationtype' => '1',
 379	    'systexpiration' => '0',
 380	    'systexpirationtime' => '',
 381	    'systexpirationtype' => '0',
 382	    'systexpirationlogin' => '',
 383		) : $passwordsetting,
 384		'use_real_names' => true,
 385
 386		'search_wildcard_infront' => false,
 387        'search_wildcard_char' => '%',
 388		'jobs' => array(
 389		    'min_retry_interval' => 30, // 30 seconds minimal job retry
 390		    'max_retries' => 5, // how many times to retry the job
 391		    'timeout' => 86400, // how long a job may spend as running before being force-failed
 392		),
 393		"cron" => array(
 394			'max_cron_jobs' => 10, // max jobs per cron schedule run
 395		    'max_cron_runtime' => 30, // max runtime for cron jobs
 396		    'min_cron_interval' => 30, // minimal interval between cron jobs
 397		),
 398    );
 399
 400	if(!is_object($locale)) {
 401		$locale = new Localization();
 402	}
 403
 404	$sugar_config_defaults['default_currencies'] = $locale->getDefaultCurrencies();
 405
 406	$sugar_config_defaults = sugarArrayMerge($locale->getLocaleConfigDefaults(), $sugar_config_defaults);
 407	return( $sugar_config_defaults );
 408}
 409
 410/**
 411 * @deprecated use SugarView::getMenu() instead
 412 */
 413function load_menu($path){
 414	global $module_menu;
 415
 416	if(file_exists($path . 'Menu.php'))
 417	{
 418		require($path . 'Menu.php');
 419	}
 420	if(file_exists('custom/' . $path . 'Ext/Menus/menu.ext.php'))
 421	{
 422		require('custom/' . $path . 'Ext/Menus/menu.ext.php');
 423	}
 424	if(file_exists('custom/application/Ext/Menus/menu.ext.php'))
 425	{
 426		require('custom/application/Ext/Menus/menu.ext.php');
 427	}
 428	return $module_menu;
 429}
 430
 431/**
 432 * get_notify_template_file
 433 * This function will return the location of the email notifications template to use
 434 *
 435 * @return string relative file path to email notifications template file
 436 */
 437function get_notify_template_file($language){
 438	/*
 439	 * Order of operation:
 440	 * 1) custom version of specified language
 441	 * 2) stock version of specified language
 442	 * 3) custom version of en_us template
 443	 * 4) stock en_us template
 444	 */
 445
 446	// set $file to the base code template so it's set if none of the conditions pass
 447	$file = "include/language/en_us.notify_template.html";
 448
 449	if(file_exists("custom/include/language/{$language}.notify_template.html")){
 450		$file = "custom/include/language/{$language}.notify_template.html";
 451	}
 452	else if(file_exists("include/language/{$language}.notify_template.html")){
 453		$file = "include/language/{$language}.notify_template.html";
 454	}
 455	else if(file_exists("custom/include/language/en_us.notify_template.html")){
 456		$file = "custom/include/language/en_us.notify_template.html";
 457	}
 458
 459	return $file;
 460}
 461
 462function sugar_config_union( $default, $override ){
 463	// a little different then array_merge and array_merge_recursive.  we want
 464	// the second array to override the first array if the same value exists,
 465	// otherwise merge the unique keys.  it handles arrays of arrays recursively
 466	// might be suitable for a generic array_union
 467	if( !is_array( $override ) ){
 468		$override = array();
 469	}
 470	foreach( $default as $key => $value ){
 471		if( !array_key_exists($key, $override) ){
 472			$override[$key] = $value;
 473		}
 474		else if( is_array( $key ) ){
 475			$override[$key] = sugar_config_union( $value, $override[$key] );
 476		}
 477	}
 478	return( $override );
 479}
 480
 481function make_not_writable( $file ){
 482	// Returns true if the given file/dir has been made not writable
 483	$ret_val = false;
 484	if( is_file($file) || is_dir($file) ){
 485		if( !is_writable($file) ){
 486			$ret_val = true;
 487		}
 488		else {
 489			$original_fileperms = fileperms($file);
 490
 491			// take away writable permissions
 492			$new_fileperms = $original_fileperms & ~0x0092;
 493			@sugar_chmod($file, $new_fileperms);
 494
 495			if( !is_writable($file) ){
 496				$ret_val = true;
 497			}
 498		}
 499	}
 500	return $ret_val;
 501}
 502
 503
 504/** This function returns the name of the person.
 505 * It currently returns "first last".  It should not put the space if either name is not available.
 506 * It should not return errors if either name is not available.
 507 * If no names are present, it will return ""
 508 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 509 * All Rights Reserved.
 510 * Contributor(s): ______________________________________..
 511 */
 512function return_name($row, $first_column, $last_column)
 513{
 514	$first_name = "";
 515	$last_name = "";
 516	$full_name = "";
 517
 518	if(isset($row[$first_column]))
 519	{
 520		$first_name = stripslashes($row[$first_column]);
 521	}
 522
 523	if(isset($row[$last_column]))
 524	{
 525		$last_name = stripslashes($row[$last_column]);
 526	}
 527
 528	$full_name = $first_name;
 529
 530	// If we have a first name and we have a last name
 531	if($full_name != "" && $last_name != "")
 532	{
 533		// append a space, then the last name
 534		$full_name .= " ".$last_name;
 535	}
 536	// If we have no first name, but we have a last name
 537	else if($last_name != "")
 538	{
 539		// append the last name without the space.
 540		$full_name .= $last_name;
 541	}
 542
 543	return $full_name;
 544}
 545
 546
 547function get_languages()
 548{
 549	global $sugar_config;
 550	$lang = $sugar_config['languages'];
 551    if(!empty($sugar_config['disabled_languages'])){
 552        foreach(explode(',', $sugar_config['disabled_languages']) as $disable) {
 553            unset($lang[$disable]);
 554        }
 555    }
 556	return $lang;
 557}
 558
 559function get_all_languages()
 560{
 561	global $sugar_config;
 562	return $sugar_config['languages'];
 563}
 564
 565
 566function get_language_display($key)
 567{
 568	global $sugar_config;
 569	return $sugar_config['languages'][$key];
 570}
 571
 572function get_assigned_user_name($assigned_user_id, $is_group = '') {
 573	static $saved_user_list = null;
 574
 575	if(empty($saved_user_list)) {
 576		$saved_user_list = get_user_array(false, '', '', false, null, $is_group);
 577	}
 578
 579	if(isset($saved_user_list[$assigned_user_id])) {
 580		return $saved_user_list[$assigned_user_id];
 581	}
 582
 583	return '';
 584}
 585
 586/**
 587 * retrieves the user_name column value (login)
 588 * @param string id GUID of user
 589 * @return string
 590 */
 591function get_user_name($id) {
 592	global $db;
 593
 594	if(empty($db))
 595	$db = DBManagerFactory::getInstance();
 596
 597	$q = "SELECT user_name FROM users WHERE id='{$id}'";
 598	$r = $db->query($q);
 599	$a = $db->fetchByAssoc($r);
 600
 601	return (empty($a)) ? '' : $a['user_name'];
 602}
 603
 604
 605//TODO Update to use global cache
 606/**
 607 * get_user_array
 608 *
 609 * This is a helper function to return an Array of users depending on the parameters passed into the function.
 610 * This function uses the get_register_value function by default to use a caching layer where supported.
 611 * This function has been updated return the array sorted by user preference of name display (bug 62712)
 612 *
 613 * @param bool $add_blank Boolean value to add a blank entry to the array results, true by default
 614 * @param string $status String value indicating the status to filter users by, "Active" by default
 615 * @param string $user_id String value to specify a particular user id value (searches the id column of users table), blank by default
 616 * @param bool $use_real_name Boolean value indicating whether or not results should include the full name or just user_name, false by default
 617 * @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
 618 * @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
 619 * @param bool $from_cache Boolean value indicating whether or not to use the get_register_value function for caching, true by default
 620 * @return array Array of users matching the filter criteria that may be from cache (if similar search was previously run)
 621 */
 622function 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) {
 623	global $locale, $sugar_config, $current_user;
 624
 625	if(empty($locale)) {
 626		$locale = new Localization();
 627	}
 628
 629	if($from_cache) {
 630        $key_name = $add_blank. $status . $user_id . $use_real_name . $user_name_filter . $portal_filter;
 631		$user_array = get_register_value('user_array', $key_name);
 632    }
 633
 634	if(empty($user_array)) {
 635		$db = DBManagerFactory::getInstance();
 636		$temp_result = Array();
 637		// Including deleted users for now.
 638		if (empty($status)) {
 639			$query = "SELECT id, first_name, last_name, user_name from users WHERE 1=1".$portal_filter;
 640		}
 641		else {
 642			$query = "SELECT id, first_name, last_name, user_name from users WHERE status='$status'".$portal_filter;
 643		}
 644        /* BEGIN - SECURITY GROUPS */
 645        global $current_user, $sugar_config;
 646        if(!is_admin($current_user)
 647            && isset($sugar_config['securitysuite_filter_user_list'])
 648            && $sugar_config['securitysuite_filter_user_list'] == true
 649            && (empty($_REQUEST['module']) || $_REQUEST['module'] != 'Home')
 650            && (empty($_REQUEST['action']) || $_REQUEST['action'] != 'DynamicAction')
 651        ) {
 652            require_once('modules/SecurityGroups/SecurityGroup.php');
 653            global $current_user;
 654            $group_where = SecurityGroup::getGroupUsersWhere($current_user->id);
 655            $query .= " AND (".$group_where.") ";
 656        }
 657        /* END - SECURITY GROUPS */
 658		if (!empty($user_name_filter)) {
 659		    $user_name_filter = $db->quote($user_name_filter);
 660			$query .= " AND user_name LIKE '$user_name_filter%' ";
 661		}
 662		if (!empty($user_id)) {
 663			$query .= " OR id='{$user_id}'";
 664		}
 665
 666        //get the user preference for name formatting, to be used in order by
 667        $order_by_string =' user_name ASC ';
 668        if(!empty($current_user) && !empty($current_user->id))
 669        {
 670            $formatString = $current_user->getPreference('default_locale_name_format');
 671
 672            //create the order by string based on position of first and last name in format string
 673            $order_by_string =' user_name ASC ';
 674            $firstNamePos = strpos( $formatString, 'f');
 675            $lastNamePos = strpos( $formatString, 'l');
 676            if($firstNamePos !== false || $lastNamePos !== false){
 677                //its possible for first name to be skipped, check for this
 678                if($firstNamePos===false){
 679                    $order_by_string =  'last_name ASC';
 680                }else{
 681                    $order_by_string =  ($lastNamePos < $firstNamePos) ? "last_name, first_name ASC" : "first_name, last_name ASC";
 682                }
 683            }
 684        }
 685
 686		$query = $query.' ORDER BY '.$order_by_string;
 687		$GLOBALS['log']->debug("get_user_array query: $query");
 688		$result = $db->query($query, true, "Error filling in user array: ");
 689
 690		if ($add_blank==true) {
 691			// Add in a blank row
 692			$temp_result[''] = '';
 693		}
 694
 695		// Get the id and the name.
 696		while($row = $db->fetchByAssoc($result)) {
 697			if($use_real_name == true || showFullName()) {
 698				if(isset($row['last_name'])) { // cn: we will ALWAYS have both first_name and last_name (empty value if blank in db)
 699					$temp_result[$row['id']] = $locale->getLocaleFormattedName($row['first_name'],$row['last_name']);
 700				} else {
 701					$temp_result[$row['id']] = $row['user_name'];
 702				}
 703			} else {
 704				$temp_result[$row['id']] = $row['user_name'];
 705			}
 706		}
 707
 708		$user_array = $temp_result;
 709		if($from_cache)
 710        {
 711			set_register_value('user_array', $key_name, $temp_result);
 712        }
 713	}
 714
 715
 716	return $user_array;
 717}
 718
 719
 720/**
 721 * uses a different query to return a list of users than get_user_array()
 722 * Used from QuickSearch.php
 723 * @param args string where clause entry
 724 * @return array Array of Users' details that match passed criteria
 725 */
 726function getUserArrayFromFullName($args, $hide_portal_users = false) {
 727	global $locale;
 728	$db = DBManagerFactory::getInstance();
 729
 730	// jmorais@dri - Bug #51411
 731	//
 732    // Refactor the code responsible for parsing supplied $args, this way we
 733    // ensure that if $args has at least one space (after trim), the $inClause
 734    // will be composed by several clauses ($inClauses) inside parenthesis.
 735    //
 736    // Ensuring that operator precedence is respected, and avoiding
 737    // inactive/deleted users to be retrieved.
 738    //
 739    $args = trim($args);
 740    if (strpos($args, ' ')) {
 741        $inClauses = array();
 742
 743        $argArray = explode(' ', $args);
 744        foreach ($argArray as $arg) {
 745            $arg = $db->quote($arg);
 746            $inClauses[] = "(first_name LIKE '{$arg}%' OR last_name LIKE '{$arg}%')";
 747        }
 748
 749        $inClause = '(' . implode('OR ', $inClauses) . ')';
 750
 751    } else {
 752        $args = $db->quote($args);
 753        $inClause = "(first_name LIKE '{$args}%' OR last_name LIKE '{$args}%')";
 754    }
 755    // ~jmorais@dri
 756
 757	$query  = "SELECT id, first_name, last_name, user_name FROM users WHERE status='Active' AND deleted=0 AND ";
 758	if ( $hide_portal_users ) {
 759	    $query .= " portal_only=0 AND ";
 760	}
 761	$query .= $inClause;
 762    /* BEGIN - SECURITY GROUPS */
 763    global $current_user, $sugar_config;
 764    if(!is_admin($current_user)
 765        && isset($sugar_config['securitysuite_filter_user_list'])
 766        && $sugar_config['securitysuite_filter_user_list'] == true
 767    ) {
 768        require_once('modules/SecurityGroups/SecurityGroup.php');
 769        global $current_user;
 770        $group_where = SecurityGroup::getGroupUsersWhere($current_user->id);
 771        $query .= " AND (".$group_where.") ";
 772    }
 773    /* END - SECURITY GROUPS */
 774	$query .= " ORDER BY last_name ASC";
 775
 776	$r = $db->query($query);
 777	$ret = array();
 778	while($a = $db->fetchByAssoc($r)) {
 779		$ret[$a['id']] = $locale->getLocaleFormattedName($a['first_name'], $a['last_name']);
 780	}
 781
 782	return $ret;
 783}
 784
 785/**
 786 *
 787 * based on user pref then system pref
 788 */
 789function showFullName() {
 790	global $sugar_config;
 791	global $current_user;
 792	static $showFullName = null;
 793
 794	if (is_null($showFullName)) {
 795		$sysPref = !empty($sugar_config['use_real_names']);
 796		$userPref = (is_object($current_user)) ? $current_user->getPreference('use_real_names') : null;
 797
 798		if($userPref != null) {
 799			$showFullName = ($userPref == 'on');
 800		} else {
 801			$showFullName = $sysPref;
 802		}
 803	}
 804
 805	return $showFullName;
 806}
 807
 808function clean($string, $maxLength)
 809{
 810	$string = substr($string, 0, $maxLength);
 811	return escapeshellcmd($string);
 812}
 813
 814/**
 815 * Copy the specified request variable to the member variable of the specified object.
 816 * Do no copy if the member variable is already set.
 817 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 818 * All Rights Reserved.
 819 * Contributor(s): ______________________________________..
 820 */
 821function safe_map($request_var, & $focus, $always_copy = false)
 822{
 823	safe_map_named($request_var, $focus, $request_var, $always_copy);
 824}
 825
 826/**
 827 * Copy the specified request variable to the member variable of the specified object.
 828 * Do no copy if the member variable is already set.
 829 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
 830 * All Rights Reserved.
 831 * Contributor(s): ______________________________________..
 832 */
 833function safe_map_named($request_var, & $focus, $member_var, $always_copy)
 834{
 835	if (isset($_REQUEST[$request_var]) && ($always_copy || is_null($focus->$member_var))) {
 836		$GLOBALS['log']->debug("safe map named called assigning '{$_REQUEST[$request_var]}' to $member_var");
 837		$focus->$member_var = $_REQUEST[$request_var];
 838	}
 839}
 840
 841/**
 842 * This function retrieves an application language file and returns the array of strings included in the $app_list_strings var.
 843 *
 844 * @param string $language specific language to load
 845 * @return array lang strings
 846 */
 847function return_app_list_strings_language($language)
 848{
 849	global $app_list_strings;
 850	global $sugar_config;
 851
 852	$cache_key = 'app_list_strings.'.$language;
 853
 854	// Check for cached value
 855	$cache_entry = sugar_cache_retrieve($cache_key);
 856	if(!empty($cache_entry))
 857	{
 858		return $cache_entry;
 859	}
 860
 861	$default_language = $sugar_config['default_language'];
 862	$temp_app_list_strings = $app_list_strings;
 863
 864	$langs = array();
 865	if ($language != 'en_us') {
 866	    $langs[] = 'en_us';
 867	}
 868	if ($default_language != 'en_us' && $language != $default_language) {
 869	    $langs[] = $default_language;
 870	}
 871	$langs[] = $language;
 872
 873	$app_list_strings_array = array();
 874
 875	foreach ( $langs as $lang ) {
 876	    $app_list_strings = array();
 877	    if(file_exists("include/language/$lang.lang.php")) {
 878            include("include/language/$lang.lang.php");
 879            $GLOBALS['log']->info("Found language file: $lang.lang.php");
 880        }
 881        if(file_exists("include/language/$lang.lang.override.php")) {
 882            include("include/language/$lang.lang.override.php");
 883            $GLOBALS['log']->info("Found override language file: $lang.lang.override.php");
 884        }
 885        if(file_exists("include/language/$lang.lang.php.override")) {
 886            include("include/language/$lang.lang.php.override");
 887            $GLOBALS['log']->info("Found override language file: $lang.lang.php.override");
 888        }
 889
 890        $app_list_strings_array[] = $app_list_strings;
 891    }
 892
 893    $app_list_strings = array();
 894    foreach ( $app_list_strings_array as $app_list_strings_item ) {
 895        $app_list_strings = sugarLangArrayMerge($app_list_strings, $app_list_strings_item);
 896    }
 897
 898    foreach ( $langs as $lang ) {
 899        if(file_exists("custom/application/Ext/Language/$lang.lang.ext.php")) {
 900            $app_list_strings = _mergeCustomAppListStrings("custom/application/Ext/Language/$lang.lang.ext.php" , $app_list_strings);
 901            $GLOBALS['log']->info("Found extended language file: $lang.lang.ext.php");
 902        }
 903        if(file_exists("custom/include/language/$lang.lang.php")) {
 904            include("custom/include/language/$lang.lang.php");
 905            $GLOBALS['log']->info("Found custom language file: $lang.lang.php");
 906        }
 907    }
 908
 909	if(!isset($app_list_strings)) {
 910		$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");
 911		return null;
 912	}
 913
 914	$return_value = $app_list_strings;
 915	$app_list_strings = $temp_app_list_strings;
 916
 917	sugar_cache_put($cache_key, $return_value);
 918
 919	return $return_value;
 920}
 921
 922/**
 923* The dropdown items in custom language files is $app_list_strings['$key']['$second_key'] = $value not
 924* $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.
 925 * @param file string the language that you want include,
 926 * @param app_list_strings array the golbal strings
 927 * @return array
 928 */
 929 //jchi 25347
 930function _mergeCustomAppListStrings($file , $app_list_strings){
 931	$app_list_strings_original = $app_list_strings;
 932	unset($app_list_strings);
 933        // FG - bug 45525 - $exemptDropdown array is defined (once) here, not inside the foreach
 934        //                  This way, language file can add items to save specific standard codelist from being overwritten
 935        $exemptDropdowns = array();
 936	include($file);
 937	if(!isset($app_list_strings) || !is_array($app_list_strings)){
 938		return $app_list_strings_original;
 939	}
 940	//Bug 25347: We should not merge custom dropdown fields unless they relate to parent fields or the module list.
 941
 942        // FG - bug 45525 - Specific codelists must NOT be overwritten
 943	$exemptDropdowns[] = "moduleList";
 944	$exemptDropdowns[] = "moduleListSingular";
 945        $exemptDropdowns = array_merge($exemptDropdowns, getTypeDisplayList());
 946
 947	foreach($app_list_strings as $key=>$value)
 948	{
 949		if (!in_array($key, $exemptDropdowns) && array_key_exists($key, $app_list_strings_original))
 950		{
 951	   		unset($app_list_strings_original["$key"]);
 952		}
 953   }
 954   $app_list_strings = sugarArrayMergeRecursive($app_list_strings_original , $app_list_strings);
 955   return $app_list_strings;
 956}
 957
 958/**
 959 * This function retrieves an application language file and returns the array of strings included.
 960 *
 961 * @param string $language specific language to load
 962 * @return array lang strings
 963 */
 964function return_application_language($language)
 965{
 966	global $app_strings, $sugar_config;
 967
 968	$cache_key = 'app_strings.'.$language;
 969
 970	// Check for cached value
 971	$cache_entry = sugar_cache_retrieve($cache_key);
 972	if(!empty($cache_entry))
 973	{
 974		return $cache_entry;
 975	}
 976
 977	$temp_app_strings = $app_strings;
 978	$default_language = $sugar_config['default_language'];
 979
 980	$langs = array();
 981	if ($language != 'en_us') {
 982	    $langs[] = 'en_us';
 983	}
 984	if ($default_language != 'en_us' && $language != $default_language) {
 985	    $langs[] = $default_language;
 986	}
 987
 988	$langs[] = $language;
 989
 990	$app_strings_array = array();
 991
 992	foreach ( $langs as $lang ) {
 993	    $app_strings = array();
 994	    if(file_exists("include/language/$lang.lang.php")) {
 995            include("include/language/$lang.lang.php");
 996            $GLOBALS['log']->info("Found language file: $lang.lang.php");
 997        }
 998        if(file_exists("include/language/$lang.lang.override.php")) {
 999            include("include/language/$lang.lang.override.php");
1000            $GLOBALS['log']->info("Found override language file: $lang.lang.override.php");
1001        }
1002        if(file_exists("include/language/$lang.lang.php.override")) {
1003            include("include/language/$lang.lang.php.override");
1004            $GLOBALS['log']->info("Found override language file: $lang.lang.php.override");
1005        }
1006        if(file_exists("custom/application/Ext/Language/$lang.lang.ext.php")) {
1007            include("custom/application/Ext/Language/$lang.lang.ext.php");
1008            $GLOBALS['log']->info("Found extended language file: $lang.lang.ext.php");
1009        }
1010        if(file_exists("custom/include/language/$lang.lang.php")) {
1011            include("custom/include/language/$lang.lang.php");
1012            $GLOBALS['log']->info("Found custom language file: $lang.lang.php");
1013        }
1014        $app_strings_array[] = $app_strings;
1015	}
1016
1017	$app_strings = array();
1018    foreach ( $app_strings_array as $app_strings_item ) {
1019        $app_strings = sugarLangArrayMerge($app_strings, $app_strings_item);
1020    }
1021
1022	if(!isset($app_strings)) {
1023		$GLOBALS['log']->fatal("Unable to load the application language strings");
1024		return null;
1025	}
1026
1027	// If we are in debug mode for translating, turn on the prefix now!
1028    if(!empty($sugar_config['translation_string_prefix']))
1029    {
1030		foreach($app_strings as $entry_key=>$entry_value) {
1031			$app_strings[$entry_key] = $language.' '.$entry_value;
1032		}
1033	}
1034	if(isset($_SESSION['show_deleted'])) {
1035		$app_strings['LBL_DELETE_BUTTON'] = $app_strings['LBL_UNDELETE_BUTTON'];
1036		$app_strings['LBL_DELETE_BUTTON_LABEL'] = $app_strings['LBL_UNDELETE_BUTTON_LABEL'];
1037		$app_strings['LBL_DELETE_BUTTON_TITLE'] = $app_strings['LBL_UNDELETE_BUTTON_TITLE'];
1038		$app_strings['LBL_DELETE'] = $app_strings['LBL_UNDELETE'];
1039	}
1040
1041	$app_strings['LBL_ALT_HOT_KEY'] = get_alt_hot_key();
1042
1043	$return_value = $app_strings;
1044	$app_strings = $temp_app_strings;
1045
1046	sugar_cache_put($cache_key, $return_value);
1047
1048	return $return_value;
1049}
1050
1051/**
1052 * This function retrieves a module's language file and returns the array of strings included.
1053 *
1054 * @param string $language specific language to load
1055 * @param string $module module name to load strings for
1056 * @param bool $refresh optional, true if you want to rebuild the language strings
1057 * @return array lang strings
1058 */
1059function return_module_language($language, $module, $refresh=false)
1060{
1061	global $mod_strings;
1062	global $sugar_config;
1063	global $currentModule;
1064
1065	// Jenny - Bug 8119: Need to check if $module is not empty
1066	if (empty($module)) {
1067		$stack  = debug_backtrace();
1068		$GLOBALS['log']->warn("Variable module is not in return_module_language ". var_export($stack, true));
1069		return array();
1070	}
1071
1072    if( !$refresh )
1073    {
1074        $cache_key = LanguageManager::getLanguageCacheKey($module, $language);
1075        // Check for cached value
1076        $cache_entry = sugar_cache_retrieve($cache_key);
1077        if(!empty($cache_entry) && is_array($cache_entry))
1078        {
1079            return $cache_entry;
1080        }
1081    }
1082	// Store the current mod strings for later
1083	$temp_mod_strings = $mod_strings;
1084	$loaded_mod_strings = array();
1085	$language_used = $language;
1086	$default_language = $sugar_config['default_language'];
1087
1088	if(empty($language)) {
1089		$language = $default_language;
1090	}
1091
1092	// Bug 21559 - So we can get all the strings defined in the template, refresh
1093	// the vardefs file if the cached language file doesn't exist.
1094    if(!file_exists(sugar_cached('modules/'). $module . '/language/'.$language.'.lang.php')
1095			&& !empty($GLOBALS['beanList'][$module])){
1096		$object = BeanFactory::getObjectName($module);
1097		VardefManager::refreshVardefs($module,$object);
1098	}
1099
1100	$loaded_mod_strings = LanguageManager::loadModuleLanguage($module, $language,$refresh);
1101
1102	// cn: bug 6048 - merge en_us with requested language
1103	if($language != $sugar_config['default_language'])
1104        $loaded_mod_strings = sugarLangArrayMerge(
1105            LanguageManager::loadModuleLanguage($module, $sugar_config['default_language'],$refresh),
1106                $loaded_mod_strings
1107            );
1108
1109    // Load in en_us strings by default
1110    if($language != 'en_us' && $sugar_config['default_language'] != 'en_us')
1111        $loaded_mod_strings = sugarLangArrayMerge(
1112            LanguageManager::loadModuleLanguage($module, 'en_us', $refresh),
1113                $loaded_mod_strings
1114            );
1115
1116	// If we are in debug mode for translating, turn on the prefix now!
1117	if($sugar_config['translation_string_prefix']) {
1118		foreach($loaded_mod_strings as $entry_key=>$entry_value) {
1119			$loaded_mod_strings[$entry_key] = $language_used.' '.$entry_value;
1120		}
1121	}
1122
1123	$return_value = $loaded_mod_strings;
1124	if(!isset($mod_strings)){
1125		$mod_strings = $return_value;
1126	}
1127	else
1128		$mod_strings = $temp_mod_strings;
1129
1130    $cache_key = LanguageManager::getLanguageCacheKey($module, $language);
1131    sugar_cache_put($cache_key, $return_value);
1132	return $return_value;
1133}
1134
1135
1136/** This function retrieves an application language file and returns the array of strings included in the $mod_list_strings var.
1137 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1138 * All Rights Reserved.
1139 * Contributor(s): ______________________________________..
1140 * If you are using the current language, do not call this function unless you are loading it for the first time */
1141function return_mod_list_strings_language($language,$module) {
1142	global $mod_list_strings;
1143	global $sugar_config;
1144	global $currentModule;
1145
1146	$cache_key = "mod_list_str_lang.".$language.$module;
1147
1148	// Check for cached value
1149	$cache_entry = sugar_cache_retrieve($cache_key);
1150	if(!empty($cache_entry))
1151	{
1152		return $cache_entry;
1153	}
1154
1155	$language_used = $language;
1156	$temp_mod_list_strings = $mod_list_strings;
1157	$default_language = $sugar_config['default_language'];
1158
1159	if($currentModule == $module && isset($mod_list_strings) && $mod_list_strings != null) {
1160		return $mod_list_strings;
1161	}
1162
1163	// cn: bug 6351 - include en_us if file langpack not available
1164	// cn: bug 6048 - merge en_us with requested language
1165	include("modules/$module/language/en_us.lang.php");
1166	$en_mod_list_strings = array();
1167	if($language_used != $default_language)
1168	$en_mod_list_strings = $mod_list_strings;
1169
1170	if(file_exists("modules/$module/language/$language.lang.php")) {
1171		include("modules/$module/language/$language.lang.php");
1172	}
1173
1174	if(file_exists("modules/$module/language/$language.lang.override.php")){
1175		include("modules/$module/language/$language.lang.override.php");
1176	}
1177
1178	if(file_exists("modules/$module/language/$language.lang.php.override")){
1179		echo 'Please Change:<br>' . "modules/$module/language/$language.lang.php.override" . '<br>to<br>' . 'Please Change:<br>' . "modules/$module/language/$language.lang.override.php";
1180		include("modules/$module/language/$language.lang.php.override");
1181	}
1182
1183	// cn: bug 6048 - merge en_us with requested language
1184	$mod_list_strings = sugarLangArrayMerge($en_mod_list_strings, $mod_list_strings);
1185
1186	// if we still don't have a language pack, then log an error
1187	if(!isset($mod_list_strings)) {
1188		$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})");
1189		return null;
1190	}
1191
1192	$return_value = $mod_list_strings;
1193	$mod_list_strings = $temp_mod_list_strings;
1194
1195	sugar_cache_put($cache_key, $return_value);
1196	return $return_value;
1197}
1198
1199
1200/** This function retrieves a theme's language file and returns the array of strings included.
1201 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1202 * All Rights Reserved.
1203 * Contributor(s): ______________________________________..
1204 */
1205function return_theme_language($language, $theme)
1206{
1207	global $mod_strings, $sugar_config, $current_language;
1208
1209	$language_used = $language;
1210	$default_language = $sugar_config['default_language'];
1211
1212	include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php");
1213	if(file_exists(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.override.php")){
1214		include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.override.php");
1215	}
1216	if(file_exists(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php.override")){
1217		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";
1218		include(SugarThemeRegistry::get($theme)->getFilePath()."/language/$current_language.lang.php.override");
1219	}
1220	if(!isset($theme_strings))
1221	{
1222		$GLOBALS['log']->warn("Unable to find the theme file for language: ".$language." and theme: ".$theme);
1223		require(SugarThemeRegistry::get($theme)->getFilePath()."/language/$default_language.lang.php");
1224		$language_used = $default_language;
1225	}
1226
1227	if(!isset($theme_strings))
1228	{
1229		$GLOBALS['log']->fatal("Unable to load the theme($theme) language file for the selected language($language) or the default language($default_language)");
1230		return null;
1231	}
1232
1233	// If we are in debug mode for translating, turn on the prefix now!
1234	if($sugar_config['translation_string_prefix'])
1235	{
1236		foreach($theme_strings as $entry_key=>$entry_value)
1237		{
1238			$theme_strings[$entry_key] = $language_used.' '.$entry_value;
1239		}
1240	}
1241
1242	return $theme_strings;
1243}
1244
1245
1246
1247/** If the session variable is defined and is not equal to "" then return it.  Otherwise, return the default value.
1248 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1249 * All Rights Reserved.
1250 * Contributor(s): ______________________________________..
1251 */
1252function return_session_value_or_default($varname, $default)
1253{
1254	if(isset($_SESSION[$varname]) && $_SESSION[$varname] != "")
1255	{
1256		return $_SESSION[$varname];
1257	}
1258
1259	return $default;
1260}
1261
1262/**
1263 * Creates an array of where restrictions.  These are used to construct a where SQL statement on the query
1264 * 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.
1265 * @param &$where_clauses - The array to append the clause to
1266 * @param $variable_name - The name of the variable to look for an add to the where clause if found
1267 * @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.
1268 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1269 * All Rights Reserved.
1270 * Contributor(s): ______________________________________..
1271 */
1272function append_where_clause(&$where_clauses, $variable_name, $SQL_name = null)
1273{
1274	if($SQL_name == null)
1275	{
1276		$SQL_name = $variable_name;
1277	}
1278
1279	if(isset($_REQUEST[$variable_name]) && $_REQUEST[$variable_name] != "")
1280	{
1281		array_push($where_clauses, "$SQL_name like '".$GLOBALS['db']->quote($_REQUEST[$variable_name])."%'");
1282	}
1283}
1284
1285/**
1286 * Generate the appropriate SQL based on the where clauses.
1287 * @param $where_clauses - An Array of individual where clauses stored as strings
1288 * @returns string where_clause - The final SQL where clause to be executed.
1289 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1290 * All Rights Reserved.
1291 * Contributor(s): ______________________________________..
1292 */
1293function generate_where_statement($where_clauses)
1294{
1295	$where = "";
1296	foreach($where_clauses as $clause)
1297	{
1298		if($where != "")
1299		$where .= " and ";
1300		$where .= $clause;
1301	}
1302
1303	$GLOBALS['log']->info("Here is the where clause for the list view: $where");
1304	return $where;
1305}
1306
1307/**
1308 * determines if a passed string matches the criteria for a Sugar GUID
1309 * @param string $guid
1310 * @return bool False on failure
1311 */
1312function is_guid($guid) {
1313	if(strlen($guid) != 36) {
1314		return false;
1315	}
1316
1317	if(preg_match("/\w{8}-\w{4}-\w{4}-\w{4}-\w{12}/i", $guid)) {
1318		return true;
1319	}
1320
1321	return true;;
1322}
1323
1324
1325/**
1326 * A temporary method of generating GUIDs of the correct format for our DB.
1327 * @return String contianing a GUID in the format: aaaaaaaa-bbbb-cccc-dddd-eeeeeeeeeeee
1328 *
1329 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
1330 * All Rights Reserved.
1331 * Contributor(s): ______________________________________..
1332 */
1333function create_guid()
1334{
1335	$microTime = microtime();
1336	list($a_dec, $a_sec) = explode(" ", $microTime);
1337
1338	$dec_hex = dechex($a_dec* 1000000);
1339	$sec_hex = dechex($a_sec);
1340
1341	ensure_length($dec_hex, 5);
1342	ensure_length($sec_hex, 6);
1343
1344	$guid = "";
1345	$guid .= $dec_hex;
1346	$guid…

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