]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UpgradeWizard/silentUpgrade_dce_step2.php
Release 6.4.0
[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-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(!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
335 // only run from command line
336 if(isset($_SERVER['HTTP_USER_AGENT'])) {
337         fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
338         exit(1);
339 }
340 //Clean_string cleans out any file  passed in as a parameter
341 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
342
343
344 ///////////////////////////////////////////////////////////////////////////////
345 ////    USAGE
346 $usage_dce =<<<eoq1
347 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
348
349 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
350 php.exe followed by -f silentUpgrade.php and the arguments.
351
352 Example:
353     [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
354                              [Old Template path] [skipdbupgrade] [exitOrContinue]
355
356 Arguments:
357     New Template Path or Upgrade Package : Upgrade package name. Template2 (upgrade to)location.
358     silentupgrade.log                    : Silent Upgarde log file.
359     Sugar451e/DCE                        : Sugar or DCE Instance instance being upgraded.
360     Old Template path                    : Template1 (upgrade from) Instance is being upgraded.
361     skipDBupgrade                        : If set to Yes then silentupgrade will only upgrade files. Default is No.
362     exitOnConflicts                      : If set to No and conflicts are found then Upgrade continues. Default Yes.
363     pathToDCEClient                      : This is path to to DCEClient directory
364
365 eoq1;
366
367 $usage_regular =<<<eoq2
368 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
369
370 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
371 php.exe followed by -f silentUpgrade.php and the arguments.
372
373 Example:
374     [path-to-PHP/]php.exe -f silentUpgrade.php [path-to-upgrade-package/]SugarEnt-Upgrade-5.2.0-to-5.5.0.zip [path-to-log-file/]silentupgrade.log  [path-to-sugar-instance/] admin
375
376 Arguments:
377     upgradeZipFile                       : Upgrade package file.
378     logFile                              : Silent Upgarde log file.
379     pathToSugarInstance                  : Sugar Instance instance being upgraded.
380     admin-user                           : admin user performing the upgrade
381 eoq2;
382 ////    END USAGE
383 ///////////////////////////////////////////////////////////////////////////////
384
385
386
387 ///////////////////////////////////////////////////////////////////////////////
388 ////    STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
389 if(!defined('sugarEntry')) define('sugarEntry', true);
390
391 $_SESSION = array();
392 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
393 $_SESSION['silent_upgrade'] = true;
394 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
395
396 $_REQUEST = array();
397 $_REQUEST['addTaskReminder'] = 'remind';
398
399
400 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
401 define('DCE_INSTANCE', 'DCE_Instance');
402
403 global $cwd;
404 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
405
406 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
407
408 ///////////////////////////////////////////////////////////////////////////////
409 //////  Verify that all the arguments are appropriately placed////////////////
410
411 ///////////////////////////////////////////////////////////////////////////////
412 ////    PREP LOCALLY USED PASSED-IN VARS & CONSTANTS
413 //$GLOBALS['log']       = LoggerManager::getLogger('SugarCRM');
414 //require_once('/var/www/html/eddy/sugarnode/SugarTemplateUtilities.php');
415
416 $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
417 //$db                           = &DBManagerFactory::getInstance();  //<---------
418
419
420 //$UWstrings            = return_module_language('en_us', 'UpgradeWizard');
421 //$adminStrings = return_module_language('en_us', 'Administration');
422 //$mod_strings  = array_merge($adminStrings, $UWstrings);
423 $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
424
425 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
426
427 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
428 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
429 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
430 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
431
432
433
434 echo "\n";
435 echo "********************************************************************\n";
436 echo "***************This Upgrade process may take sometime***************\n";
437 echo "********************************************************************\n";
438 echo "\n";
439
440 global $sugar_config;
441 $isDCEInstance = false;
442 $errors = array();
443
444
445 if($upgradeType == constant('DCE_INSTANCE')){
446         //$instanceUpgradePath = "{$argv[1]}/DCEUpgrade/{$zip_from_dir}";
447         //$instanceUpgradePath = "{$argv[1]}";
448         include ("ini_setup.php");
449
450         //get new template path for use in later processing
451     $dceupgrade_pos = strpos($argv[1], '/DCEUpgrade');
452     $newtemplate_path = substr($argv[1], 0, $dceupgrade_pos);
453
454         require("{$argv[4]}/sugar_version.php");
455         global $sugar_version;
456
457         /*
458         //require classes if they do not exist, as these were not in pre 550 entrypoint.php and need to be loaded first
459     if(!class_exists('VardefManager')){
460         require_once("{$newtemplate_path}/include/SugarObjects/VardefManager.php");
461     }
462     if (!class_exists('Sugar_Smarty')){
463         require_once("{$newtemplate_path}/include/Sugar_Smarty.php");
464     }
465     if (!class_exists('LanguageManager')){
466                 require_once("{$newtemplate_path}/include/SugarObjects/LanguageManager.php");
467         }
468     */
469
470         //load up entrypoint from original template
471         require_once("{$argv[4]}/include/entryPoint.php");
472
473         require_once("{$newtemplate_path}/include/utils/zip_utils.php");
474         require_once("{$newtemplate_path}/modules/Administration/UpgradeHistory.php");
475
476         // We need to run the silent upgrade as the admin user
477         require_once("{$newtemplate_path}/modules/Users/User.php");
478         global $current_user;
479         $current_user = new User();
480         $current_user->retrieve('1');
481
482
483         //This is DCE instance
484       global $sugar_config;
485       global $sugar_version;
486 //    require_once("{$cwd}/sugar_version.php"); //provides instance version, flavor etc..
487      //provides instance version, flavor etc..
488     $isDCEInstance = true;
489     $configOptions = $sugar_config['dbconfig'];
490
491         $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
492         $db                             = &DBManagerFactory::getInstance();
493                 ///////////////////////////////////////////////////////////////////////////////
494         ////    MAKE SURE PATCH IS COMPATIBLE
495
496         if(is_file("{$argv[1]}/manifest.php")) {
497                 // provides $manifest array
498                 include("{$argv[1]}/manifest.php");
499         }
500         //If Instance then the files will be accessed from Template/DCEUpgrade folder
501         $zip_from_dir = '';
502     if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
503             $zip_from_dir   = $manifest['copy_files']['from_dir'];
504         }
505
506         $instanceUpgradePath = "{$argv[1]}/{$zip_from_dir}";
507         $_SESSION['sugar_version_file'] = '';
508         $srcFile = clean_path("{$instanceUpgradePath}/sugar_version.php");
509         if(file_exists($srcFile)) {
510            $_SESSION['sugar_version_file'] = $srcFile;
511         }
512
513
514         global $instancePath;
515         $instancePath = $instanceUpgradePath;
516         $_SESSION['instancePath'] = $instancePath;
517         if(file_exists("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php")){
518                 require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
519         } else{
520                 require_once("{$newtemplate_path}/modules/UpgradeWizard/uw_utils.php");
521         }
522
523     $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');
524         $_SESSION['upgrade_from_flavor'] = $manifest['name'];
525
526     //check for db upgrade
527     //check exit on conflicts
528     $skipDBUpgrade = 'no'; //default
529     if($argv[6] != null && !empty($argv[6])){
530         if(strtolower($argv[6]) == 'yes'){
531           $skipDBUpgrade = 'yes'; //override
532         }
533     }
534     global $unzip_dir;
535     $unzip_dir = $argv[1];
536     $_SESSION['unzip_dir'] = $unzip_dir;
537     global $path;
538     $path = $argv[2];
539
540     if($skipDBUpgrade == 'no'){
541         //upgrade the db
542             ///////////////////////////////////////////////////////////////////////////////
543                 ////    HANDLE PREINSTALL SCRIPTS
544                 $file = "{$argv[1]}/".constant('SUGARCRM_PRE_INSTALL_FILE');
545                 if(is_file($file)) {
546                         include($file);
547                         logThis('Running pre_install()...', $path);
548                         pre_install();
549                         logThis('pre_install() done.', $path);
550                 }
551
552
553         //run the 3-way merge
554         if(file_exists($newtemplate_path.'/modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
555             logThis('Running 3 way merge()...', $path);
556             require_once($newtemplate_path.'/modules/UpgradeWizard/SugarMerge/SugarMerge.php');
557             $merger = new SugarMerge($instanceUpgradePath, $argv[4].'/', $argv[3].'/custom');
558             $merger->mergeAll();
559             logThis('Finished 3 way merge()...', $path);
560         }
561
562                 logThis('Starting post_install()...', $path);
563                 $file = "{$argv[1]}/".constant('SUGARCRM_POST_INSTALL_FILE');
564                 if(is_file($file)) {
565                     include($file);
566                         post_install();
567                 }
568                 logThis('post_install() done.', $path);
569
570         ///////////////////////////////////////////////////////////////////////////////
571                 //clean vardefs
572                 logThis('Performing UWrebuild()...', $path);
573                         UWrebuild();
574                 logThis('UWrebuild() done.', $path);
575
576                 logThis('begin check default permissions .', $path);
577                 checkConfigForPermissions();
578             logThis('end check default permissions .', $path);
579
580         logThis('begin check logger settings .', $path);
581             checkLoggerSettings();
582         logThis('end check logger settings .', $path);
583
584         logThis('Set default_max_tabs to 7', $path);
585         $sugar_config['default_max_tabs'] = '7';
586
587         if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
588             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
589             $errors[] = 'Could not write config.php!';
590         }
591
592         //check to see if there are any new files that need to be added to systems tab
593         //retrieve old modules list
594         logThis('check to see if new modules exist',$path);
595         $oldModuleList = array();
596         $newModuleList = array();
597         include($argv[4].'/include/modules.php');
598         $oldModuleList = $moduleList;
599         include($newtemplate_path.'/include/modules.php');
600         $newModuleList = $moduleList;
601
602                 ///    RELOAD NEW DEFINITIONS
603                 global $ACLActions, $beanList, $beanFiles;
604                 include($newtemplate_path.'/modules/ACLActions/actiondefs.php');
605
606                 //First repair the databse to ensure it is up to date with the new vardefs/tabledefs
607                 logThis('About to repair the database.', $path);
608                 //Use Repair and rebuild to update the database.
609                 global $dictionary;
610                 require_once($newtemplate_path.'/modules/Administration/QuickRepairAndRebuild.php');
611                 $rac = new RepairAndClear();
612                 $rac->clearVardefs();
613                 $rac->rebuildExtensions();
614
615                 $repairedTables = array();
616
617                 //Force vardefs to be reloaded
618                 $GLOBALS['reload_vardefs'] = true;
619
620                 foreach ($beanFiles as $bean => $file) {
621                         if(file_exists($newtemplate_path . '/' . $file) && $bean != 'UpgradeHistory'){
622                                 unset($GLOBALS['dictionary'][$bean]);
623                                 require_once($newtemplate_path . '/' . $file);
624
625                                 $focus = new $bean ();
626                                 if(empty($focus->table_name) || isset($repairedTables[$focus->table_name])) {
627                                    continue;
628                                 }
629
630                                 if (($focus instanceOf SugarBean)) {
631                                         $sql = $db->repairTable($focus, true);
632                                         if(!empty($sql)) {
633                                            logThis($sql, $path);
634                                            $repairedTables[$focus->table_name] = true;
635                                         }
636                                 }
637                         }
638                 }
639
640                 unset ($dictionary);
641                 include ($newtemplate_path.'/modules/TableDictionary.php');
642                 foreach ($dictionary as $meta) {
643                         $tablename = $meta['table'];
644
645                         if(isset($repairedTables[$tablename])) {
646                            continue;
647                         }
648
649                         $fielddefs = $meta['fields'];
650                         $indices = $meta['indices'];
651                         $sql = $GLOBALS['db']->repairTableParams($tablename, $fielddefs, $indices, true);
652                         if(!empty($sql)) {
653                             logThis($sql, $path);
654                             $repairedTables[$tablename] = true;
655                         }
656
657                 }
658                 logThis('database repaired', $path);
659
660         //include tab controller
661         require_once($newtemplate_path.'/modules/MySettings/TabController.php');
662         $newTB = new TabController();
663
664         //make sure new modules list has a key we can reference directly
665         $newModuleList = $newTB->get_key_array($newModuleList);
666         $oldModuleList = $newTB->get_key_array($oldModuleList);
667
668         //iterate through list and remove commonalities to get new modules
669         foreach ($newModuleList as $remove_mod){
670             if(in_array($remove_mod, $oldModuleList)){
671                 unset($newModuleList[$remove_mod]);
672             }
673         }
674         //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
675         logThis('new modules to add are '.var_export($newModuleList,true),$path);
676
677         //grab the existing system tabs
678         $tabs = $newTB->get_system_tabs();
679
680         //add the new tabs to the array
681         foreach($newModuleList as $nm ){
682           $tabs[$nm] = $nm;
683         }
684
685         //now assign the modules to system tabs
686         $newTB->set_system_tabs($tabs);
687         logThis('module tabs updated',$path);
688
689
690
691             if($ce_to_pro_ent){
692                 //add the global team if it does not exist
693                         $globalteam = new Team();
694                         $globalteam->retrieve('1');
695                         include($newtemplate_path.'/modules/Administration/language/en_us.lang.php');
696                         if(isset($globalteam->name)){
697
698                            echo 'Global '.$mod_strings['LBL_UPGRADE_TEAM_EXISTS'].'<br>';
699                            logThis(" Finish Building private teams", $path);
700
701                         }else{
702                            $globalteam->create_team("Global", $mod_strings['LBL_GLOBAL_TEAM_DESC'], $globalteam->global_team);
703                         }
704
705                 //build private teams
706                     logThis(" Start Building private teams", $path);
707                     upgradeModulesForTeam();
708                     logThis(" Finish Building private teams", $path);
709
710                         //build team sets
711                     logThis(" Start Building the team_set and team_sets_teams", $path);
712                     upgradeModulesForTeamsets();
713                     logThis(" Finish Building the team_set and team_sets_teams", $path);
714
715                     //upgrade teams
716                         if(file_exists($newtemplate_path.'/modules/Administration/upgradeTeams.php')) {
717                                 logThis(" Start {$newtemplate_path}/modules/Administration/upgradeTeams.php", $path);
718                                 include($newtemplate_path.'/modules/Administration/upgradeTeams.php');
719                                 logThis(" Finish {$newtemplate_path}/modules/Administration/upgradeTeams.php", $path);
720
721                                 //update the users records to have default team
722                                 logThis('running query to populate default_team on users table',$path);
723                                 $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)");
724
725                         }
726
727                         //run upgrade script for dashlets to include sales/marketing
728                         if(function_exists('upgradeDashletsForSalesAndMarketing')){
729                    logThis('calling upgradeDashlets script',$path);
730                            upgradeDashletsForSalesAndMarketing();
731                         }
732
733             }
734
735                 require("sugar_version.php");
736                 require('config.php');
737                 global $sugar_config;
738
739                 require("{$instanceUpgradePath}/sugar_version.php");
740                 if(!rebuildConfigFile($sugar_config, $sugar_version)) {
741                         logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
742                         $errors[] = 'Could not write config.php!';
743                 }
744                 checkConfigForPermissions();
745
746         // clear out the theme cache
747                 if(!class_exists('SugarThemeRegistry')){
748                     require_once($newtemplate_path . '/include/SugarTheme/SugarTheme.php');
749                 }
750                 SugarThemeRegistry::buildRegistry();
751                 SugarThemeRegistry::clearAllCaches();
752
753                 // re-minify the JS source files
754                 $_REQUEST['root_directory'] = getcwd();
755                 $_REQUEST['js_rebuild_concat'] = 'rebuild';
756                 require_once($newtemplate_path . '/jssource/minify.php');
757
758                 //as last step, rebuild the language files and rebuild relationships
759                 /*
760                 if(file_exists($newtemplate_path.'/modules/Administration/RebuildJSLang.php')) {
761                         logThis("begin rebuilding js language files. via ".$newtemplate_path.'/modules/Administration/RebuildJSLang.php', $path);
762                         include($newtemplate_path.'/modules/Administration/RebuildJSLang.php');
763                         rebuildRelations($newtemplate_path.'/');
764                 }
765                 */
766
767     }
768
769 } //END OF BIG if block
770
771
772 //Also set the tracker settings if  flavor conversion ce->pro or ce->ent
773 if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
774         if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){
775             $_REQUEST['upgradeWizard'] = true;
776             ob_start();
777                 include('include/Smarty/internals/core.write_file.php');
778                 ob_end_clean();
779                 $db =& DBManagerFactory::getInstance();
780                 if($ce_to_pro_ent){
781                 //Also set license information
782                 $admin = new Administration();
783                         $category = 'license';
784                         $value = 0;
785                         $admin->saveSetting($category, 'users', $value);
786                         $key = array('num_lic_oc','key','expire_date');
787                         $value = '';
788                         foreach($key as $k){
789                                 $admin->saveSetting($category, $k, $value);
790                         }
791                 }
792         }
793 }
794
795 set_upgrade_progress('end','done','end','done');
796
797 if(file_exists($newtemplate_path . '/modules/Configurator/Configurator.php')){
798         set_upgrade_progress('configurator','in_progress');
799         require_once($newtemplate_path . '/include/utils/array_utils.php');
800         if(!class_exists('Configurator')){
801                 require_once($newtemplate_path . '/modules/Configurator/Configurator.php');
802         }
803         $Configurator = new Configurator();
804         if(class_exists('Configurator')){
805                 $Configurator->parseLoggerSettings();
806         }
807         set_upgrade_progress('configurator','done');
808 }
809
810 //unset the logger previously instantiated
811 if(file_exists($newtemplate_path . '/include/SugarLogger/LoggerManager.php')){
812         set_upgrade_progress('logger','in_progress');
813         if(!class_exists('LoggerManager')){
814
815         }
816         if(class_exists('LoggerManager')){
817                 unset($GLOBALS['log']);
818                 $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
819         }
820         set_upgrade_progress('logger','done');
821 }
822
823 ///////////////////////////////////////////////////////////////////////////////
824 ////    RECORD ERRORS
825 $phpErrors = ob_get_contents();
826 ob_end_clean();
827
828 if(count($errors) > 0) {
829         foreach($errors as $error) {
830                 logThis("****** SilentUpgrade ERROR: {$error}", $path);
831         }
832         echo "FAILED\n";
833 } else {
834         logThis("***** SilentUpgrade completed successfully.", $path);
835         echo "********************************************************************\n";
836         echo "*************************** SUCCESS*********************************\n";
837         echo "********************************************************************\n";
838         echo "******** If your pre-upgrade Leads data is not showing  ************\n";
839         echo "******** Or you see errors in detailview subpanels  ****************\n";
840         echo "************* In order to resolve them  ****************************\n";
841         echo "******** Log into application as Administrator  ********************\n";
842         echo "******** Go to Admin panel  ****************************************\n";
843         echo "******** Run Repair -> Rebuild Relationships  **********************\n";
844         echo "********************************************************************\n";
845 }
846
847
848 ?>