Issues (4069)

Security Analysis    not enabled

This project does not seem to handle request data directly as such no vulnerable execution paths were found.

  Cross-Site Scripting
Cross-Site Scripting enables an attacker to inject code into the response of a web-request that is viewed by other users. It can for example be used to bypass access controls, or even to take over other users' accounts.
  File Exposure
File Exposure allows an attacker to gain access to local files that he should not be able to access. These files can for example include database credentials, or other configuration files.
  File Manipulation
File Manipulation enables an attacker to write custom data to files. This potentially leads to injection of arbitrary code on the server.
  Object Injection
Object Injection enables an attacker to inject an object into PHP code, and can lead to arbitrary code execution, file exposure, or file manipulation attacks.
  Code Injection
Code Injection enables an attacker to execute arbitrary code on the server.
  Response Splitting
Response Splitting can be used to send arbitrary responses.
  File Inclusion
File Inclusion enables an attacker to inject custom files into PHP's file loading mechanism, either explicitly passed to include, or for example via PHP's auto-loading mechanism.
  Command Injection
Command Injection enables an attacker to inject a shell command that is execute with the privileges of the web-server. This can be used to expose sensitive data, or gain access of your server.
  SQL Injection
SQL Injection enables an attacker to execute arbitrary SQL code on your database server gaining access to user data, or manipulating user data.
  XPath Injection
XPath Injection enables an attacker to modify the parts of XML document that are read. If that XML document is for example used for authentication, this can lead to further vulnerabilities similar to SQL Injection.
  LDAP Injection
LDAP Injection enables an attacker to inject LDAP statements potentially granting permission to run unauthorized queries, or modify content inside the LDAP tree.
  Header Injection
  Other Vulnerability
This category comprises other attack vectors such as manipulating the PHP runtime, loading custom extensions, freezing the runtime, or similar.
  Regex Injection
Regex Injection enables an attacker to execute arbitrary code in your PHP process.
  XML Injection
XML Injection enables an attacker to read files on your local filesystem including configuration files, or can be abused to freeze your web-server process.
  Variable Injection
Variable Injection enables an attacker to overwrite program variables with custom data, and can lead to further vulnerabilities.
Unfortunately, the security analysis is currently not available for your project. If you are a non-commercial open-source project, please contact support to gain access.

modules/UpgradeWizard/silentUpgrade_step1.php (22 issues)

Upgrade to new PHP Analysis Engine

These results are based on our legacy PHP analysis, consider migrating to our new PHP analysis engine instead. Learn more

1
<?php
2
3
/*********************************************************************************
4
 * SugarCRM Community Edition is a customer relationship management program developed by
5
 * SugarCRM, Inc. Copyright (C) 2004-2013 SugarCRM Inc.
6
 * 
7
 * This program is free software; you can redistribute it and/or modify it under
8
 * the terms of the GNU Affero General Public License version 3 as published by the
9
 * Free Software Foundation with the addition of the following permission added
10
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13
 * 
14
 * This program is distributed in the hope that it will be useful, but WITHOUT
15
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17
 * details.
18
 * 
19
 * You should have received a copy of the GNU Affero General Public License along with
20
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22
 * 02110-1301 USA.
23
 * 
24
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
26
 * 
27
 * The interactive user interfaces in modified source and object code versions
28
 * of this program must display Appropriate Legal Notices, as required under
29
 * Section 5 of the GNU Affero General Public License version 3.
30
 * 
31
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32
 * these Appropriate Legal Notices must retain the display of the "Powered by
33
 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34
 * technical reasons, the Appropriate Legal Notices must display the words
35
 * "Powered by SugarCRM".
36
 ********************************************************************************/
37
38
39
//////////////////////////////////////////////////////////////////////////////////////////
40
//// This is a stand alone file that can be run from the command prompt for upgrading a
41
//// Sugar Instance. Three parameters are required to be defined in order to execute this file.
42
//// php.exe -f silentUpgrade.php [Path to Upgrade Package zip] [Path to Log file] [Path to Instance]
43
//// See below the Usage for more details.
44
/////////////////////////////////////////////////////////////////////////////////////////
45
ini_set('memory_limit',-1);
46
///////////////////////////////////////////////////////////////////////////////
47
////	UTILITIES THAT MUST BE LOCAL :(
48
function prepSystemForUpgradeSilent() {
0 ignored issues
show
The function prepSystemForUpgradeSilent() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L48-59) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
49
	global $subdirs;
50
	global $cwd;
51
	global $sugar_config;
52
53
	// make sure dirs exist
54
	foreach($subdirs as $subdir) {
55
		if(!is_dir($sugar_config['upload_dir']."/upgrades/{$subdir}")) {
56
	    	mkdir_recursive($sugar_config['upload_dir']."/upgrades/{$subdir}");
57
		}
58
	}
59
}
60
61
//local function for clearing cache
62
function clearCacheSU($thedir, $extension) {
0 ignored issues
show
The function clearCacheSU() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L62-75) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
63
	if ($current = @opendir($thedir)) {
64
		while (false !== ($children = readdir($current))) {
65
			if ($children != "." && $children != "..") {
66
				if (is_dir($thedir . "/" . $children)) {
67
					clearCacheSU($thedir . "/" . $children, $extension);
68
				}
69
				elseif (is_file($thedir . "/" . $children) && substr_count($children, $extension)) {
70
					unlink($thedir . "/" . $children);
71
				}
72
			}
73
		}
74
	}
75
 }
76
 //Bug 24890, 24892. default_permissions not written to config.php. Following function checks and if
77
 //no found then adds default_permissions to the config file.
78
 function checkConfigForPermissions(){
0 ignored issues
show
The function checkConfigForPermissions() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L78-95) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
79
     if(file_exists(getcwd().'/config.php')){
80
         require(getcwd().'/config.php');
81
     }
82
     global $sugar_config;
83
     if(!isset($sugar_config['default_permissions'])){
84
             $sugar_config['default_permissions'] = array (
85
                     'dir_mode' => 02770,
86
                     'file_mode' => 0660,
87
                     'user' => '',
88
                     'group' => '',
89
             );
90
         ksort($sugar_config);
91
         if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
92
        	//writing to the file
93
 		}
94
     }
95
}
96
function checkLoggerSettings(){
0 ignored issues
show
The function checkLoggerSettings() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L96-119) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
97
	if(file_exists(getcwd().'/config.php')){
98
         require(getcwd().'/config.php');
99
     }
100
    global $sugar_config;
101
	if(!isset($sugar_config['logger'])){
102
	    $sugar_config['logger'] =array (
103
			'level'=>'fatal',
104
		    'file' =>
105
		     array (
106
		      'ext' => '.log',
107
		      'name' => 'sugarcrm',
108
		      'dateFormat' => '%c',
109
		      'maxSize' => '10MB',
110
		      'maxLogs' => 10,
111
		      'suffix' => '', // bug51583, change default suffix to blank for backwards comptability
112
		    ),
113
		  );
114
		 ksort($sugar_config);
115
         if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
116
        	//writing to the file
117
 		}
118
	 }
119
}
120
121
function checkLeadConversionSettings() {
122
    if (file_exists(getcwd().'/config.php')) {
123
         require(getcwd().'/config.php');
124
    }
125
    global $sugar_config;
126
    if (!isset($sugar_config['lead_conv_activity_opt'])) {
127
        $sugar_config['lead_conv_activity_opt'] = 'copy';
128
        ksort($sugar_config);
129
        if (is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
130
            //writing to the file
131
        }
132
    }
133
}
134
135
function checkResourceSettings(){
0 ignored issues
show
The function checkResourceSettings() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L121-145) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
136
	if(file_exists(getcwd().'/config.php')){
137
         require(getcwd().'/config.php');
138
     }
139
    global $sugar_config;
140
	if(!isset($sugar_config['resource_management'])){
141
	  $sugar_config['resource_management'] =
142
		  array (
143
		    'special_query_limit' => 50000,
144
		    'special_query_modules' =>
145
		    array (
146
		      0 => 'Reports',
147
		      1 => 'Export',
148
		      2 => 'Import',
149
		      3 => 'Administration',
150
		      4 => 'Sync',
151
		    ),
152
		    'default_limit' => 1000,
153
		  );
154
		 ksort($sugar_config);
155
         if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
0 ignored issues
show
This if statement is empty and can be removed.

This check looks for the bodies of if statements that have no statements or where all statements have been commented out. This may be the result of changes for debugging or the code may simply be obsolete.

These if bodies can be removed. If you have an empty if but statements in the else branch, consider inverting the condition.

if (rand(1, 6) > 3) {
//print "Check failed";
} else {
    print "Check succeeded";
}

could be turned into

if (rand(1, 6) <= 3) {
    print "Check succeeded";
}

This is much more concise to read.

Loading history...
156
        	//writing to the file
157
 		}
158
	}
159
}
160
161
162
function createMissingRels(){
0 ignored issues
show
The function createMissingRels() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L156-194) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
163
	$relForObjects = array('leads'=>'Leads','campaigns'=>'Campaigns','prospects'=>'Prospects');
164
	foreach($relForObjects as $relObjName=>$relModName){
165
		//assigned_user
166
		$guid = create_guid();
167
		$query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_assigned_user'";
168
		$result= $GLOBALS['db']->query($query, true);
169
		$a = null;
170
		$a = $GLOBALS['db']->fetchByAssoc($result);
171
		if(!isset($a['id']) && empty($a['id']) ){
172
			$qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
173
						VALUES ('{$guid}', '{$relObjName}_assigned_user','Users','users','id','{$relModName}','{$relObjName}','assigned_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
174
			$GLOBALS['db']->query($qRel);
175
		}
176
		//modified_user
177
		$guid = create_guid();
178
		$query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_modified_user'";
179
		$result= $GLOBALS['db']->query($query, true);
180
		$a = null;
181
		$a = $GLOBALS['db']->fetchByAssoc($result);
182
		if(!isset($a['id']) && empty($a['id']) ){
183
			$qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
184
						VALUES ('{$guid}', '{$relObjName}_modified_user','Users','users','id','{$relModName}','{$relObjName}','modified_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
185
			$GLOBALS['db']->query($qRel);
186
		}
187
		//created_by
188
		$guid = create_guid();
189
		$query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
190
		$result= $GLOBALS['db']->query($query, true);
191
		$a = null;
192
		$a = $GLOBALS['db']->fetchByAssoc($result);
193
    	if(!isset($a['id']) && empty($a['id']) ){
194
			$qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
195
						VALUES ('{$guid}', '{$relObjName}_created_by','Users','users','id','{$relModName}','{$relObjName}','created_by',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
196
			$GLOBALS['db']->query($qRel);
197
    	}
198
		$guid = create_guid();
199
		$query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_team'";
200
		$result= $GLOBALS['db']->query($query, true);
201
		$a = null;
202
		$a = $GLOBALS['db']->fetchByAssoc($result);
203
		if(!isset($a['id']) && empty($a['id']) ){
204
			$qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
205
							VALUES ('{$guid}', '{$relObjName}_team','Teams','teams','id','{$relModName}','{$relObjName}','team_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
206
			$GLOBALS['db']->query($qRel);
207
		}
208
	}
209
	//Also add tracker perf relationship
210
	$guid = create_guid();
211
	$query = "SELECT id FROM relationships WHERE relationship_name = 'tracker_monitor_id'";
212
	$result= $GLOBALS['db']->query($query, true);
213
	$a = null;
214
	$a = $GLOBALS['db']->fetchByAssoc($result);
215
	if(!isset($a['id']) && empty($a['id']) ){
216
		$qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
217
					VALUES ('{$guid}', 'tracker_monitor_id','TrackerPerfs','tracker_perf','monitor_id','Trackers','tracker','monitor_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
218
		$GLOBALS['db']->query($qRel);
219
	}
220
}
221
222
223
/**
224
 * This function will merge password default settings into config file
225
 * @param   $sugar_config
226
 * @param   $sugar_version
227
 * @return  bool true if successful
228
 */
229
function merge_passwordsetting($sugar_config, $sugar_version) {
0 ignored issues
show
The function merge_passwordsetting() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L203-234) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
230
231
     $passwordsetting_defaults = array (
232
        'passwordsetting' => array (
233
            'minpwdlength' => '',
234
            'maxpwdlength' => '',
235
            'oneupper' => '',
236
            'onelower' => '',
237
            'onenumber' => '',
238
            'onespecial' => '',
239
            'SystemGeneratedPasswordON' => '',
240
            'generatepasswordtmpl' => '',
241
            'lostpasswordtmpl' => '',
242
            'customregex' => '',
243
            'regexcomment' => '',
244
            'forgotpasswordON' => false,
245
            'linkexpiration' => '1',
246
            'linkexpirationtime' => '30',
247
            'linkexpirationtype' => '1',
248
            'userexpiration' => '0',
249
            'userexpirationtime' => '',
250
            'userexpirationtype' => '1',
251
            'userexpirationlogin' => '',
252
            'systexpiration' => '0',
253
            'systexpirationtime' => '',
254
            'systexpirationtype' => '0',
255
            'systexpirationlogin' => '',
256
            'lockoutexpiration' => '0',
257
            'lockoutexpirationtime' => '',
258
            'lockoutexpirationtype' => '1',
259
            'lockoutexpirationlogin' => '',
260
        ),
261
    );
262
263
    $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
264
265
    // need to override version with default no matter what
266
    $sugar_config['sugar_version'] = $sugar_version;
267
268
    ksort( $sugar_config );
269
270
    if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
271
        return true;
272
    }
273
    else {
274
        return false;
275
    }
276
}
277
278
function addDefaultModuleRoles($defaultRoles = array()) {
0 ignored issues
show
The function addDefaultModuleRoles() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L236-253) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
279
	foreach($defaultRoles as $roleName=>$role){
280
        foreach($role as $category=>$actions){
281
            foreach($actions as $name=>$access_override){
282
                    $query = "SELECT * FROM acl_actions WHERE name='$name' AND category = '$category' AND acltype='$roleName' AND deleted=0 ";
283
					$result = $GLOBALS['db']->query($query);
284
					//only add if an action with that name and category don't exist
285
					$row=$GLOBALS['db']->fetchByAssoc($result);
286
					if ($row == null) {
287
	                	$guid = create_guid();
288
	                	$currdate = gmdate('Y-m-d H:i:s');
289
	                	$query= "INSERT INTO acl_actions (id,date_entered,date_modified,modified_user_id,name,category,acltype,aclaccess,deleted ) VALUES ('$guid','$currdate','$currdate','1','$name','$category','$roleName','$access_override','0')";
290
						$GLOBALS['db']->query($query);
291
	                }
292
            }
293
        }
294
	}
295
}
296
297
function verifyArguments($argv,$usage_regular){
0 ignored issues
show
The function verifyArguments() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L255-322) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
298
    $upgradeType = '';
299
    $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
300
    if(isset($argv[3])) {
301
        if(is_dir($argv[3])) {
302
            $cwd = $argv[3];
303
            chdir($cwd);
304
        } else {
305
            echo "*******************************************************************************\n";
306
            echo "*** ERROR: 3rd parameter must be a valid directory.  Tried to cd to [ {$argv[3]} ].\n";
307
            exit(1);
308
        }
309
    }
310
311
    if(is_file("{$cwd}/include/entryPoint.php")) {
312
        //this should be a regular sugar install
313
        $upgradeType = constant('SUGARCRM_INSTALL');
314
        //check if this is a valid zip file
315
        if(!is_file($argv[1])) { // valid zip?
316
            echo "*******************************************************************************\n";
317
            echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
318
            echo $usage_regular;
319
            echo "FAILURE\n";
320
            exit(1);
321
        }
322
        if(count($argv) < 5) {
323
            echo "*******************************************************************************\n";
324
            echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 5.\n";
325
            echo $usage_regular;
326
            echo "FAILURE\n";
327
            exit(1);
328
        }
329
    } else {
330
        //this should be a regular sugar install
331
        echo "*******************************************************************************\n";
332
        echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
333
        exit(1);
334
    }
335
336
    if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
337
        require_once($argv[7].'SugarTemplateUtilties.php');
338
    }
339
340
    return $upgradeType;
341
}
342
343
344
345
function threeWayMerge(){
0 ignored issues
show
The function threeWayMerge() has been defined more than once; this definition is ignored, only the first definition in modules/UpgradeWizard/silentUpgrade_dce_step1.php (L350-352) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
346
	//using threeway merge apis
347
}
348
349
////	END UTILITIES THAT MUST BE LOCAL :(
350
///////////////////////////////////////////////////////////////////////////////
351
352
//Bug 52872. Dies if the request does not come from CLI.
353
$sapi_type = php_sapi_name();
354
if (substr($sapi_type, 0, 3) != 'cli') {
355
    die("This is command-line only script");
356
}
357
//End of #52872
358
359
// only run from command line
360
if(isset($_SERVER['HTTP_USER_AGENT'])) {
361
	fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
362
	exit(1);
363
}
364
//Clean_string cleans out any file  passed in as a parameter
365
$_SERVER['PHP_SELF'] = 'silentUpgrade.php';
366
367
$usage_regular =<<<eoq2
368
Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
369
370
On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
371
php.exe followed by -f silentUpgrade.php and the arguments.
372
373
Example:
374
    [path-to-PHP/]php.exe -f silentUpgrade.php [path-to-upgrade-package/]SugarEnt-Upgrade-5.2.0-to-5.5.0.zip [path-to-log-file/]silentupgrade.log  [path-to-sugar-instance/] admin
375
376
Arguments:
377
    upgradeZipFile                       : Upgrade package file.
378
    logFile                              : Silent Upgarde log file.
379
    pathToSugarInstance                  : Sugar Instance instance being upgraded.
380
    admin-user                           : admin user performing the upgrade
381
eoq2;
382
////	END USAGE
383
///////////////////////////////////////////////////////////////////////////////
384
385
386
387
///////////////////////////////////////////////////////////////////////////////
388
////	STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
389
if(!defined('sugarEntry')) define('sugarEntry', true);
390
391
$_SESSION = array();
392
$_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
393
$_SESSION['silent_upgrade'] = true;
394
$_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
395
396
$_REQUEST = array();
397
$_REQUEST['addTaskReminder'] = 'remind';
398
399
400
define('SUGARCRM_INSTALL', 'SugarCRM_Install');
401
define('DCE_INSTANCE', 'DCE_Instance');
402
403
global $cwd;
404
$cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
405
406
$upgradeType = verifyArguments($argv,$usage_regular);
0 ignored issues
show
The call to verifyArguments() misses a required argument $usage_regular.

This check looks for function calls that miss required arguments.

Loading history...
407
408
///////////////////////////////////////////////////////////////////////////////
409
//////  Verify that all the arguments are appropriately placed////////////////
410
411
$path			= $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
412
$subdirs		= array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
413
414
//$_REQUEST['zip_from_dir'] = $zip_from_dir;
415
416
define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
417
define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
418
define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
419
define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
420
421
422
423
echo "\n";
424
echo "********************************************************************\n";
425
echo "***************This Upgrade process may take sometime***************\n";
426
echo "********************************************************************\n";
427
echo "\n";
428
429
global $sugar_config;
430
$isDCEInstance = false;
431
$errors = array();
432
433
434
if($upgradeType != constant('DCE_INSTANCE')) {
435
436
	ini_set('error_reporting',1);
437
	require_once('include/entryPoint.php');
438
	require_once('include/SugarLogger/SugarLogger.php');
439
	require_once('include/utils/zip_utils.php');
440
441
442
if(!function_exists('sugar_cached'))
443
{
444
    /**
445
     * sugar_cached
446
     *
447
     * @param $file The path to retrieve cache lookup information for
448
     * @return string The cached path according to $GLOBALS['sugar_config']['cache_dir'] or just appended with cache if not defined
449
     */
450
    function sugar_cached($file)
0 ignored issues
show
The function sugar_cached() has been defined more than once; this definition is ignored, only the first definition in include/utils/sugar_file_utils.php (L391-401) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
451
    {
452
        static $cdir = null;
453
        if(empty($cdir) && !empty($GLOBALS['sugar_config']['cache_dir'])) {
454
            $cdir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
455
        }
456
        if(empty($cdir)) {
457
            $cdir = "cache";
458
        }
459
        return "$cdir/$file";
460
    }
461
}
462
463
	require('config.php');
464
	//require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
465
	if(isset($argv[3])) {
466
		if(is_dir($argv[3])) {
467
			$cwd = $argv[3];
468
			chdir($cwd);
469
		}
470
	}
471
472
	require_once("{$cwd}/sugar_version.php"); // provides $sugar_version & $sugar_flavor
473
474
    $GLOBALS['log']	= LoggerManager::getLogger('SugarCRM');
0 ignored issues
show
The call to LoggerManager::getLogger() has too many arguments starting with 'SugarCRM'.

This check compares calls to functions or methods with their respective definitions. If the call has more arguments than are defined, it raises an issue.

If a function is defined several times with a different number of parameters, the check may pick up the wrong definition and report false positives. One codebase where this has been known to happen is Wordpress.

In this case you can add the @ignore PhpDoc annotation to the duplicate definition and it will be ignored.

Loading history...
475
	$patchName		= basename($argv[1]);
476
	$zip_from_dir	= substr($patchName, 0, strlen($patchName) - 4); // patch folder name (minus ".zip")
477
	$path			= $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
478
479
    $db				= &DBManagerFactory::getInstance();
480
	$UWstrings		= return_module_language('en_us', 'UpgradeWizard');
481
	$adminStrings	= return_module_language('en_us', 'Administration');
482
    $app_list_strings = return_app_list_strings_language('en_us');
483
	$mod_strings	= array_merge($adminStrings, $UWstrings);
484
	$subdirs		= array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
485
	global $unzip_dir;
486
    $license_accepted = false;
487
    if(isset($argv[5]) && (strtolower($argv[5])=='yes' || strtolower($argv[5])=='y')){
488
    	$license_accepted = true;
489
	 }
490
	//////////////////////////////////////////////////////////////////////////////
491
	//Adding admin user to the silent upgrade
492
493
	$current_user = new User();
494
	if(isset($argv[4])) {
495
	   //if being used for internal upgrades avoid admin user verification
496
	   $user_name = $argv[4];
497
	   $q = "select id from users where user_name = '" . $user_name . "' and is_admin=1";
498
	   $result = $GLOBALS['db']->query($q, false);
499
	   $logged_user = $GLOBALS['db']->fetchByAssoc($result);
500
	   if(isset($logged_user['id']) && $logged_user['id'] != null){
501
		//do nothing
502
	    $current_user->retrieve($logged_user['id']);
503
	   }
504
	   else{
505
	   	echo "FAILURE: Not an admin user in users table. Please provide an admin user\n";
506
		exit(1);
507
	   }
508
	}
509
	else {
510
		echo "*******************************************************************************\n";
511
		echo "*** ERROR: 4th parameter must be a valid admin user.\n";
512
		echo $usage;
513
		echo "FAILURE\n";
514
		exit(1);
515
	}
516
517
518
		/////retrieve admin user
519
	global $sugar_config;
520
	$configOptions = $sugar_config['dbconfig'];
521
522
523
///////////////////////////////////////////////////////////////////////////////
524
////	UPGRADE PREP
525
prepSystemForUpgradeSilent();
526
527
//repair tabledictionary.ext.php file if needed
528
repairTableDictionaryExtFile();
529
530
$unzip_dir = sugar_cached("upgrades/temp");
531
$install_file = $sugar_config['upload_dir']."/upgrades/patch/".basename($argv[1]);
532
533
$_SESSION['unzip_dir'] = $unzip_dir;
534
$_SESSION['install_file'] = $install_file;
535
$_SESSION['zip_from_dir'] = $zip_from_dir;
536
if(is_dir($unzip_dir.'/scripts'))
537
{
538
	rmdir_recursive($unzip_dir.'/scripts');
539
}
540
if(is_file($unzip_dir.'/manifest.php'))
541
{
542
	rmdir_recursive($unzip_dir.'/manifest.php');
543
}
544
mkdir_recursive($unzip_dir);
545
if(!is_dir($unzip_dir)) {
546
	echo "\n{$unzip_dir} is not an available directory\nFAILURE\n";
547
	fwrite(STDERR,"\n{$unzip_dir} is not an available directory\nFAILURE\n");
548
	exit(1);
549
}
550
551
unzip($argv[1], $unzip_dir);
552
// mimic standard UW by copy patch zip to appropriate dir
553
copy($argv[1], $install_file);
554
////	END UPGRADE PREP
555
///////////////////////////////////////////////////////////////////////////////
556
557
///////////////////////////////////////////////////////////////////////////////
558
////	UPGRADE UPGRADEWIZARD
559
560
$zipBasePath = "$unzip_dir/{$zip_from_dir}";
561
$uwFiles = findAllFiles("{$zipBasePath}/modules/UpgradeWizard", array());
562
$destFiles = array();
563
564
foreach($uwFiles as $uwFile) {
565
	$destFile = str_replace($zipBasePath."/", '', $uwFile);
566
	copy($uwFile, $destFile);
567
}
568
require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
569
removeSilentUpgradeVarsCache(); // Clear the silent upgrade vars - Note: Any calls to these functions within this file are removed here
570
logThis("*** SILENT UPGRADE INITIATED.", $path);
571
logThis("*** UpgradeWizard Upgraded  ", $path);
572
573
if(function_exists('set_upgrade_vars')){
574
	set_upgrade_vars();
575
}
576
577
if($configOptions['db_type'] == 'mysql'){
578
	//Change the db wait_timeout for this session
579
	$now_timeout = $db->getOne("select @@wait_timeout");
580
	logThis('Wait Timeout before change ***** '.$now_timeout , $path);
581
	$db->query("set wait_timeout=28800");	
582
	$now_timeout = $db->getOne("select @@wait_timeout");	
583
	logThis('Wait Timeout after change ***** '.$now_timeout , $path);
584
}
585
586
////	END UPGRADE UPGRADEWIZARD
587
///////////////////////////////////////////////////////////////////////////////
588
589
///////////////////////////////////////////////////////////////////////////////
590
////	MAKE SURE PATCH IS COMPATIBLE
591
if(is_file("$unzip_dir/manifest.php")) {
592
	// provides $manifest array
593
	include("$unzip_dir/manifest.php");
594
	if(!isset($manifest)) {
595
		fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
596
	    exit(1);
597
	} else {
598
		copy("$unzip_dir/manifest.php", $sugar_config['upload_dir']."/upgrades/patch/{$zip_from_dir}-manifest.php");
599
600
		$error = validate_manifest($manifest);
601
		if(!empty($error)) {
602
			$error = strip_tags(br2nl($error));
603
			fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
604
			exit(1);
605
		}
606
	}
607
} else {
608
	fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
609
	exit(1);
610
}
611
612
$ce_to_pro_ent = isset($manifest['name']) && ($manifest['name'] == 'SugarCE to SugarPro' || $manifest['name'] == 'SugarCE to SugarEnt' || $manifest['name'] == 'SugarCE to SugarCorp' || $manifest['name'] == 'SugarCE to SugarUlt');
613
$_SESSION['upgrade_from_flavor'] = $manifest['name'];
614
615
global $sugar_config;
616
global $sugar_version;
617
global $sugar_flavor;
618
619
////	END MAKE SURE PATCH IS COMPATIBLE
620
///////////////////////////////////////////////////////////////////////////////
621
622
///////////////////////////////////////////////////////////////////////////////
623
////	RUN SILENT UPGRADE
624
ob_start();
625
set_time_limit(0);
626
if(file_exists('ModuleInstall/PackageManager/PackageManagerDisplay.php')) {
627
	require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php');
628
}
629
630
631
	//copy minimum required files including sugar_file_utils.php
632
	if(file_exists("{$zipBasePath}/include/utils/sugar_file_utils.php")){
633
		$destFile = clean_path(str_replace($zipBasePath, $cwd, "{$zipBasePath}/include/utils/sugar_file_utils.php"));
634
		copy("{$zipBasePath}/include/utils/sugar_file_utils.php", $destFile);
635
	}
636
	if(file_exists('include/utils/sugar_file_utils.php')){
637
    	require_once('include/utils/sugar_file_utils.php');
638
    }
639
640
/*
641
$errors = preflightCheck();
642
if((count($errors) == 1)) { // only diffs
643
	logThis('file preflight check passed successfully.', $path);
644
}
645
else{
646
	fwrite(STDERR,"\nThe user doesn't have sufficient permissions to write to database'.\n\n");
647
	exit(1);
648
}
649
*/
650
//If version less than 500 then look for modules to be upgraded
651
if(function_exists('set_upgrade_vars')){
652
	set_upgrade_vars();
653
}
654
//Initialize the session variables. If upgrade_progress.php is already created
655
//look for session vars there and restore them
656
if(function_exists('initialize_session_vars')){
657
	initialize_session_vars();
658
}
659
660
if(!didThisStepRunBefore('preflight')){
661
	set_upgrade_progress('preflight','in_progress');
662
	//Quickcreatedefs on the basis of editviewdefs
663
    updateQuickCreateDefs();
664
	set_upgrade_progress('preflight','done');
665
}
666
////////////////COMMIT PROCESS BEGINS///////////////////////////////////////////////////////////////
667
////	MAKE BACKUPS OF TARGET FILES
668
669
if(!didThisStepRunBefore('commit')){
670
	set_upgrade_progress('commit','in_progress','commit','in_progress');
671
	if(!didThisStepRunBefore('commit','commitMakeBackupFiles')){
672
		set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','in_progress');
673
		$errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
674
		set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','done');
675
	}
676
677
	//Need to make sure we have the matching copy of SetValueAction for static/instance method matching
678
    if(file_exists("include/Expressions/Actions/SetValueAction.php")){
679
        require_once("include/Expressions/Actions/SetValueAction.php");
680
    }
681
682
	///////////////////////////////////////////////////////////////////////////////
683
	////	HANDLE PREINSTALL SCRIPTS
684
	if(empty($errors)) {
685
		$file = "{$unzip_dir}/".constant('SUGARCRM_PRE_INSTALL_FILE');
686
687
		if(is_file($file)) {
688
			include($file);
689
			if(!didThisStepRunBefore('commit','pre_install')){
690
				set_upgrade_progress('commit','in_progress','pre_install','in_progress');
691
				pre_install();
692
				set_upgrade_progress('commit','in_progress','pre_install','done');
693
			}
694
		}
695
	}
696
697
	//Clean smarty from cache
698
	$cachedir = sugar_cached('smarty');
699
	if(is_dir($cachedir)){
700
		$allModFiles = array();
701
		$allModFiles = findAllFiles($cachedir,$allModFiles);
702
	   foreach($allModFiles as $file){
703
	       	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
704
	       	if(file_exists($file)){
705
				unlink($file);
706
	       	}
707
	   }
708
	}
709
710
		//Also add the three-way merge here. The idea is after the 451 html files have
711
		//been converted run the 3-way merge. If 500 then just run the 3-way merge
712
		if(file_exists('modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
713
		    set_upgrade_progress('end','in_progress','threewaymerge','in_progress');
714
		    require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php');
715
		    $merger = new SugarMerge($zipBasePath);
716
		    $merger->mergeAll();
717
		    set_upgrade_progress('end','in_progress','threewaymerge','done');
718
		}
719
	///////////////////////////////////////////////////////////////////////////////
720
	////	COPY NEW FILES INTO TARGET INSTANCE
721
722
     if(!didThisStepRunBefore('commit','commitCopyNewFiles')){
723
			set_upgrade_progress('commit','in_progress','commitCopyNewFiles','in_progress');
724
			$split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
725
	 		$copiedFiles = $split['copiedFiles'];
726
	 		$skippedFiles = $split['skippedFiles'];
727
			set_upgrade_progress('commit','in_progress','commitCopyNewFiles','done');
728
	 }
729
	require_once(clean_path($unzip_dir.'/scripts/upgrade_utils.php'));
730
	$new_sugar_version = getUpgradeVersion();
731
    $siv_varset_1 = setSilentUpgradeVar('origVersion', $sugar_version);
732
    $siv_varset_2 = setSilentUpgradeVar('destVersion', $new_sugar_version);
733
    $siv_write    = writeSilentUpgradeVars();
734
    if(!$siv_varset_1 || !$siv_varset_2 || !$siv_write){
735
        logThis("Error with silent upgrade variables: origVersion write success is ({$siv_varset_1}) ".
736
        		"-- destVersion write success is ({$siv_varset_2}) -- ".
737
        		"writeSilentUpgradeVars success is ({$siv_write}) -- ".
738
        		"path to cache dir is ({$GLOBALS['sugar_config']['cache_dir']})", $path);
739
    }
740
     require_once('modules/DynamicFields/templates/Fields/TemplateText.php');
741
	///////////////////////////////////////////////////////////////////////////////
742
    ///    RELOAD NEW DEFINITIONS
743
    global $ACLActions, $beanList, $beanFiles;
744
    include('modules/ACLActions/actiondefs.php');
745
    include('include/modules.php');
746
	/////////////////////////////////////////////
747
748
    if (!function_exists("inDeveloperMode")) {
749
        //this function was introduced from tokyo in the file include/utils.php, so when upgrading from 5.1x and 5.2x we should declare the this function
750
        function inDeveloperMode()
0 ignored issues
show
The function inDeveloperMode() has been defined more than once; this definition is ignored, only the first definition in include/utils.php (L4570-4573) is considered.

This check looks for functions that have already been defined in other files.

Some Codebases, like WordPress, make a practice of defining functions multiple times. This may lead to problems with the detection of function parameters and types. If you really need to do this, you can mark the duplicate definition with the @ignore annotation.

/**
 * @ignore
 */
function getUser() {

}

function getUser($id, $realm) {

}

See also the PhpDoc documentation for @ignore.

Loading history...
751
        {
752
            return isset($GLOBALS['sugar_config']['developerMode']) && $GLOBALS['sugar_config']['developerMode'];
753
        }
754
    }
755
	///////////////////////////////////////////////////////////////////////////////
756
	////	HANDLE POSTINSTALL SCRIPTS
757
	if(empty($errors)) {
758
		logThis('Starting post_install()...', $path);
759
760
		$trackerManager = TrackerManager::getInstance();
761
        $trackerManager->pause();
762
        $trackerManager->unsetMonitors();
763
764
		if(!didThisStepRunBefore('commit','post_install')){
765
			$file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
766
			if(is_file($file)) {
767
				//set_upgrade_progress('commit','in_progress','post_install','in_progress');
768
				$progArray['post_install']='in_progress';
769
				post_install_progress($progArray,'set');
770
				    global $moduleList;
771
					include($file);
772
					post_install();
773
				// cn: only run conversion if admin selects "Sugar runs SQL"
774
				if(!empty($_SESSION['allTables']) && $_SESSION['schema_change'] == 'sugar')
775
					executeConvertTablesSql($_SESSION['allTables']);
776
				//set process to done
777
				$progArray['post_install']='done';
778
				//set_upgrade_progress('commit','in_progress','post_install','done');
779
				post_install_progress($progArray,'set');
780
			}
781
		}
782
	    //clean vardefs
783
		logThis('Performing UWrebuild()...', $path);
784
		ob_start();
785
			@UWrebuild();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
786
		ob_end_clean();
787
		logThis('UWrebuild() done.', $path);
788
789
		logThis('begin check default permissions .', $path);
790
	    	checkConfigForPermissions();
791
	    logThis('end check default permissions .', $path);
792
793
	    logThis('begin check logger settings .', $path);
794
	    	checkLoggerSettings();
795
	    logThis('begin check logger settings .', $path);
796
797
            logThis('begin check lead conversion settings .', $path);
798
            checkLeadConversionSettings();
799
	    logThis('end check lead conversion settings .', $path);
800
801
	    logThis('begin check resource settings .', $path);
802
			checkResourceSettings();
803
		logThis('begin check resource settings .', $path);
804
805
806
		require("sugar_version.php");
807
		require('config.php');
808
		global $sugar_config;
809
810
		if($ce_to_pro_ent){
811
			if(isset($sugar_config['sugarbeet']))
812
			{
813
			    //$sugar_config['sugarbeet'] is only set in COMM
814
			    unset($sugar_config['sugarbeet']);
815
			}
816
		    if(isset($sugar_config['disable_team_access_check']))
817
			{
818
			    //$sugar_config['disable_team_access_check'] is a runtime configration,
819
			    //no need to write to config.php
820
			    unset($sugar_config['disable_team_access_check']);
821
			}
822
			if(!merge_passwordsetting($sugar_config, $sugar_version)) {
823
				logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
824
				$errors[] = 'Could not write config.php!';
825
			}
826
827
		}
828
829
		logThis('Set default_theme to Sugar', $path);
830
		$sugar_config['default_theme'] = 'Sugar';
831
832
		if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
833
            logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
834
            $errors[] = 'Could not write config.php!';
835
        }
836
837
        logThis('Set default_max_tabs to 7', $path);
838
		$sugar_config['default_max_tabs'] = '7';
839
840
		if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
841
            logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
842
            $errors[] = 'Could not write config.php!';
843
        }
844
845
        if (version_compare($new_sugar_version, $sugar_version, '='))
846
        {
847
            require('config.php');
848
        }
849
        //upgrade the sugar version prior to writing config file.
850
        logThis('Upgrade the sugar_version', $path);
851
        $sugar_config['sugar_version'] = $sugar_version;
852
853
        if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
854
            logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
855
            $errors[] = 'Could not write config.php!';
856
        }
857
858
		logThis('post_install() done.', $path);
859
	}
860
861
	///////////////////////////////////////////////////////////////////////////////
862
	////	REGISTER UPGRADE
863
	if(empty($errors)) {
864
		logThis('Registering upgrade with UpgradeHistory', $path);
865
		if(!didThisStepRunBefore('commit','upgradeHistory')){
866
			set_upgrade_progress('commit','in_progress','upgradeHistory','in_progress');
867
			$file_action = "copied";
868
			// if error was encountered, script should have died before now
869
			$new_upgrade = new UpgradeHistory();
870
			$new_upgrade->filename = $install_file;
871
			$new_upgrade->md5sum = md5_file($install_file);
872
			$new_upgrade->name = $zip_from_dir;
873
			$new_upgrade->description = $manifest['description'];
874
			$new_upgrade->type = 'patch';
875
			$new_upgrade->version = $sugar_version;
876
			$new_upgrade->status = "installed";
877
			$new_upgrade->manifest = (!empty($_SESSION['install_manifest']) ? $_SESSION['install_manifest'] : '');
878
879
			if($new_upgrade->description == null){
880
				$new_upgrade->description = "Silent Upgrade was used to upgrade the instance";
881
			}
882
			else{
883
				$new_upgrade->description = $new_upgrade->description." Silent Upgrade was used to upgrade the instance.";
884
			}
885
		   $new_upgrade->save();
886
		   set_upgrade_progress('commit','in_progress','upgradeHistory','done');
887
		   set_upgrade_progress('commit','done','commit','done');
888
		}
889
	  }
890
891
	//Clean modules from cache
892
	    $cachedir = sugar_cached('smarty');
893
		if(is_dir($cachedir)){
894
			$allModFiles = array();
895
			$allModFiles = findAllFiles($cachedir,$allModFiles);
896
		   foreach($allModFiles as $file){
897
		       	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
898
		       	if(file_exists($file)){
899
					unlink($file);
900
		       	}
901
		   }
902
		}
903
   //delete cache/modules before rebuilding the relations
904
   	//Clean modules from cache
905
   	    $cachedir = sugar_cached('modules');
906
		if(is_dir($cachedir)){
907
			$allModFiles = array();
908
			$allModFiles = findAllFiles($cachedir,$allModFiles);
909
		   foreach($allModFiles as $file){
910
		       	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
911
		       	if(file_exists($file)){
912
					unlink($file);
913
		       	}
914
		   }
915
		}
916
917
		//delete cache/themes
918
		$cachedir = sugar_cached('themes');
919
		if(is_dir($cachedir)){
920
			$allModFiles = array();
921
			$allModFiles = findAllFiles($cachedir,$allModFiles);
922
		   foreach($allModFiles as $file){
923
		       	//$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
924
		       	if(file_exists($file)){
925
					unlink($file);
926
		       	}
927
		   }
928
		}
929
	ob_start();
930
	if(!isset($_REQUEST['silent'])){
931
		$_REQUEST['silent'] = true;
932
	}
933
	else if(isset($_REQUEST['silent']) && $_REQUEST['silent'] != true){
0 ignored issues
show
Bug Best Practice introduced by
It seems like you are loosely comparing $_REQUEST['silent'] of type string to the boolean true. If you are specifically checking for an empty string, consider using the more explicit === '' instead.
Loading history...
934
		$_REQUEST['silent'] = true;
935
	}
936
937
	 //logThis('Checking for leads_assigned_user relationship and if not found then create.', $path);
938
	@createMissingRels();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
939
	 //logThis('Checked for leads_assigned_user relationship.', $path);
940
	ob_end_clean();
941
	//// run fix on dropdown lists that may have been incorrectly named
942
    //fix_dropdown_list();
943
}
944
945
set_upgrade_progress('end','in_progress','end','in_progress');
946
/////////////////////////Old Logger settings///////////////////////////////////////
947
///////////////////////////////////////////////////////////////////////////////
948
949
if(function_exists('deleteCache')){
950
	set_upgrade_progress('end','in_progress','deleteCache','in_progress');
951
	@deleteCache();
0 ignored issues
show
Security Best Practice introduced by
It seems like you do not handle an error condition here. This can introduce security issues, and is generally not recommended.

If you suppress an error, we recommend checking for the error condition explicitly:

// For example instead of
@mkdir($dir);

// Better use
if (@mkdir($dir) === false) {
    throw new \RuntimeException('The directory '.$dir.' could not be created.');
}
Loading history...
952
	set_upgrade_progress('end','in_progress','deleteCache','done');
953
}
954
955
///////////////////////////////////////////////////////////////////////////////
956
////	HANDLE REMINDERS
957
if(empty($errors)) {
958
	commitHandleReminders($skippedFiles, $path);
959
}
960
961
if(file_exists(clean_path(getcwd()).'/original451files')){
962
	rmdir_recursive(clean_path(getcwd()).'/original451files');
963
}
964
965
require_once('modules/Administration/Administration.php');
966
$admin = new Administration();
967
$admin->saveSetting('system','adminwizard',1);
968
969
970
if($ce_to_pro_ent)
971
{
972
        //check to see if there are any new files that need to be added to systems tab
973
        //retrieve old modules list
974
        logThis('check to see if new modules exist',$path);
975
        $oldModuleList = array();
976
        $newModuleList = array();
977
        include($argv[3].'/include/modules.php');
978
        $oldModuleList = $moduleList;
979
        include('include/modules.php');
980
        $newModuleList = $moduleList;
981
982
        //include tab controller
983
        require_once('modules/MySettings/TabController.php');
984
        $newTB = new TabController();
985
986
        //make sure new modules list has a key we can reference directly
987
        $newModuleList = $newTB->get_key_array($newModuleList);
988
        $oldModuleList = $newTB->get_key_array($oldModuleList);
989
990
        //iterate through list and remove commonalities to get new modules
991
        foreach ($newModuleList as $remove_mod){
992
            if(in_array($remove_mod, $oldModuleList)){
993
                unset($newModuleList[$remove_mod]);
994
            }
995
        }
996
997
        $must_have_modules= array(
998
			  'Activities'=>'Activities',
999
        	  'Calendar'=>'Calendar',
1000
        	  'Reports' => 'Reports',
1001
			  'Quotes' => 'Quotes',
1002
			  'Products' => 'Products',
1003
			  'Forecasts' => 'Forecasts',
1004
			  'Contracts' => 'Contracts',
1005
			  'KBDocuments' => 'KBDocuments'
1006
        );
1007
        $newModuleList = array_merge($newModuleList,$must_have_modules);
1008
1009
        //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
1010
        logThis('new modules to add are '.var_export($newModuleList,true),$path);
1011
1012
        //grab the existing system tabs
1013
        $tabs = $newTB->get_system_tabs();
1014
1015
        //add the new tabs to the array
1016
        foreach($newModuleList as $nm ){
1017
          $tabs[$nm] = $nm;
1018
        }
1019
1020
        //now assign the modules to system tabs
1021
        $newTB->set_system_tabs($tabs);
1022
        logThis('module tabs updated',$path);
1023
}
1024
1025
//Also set the tracker settings if  flavor conversion ce->pro or ce->ent
1026
if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
1027
    if (version_compare($_SESSION['current_db_version'], $_SESSION['target_db_version'], '='))
1028
    {
1029
	    $_REQUEST['upgradeWizard'] = true;
1030
	    ob_start();
1031
			include('include/Smarty/internals/core.write_file.php');
1032
		ob_end_clean();
1033
	 	$db =& DBManagerFactory::getInstance();
1034
		if($ce_to_pro_ent){
1035
	        //Also set license information
1036
	        $admin = new Administration();
1037
			$category = 'license';
1038
			$value = 0;
1039
			$admin->saveSetting($category, 'users', $value);
1040
			$key = array('num_lic_oc','key','expire_date');
1041
			$value = '';
1042
			foreach($key as $k){
1043
				$admin->saveSetting($category, $k, $value);
1044
			}
1045
		}
1046
	}
1047
}
1048
1049
	$phpErrors = ob_get_contents();
1050
	ob_end_clean();
1051
	logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
1052
1053
	if(count($errors) > 0) {
1054
		foreach($errors as $error) {
1055
			logThis("****** SilentUpgrade ERROR: {$error}", $path);
1056
		}
1057
		echo "FAILED\n";
1058
	}
1059
1060
1061
}
1062
1063
1064
/**
1065
 * repairTableDictionaryExtFile
1066
 *
1067
 * There were some scenarios in 6.0.x whereby the files loaded in the extension tabledictionary.ext.php file
1068
 * did not exist.  This would cause warnings to appear during the upgrade.  As a result, this
1069
 * function scans the contents of tabledictionary.ext.php and then remove entries where the file does exist.
1070
 */
1071
function repairTableDictionaryExtFile()
1072
{
1073
	$tableDictionaryExtDirs = array('custom/Extension/application/Ext/TableDictionary', 'custom/application/Ext/TableDictionary');
1074
1075
	foreach($tableDictionaryExtDirs as $tableDictionaryExt)
1076
	{
1077
1078
		if(is_dir($tableDictionaryExt) && is_writable($tableDictionaryExt)){
1079
			$dir = dir($tableDictionaryExt);
1080
			while(($entry = $dir->read()) !== false)
1081
			{
1082
				$entry = $tableDictionaryExt . '/' . $entry;
1083
				if(is_file($entry) && preg_match('/\.php$/i', $entry) && is_writeable($entry))
1084
				{
1085
1086
						if(function_exists('sugar_fopen'))
1087
						{
1088
							$fp = @sugar_fopen($entry, 'r');
1089
						} else {
1090
							$fp = fopen($entry, 'r');
1091
						}
1092
1093
1094
					    if($fp)
1095
				        {
1096
				             $altered = false;
1097
				             $contents = '';
1098
1099
				             while($line = fgets($fp))
1100
						     {
1101
						    	if(preg_match('/\s*include\s*\(\s*[\'|\"](.*?)[\"|\']\s*\)\s*;/', $line, $match))
1102
						    	{
1103
						    	   if(!file_exists($match[1]))
1104
						    	   {
1105
						    	      $altered = true;
1106
						    	   } else {
1107
						    	   	  $contents .= $line;
1108
						    	   }
1109
						    	} else {
1110
						    	   $contents .= $line;
1111
						    	}
1112
						     }
1113
1114
						     fclose($fp);
1115
				        }
1116
1117
1118
					    if($altered)
1119
					    {
1120
							if(function_exists('sugar_fopen'))
1121
							{
1122
								$fp = @sugar_fopen($entry, 'w');
1123
							} else {
1124
								$fp = fopen($entry, 'w');
1125
							}
1126
1127
							if($fp && fwrite($fp, $contents))
1128
							{
1129
								fclose($fp);
1130
							}
1131
					    }
1132
				} //if
1133
			} //while
1134
		} //if
1135
	}
1136
}
1137