]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UpgradeWizard/silentUpgrade_dce_step2.php
Release 6.5.1
[Github/sugarcrm.git] / modules / UpgradeWizard / silentUpgrade_dce_step2.php
1 <?php
2
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 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 //local function for clearing cache
49 function clearCacheSU($thedir, $extension) {
50         if ($current = @opendir($thedir)) {
51                 while (false !== ($children = readdir($current))) {
52                         if ($children != "." && $children != "..") {
53                                 if (is_dir($thedir . "/" . $children)) {
54                                         clearCacheSU($thedir . "/" . $children, $extension);
55                                 }
56                                 elseif (is_file($thedir . "/" . $children) && substr_count($children, $extension)) {
57                                         unlink($thedir . "/" . $children);
58                                 }
59                         }
60                 }
61         }
62  }
63  //Bug 24890, 24892. default_permissions not written to config.php. Following function checks and if
64  //no found then adds default_permissions to the config file.
65  function checkConfigForPermissions(){
66      if(file_exists(getcwd().'/config.php')){
67          require(getcwd().'/config.php');
68      }
69      global $sugar_config;
70      if(!isset($sugar_config['default_permissions'])){
71              $sugar_config['default_permissions'] = array (
72                      'dir_mode' => 02770,
73                      'file_mode' => 0660,
74                      'user' => '',
75                      'group' => '',
76              );
77          ksort($sugar_config);
78          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
79                 //writing to the file
80                 }
81      }
82 }
83 function checkLoggerSettings(){
84         if(file_exists(getcwd().'/config.php')){
85          require(getcwd().'/config.php');
86      }
87     global $sugar_config;
88         if(!isset($sugar_config['logger'])){
89             $sugar_config['logger'] =array (
90                         'level'=>'fatal',
91                     'file' =>
92                      array (
93                       'ext' => '.log',
94                       'name' => 'sugarcrm',
95                       'dateFormat' => '%c',
96                       'maxSize' => '10MB',
97                       'maxLogs' => 10,
98                       'suffix' => '', // bug51583, change default suffix to blank for backwards comptability
99                     ),
100                   );
101                  ksort($sugar_config);
102          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
103                 //writing to the file
104                 }
105          }
106 }
107
108 function checkResourceSettings(){
109         if(file_exists(getcwd().'/config.php')){
110          require(getcwd().'/config.php');
111      }
112     global $sugar_config;
113         if(!isset($sugar_config['resource_management'])){
114           $sugar_config['resource_management'] =
115                   array (
116                     'special_query_limit' => 50000,
117                     'special_query_modules' =>
118                     array (
119                       0 => 'Reports',
120                       1 => 'Export',
121                       2 => 'Import',
122                       3 => 'Administration',
123                       4 => 'Sync',
124                     ),
125                     'default_limit' => 1000,
126                   );
127                  ksort($sugar_config);
128          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
129                 //writing to the file
130                 }
131         }
132 }
133
134 function createMissingRels(){
135         $relForObjects = array('leads'=>'Leads','campaigns'=>'Campaigns','prospects'=>'Prospects');
136         foreach($relForObjects as $relObjName=>$relModName){
137                 //assigned_user
138                 $guid = create_guid();
139                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_assigned_user'";
140                 $result= $GLOBALS['db']->query($query, true);
141                 $a = null;
142                 $a = $GLOBALS['db']->fetchByAssoc($result);
143                 if(!isset($a['id']) && empty($a['id']) ){
144                         $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)
145                                                 VALUES ('{$guid}', '{$relObjName}_assigned_user','Users','users','id','{$relModName}','{$relObjName}','assigned_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
146                         $GLOBALS['db']->query($qRel);
147                 }
148                 //modified_user
149                 $guid = create_guid();
150                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_modified_user'";
151                 $result= $GLOBALS['db']->query($query, true);
152                 $a = null;
153                 $a = $GLOBALS['db']->fetchByAssoc($result);
154                 if(!isset($a['id']) && empty($a['id']) ){
155                         $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)
156                                                 VALUES ('{$guid}', '{$relObjName}_modified_user','Users','users','id','{$relModName}','{$relObjName}','modified_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
157                         $GLOBALS['db']->query($qRel);
158                 }
159                 //created_by
160                 $guid = create_guid();
161                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
162                 $result= $GLOBALS['db']->query($query, true);
163                 $a = null;
164                 $a = $GLOBALS['db']->fetchByAssoc($result);
165         if(!isset($a['id']) && empty($a['id']) ){
166                         $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)
167                                                 VALUES ('{$guid}', '{$relObjName}_created_by','Users','users','id','{$relModName}','{$relObjName}','created_by',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
168                         $GLOBALS['db']->query($qRel);
169         }
170         }
171         //Also add tracker perf relationship
172 }
173
174
175 /**
176  * This function will merge password default settings into config file
177  * @param   $sugar_config
178  * @param   $sugar_version
179  * @return  bool true if successful
180  */
181 function merge_passwordsetting($sugar_config, $sugar_version) {
182     $passwordsetting_defaults = array(
183     'passwordsetting' => array (
184         'SystemGeneratedPasswordON' => '',
185         'generatepasswordtmpl' => '',
186         'lostpasswordtmpl' => '',
187         'forgotpasswordON' => false,
188         'linkexpiration' => '1',
189         'linkexpirationtime' => '30',
190         'linkexpirationtype' => '1',
191         'systexpiration' => '0',
192         'systexpirationtime' => '',
193         'systexpirationtype' => '0',
194         'systexpirationlogin' => '',
195         ) ,
196     );
197
198
199     $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
200
201     // need to override version with default no matter what
202     $sugar_config['sugar_version'] = $sugar_version;
203
204     ksort( $sugar_config );
205
206     if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
207         return true;
208     }
209     else {
210         return false;
211     }
212 }
213
214 function addDefaultModuleRoles($defaultRoles = array()) {
215         foreach($defaultRoles as $roleName=>$role){
216         foreach($role as $category=>$actions){
217             foreach($actions as $name=>$access_override){
218                     $query = "SELECT * FROM acl_actions WHERE name='$name' AND category = '$category' AND acltype='$roleName' AND deleted=0 ";
219                                         $result = $GLOBALS['db']->query($query);
220                                         //only add if an action with that name and category don't exist
221                                         $row=$GLOBALS['db']->fetchByAssoc($result);
222                                         if ($row == null) {
223                                 $guid = create_guid();
224                                 $currdate = gmdate('Y-m-d H:i:s');
225                                 $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')";
226                                                 $GLOBALS['db']->query($query);
227                         }
228             }
229         }
230         }
231 }
232
233 function verifyArguments($argv,$usage_dce,$usage_regular){
234     $upgradeType = '';
235     $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
236     if(isset($argv[3])) {
237         if(is_dir($argv[3])) {
238             $cwd = $argv[3];
239             chdir($cwd);
240         } else {
241             echo "*******************************************************************************\n";
242             echo "*** ERROR: 3rd parameter must be a valid directory.  Tried to cd to [ {$argv[3]} ].\n";
243             exit(1);
244         }
245     }
246
247     //check if this is an instance
248     if(is_file("{$cwd}/ini_setup.php")){
249         // this is an instance
250         $upgradeType = constant('DCE_INSTANCE');
251         //now that this is dce instance we want to make sure that there are
252         // 7 arguments
253         if(count($argv) < 7) {
254             echo "*******************************************************************************\n";
255             echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 7.\n";
256             echo $usage_dce;
257             echo "FAILURE\n";
258             exit(1);
259         }
260         // this is an instance
261         if(!is_dir($argv[1])) { // valid directory . template path?
262             echo "*******************************************************************************\n";
263             echo "*** ERROR: First argument must be a full path to the template. Got [ {$argv[1]} ].\n";
264             echo $usage_dce;
265             echo "FAILURE\n";
266             exit(1);
267         }
268     }
269     else if(is_file("{$cwd}/include/entryPoint.php")) {
270         //this should be a regular sugar install
271         $upgradeType = constant('SUGARCRM_INSTALL');
272         //check if this is a valid zip file
273         if(!is_file($argv[1])) { // valid zip?
274             echo "*******************************************************************************\n";
275             echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
276             echo $usage_regular;
277             echo "FAILURE\n";
278             exit(1);
279         }
280         if(count($argv) < 5) {
281             echo "*******************************************************************************\n";
282             echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 5.\n";
283             echo $usage_regular;
284             echo "FAILURE\n";
285             exit(1);
286         }
287     }
288     else {
289         //this should be a regular sugar install
290         echo "*******************************************************************************\n";
291         echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
292         exit(1);
293     }
294
295     if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
296         require_once($argv[7].'SugarTemplateUtilties.php');
297     }
298
299     return $upgradeType;
300 }
301
302 function upgradeDCEFiles($argv,$instanceUpgradePath){
303         //copy and update following files from upgrade package
304         $upgradeTheseFiles = array('cron.php','download.php','index.php','install.php','soap.php','sugar_version.php','vcal_server.php');
305         foreach($upgradeTheseFiles as $file){
306                 $srcFile = clean_path("{$instanceUpgradePath}/$file");
307                 $destFile = clean_path("{$argv[3]}/$file");
308                 if(file_exists($srcFile)){
309                         if(!is_dir(dirname($destFile))) {
310                                 mkdir_recursive(dirname($destFile)); // make sure the directory exists
311                         }
312                         copy_recursive($srcFile,$destFile);
313                         $_GET['TEMPLATE_PATH'] = $destFile;
314                         $_GET['CONVERT_FILE_ONLY'] = true;
315                         if(!class_exists('TemplateConverter')){
316                                 include($argv[7].'templateConverter.php');
317                         }else{
318                                 TemplateConverter::convertFile($_GET['TEMPLATE_PATH']);
319                         }
320
321
322                 }
323         }
324 }
325
326
327
328 function threeWayMerge(){
329         //using threeway merge apis
330 }
331 ////    END UTILITIES THAT MUST BE LOCAL :(
332 ///////////////////////////////////////////////////////////////////////////////
333
334 //Bug 52872. Dies if the request does not come from CLI.
335 $sapi_type = php_sapi_name();
336 if (substr($sapi_type, 0, 3) != 'cli') {
337     die("This is command-line only script");
338 }
339 //End of #52872
340
341 // only run from command line
342 if(isset($_SERVER['HTTP_USER_AGENT'])) {
343         fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
344         exit(1);
345 }
346 //Clean_string cleans out any file  passed in as a parameter
347 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
348
349
350 ///////////////////////////////////////////////////////////////////////////////
351 ////    USAGE
352 $usage_dce =<<<eoq1
353 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
354
355 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
356 php.exe followed by -f silentUpgrade.php and the arguments.
357
358 Example:
359     [path-to-PHP/]php.exe -f silentUpgrade.php [path-to-upgrade-package/]SugarEnt-Upgrade-4.5.1-to-5.0.0b.zip [path-to-log-file/]silentupgrade.log  [path-to-sugar-instance/]Sugar451e
360                              [Old Template path] [skipdbupgrade] [exitOrContinue]
361
362 Arguments:
363     New Template Path or Upgrade Package : Upgrade package name. Template2 (upgrade to)location.
364     silentupgrade.log                    : Silent Upgarde log file.
365     Sugar451e/DCE                        : Sugar or DCE Instance instance being upgraded.
366     Old Template path                    : Template1 (upgrade from) Instance is being upgraded.
367     skipDBupgrade                        : If set to Yes then silentupgrade will only upgrade files. Default is No.
368     exitOnConflicts                      : If set to No and conflicts are found then Upgrade continues. Default Yes.
369     pathToDCEClient                      : This is path to to DCEClient directory
370
371 eoq1;
372
373 $usage_regular =<<<eoq2
374 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
375
376 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
377 php.exe followed by -f silentUpgrade.php and the arguments.
378
379 Example:
380     [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
381
382 Arguments:
383     upgradeZipFile                       : Upgrade package file.
384     logFile                              : Silent Upgarde log file.
385     pathToSugarInstance                  : Sugar Instance instance being upgraded.
386     admin-user                           : admin user performing the upgrade
387 eoq2;
388 ////    END USAGE
389 ///////////////////////////////////////////////////////////////////////////////
390
391
392
393 ///////////////////////////////////////////////////////////////////////////////
394 ////    STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
395 if(!defined('sugarEntry')) define('sugarEntry', true);
396
397 $_SESSION = array();
398 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
399 $_SESSION['silent_upgrade'] = true;
400 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
401
402 $_REQUEST = array();
403 $_REQUEST['addTaskReminder'] = 'remind';
404
405
406 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
407 define('DCE_INSTANCE', 'DCE_Instance');
408
409 global $cwd;
410 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
411
412 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
413
414 ///////////////////////////////////////////////////////////////////////////////
415 //////  Verify that all the arguments are appropriately placed////////////////
416
417 ///////////////////////////////////////////////////////////////////////////////
418 ////    PREP LOCALLY USED PASSED-IN VARS & CONSTANTS
419 //$GLOBALS['log']       = LoggerManager::getLogger('SugarCRM');
420 //require_once('/var/www/html/eddy/sugarnode/SugarTemplateUtilities.php');
421
422 $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
423 //$db                           = &DBManagerFactory::getInstance();  //<---------
424
425
426 //$UWstrings            = return_module_language('en_us', 'UpgradeWizard');
427 //$adminStrings = return_module_language('en_us', 'Administration');
428 //$mod_strings  = array_merge($adminStrings, $UWstrings);
429 $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
430
431 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
432
433 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
434 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
435 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
436 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
437
438
439
440 echo "\n";
441 echo "********************************************************************\n";
442 echo "***************This Upgrade process may take sometime***************\n";
443 echo "********************************************************************\n";
444 echo "\n";
445
446 global $sugar_config;
447 $isDCEInstance = false;
448 $errors = array();
449
450
451 if($upgradeType == constant('DCE_INSTANCE')){
452         //$instanceUpgradePath = "{$argv[1]}/DCEUpgrade/{$zip_from_dir}";
453         //$instanceUpgradePath = "{$argv[1]}";
454         include ("ini_setup.php");
455
456         //get new template path for use in later processing
457     $dceupgrade_pos = strpos($argv[1], '/DCEUpgrade');
458     $newtemplate_path = substr($argv[1], 0, $dceupgrade_pos);
459
460         require("{$argv[4]}/sugar_version.php");
461         global $sugar_version;
462
463         /*
464         //require classes if they do not exist, as these were not in pre 550 entrypoint.php and need to be loaded first
465     if(!class_exists('VardefManager')){
466         require_once("{$newtemplate_path}/include/SugarObjects/VardefManager.php");
467     }
468     if (!class_exists('Sugar_Smarty')){
469         require_once("{$newtemplate_path}/include/Sugar_Smarty.php");
470     }
471     if (!class_exists('LanguageManager')){
472                 require_once("{$newtemplate_path}/include/SugarObjects/LanguageManager.php");
473         }
474     */
475
476         //load up entrypoint from original template
477         require_once("{$argv[4]}/include/entryPoint.php");
478
479         require_once("{$newtemplate_path}/include/utils/zip_utils.php");
480         require_once("{$newtemplate_path}/modules/Administration/UpgradeHistory.php");
481
482         // We need to run the silent upgrade as the admin user
483         require_once("{$newtemplate_path}/modules/Users/User.php");
484         global $current_user;
485         $current_user = new User();
486         $current_user->retrieve('1');
487
488
489         //This is DCE instance
490       global $sugar_config;
491       global $sugar_version;
492 //    require_once("{$cwd}/sugar_version.php"); //provides instance version, flavor etc..
493      //provides instance version, flavor etc..
494     $isDCEInstance = true;
495     $configOptions = $sugar_config['dbconfig'];
496
497         $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
498         $db                             = &DBManagerFactory::getInstance();
499                 ///////////////////////////////////////////////////////////////////////////////
500         ////    MAKE SURE PATCH IS COMPATIBLE
501
502         if(is_file("{$argv[1]}/manifest.php")) {
503                 // provides $manifest array
504                 include("{$argv[1]}/manifest.php");
505         }
506         //If Instance then the files will be accessed from Template/DCEUpgrade folder
507         $zip_from_dir = '';
508     if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
509             $zip_from_dir   = $manifest['copy_files']['from_dir'];
510         }
511
512         $instanceUpgradePath = "{$argv[1]}/{$zip_from_dir}";
513         $_SESSION['sugar_version_file'] = '';
514         $srcFile = clean_path("{$instanceUpgradePath}/sugar_version.php");
515         if(file_exists($srcFile)) {
516            $_SESSION['sugar_version_file'] = $srcFile;
517         }
518
519
520         global $instancePath;
521         $instancePath = $instanceUpgradePath;
522         $_SESSION['instancePath'] = $instancePath;
523         if(file_exists("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php")){
524                 require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
525         } else{
526                 require_once("{$newtemplate_path}/modules/UpgradeWizard/uw_utils.php");
527         }
528
529     $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');
530         $_SESSION['upgrade_from_flavor'] = $manifest['name'];
531
532     //check for db upgrade
533     //check exit on conflicts
534     $skipDBUpgrade = 'no'; //default
535     if($argv[6] != null && !empty($argv[6])){
536         if(strtolower($argv[6]) == 'yes'){
537           $skipDBUpgrade = 'yes'; //override
538         }
539     }
540     global $unzip_dir;
541     $unzip_dir = $argv[1];
542     $_SESSION['unzip_dir'] = $unzip_dir;
543     global $path;
544     $path = $argv[2];
545
546     if($skipDBUpgrade == 'no'){
547         //upgrade the db
548             ///////////////////////////////////////////////////////////////////////////////
549                 ////    HANDLE PREINSTALL SCRIPTS
550                 $file = "{$argv[1]}/".constant('SUGARCRM_PRE_INSTALL_FILE');
551                 if(is_file($file)) {
552                         include($file);
553                         logThis('Running pre_install()...', $path);
554                         pre_install();
555                         logThis('pre_install() done.', $path);
556                 }
557
558
559         //run the 3-way merge
560         if(file_exists($newtemplate_path.'/modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
561             logThis('Running 3 way merge()...', $path);
562             require_once($newtemplate_path.'/modules/UpgradeWizard/SugarMerge/SugarMerge.php');
563             $merger = new SugarMerge($instanceUpgradePath, $argv[4].'/', $argv[3].'/custom');
564             $merger->mergeAll();
565             logThis('Finished 3 way merge()...', $path);
566         }
567
568                 logThis('Starting post_install()...', $path);
569                 $file = "{$argv[1]}/".constant('SUGARCRM_POST_INSTALL_FILE');
570                 if(is_file($file)) {
571                     include($file);
572                         post_install();
573                 }
574                 logThis('post_install() done.', $path);
575
576         ///////////////////////////////////////////////////////////////////////////////
577                 //clean vardefs
578                 logThis('Performing UWrebuild()...', $path);
579                         UWrebuild();
580                 logThis('UWrebuild() done.', $path);
581
582                 logThis('begin check default permissions .', $path);
583                 checkConfigForPermissions();
584             logThis('end check default permissions .', $path);
585
586         logThis('begin check logger settings .', $path);
587             checkLoggerSettings();
588         logThis('end check logger settings .', $path);
589
590         logThis('Set default_max_tabs to 7', $path);
591         $sugar_config['default_max_tabs'] = '7';
592
593         if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
594             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
595             $errors[] = 'Could not write config.php!';
596         }
597
598         //check to see if there are any new files that need to be added to systems tab
599         //retrieve old modules list
600         logThis('check to see if new modules exist',$path);
601         $oldModuleList = array();
602         $newModuleList = array();
603         include($argv[4].'/include/modules.php');
604         $oldModuleList = $moduleList;
605         include($newtemplate_path.'/include/modules.php');
606         $newModuleList = $moduleList;
607
608                 ///    RELOAD NEW DEFINITIONS
609                 global $ACLActions, $beanList, $beanFiles;
610                 include($newtemplate_path.'/modules/ACLActions/actiondefs.php');
611
612                 //First repair the databse to ensure it is up to date with the new vardefs/tabledefs
613                 logThis('About to repair the database.', $path);
614                 //Use Repair and rebuild to update the database.
615                 global $dictionary;
616                 require_once($newtemplate_path.'/modules/Administration/QuickRepairAndRebuild.php');
617                 $rac = new RepairAndClear();
618                 $rac->clearVardefs();
619                 $rac->rebuildExtensions();
620
621                 $repairedTables = array();
622
623                 //Force vardefs to be reloaded
624                 $GLOBALS['reload_vardefs'] = true;
625
626                 foreach ($beanFiles as $bean => $file) {
627                         if(file_exists($newtemplate_path . '/' . $file) && $bean != 'UpgradeHistory'){
628                                 unset($GLOBALS['dictionary'][$bean]);
629                                 require_once($newtemplate_path . '/' . $file);
630
631                                 $focus = new $bean ();
632                                 if(empty($focus->table_name) || isset($repairedTables[$focus->table_name])) {
633                                    continue;
634                                 }
635
636                                 if (($focus instanceOf SugarBean)) {
637                                         $sql = $db->repairTable($focus, true);
638                                         if(!empty($sql)) {
639                                            logThis($sql, $path);
640                                            $repairedTables[$focus->table_name] = true;
641                                         }
642                                 }
643                         }
644                 }
645
646                 unset ($dictionary);
647                 include ($newtemplate_path.'/modules/TableDictionary.php');
648                 foreach ($dictionary as $meta) {
649                         $tablename = $meta['table'];
650
651                         if(isset($repairedTables[$tablename])) {
652                            continue;
653                         }
654
655                         $fielddefs = $meta['fields'];
656                         $indices = $meta['indices'];
657                         $sql = $GLOBALS['db']->repairTableParams($tablename, $fielddefs, $indices, true);
658                         if(!empty($sql)) {
659                             logThis($sql, $path);
660                             $repairedTables[$tablename] = true;
661                         }
662
663                 }
664                 logThis('database repaired', $path);
665
666         //include tab controller
667         require_once($newtemplate_path.'/modules/MySettings/TabController.php');
668         $newTB = new TabController();
669
670         //make sure new modules list has a key we can reference directly
671         $newModuleList = $newTB->get_key_array($newModuleList);
672         $oldModuleList = $newTB->get_key_array($oldModuleList);
673
674         //iterate through list and remove commonalities to get new modules
675         foreach ($newModuleList as $remove_mod){
676             if(in_array($remove_mod, $oldModuleList)){
677                 unset($newModuleList[$remove_mod]);
678             }
679         }
680         //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
681         logThis('new modules to add are '.var_export($newModuleList,true),$path);
682
683         //grab the existing system tabs
684         $tabs = $newTB->get_system_tabs();
685
686         //add the new tabs to the array
687         foreach($newModuleList as $nm ){
688           $tabs[$nm] = $nm;
689         }
690
691         //now assign the modules to system tabs
692         $newTB->set_system_tabs($tabs);
693         logThis('module tabs updated',$path);
694
695
696
697             if($ce_to_pro_ent){
698                 //add the global team if it does not exist
699                         $globalteam = new Team();
700                         $globalteam->retrieve('1');
701                         include($newtemplate_path.'/modules/Administration/language/en_us.lang.php');
702                         if(isset($globalteam->name)){
703
704                            echo 'Global '.$mod_strings['LBL_UPGRADE_TEAM_EXISTS'].'<br>';
705                            logThis(" Finish Building private teams", $path);
706
707                         }else{
708                            $globalteam->create_team("Global", $mod_strings['LBL_GLOBAL_TEAM_DESC'], $globalteam->global_team);
709                         }
710
711                 //build private teams
712                     logThis(" Start Building private teams", $path);
713                     upgradeModulesForTeam();
714                     logThis(" Finish Building private teams", $path);
715
716                         //build team sets
717                     logThis(" Start Building the team_set and team_sets_teams", $path);
718                     upgradeModulesForTeamsets();
719                     logThis(" Finish Building the team_set and team_sets_teams", $path);
720
721                     //upgrade teams
722                         if(file_exists($newtemplate_path.'/modules/Administration/upgradeTeams.php')) {
723                                 logThis(" Start {$newtemplate_path}/modules/Administration/upgradeTeams.php", $path);
724                                 include($newtemplate_path.'/modules/Administration/upgradeTeams.php');
725                                 logThis(" Finish {$newtemplate_path}/modules/Administration/upgradeTeams.php", $path);
726
727                                 //update the users records to have default team
728                                 logThis('running query to populate default_team on users table',$path);
729                                 $GLOBALS['db']->query("update users set default_team = (select teams.id from teams where teams.name = concat('(',users.user_name, ')') or team.associated_user_id = users.id)");
730
731                         }
732
733                         //run upgrade script for dashlets to include sales/marketing
734                         if(function_exists('upgradeDashletsForSalesAndMarketing')){
735                    logThis('calling upgradeDashlets script',$path);
736                            upgradeDashletsForSalesAndMarketing();
737                         }
738
739             }
740
741                 require("sugar_version.php");
742                 require('config.php');
743                 global $sugar_config;
744
745                 require("{$instanceUpgradePath}/sugar_version.php");
746                 if(!rebuildConfigFile($sugar_config, $sugar_version)) {
747                         logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
748                         $errors[] = 'Could not write config.php!';
749                 }
750                 checkConfigForPermissions();
751
752         // clear out the theme cache
753                 if(!class_exists('SugarThemeRegistry')){
754                     require_once($newtemplate_path . '/include/SugarTheme/SugarTheme.php');
755                 }
756                 SugarThemeRegistry::buildRegistry();
757                 SugarThemeRegistry::clearAllCaches();
758
759                 // re-minify the JS source files
760                 $_REQUEST['root_directory'] = getcwd();
761                 $_REQUEST['js_rebuild_concat'] = 'rebuild';
762                 require_once($newtemplate_path . '/jssource/minify.php');
763
764                 //as last step, rebuild the language files and rebuild relationships
765                 /*
766                 if(file_exists($newtemplate_path.'/modules/Administration/RebuildJSLang.php')) {
767                         logThis("begin rebuilding js language files. via ".$newtemplate_path.'/modules/Administration/RebuildJSLang.php', $path);
768                         include($newtemplate_path.'/modules/Administration/RebuildJSLang.php');
769                         rebuildRelations($newtemplate_path.'/');
770                 }
771                 */
772
773     }
774
775 } //END OF BIG if block
776
777
778 //Also set the tracker settings if  flavor conversion ce->pro or ce->ent
779 if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
780         if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){
781             $_REQUEST['upgradeWizard'] = true;
782             ob_start();
783                 include('include/Smarty/internals/core.write_file.php');
784                 ob_end_clean();
785                 $db =& DBManagerFactory::getInstance();
786                 if($ce_to_pro_ent){
787                 //Also set license information
788                 $admin = new Administration();
789                         $category = 'license';
790                         $value = 0;
791                         $admin->saveSetting($category, 'users', $value);
792                         $key = array('num_lic_oc','key','expire_date');
793                         $value = '';
794                         foreach($key as $k){
795                                 $admin->saveSetting($category, $k, $value);
796                         }
797                 }
798         }
799 }
800
801 set_upgrade_progress('end','done','end','done');
802
803 if(file_exists($newtemplate_path . '/modules/Configurator/Configurator.php')){
804         set_upgrade_progress('configurator','in_progress');
805         require_once($newtemplate_path . '/include/utils/array_utils.php');
806         if(!class_exists('Configurator')){
807                 require_once($newtemplate_path . '/modules/Configurator/Configurator.php');
808         }
809         $Configurator = new Configurator();
810         if(class_exists('Configurator')){
811                 $Configurator->parseLoggerSettings();
812         }
813         set_upgrade_progress('configurator','done');
814 }
815
816 //unset the logger previously instantiated
817 if(file_exists($newtemplate_path . '/include/SugarLogger/LoggerManager.php')){
818         set_upgrade_progress('logger','in_progress');
819         if(!class_exists('LoggerManager')){
820
821         }
822         if(class_exists('LoggerManager')){
823                 unset($GLOBALS['log']);
824                 $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
825         }
826         set_upgrade_progress('logger','done');
827 }
828
829 ///////////////////////////////////////////////////////////////////////////////
830 ////    RECORD ERRORS
831 $phpErrors = ob_get_contents();
832 ob_end_clean();
833
834 if(count($errors) > 0) {
835         foreach($errors as $error) {
836                 logThis("****** SilentUpgrade ERROR: {$error}", $path);
837         }
838         echo "FAILED\n";
839 } else {
840         logThis("***** SilentUpgrade completed successfully.", $path);
841         echo "********************************************************************\n";
842         echo "*************************** SUCCESS*********************************\n";
843         echo "********************************************************************\n";
844         echo "******** If your pre-upgrade Leads data is not showing  ************\n";
845         echo "******** Or you see errors in detailview subpanels  ****************\n";
846         echo "************* In order to resolve them  ****************************\n";
847         echo "******** Log into application as Administrator  ********************\n";
848         echo "******** Go to Admin panel  ****************************************\n";
849         echo "******** Run Repair -> Rebuild Relationships  **********************\n";
850         echo "********************************************************************\n";
851 }
852
853
854 ?>