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