]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UpgradeWizard/silentUpgrade_step1.php
Release 6.4.0
[Github/sugarcrm.git] / modules / UpgradeWizard / silentUpgrade_step1.php
1 <?php
2
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 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 contact@sugarcrm.com.
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() {
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) {
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(){
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')) {
92                 //writing to the file
93                 }
94      }
95 }
96 function checkLoggerSettings(){
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' => '%m_%Y',
112                     ),
113                   );
114                  ksort($sugar_config);
115          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
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')) {
130             //writing to the file
131         }
132     }
133 }
134
135 function checkResourceSettings(){
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')) {
156                 //writing to the file
157                 }
158         }
159 }
160
161
162 function createMissingRels(){
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) {
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()) {
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){
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(){
346         //using threeway merge apis
347 }
348
349 ////    END UTILITIES THAT MUST BE LOCAL :(
350 ///////////////////////////////////////////////////////////////////////////////
351
352
353 // only run from command line
354 if(isset($_SERVER['HTTP_USER_AGENT'])) {
355         fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
356         exit(1);
357 }
358 //Clean_string cleans out any file  passed in as a parameter
359 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
360
361 $usage_regular =<<<eoq2
362 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
363
364 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
365 php.exe followed by -f silentUpgrade.php and the arguments.
366
367 Example:
368     [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
369
370 Arguments:
371     upgradeZipFile                       : Upgrade package file.
372     logFile                              : Silent Upgarde log file.
373     pathToSugarInstance                  : Sugar Instance instance being upgraded.
374     admin-user                           : admin user performing the upgrade
375 eoq2;
376 ////    END USAGE
377 ///////////////////////////////////////////////////////////////////////////////
378
379
380
381 ///////////////////////////////////////////////////////////////////////////////
382 ////    STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
383 if(!defined('sugarEntry')) define('sugarEntry', true);
384
385 $_SESSION = array();
386 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
387 $_SESSION['silent_upgrade'] = true;
388 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
389
390 $_REQUEST = array();
391 $_REQUEST['addTaskReminder'] = 'remind';
392
393
394 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
395 define('DCE_INSTANCE', 'DCE_Instance');
396
397 global $cwd;
398 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
399
400 $upgradeType = verifyArguments($argv,$usage_regular);
401
402 ///////////////////////////////////////////////////////////////////////////////
403 //////  Verify that all the arguments are appropriately placed////////////////
404
405 $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
406 $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
407
408 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
409
410 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
411 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
412 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
413 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
414
415
416
417 echo "\n";
418 echo "********************************************************************\n";
419 echo "***************This Upgrade process may take sometime***************\n";
420 echo "********************************************************************\n";
421 echo "\n";
422
423 global $sugar_config;
424 $isDCEInstance = false;
425 $errors = array();
426
427
428 if($upgradeType != constant('DCE_INSTANCE')) {
429
430         ini_set('error_reporting',1);
431         require_once('include/entryPoint.php');
432         require_once('include/SugarLogger/SugarLogger.php');
433         require_once('include/utils/zip_utils.php');
434
435
436 if(!function_exists('sugar_cached'))
437 {
438     /**
439      * sugar_cached
440      *
441      * @param $file The path to retrieve cache lookup information for
442      * @return string The cached path according to $GLOBALS['sugar_config']['cache_dir'] or just appended with cache if not defined
443      */
444     function sugar_cached($file)
445     {
446         static $cdir = null;
447         if(empty($cdir) && !empty($GLOBALS['sugar_config']['cache_dir'])) {
448             $cdir = rtrim($GLOBALS['sugar_config']['cache_dir'], '/\\');
449         }
450         if(empty($cdir)) {
451             $cdir = "cache";
452         }
453         return "$cdir/$file";
454     }
455 }
456
457         require('config.php');
458         //require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
459         if(isset($argv[3])) {
460                 if(is_dir($argv[3])) {
461                         $cwd = $argv[3];
462                         chdir($cwd);
463                 }
464         }
465
466         require_once("{$cwd}/sugar_version.php"); // provides $sugar_version & $sugar_flavor
467
468     $GLOBALS['log']     = LoggerManager::getLogger('SugarCRM');
469         $patchName              = basename($argv[1]);
470         $zip_from_dir   = substr($patchName, 0, strlen($patchName) - 4); // patch folder name (minus ".zip")
471         $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
472
473     $db                         = &DBManagerFactory::getInstance();
474         $UWstrings              = return_module_language('en_us', 'UpgradeWizard');
475         $adminStrings   = return_module_language('en_us', 'Administration');
476     $app_list_strings = return_app_list_strings_language('en_us');
477         $mod_strings    = array_merge($adminStrings, $UWstrings);
478         $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
479         global $unzip_dir;
480     $license_accepted = false;
481     if(isset($argv[5]) && (strtolower($argv[5])=='yes' || strtolower($argv[5])=='y')){
482         $license_accepted = true;
483          }
484         //////////////////////////////////////////////////////////////////////////////
485         //Adding admin user to the silent upgrade
486
487         $current_user = new User();
488         if(isset($argv[4])) {
489            //if being used for internal upgrades avoid admin user verification
490            $user_name = $argv[4];
491            $q = "select id from users where user_name = '" . $user_name . "' and is_admin=1";
492            $result = $GLOBALS['db']->query($q, false);
493            $logged_user = $GLOBALS['db']->fetchByAssoc($result);
494            if(isset($logged_user['id']) && $logged_user['id'] != null){
495                 //do nothing
496             $current_user->retrieve($logged_user['id']);
497            }
498            else{
499                 echo "FAILURE: Not an admin user in users table. Please provide an admin user\n";
500                 exit(1);
501            }
502         }
503         else {
504                 echo "*******************************************************************************\n";
505                 echo "*** ERROR: 4th parameter must be a valid admin user.\n";
506                 echo $usage;
507                 echo "FAILURE\n";
508                 exit(1);
509         }
510
511
512                 /////retrieve admin user
513         global $sugar_config;
514         $configOptions = $sugar_config['dbconfig'];
515
516
517 ///////////////////////////////////////////////////////////////////////////////
518 ////    UPGRADE PREP
519 prepSystemForUpgradeSilent();
520
521 //repair tabledictionary.ext.php file if needed
522 repairTableDictionaryExtFile();
523
524 $unzip_dir = sugar_cached("upgrades/temp");
525 $install_file = $sugar_config['upload_dir']."/upgrades/patch/".basename($argv[1]);
526
527 $_SESSION['unzip_dir'] = $unzip_dir;
528 $_SESSION['install_file'] = $install_file;
529 $_SESSION['zip_from_dir'] = $zip_from_dir;
530 if(is_dir($unzip_dir.'/scripts'))
531 {
532         rmdir_recursive($unzip_dir.'/scripts');
533 }
534 if(is_file($unzip_dir.'/manifest.php'))
535 {
536         rmdir_recursive($unzip_dir.'/manifest.php');
537 }
538 mkdir_recursive($unzip_dir);
539 if(!is_dir($unzip_dir)) {
540         echo "\n{$unzip_dir} is not an available directory\nFAILURE\n";
541         fwrite(STDERR,"\n{$unzip_dir} is not an available directory\nFAILURE\n");
542         exit(1);
543 }
544
545 unzip($argv[1], $unzip_dir);
546 // mimic standard UW by copy patch zip to appropriate dir
547 copy($argv[1], $install_file);
548 ////    END UPGRADE PREP
549 ///////////////////////////////////////////////////////////////////////////////
550
551 ///////////////////////////////////////////////////////////////////////////////
552 ////    UPGRADE UPGRADEWIZARD
553
554 $zipBasePath = "$unzip_dir/{$zip_from_dir}";
555 $uwFiles = findAllFiles("{$zipBasePath}/modules/UpgradeWizard", array());
556 $destFiles = array();
557
558 foreach($uwFiles as $uwFile) {
559         $destFile = str_replace($zipBasePath."/", '', $uwFile);
560         copy($uwFile, $destFile);
561 }
562 require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
563 removeSilentUpgradeVarsCache(); // Clear the silent upgrade vars - Note: Any calls to these functions within this file are removed here
564 logThis("*** SILENT UPGRADE INITIATED.", $path);
565 logThis("*** UpgradeWizard Upgraded  ", $path);
566
567 if(function_exists('set_upgrade_vars')){
568         set_upgrade_vars();
569 }
570
571 if($configOptions['db_type'] == 'mysql'){
572         //Change the db wait_timeout for this session
573         $now_timeout = $db->getOne("select @@wait_timeout");
574         logThis('Wait Timeout before change ***** '.$now_timeout , $path);
575         $now_timeout = $db->getOne("set wait_timeout=28800");
576         logThis('Wait Timeout after change ***** '.$now_timeout , $path);
577 }
578
579 ////    END UPGRADE UPGRADEWIZARD
580 ///////////////////////////////////////////////////////////////////////////////
581
582 ///////////////////////////////////////////////////////////////////////////////
583 ////    MAKE SURE PATCH IS COMPATIBLE
584 if(is_file("$unzip_dir/manifest.php")) {
585         // provides $manifest array
586         include("$unzip_dir/manifest.php");
587         if(!isset($manifest)) {
588                 fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
589             exit(1);
590         } else {
591                 copy("$unzip_dir/manifest.php", $sugar_config['upload_dir']."/upgrades/patch/{$zip_from_dir}-manifest.php");
592
593                 $error = validate_manifest($manifest);
594                 if(!empty($error)) {
595                         $error = strip_tags(br2nl($error));
596                         fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
597                         exit(1);
598                 }
599         }
600 } else {
601         fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
602         exit(1);
603 }
604
605 $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');
606 $_SESSION['upgrade_from_flavor'] = $manifest['name'];
607
608 global $sugar_config;
609 global $sugar_version;
610 global $sugar_flavor;
611
612 ////    END MAKE SURE PATCH IS COMPATIBLE
613 ///////////////////////////////////////////////////////////////////////////////
614
615 ///////////////////////////////////////////////////////////////////////////////
616 ////    RUN SILENT UPGRADE
617 ob_start();
618 set_time_limit(0);
619 if(file_exists('ModuleInstall/PackageManager/PackageManagerDisplay.php')) {
620         require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php');
621 }
622
623
624         //copy minimum required files including sugar_file_utils.php
625         if(file_exists("{$zipBasePath}/include/utils/sugar_file_utils.php")){
626                 $destFile = clean_path(str_replace($zipBasePath, $cwd, "{$zipBasePath}/include/utils/sugar_file_utils.php"));
627                 copy("{$zipBasePath}/include/utils/sugar_file_utils.php", $destFile);
628         }
629         if(file_exists('include/utils/sugar_file_utils.php')){
630         require_once('include/utils/sugar_file_utils.php');
631     }
632
633 /*
634 $errors = preflightCheck();
635 if((count($errors) == 1)) { // only diffs
636         logThis('file preflight check passed successfully.', $path);
637 }
638 else{
639         fwrite(STDERR,"\nThe user doesn't have sufficient permissions to write to database'.\n\n");
640         exit(1);
641 }
642 */
643 //If version less than 500 then look for modules to be upgraded
644 if(function_exists('set_upgrade_vars')){
645         set_upgrade_vars();
646 }
647 //Initialize the session variables. If upgrade_progress.php is already created
648 //look for session vars there and restore them
649 if(function_exists('initialize_session_vars')){
650         initialize_session_vars();
651 }
652
653 if(!didThisStepRunBefore('preflight')){
654         set_upgrade_progress('preflight','in_progress');
655         //Quickcreatedefs on the basis of editviewdefs
656     if(substr($sugar_version,0,1) >= 5){
657         updateQuickCreateDefs();
658         }
659         set_upgrade_progress('preflight','done');
660 }
661 ////////////////COMMIT PROCESS BEGINS///////////////////////////////////////////////////////////////
662 ////    MAKE BACKUPS OF TARGET FILES
663
664 if(!didThisStepRunBefore('commit')){
665         set_upgrade_progress('commit','in_progress','commit','in_progress');
666         if(!didThisStepRunBefore('commit','commitMakeBackupFiles')){
667                 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','in_progress');
668                 $errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
669                 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','done');
670         }
671
672         //Need to make sure we have the matching copy of SetValueAction for static/instance method matching
673     if(file_exists("include/Expressions/Actions/SetValueAction.php")){
674         require_once("include/Expressions/Actions/SetValueAction.php");
675     }
676
677         ///////////////////////////////////////////////////////////////////////////////
678         ////    HANDLE PREINSTALL SCRIPTS
679         if(empty($errors)) {
680                 $file = "{$unzip_dir}/".constant('SUGARCRM_PRE_INSTALL_FILE');
681
682                 if(is_file($file)) {
683                         include($file);
684                         if(!didThisStepRunBefore('commit','pre_install')){
685                                 set_upgrade_progress('commit','in_progress','pre_install','in_progress');
686                                 pre_install();
687                                 set_upgrade_progress('commit','in_progress','pre_install','done');
688                         }
689                 }
690         }
691
692         //Clean smarty from cache
693         $cachedir = sugar_cached('smarty');
694         if(is_dir($cachedir)){
695                 $allModFiles = array();
696                 $allModFiles = findAllFiles($cachedir,$allModFiles);
697            foreach($allModFiles as $file){
698                 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
699                 if(file_exists($file)){
700                                 unlink($file);
701                 }
702            }
703         }
704
705                 //Also add the three-way merge here. The idea is after the 451 html files have
706                 //been converted run the 3-way merge. If 500 then just run the 3-way merge
707                 if(file_exists('modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
708                     set_upgrade_progress('end','in_progress','threewaymerge','in_progress');
709                     require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php');
710                     $merger = new SugarMerge($zipBasePath);
711                     $merger->mergeAll();
712                     set_upgrade_progress('end','in_progress','threewaymerge','done');
713                 }
714         ///////////////////////////////////////////////////////////////////////////////
715         ////    COPY NEW FILES INTO TARGET INSTANCE
716
717      if(!didThisStepRunBefore('commit','commitCopyNewFiles')){
718                         set_upgrade_progress('commit','in_progress','commitCopyNewFiles','in_progress');
719                         $split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
720                         $copiedFiles = $split['copiedFiles'];
721                         $skippedFiles = $split['skippedFiles'];
722                         set_upgrade_progress('commit','in_progress','commitCopyNewFiles','done');
723          }
724         require_once(clean_path($unzip_dir.'/scripts/upgrade_utils.php'));
725         $new_sugar_version = getUpgradeVersion();
726     $origVersion = substr(preg_replace("/[^0-9]/", "", $sugar_version),0,3);
727     $destVersion = substr(preg_replace("/[^0-9]/", "", $new_sugar_version),0,3);
728     $siv_varset_1 = setSilentUpgradeVar('origVersion', $origVersion);
729     $siv_varset_2 = setSilentUpgradeVar('destVersion', $destVersion);
730     $siv_write    = writeSilentUpgradeVars();
731     if(!$siv_varset_1 || !$siv_varset_2 || !$siv_write){
732         logThis("Error with silent upgrade variables: origVersion write success is ({$siv_varset_1}) ".
733                         "-- destVersion write success is ({$siv_varset_2}) -- ".
734                         "writeSilentUpgradeVars success is ({$siv_write}) -- ".
735                         "path to cache dir is ({$GLOBALS['sugar_config']['cache_dir']})", $path);
736     }
737      require_once('modules/DynamicFields/templates/Fields/TemplateText.php');
738         ///////////////////////////////////////////////////////////////////////////////
739     ///    RELOAD NEW DEFINITIONS
740     global $ACLActions, $beanList, $beanFiles;
741     include('modules/ACLActions/actiondefs.php');
742     include('include/modules.php');
743         /////////////////////////////////////////////
744
745     if (!function_exists("inDeveloperMode")) {
746         //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
747         function inDeveloperMode()
748         {
749             return isset($GLOBALS['sugar_config']['developerMode']) && $GLOBALS['sugar_config']['developerMode'];
750         }
751     }
752         ///////////////////////////////////////////////////////////////////////////////
753         ////    HANDLE POSTINSTALL SCRIPTS
754         if(empty($errors)) {
755                 logThis('Starting post_install()...', $path);
756
757                 $trackerManager = TrackerManager::getInstance();
758         $trackerManager->pause();
759         $trackerManager->unsetMonitors();
760
761                 if(!didThisStepRunBefore('commit','post_install')){
762                         $file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
763                         if(is_file($file)) {
764                                 //set_upgrade_progress('commit','in_progress','post_install','in_progress');
765                                 $progArray['post_install']='in_progress';
766                                 post_install_progress($progArray,'set');
767                                     global $moduleList;
768                                         include($file);
769                                         post_install();
770                                 // cn: only run conversion if admin selects "Sugar runs SQL"
771                                 if(!empty($_SESSION['allTables']) && $_SESSION['schema_change'] == 'sugar')
772                                         executeConvertTablesSql($_SESSION['allTables']);
773                                 //set process to done
774                                 $progArray['post_install']='done';
775                                 //set_upgrade_progress('commit','in_progress','post_install','done');
776                                 post_install_progress($progArray,'set');
777                         }
778                 }
779             //clean vardefs
780                 logThis('Performing UWrebuild()...', $path);
781                 ob_start();
782                         @UWrebuild();
783                 ob_end_clean();
784                 logThis('UWrebuild() done.', $path);
785
786                 logThis('begin check default permissions .', $path);
787                 checkConfigForPermissions();
788             logThis('end check default permissions .', $path);
789
790             logThis('begin check logger settings .', $path);
791                 checkLoggerSettings();
792             logThis('begin check logger settings .', $path);
793
794             logThis('begin check lead conversion settings .', $path);
795             checkLeadConversionSettings();
796             logThis('end check lead conversion settings .', $path);
797
798             logThis('begin check resource settings .', $path);
799                         checkResourceSettings();
800                 logThis('begin check resource settings .', $path);
801
802
803                 require("sugar_version.php");
804                 require('config.php');
805                 global $sugar_config;
806
807                 if($ce_to_pro_ent){
808                         if(isset($sugar_config['sugarbeet']))
809                         {
810                             //$sugar_config['sugarbeet'] is only set in COMM
811                             unset($sugar_config['sugarbeet']);
812                         }
813                     if(isset($sugar_config['disable_team_access_check']))
814                         {
815                             //$sugar_config['disable_team_access_check'] is a runtime configration,
816                             //no need to write to config.php
817                             unset($sugar_config['disable_team_access_check']);
818                         }
819                         if(!merge_passwordsetting($sugar_config, $sugar_version)) {
820                                 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
821                                 $errors[] = 'Could not write config.php!';
822                         }
823
824                 }
825
826                 logThis('Set default_theme to Sugar', $path);
827                 $sugar_config['default_theme'] = 'Sugar';
828
829                 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
830             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
831             $errors[] = 'Could not write config.php!';
832         }
833
834         logThis('Set default_max_tabs to 7', $path);
835                 $sugar_config['default_max_tabs'] = '7';
836
837                 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
838             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
839             $errors[] = 'Could not write config.php!';
840         }
841
842                 logThis('Upgrade the sugar_version', $path);
843                 $sugar_config['sugar_version'] = $sugar_version;
844                 if($destVersion == $origVersion)
845                         require('config.php');
846         if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
847             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
848             $errors[] = 'Could not write config.php!';
849         }
850
851                 logThis('post_install() done.', $path);
852         }
853
854         ///////////////////////////////////////////////////////////////////////////////
855         ////    REGISTER UPGRADE
856         if(empty($errors)) {
857                 logThis('Registering upgrade with UpgradeHistory', $path);
858                 if(!didThisStepRunBefore('commit','upgradeHistory')){
859                         set_upgrade_progress('commit','in_progress','upgradeHistory','in_progress');
860                         $file_action = "copied";
861                         // if error was encountered, script should have died before now
862                         $new_upgrade = new UpgradeHistory();
863                         $new_upgrade->filename = $install_file;
864                         $new_upgrade->md5sum = md5_file($install_file);
865                         $new_upgrade->name = $zip_from_dir;
866                         $new_upgrade->description = $manifest['description'];
867                         $new_upgrade->type = 'patch';
868                         $new_upgrade->version = $sugar_version;
869                         $new_upgrade->status = "installed";
870                         $new_upgrade->manifest = (!empty($_SESSION['install_manifest']) ? $_SESSION['install_manifest'] : '');
871
872                         if($new_upgrade->description == null){
873                                 $new_upgrade->description = "Silent Upgrade was used to upgrade the instance";
874                         }
875                         else{
876                                 $new_upgrade->description = $new_upgrade->description." Silent Upgrade was used to upgrade the instance.";
877                         }
878                    $new_upgrade->save();
879                    set_upgrade_progress('commit','in_progress','upgradeHistory','done');
880                    set_upgrade_progress('commit','done','commit','done');
881                 }
882           }
883
884         //Clean modules from cache
885             $cachedir = sugar_cached('smarty');
886                 if(is_dir($cachedir)){
887                         $allModFiles = array();
888                         $allModFiles = findAllFiles($cachedir,$allModFiles);
889                    foreach($allModFiles as $file){
890                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
891                         if(file_exists($file)){
892                                         unlink($file);
893                         }
894                    }
895                 }
896    //delete cache/modules before rebuilding the relations
897         //Clean modules from cache
898             $cachedir = sugar_cached('modules');
899                 if(is_dir($cachedir)){
900                         $allModFiles = array();
901                         $allModFiles = findAllFiles($cachedir,$allModFiles);
902                    foreach($allModFiles as $file){
903                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
904                         if(file_exists($file)){
905                                         unlink($file);
906                         }
907                    }
908                 }
909
910                 //delete cache/themes
911                 $cachedir = sugar_cached('themes');
912                 if(is_dir($cachedir)){
913                         $allModFiles = array();
914                         $allModFiles = findAllFiles($cachedir,$allModFiles);
915                    foreach($allModFiles as $file){
916                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
917                         if(file_exists($file)){
918                                         unlink($file);
919                         }
920                    }
921                 }
922         ob_start();
923         if(!isset($_REQUEST['silent'])){
924                 $_REQUEST['silent'] = true;
925         }
926         else if(isset($_REQUEST['silent']) && $_REQUEST['silent'] != true){
927                 $_REQUEST['silent'] = true;
928         }
929
930          //logThis('Checking for leads_assigned_user relationship and if not found then create.', $path);
931         @createMissingRels();
932          //logThis('Checked for leads_assigned_user relationship.', $path);
933         ob_end_clean();
934         //// run fix on dropdown lists that may have been incorrectly named
935     //fix_dropdown_list();
936 }
937
938 set_upgrade_progress('end','in_progress','end','in_progress');
939 /////////////////////////Old Logger settings///////////////////////////////////////
940 ///////////////////////////////////////////////////////////////////////////////
941
942 if(function_exists('deleteCache')){
943         set_upgrade_progress('end','in_progress','deleteCache','in_progress');
944         @deleteCache();
945         set_upgrade_progress('end','in_progress','deleteCache','done');
946 }
947
948 ///////////////////////////////////////////////////////////////////////////////
949 ////    HANDLE REMINDERS
950 if(empty($errors)) {
951         commitHandleReminders($skippedFiles, $path);
952 }
953
954 if(file_exists(clean_path(getcwd()).'/original451files')){
955         rmdir_recursive(clean_path(getcwd()).'/original451files');
956 }
957
958 require_once('modules/Administration/Administration.php');
959 $admin = new Administration();
960 $admin->saveSetting('system','adminwizard',1);
961
962
963 if($ce_to_pro_ent)
964 {
965         //check to see if there are any new files that need to be added to systems tab
966         //retrieve old modules list
967         logThis('check to see if new modules exist',$path);
968         $oldModuleList = array();
969         $newModuleList = array();
970         include($argv[3].'/include/modules.php');
971         $oldModuleList = $moduleList;
972         include('include/modules.php');
973         $newModuleList = $moduleList;
974
975         //include tab controller
976         require_once('modules/MySettings/TabController.php');
977         $newTB = new TabController();
978
979         //make sure new modules list has a key we can reference directly
980         $newModuleList = $newTB->get_key_array($newModuleList);
981         $oldModuleList = $newTB->get_key_array($oldModuleList);
982
983         //iterate through list and remove commonalities to get new modules
984         foreach ($newModuleList as $remove_mod){
985             if(in_array($remove_mod, $oldModuleList)){
986                 unset($newModuleList[$remove_mod]);
987             }
988         }
989
990         $must_have_modules= array(
991                           'Activities'=>'Activities',
992                   'Calendar'=>'Calendar',
993                   'Reports' => 'Reports',
994                           'Quotes' => 'Quotes',
995                           'Products' => 'Products',
996                           'Forecasts' => 'Forecasts',
997                           'Contracts' => 'Contracts',
998                           'KBDocuments' => 'KBDocuments'
999         );
1000         $newModuleList = array_merge($newModuleList,$must_have_modules);
1001
1002         //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
1003         logThis('new modules to add are '.var_export($newModuleList,true),$path);
1004
1005         //grab the existing system tabs
1006         $tabs = $newTB->get_system_tabs();
1007
1008         //add the new tabs to the array
1009         foreach($newModuleList as $nm ){
1010           $tabs[$nm] = $nm;
1011         }
1012
1013         //now assign the modules to system tabs
1014         $newTB->set_system_tabs($tabs);
1015         logThis('module tabs updated',$path);
1016 }
1017
1018 //Also set the tracker settings if  flavor conversion ce->pro or ce->ent
1019 if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
1020         if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){
1021             $_REQUEST['upgradeWizard'] = true;
1022             ob_start();
1023                         include('include/Smarty/internals/core.write_file.php');
1024                 ob_end_clean();
1025                 $db =& DBManagerFactory::getInstance();
1026                 if($ce_to_pro_ent){
1027                 //Also set license information
1028                 $admin = new Administration();
1029                         $category = 'license';
1030                         $value = 0;
1031                         $admin->saveSetting($category, 'users', $value);
1032                         $key = array('num_lic_oc','key','expire_date');
1033                         $value = '';
1034                         foreach($key as $k){
1035                                 $admin->saveSetting($category, $k, $value);
1036                         }
1037                 }
1038         }
1039 }
1040
1041         $phpErrors = ob_get_contents();
1042         ob_end_clean();
1043         logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
1044
1045         if(count($errors) > 0) {
1046                 foreach($errors as $error) {
1047                         logThis("****** SilentUpgrade ERROR: {$error}", $path);
1048                 }
1049                 echo "FAILED\n";
1050         }
1051
1052
1053 }
1054
1055
1056 /**
1057  * repairTableDictionaryExtFile
1058  *
1059  * There were some scenarios in 6.0.x whereby the files loaded in the extension tabledictionary.ext.php file
1060  * did not exist.  This would cause warnings to appear during the upgrade.  As a result, this
1061  * function scans the contents of tabledictionary.ext.php and then remove entries where the file does exist.
1062  */
1063 function repairTableDictionaryExtFile()
1064 {
1065         $tableDictionaryExtDirs = array('custom/Extension/application/Ext/TableDictionary', 'custom/application/Ext/TableDictionary');
1066
1067         foreach($tableDictionaryExtDirs as $tableDictionaryExt)
1068         {
1069
1070                 if(is_dir($tableDictionaryExt) && is_writable($tableDictionaryExt)){
1071                         $dir = dir($tableDictionaryExt);
1072                         while(($entry = $dir->read()) !== false)
1073                         {
1074                                 $entry = $tableDictionaryExt . '/' . $entry;
1075                                 if(is_file($entry) && preg_match('/\.php$/i', $entry) && is_writeable($entry))
1076                                 {
1077
1078                                                 if(function_exists('sugar_fopen'))
1079                                                 {
1080                                                         $fp = @sugar_fopen($entry, 'r');
1081                                                 } else {
1082                                                         $fp = fopen($entry, 'r');
1083                                                 }
1084
1085
1086                                             if($fp)
1087                                         {
1088                                              $altered = false;
1089                                              $contents = '';
1090
1091                                              while($line = fgets($fp))
1092                                                      {
1093                                                         if(preg_match('/\s*include\s*\(\s*[\'|\"](.*?)[\"|\']\s*\)\s*;/', $line, $match))
1094                                                         {
1095                                                            if(!file_exists($match[1]))
1096                                                            {
1097                                                               $altered = true;
1098                                                            } else {
1099                                                                   $contents .= $line;
1100                                                            }
1101                                                         } else {
1102                                                            $contents .= $line;
1103                                                         }
1104                                                      }
1105
1106                                                      fclose($fp);
1107                                         }
1108
1109
1110                                             if($altered)
1111                                             {
1112                                                         if(function_exists('sugar_fopen'))
1113                                                         {
1114                                                                 $fp = @sugar_fopen($entry, 'w');
1115                                                         } else {
1116                                                                 $fp = fopen($entry, 'w');
1117                                                         }
1118
1119                                                         if($fp && fwrite($fp, $contents))
1120                                                         {
1121                                                                 fclose($fp);
1122                                                         }
1123                                             }
1124                                 } //if
1125                         } //while
1126                 } //if
1127         }
1128 }
1129
1130
1131 ?>