Configurator::handleOverride()   C
last analyzed

Complexity

Conditions 17
Paths 72

Size

Total Lines 51
Code Lines 33

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 0
CRAP Score 306
Metric Value
cc 17
eloc 33
nc 72
nop 1
dl 0
loc 51
ccs 0
cts 42
cp 0
crap 306
rs 5.6079

How to fix   Long Method    Complexity   

Long Method

Small methods make your code easier to understand, in particular if combined with a good name. Besides, if your method is small, finding a good name is usually much easier.

For example, if you find yourself adding comments to a method's body, this is usually a good sign to extract the commented part to a new method, and use the comment as a starting point when coming up with a good name for this new method.

Commonly applied refactorings include:

1
<?php
2
if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
42
43
44
45
class Configurator {
46
	var $config = '';
47
	var $override = '';
48
	var $allow_undefined = array ('stack_trace_errors', 'export_delimiter', 'use_real_names', 'developerMode', 'default_module_favicon', 'authenticationClass', 'SAML_loginurl', 'SAML_X509Cert', 'dashlet_auto_refresh_min', 'show_download_tab', 'enable_action_menu','enable_line_editing_list','enable_line_editing_detail');
49
	var $errors = array ('main' => '');
50
	var $logger = NULL;
51
	var $previous_sugar_override_config_array = array();
52
	var $useAuthenticationClass = false;
53
    protected $error = null;
54
55
	function __construct() {
56
		$this->loadConfig();
57
	}
58
59
    /**
60
     * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
61
     */
62
    function Configurator(){
63
        $deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
64
        if(isset($GLOBALS['log'])) {
65
            $GLOBALS['log']->deprecated($deprecatedMessage);
66
        }
67
        else {
68
            trigger_error($deprecatedMessage, E_USER_DEPRECATED);
69
        }
70
        self::__construct();
71
    }
72
73
74
	function loadConfig() {
75
		$this->logger = LoggerManager::getLogger();
76
		global $sugar_config;
77
		$this->config = $sugar_config;
78
	}
79
80
	function populateFromPost() {
81
		$sugarConfig = SugarConfig::getInstance();
82
		foreach ($_POST as $key => $value) {
83
			if ($key == "logger_file_ext") {
84
			    $trim_value = preg_replace('/.*\.([^\.]+)$/', '\1', $value);
85
			    if(in_array($trim_value, $this->config['upload_badext'])) {
86
			        $GLOBALS['log']->security("Invalid log file extension: trying to use invalid file extension '$value'.");
87
			        continue;
88
			    }
89
			}
90
			if (isset ($this->config[$key]) || in_array($key, $this->allow_undefined)) {
91
				if (strcmp("$value", 'true') == 0) {
92
					$value = true;
93
				}
94
				if (strcmp("$value", 'false') == 0) {
95
					$value = false;
96
				}
97
                $this->config[$key] = $value;
98
			} else {
99
                $v = $sugarConfig->get(str_replace('_', '.', $key));
100
            if ($v  !== null){
101
			   setDeepArrayValue($this->config, $key, $value);
102
			}}
103
104
		}
105
106
	}
107
108
	function handleOverride($fromParseLoggerSettings=false) {
109
		global $sugar_config, $sugar_version;
110
		$sc = SugarConfig::getInstance();
111
		$overrideArray = $this->readOverride();
112
		$this->previous_sugar_override_config_array = $overrideArray;
113
		$diffArray = deepArrayDiff($this->config, $sugar_config);
114
		$overrideArray = sugarArrayMergeRecursive($overrideArray, $diffArray);
115
116
		// To remember checkbox state
117
      if (!$this->useAuthenticationClass && !$fromParseLoggerSettings) {
118
         if (isset($overrideArray['authenticationClass']) &&
119
            $overrideArray['authenticationClass'] == 'SAMLAuthenticate') {
120
      	  unset($overrideArray['authenticationClass']);
121
      	}
122
      }
123
124
		$overideString = "<?php\n/***CONFIGURATOR***/\n";
125
126
		sugar_cache_put('sugar_config', $this->config);
127
		$GLOBALS['sugar_config'] = $this->config;
128
129
		//print_r($overrideArray);
130
        //Bug#53013: Clean the tpl cache if action menu style has been changed.
131
        if( isset($overrideArray['enable_action_menu']) &&
132
                ( !isset($this->previous_sugar_override_config_array['enable_action_menu']) ||
133
                    $overrideArray['enable_action_menu'] != $this->previous_sugar_override_config_array['enable_action_menu'] )
134
        ) {
135
            require_once('modules/Administration/QuickRepairAndRebuild.php');
136
            $repair = new RepairAndClear;
137
            $repair->module_list = array();
138
            $repair->clearTpls();
139
        }
140
141
		foreach($overrideArray as $key => $val) {
142
			if (in_array($key, $this->allow_undefined) || isset ($sugar_config[$key])) {
143
				if (is_string($val) && strcmp($val, 'true') == 0) {
144
					$val = true;
145
					$this->config[$key] = $val;
146
				}
147
				if (is_string($val) && strcmp($val, 'false') == 0) {
148
					$val = false;
149
					$this->config[$key] = false;
150
				}
151
			}
152
			$overideString .= override_value_to_string_recursive2('sugar_config', $key, $val);
153
		}
154
		$overideString .= '/***CONFIGURATOR***/';
155
156
		$this->saveOverride($overideString);
157
		if(isset($this->config['logger']['level']) && $this->logger) $this->logger->setLevel($this->config['logger']['level']);
158
	}
159
160
	//bug #27947 , if previous $sugar_config['stack_trace_errors'] is true and now we disable it , we should clear all the cache.
161
	function clearCache(){
162
		global $sugar_config, $sugar_version;
163
		$currentConfigArray = $this->readOverride();
164
		foreach($currentConfigArray as $key => $val) {
165
			if (in_array($key, $this->allow_undefined) || isset ($sugar_config[$key])) {
166
				if (empty($val) ) {
167
					if(!empty($this->previous_sugar_override_config_array['stack_trace_errors']) && $key == 'stack_trace_errors'){
168
						require_once('include/TemplateHandler/TemplateHandler.php');
169
						TemplateHandler::clearAll();
170
						return;
171
					}
172
				}
173
			}
174
		}
175
	}
176
177
	function saveConfig() {
178
        if($this->saveImages() === false)
179
        {
180
            return false;
181
        }
182
183
		$this->populateFromPost();
184
		$this->handleOverride();
185
		$this->clearCache();
186
	}
187
188
	function readOverride() {
189
		$sugar_config = array();
190
		if (file_exists('config_override.php')) {
191
		    if ( !is_readable('config_override.php') ) {
192
		        $GLOBALS['log']->fatal("Unable to read the config_override.php file. Check the file permissions");
193
		    }
194
	        else {
195
	            include('config_override.php');
196
	        }
197
		}
198
		return $sugar_config;
199
	}
200
	function saveOverride($override) {
201
        require_once('install/install_utils.php');
202
	    if ( !file_exists('config_override.php') ) {
203
	    	touch('config_override.php');
204
	    }
205
	    if ( !(make_writable('config_override.php')) ||  !(is_writable('config_override.php')) ) {
206
	        $GLOBALS['log']->fatal("Unable to write to the config_override.php file. Check the file permissions");
207
	        return;
208
	    }
209
		$fp = sugar_fopen('config_override.php', 'w');
210
		fwrite($fp, $override);
211
		fclose($fp);
212
	}
213
214
	function overrideClearDuplicates($array_name, $key) {
215
		if (!empty ($this->override)) {
216
			$pattern = '/.*CONFIGURATOR[^\$]*\$'.$array_name.'\[\''.$key.'\'\][\ ]*=[\ ]*[^;]*;\n/';
217
			$this->override = preg_replace($pattern, '', $this->override);
218
		} else {
219
			$this->override = "<?php\n\n?>";
220
		}
221
222
	}
223
224
	function replaceOverride($array_name, $key, $value) {
225
		$GLOBALS[$array_name][$key] = $value;
226
		$this->overrideClearDuplicates($array_name, $key);
227
		$new_entry = '/***CONFIGURATOR***/'.override_value_to_string($array_name, $key, $value);
228
		$this->override = str_replace('?>', "$new_entry\n?>", $this->override);
229
	}
230
231
	function restoreConfig() {
232
		$this->readOverride();
233
		$this->overrideClearDuplicates('sugar_config', '[a-zA-Z0-9\_]+');
234
		$this->saveOverride();
0 ignored issues
show
Bug introduced by
The call to saveOverride() misses a required argument $override.

This check looks for function calls that miss required arguments.

Loading history...
235
		ob_clean();
236
		header('Location: index.php?action=EditView&module=Configurator');
237
	}
238
239
	function saveImages() {
240
		if (!empty ($_POST['company_logo'])) {
241
            if($this->saveCompanyLogo("upload://".$_POST['company_logo']) === false)
242
            {
243
                return false;
244
            }
245
		}
246
	}
247
248
	function checkTempImage($path)
249
	{
250
        if(!verify_uploaded_image($path)) {
251
            $error = translate('LBL_ALERT_TYPE_IMAGE');
252
        	$GLOBALS['log']->fatal("A user ({$GLOBALS['current_user']->id}) attempted to use an invalid file for the logo - {$path}");
253
            $this->error = $error;
254
            return false;
255
		}
256
		return $path;
257
	}
258
259
    public function getError()
260
    {
261
        $e = $this->error;
262
        $this->error = null;
263
        return $e;
264
    }
265
    /**
266
     * Saves the company logo to the custom directory for the default theme, so all themes can use it
267
     *
268
     * @param string $path path to the image to set as the company logo image
269
     */
270
	function saveCompanyLogo($path)
271
    {
272
    	$path = $this->checkTempImage($path);
273
        if($path === false)
274
        {
275
            return false;
276
        }
277
278
        mkdir_recursive('custom/'.SugarThemeRegistry::current()->getDefaultImagePath(), true);
279
        copy($path,'custom/'. SugarThemeRegistry::current()->getDefaultImagePath(). '/company_logo.png');
280
        sugar_cache_clear('company_logo_attributes');
281
        SugarThemeRegistry::clearAllCaches();
282
	}
283
	/**
284
	 * @params : none
285
	 * @return : An array of logger configuration properties including log size, file extensions etc. See SugarLogger for more details.
286
	 * Parses the old logger settings from the log4php.properties files.
0 ignored issues
show
Documentation introduced by
The doc-type : could not be parsed: Unknown type name ":" at position 0. (view supported doc-types)

This check marks PHPDoc comments that could not be parsed by our parser. To see which comment annotations we can parse, please refer to our documentation on supported doc-types.

Loading history...
287
	 *
288
	 */
289
290
	function parseLoggerSettings(){
291
		if(!function_exists('setDeepArrayValue')){
292
			require('include/utils/array_utils.php');
293
		}
294
		if (file_exists('log4php.properties')) {
295
			$fileContent = file_get_contents('log4php.properties');
296
			$old_props = explode('\n', $fileContent);
297
			$new_props = array();
298
			$key_names=array();
299
			foreach($old_props as $value) {
300
				if(!empty($value) && !preg_match("/^\/\//", $value)) {
301
					$temp = explode("=",$value);
302
					$property = isset( $temp[1])? $temp[1] : array();
303
					if(preg_match("/log4php.appender.A2.MaxFileSize=/",$value)){
304
						setDeepArrayValue($this->config, 'logger_file_maxSize', rtrim( $property));
305
					}
306
					elseif(preg_match("/log4php.appender.A2.File=/", $value)){
307
						$ext = preg_split("/\./",$property);
308
						if(preg_match( "/^\./", $property)){ //begins with .
309
							setDeepArrayValue($this->config, 'logger_file_ext', isset($ext[2]) ? '.' . rtrim( $ext[2]):'.log');
310
							setDeepArrayValue($this->config, 'logger_file_name', rtrim( ".".$ext[1]));
311
						}else{
312
							setDeepArrayValue($this->config, 'logger_file_ext', isset($ext[1]) ? '.' . rtrim( $ext[1]):'.log');
313
							setDeepArrayValue($this->config, 'logger_file_name', rtrim( $ext[0] ));
314
						}
315
					}elseif(preg_match("/log4php.appender.A2.layout.DateFormat=/",$value)){
316
						setDeepArrayValue($this->config, 'logger_file_dateFormat', trim(rtrim( $property), '""'));
317
318
					}elseif(preg_match("/log4php.rootLogger=/",$value)){
319
						$property = explode(",",$property);
320
						setDeepArrayValue($this->config, 'logger_level', rtrim( $property[0]));
321
					}
322
				}
323
			}
324
			setDeepArrayValue($this->config, 'logger_file_maxLogs', 10);
325
			setDeepArrayValue($this->config, 'logger_file_suffix', "%m_%Y");
326
			$this->handleOverride();
327
			unlink('log4php.properties');
328
			$GLOBALS['sugar_config'] = $this->config; //load the rest of the sugar_config settings.
329
			require_once('include/SugarLogger/SugarLogger.php');
330
			//$logger = new SugarLogger(); //this will create the log file.
331
332
		}
333
334
		if (!isset($this->config['logger']) || empty($this->config['logger'])) {
335
			$this->config['logger'] = array (
336
			'file' => array(
337
				'ext' => '.log',
338
				'name' => 'sugarcrm',
339
				'dateFormat' => '%c',
340
				'maxSize' => '10MB',
341
				'maxLogs' => 10,
342
				'suffix' => ''), // bug51583, change default suffix to blank for backwards comptability
343
			'level' => 'fatal');
344
		}
345
		$this->handleOverride(true);
346
347
348
	}
349
350
351
352
353
}
354
?>
355