]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UpgradeWizard/silentUpgrade_step1.php
Release 6.3.0
[Github/sugarcrm.git] / modules / UpgradeWizard / silentUpgrade_step1.php
1 <?php
2
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39 //////////////////////////////////////////////////////////////////////////////////////////
40 //// This is a stand alone file that can be run from the command prompt for upgrading a
41 //// Sugar Instance. Three parameters are required to be defined in order to execute this file.
42 //// php.exe -f silentUpgrade.php [Path to Upgrade Package zip] [Path to Log file] [Path to Instance]
43 //// See below the Usage for more details.
44 /////////////////////////////////////////////////////////////////////////////////////////
45 ini_set('memory_limit',-1);
46 ///////////////////////////////////////////////////////////////////////////////
47 ////    UTILITIES THAT MUST BE LOCAL :(
48 function prepSystemForUpgradeSilent() {
49         global $subdirs;
50         global $cwd;
51         global $sugar_config;
52
53         // make sure dirs exist
54         foreach($subdirs as $subdir) {
55                 if(!is_dir(clean_path("{$cwd}/{$sugar_config['upload_dir']}upgrades/{$subdir}"))) {
56                 mkdir_recursive(clean_path("{$cwd}/{$sugar_config['upload_dir']}upgrades/{$subdir}"));
57                 }
58         }
59 }
60
61 //local function for clearing cache
62 function clearCacheSU($thedir, $extension) {
63         if ($current = @opendir($thedir)) {
64                 while (false !== ($children = readdir($current))) {
65                         if ($children != "." && $children != "..") {
66                                 if (is_dir($thedir . "/" . $children)) {
67                                         clearCacheSU($thedir . "/" . $children, $extension);
68                                 }
69                                 elseif (is_file($thedir . "/" . $children) && substr_count($children, $extension)) {
70                                         unlink($thedir . "/" . $children);
71                                 }
72                         }
73                 }
74         }
75  }
76  //Bug 24890, 24892. default_permissions not written to config.php. Following function checks and if
77  //no found then adds default_permissions to the config file.
78  function checkConfigForPermissions(){
79      if(file_exists(getcwd().'/config.php')){
80          require(getcwd().'/config.php');
81      }
82      global $sugar_config;
83      if(!isset($sugar_config['default_permissions'])){
84              $sugar_config['default_permissions'] = array (
85                      'dir_mode' => 02770,
86                      'file_mode' => 0660,
87                      'user' => '',
88                      'group' => '',
89              );
90          ksort($sugar_config);
91          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
92                 //writing to the file
93                 }
94      }
95 }
96 function checkLoggerSettings(){
97         if(file_exists(getcwd().'/config.php')){
98          require(getcwd().'/config.php');
99      }
100     global $sugar_config;
101         if(!isset($sugar_config['logger'])){
102             $sugar_config['logger'] =array (
103                         'level'=>'fatal',
104                     'file' =>
105                      array (
106                       'ext' => '.log',
107                       'name' => 'sugarcrm',
108                       'dateFormat' => '%c',
109                       'maxSize' => '10MB',
110                       'maxLogs' => 10,
111                       'suffix' => '%m_%Y',
112                     ),
113                   );
114                  ksort($sugar_config);
115          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
116                 //writing to the file
117                 }
118          }
119 }
120
121 function checkLeadConversionSettings() {
122     if (file_exists(getcwd().'/config.php')) {
123          require(getcwd().'/config.php');
124     }
125     global $sugar_config;
126     if (!isset($sugar_config['lead_conv_activity_opt'])) {
127         $sugar_config['lead_conv_activity_opt'] = 'copy';
128         ksort($sugar_config);
129         if (is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
130             //writing to the file
131         }
132     }
133 }
134
135 function checkResourceSettings(){
136         if(file_exists(getcwd().'/config.php')){
137          require(getcwd().'/config.php');
138      }
139     global $sugar_config;
140         if(!isset($sugar_config['resource_management'])){
141           $sugar_config['resource_management'] =
142                   array (
143                     'special_query_limit' => 50000,
144                     'special_query_modules' =>
145                     array (
146                       0 => 'Reports',
147                       1 => 'Export',
148                       2 => 'Import',
149                       3 => 'Administration',
150                       4 => 'Sync',
151                     ),
152                     'default_limit' => 1000,
153                   );
154                  ksort($sugar_config);
155          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
156                 //writing to the file
157                 }
158         }
159 }
160
161
162 function createMissingRels(){
163         $relForObjects = array('leads'=>'Leads','campaigns'=>'Campaigns','prospects'=>'Prospects');
164         foreach($relForObjects as $relObjName=>$relModName){
165                 //assigned_user
166                 $guid = create_guid();
167                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_assigned_user'";
168                 $result= $GLOBALS['db']->query($query, true);
169                 $a = null;
170                 $a = $GLOBALS['db']->fetchByAssoc($result);
171                 if($GLOBALS['db']->checkError()){
172                         //log this
173                 }
174                 if(!isset($a['id']) && empty($a['id']) ){
175                         $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)
176                                                 VALUES ('{$guid}', '{$relObjName}_assigned_user','Users','users','id','{$relModName}','{$relObjName}','assigned_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
177                         $GLOBALS['db']->query($qRel);
178                         if($GLOBALS['db']->checkError()){
179                                 //log this
180                         }
181                 }
182                 //modified_user
183                 $guid = create_guid();
184                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_modified_user'";
185                 $result= $GLOBALS['db']->query($query, true);
186                 if($GLOBALS['db']->checkError()){
187                         //log this
188                 }
189                 $a = null;
190                 $a = $GLOBALS['db']->fetchByAssoc($result);
191                 if(!isset($a['id']) && empty($a['id']) ){
192                         $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)
193                                                 VALUES ('{$guid}', '{$relObjName}_modified_user','Users','users','id','{$relModName}','{$relObjName}','modified_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
194                         $GLOBALS['db']->query($qRel);
195                         if($GLOBALS['db']->checkError()){
196                                 //log this
197                         }
198                 }
199                 //created_by
200                 $guid = create_guid();
201                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
202                 $result= $GLOBALS['db']->query($query, true);
203                 $a = null;
204                 $a = $GLOBALS['db']->fetchByAssoc($result);
205         if(!isset($a['id']) && empty($a['id']) ){
206                         $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)
207                                                 VALUES ('{$guid}', '{$relObjName}_created_by','Users','users','id','{$relModName}','{$relObjName}','created_by',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
208                         $GLOBALS['db']->query($qRel);
209                         if($GLOBALS['db']->checkError()){
210                                 //log this
211                         }
212         }
213                 $guid = create_guid();
214                 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_team'";
215                 $result= $GLOBALS['db']->query($query, true);
216                 $a = null;
217                 $a = $GLOBALS['db']->fetchByAssoc($result);
218                 if(!isset($a['id']) && empty($a['id']) ){
219                         $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)
220                                                         VALUES ('{$guid}', '{$relObjName}_team','Teams','teams','id','{$relModName}','{$relObjName}','team_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
221                         $GLOBALS['db']->query($qRel);
222                         if($GLOBALS['db']->checkError()){
223                                 //log this
224                         }
225
226                 }
227         }
228         //Also add tracker perf relationship
229         $guid = create_guid();
230         $query = "SELECT id FROM relationships WHERE relationship_name = 'tracker_monitor_id'";
231         $result= $GLOBALS['db']->query($query, true);
232         if($GLOBALS['db']->checkError()){
233                 //log this
234         }
235         $a = null;
236         $a = $GLOBALS['db']->fetchByAssoc($result);
237         if($GLOBALS['db']->checkError()){
238                 //log this
239         }
240         if(!isset($a['id']) && empty($a['id']) ){
241                 $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)
242                                         VALUES ('{$guid}', 'tracker_monitor_id','TrackerPerfs','tracker_perf','monitor_id','Trackers','tracker','monitor_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
243                 $GLOBALS['db']->query($qRel);
244                 if($GLOBALS['db']->checkError()){
245                         //log this
246                 }
247         }
248 }
249
250
251 /**
252  * This function will merge password default settings into config file
253  * @param   $sugar_config
254  * @param   $sugar_version
255  * @return  bool true if successful
256  */
257 function merge_passwordsetting($sugar_config, $sugar_version) {
258
259      $passwordsetting_defaults = array (
260         'passwordsetting' => array (
261             'minpwdlength' => '',
262             'maxpwdlength' => '',
263             'oneupper' => '',
264             'onelower' => '',
265             'onenumber' => '',
266             'onespecial' => '',
267             'SystemGeneratedPasswordON' => '',
268             'generatepasswordtmpl' => '',
269             'lostpasswordtmpl' => '',
270             'customregex' => '',
271             'regexcomment' => '',
272             'forgotpasswordON' => false,
273             'linkexpiration' => '1',
274             'linkexpirationtime' => '30',
275             'linkexpirationtype' => '1',
276             'userexpiration' => '0',
277             'userexpirationtime' => '',
278             'userexpirationtype' => '1',
279             'userexpirationlogin' => '',
280             'systexpiration' => '0',
281             'systexpirationtime' => '',
282             'systexpirationtype' => '0',
283             'systexpirationlogin' => '',
284             'lockoutexpiration' => '0',
285             'lockoutexpirationtime' => '',
286             'lockoutexpirationtype' => '1',
287             'lockoutexpirationlogin' => '',
288         ),
289     );
290
291     $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
292
293     // need to override version with default no matter what
294     $sugar_config['sugar_version'] = $sugar_version;
295
296     ksort( $sugar_config );
297
298     if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
299         return true;
300     }
301     else {
302         return false;
303     }
304 }
305
306 function addDefaultModuleRoles($defaultRoles = array()) {
307         foreach($defaultRoles as $roleName=>$role){
308         foreach($role as $category=>$actions){
309             foreach($actions as $name=>$access_override){
310                     $query = "SELECT * FROM acl_actions WHERE name='$name' AND category = '$category' AND acltype='$roleName' AND deleted=0 ";
311                                         $result = $GLOBALS['db']->query($query);
312                                         //only add if an action with that name and category don't exist
313                                         $row=$GLOBALS['db']->fetchByAssoc($result);
314                                         if ($row == null) {
315                                 $guid = create_guid();
316                                 $currdate = gmdate('Y-m-d H:i:s');
317                                 $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')";
318                                                 $GLOBALS['db']->query($query);
319                                                 if($GLOBALS['db']->checkError()){
320                                                         //log this
321                                                 }
322                         }
323             }
324         }
325         }
326 }
327
328 function verifyArguments($argv,$usage_dce,$usage_regular){
329     $upgradeType = '';
330     $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
331     if(isset($argv[3])) {
332         if(is_dir($argv[3])) {
333             $cwd = $argv[3];
334             chdir($cwd);
335         } else {
336             echo "*******************************************************************************\n";
337             echo "*** ERROR: 3rd parameter must be a valid directory.  Tried to cd to [ {$argv[3]} ].\n";
338             exit(1);
339         }
340     }
341
342     //check if this is an instance
343     if(is_file("{$cwd}/ini_setup.php")){
344         // this is an instance
345         $upgradeType = constant('DCE_INSTANCE');
346         //now that this is dce instance we want to make sure that there are
347         // 7 arguments
348         if(count($argv) < 7) {
349             echo "*******************************************************************************\n";
350             echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 7.\n";
351             echo $usage_dce;
352             echo "FAILURE\n";
353             exit(1);
354         }
355         // this is an instance
356         if(!is_dir($argv[1])) { // valid directory . template path?
357             echo "*******************************************************************************\n";
358             echo "*** ERROR: First argument must be a full path to the template. Got [ {$argv[1]} ].\n";
359             echo $usage_dce;
360             echo "FAILURE\n";
361             exit(1);
362         }
363     }
364     else if(is_file("{$cwd}/include/entryPoint.php")) {
365         //this should be a regular sugar install
366         $upgradeType = constant('SUGARCRM_INSTALL');
367         //check if this is a valid zip file
368         if(!is_file($argv[1])) { // valid zip?
369             echo "*******************************************************************************\n";
370             echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
371             echo $usage_regular;
372             echo "FAILURE\n";
373             exit(1);
374         }
375         if(count($argv) < 5) {
376             echo "*******************************************************************************\n";
377             echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 5.\n";
378             echo $usage_regular;
379             echo "FAILURE\n";
380             exit(1);
381         }
382     }
383     else {
384         //this should be a regular sugar install
385         echo "*******************************************************************************\n";
386         echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
387         exit(1);
388     }
389
390     if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
391         require_once($argv[7].'SugarTemplateUtilties.php');
392     }
393
394     return $upgradeType;
395 }
396
397 function upgradeDCEFiles($argv,$instanceUpgradePath){
398         //copy and update following files from upgrade package
399         $upgradeTheseFiles = array('cron.php','download.php','index.php','install.php','soap.php','sugar_version.php','vcal_server.php');
400         foreach($upgradeTheseFiles as $file){
401                 $srcFile = clean_path("{$instanceUpgradePath}/$file");
402                 $destFile = clean_path("{$argv[3]}/$file");
403                 if(file_exists($srcFile)){
404                         if(!is_dir(dirname($destFile))) {
405                                 mkdir_recursive(dirname($destFile)); // make sure the directory exists
406                         }
407                         copy_recursive($srcFile,$destFile);
408                         $_GET['TEMPLATE_PATH'] = $destFile;
409                         $_GET['CONVERT_FILE_ONLY'] = true;
410                         if(!class_exists('TemplateConverter')){
411                                 include($argv[7].'templateConverter.php');
412                         }else{
413                                 TemplateConverter::convertFile($_GET['TEMPLATE_PATH']);
414                         }
415
416
417                 }
418         }
419 }
420
421
422
423 function threeWayMerge(){
424         //using threeway merge apis
425 }
426
427 ////    END UTILITIES THAT MUST BE LOCAL :(
428 ///////////////////////////////////////////////////////////////////////////////
429
430
431 // only run from command line
432 if(isset($_SERVER['HTTP_USER_AGENT'])) {
433         fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
434         exit(1);
435 }
436 //Clean_string cleans out any file  passed in as a parameter
437 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
438
439
440 ///////////////////////////////////////////////////////////////////////////////
441 ////    USAGE
442 $usage_dce =<<<eoq1
443 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
444
445 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
446 php.exe followed by -f silentUpgrade.php and the arguments.
447
448 Example:
449     [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
450                              [Old Template path] [skipdbupgrade] [exitOrContinue]
451
452 Arguments:
453     New Template Path or Upgrade Package : Upgrade package name. Template2 (upgrade to)location.
454     silentupgrade.log                    : Silent Upgarde log file.
455     Sugar451e/DCE                        : Sugar or DCE Instance instance being upgraded.
456     Old Template path                    : Template1 (upgrade from) Instance is being upgraded.
457     skipDBupgrade                        : If set to Yes then silentupgrade will only upgrade files. Default is No.
458     exitOnConflicts                      : If set to No and conflicts are found then Upgrade continues. Default Yes.
459     pathToDCEClient                      : This is path to to DCEClient directory
460
461 eoq1;
462
463 $usage_regular =<<<eoq2
464 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
465
466 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
467 php.exe followed by -f silentUpgrade.php and the arguments.
468
469 Example:
470     [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
471
472 Arguments:
473     upgradeZipFile                       : Upgrade package file.
474     logFile                              : Silent Upgarde log file.
475     pathToSugarInstance                  : Sugar Instance instance being upgraded.
476     admin-user                           : admin user performing the upgrade
477 eoq2;
478 ////    END USAGE
479 ///////////////////////////////////////////////////////////////////////////////
480
481
482
483 ///////////////////////////////////////////////////////////////////////////////
484 ////    STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
485 if(!defined('sugarEntry')) define('sugarEntry', true);
486
487 $_SESSION = array();
488 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
489 $_SESSION['silent_upgrade'] = true;
490 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
491
492 $_REQUEST = array();
493 $_REQUEST['addTaskReminder'] = 'remind';
494
495
496 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
497 define('DCE_INSTANCE', 'DCE_Instance');
498
499 global $cwd;
500 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
501
502 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
503
504 ///////////////////////////////////////////////////////////////////////////////
505 //////  Verify that all the arguments are appropriately placed////////////////
506
507 ///////////////////////////////////////////////////////////////////////////////
508 ////    PREP LOCALLY USED PASSED-IN VARS & CONSTANTS
509 //$GLOBALS['log']       = LoggerManager::getLogger('SugarCRM');
510 //require_once('/var/www/html/eddy/sugarnode/SugarTemplateUtilities.php');
511
512 $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
513 //$db                           = &DBManagerFactory::getInstance();  //<---------
514
515
516 //$UWstrings            = return_module_language('en_us', 'UpgradeWizard');
517 //$adminStrings = return_module_language('en_us', 'Administration');
518 //$mod_strings  = array_merge($adminStrings, $UWstrings);
519 $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
520
521 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
522
523 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
524 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
525 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
526 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
527
528
529
530 echo "\n";
531 echo "********************************************************************\n";
532 echo "***************This Upgrade process may take sometime***************\n";
533 echo "********************************************************************\n";
534 echo "\n";
535
536 global $sugar_config;
537 $isDCEInstance = false;
538 $errors = array();
539
540
541 if($upgradeType != constant('DCE_INSTANCE')) {
542
543         ini_set('error_reporting',1);
544         require_once('include/entryPoint.php');
545         require_once('include/SugarLogger/SugarLogger.php');
546         require_once('include/utils/zip_utils.php');
547
548
549
550         require('config.php');
551         //require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
552         if(isset($argv[3])) {
553                 if(is_dir($argv[3])) {
554                         $cwd = $argv[3];
555                         chdir($cwd);
556                 }
557         }
558
559         require_once("{$cwd}/sugar_version.php"); // provides $sugar_version & $sugar_flavor
560
561     $GLOBALS['log']     = LoggerManager::getLogger('SugarCRM');
562         $patchName              = basename($argv[1]);
563         $zip_from_dir   = substr($patchName, 0, strlen($patchName) - 4); // patch folder name (minus ".zip")
564         $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
565
566         if($sugar_version < '5.1.0'){
567                 $db                             = &DBManager :: getInstance();
568         }
569         else{
570                 $db                             = &DBManagerFactory::getInstance();
571         }
572         $UWstrings              = return_module_language('en_us', 'UpgradeWizard');
573         $adminStrings   = return_module_language('en_us', 'Administration');
574         $mod_strings    = array_merge($adminStrings, $UWstrings);
575         $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
576         global $unzip_dir;
577     $license_accepted = false;
578     if(isset($argv[5]) && (strtolower($argv[5])=='yes' || strtolower($argv[5])=='y')){
579         $license_accepted = true;
580          }
581         //////////////////////////////////////////////////////////////////////////////
582         //Adding admin user to the silent upgrade
583
584         $current_user = new User();
585         if(isset($argv[4])) {
586            //if being used for internal upgrades avoid admin user verification
587            $user_name = $argv[4];
588            $q = "select id from users where user_name = '" . $user_name . "' and is_admin=1";
589            $result = $GLOBALS['db']->query($q, false);
590            $logged_user = $GLOBALS['db']->fetchByAssoc($result);
591            if(isset($logged_user['id']) && $logged_user['id'] != null){
592                 //do nothing
593             $current_user->retrieve($logged_user['id']);
594            }
595            else{
596                 echo "FAILURE: Not an admin user in users table. Please provide an admin user\n";
597                 exit(1);
598            }
599         }
600         else {
601                 echo "*******************************************************************************\n";
602                 echo "*** ERROR: 4th parameter must be a valid admin user.\n";
603                 echo $usage;
604                 echo "FAILURE\n";
605                 exit(1);
606         }
607
608
609                 /////retrieve admin user
610         global $sugar_config;
611         $configOptions = $sugar_config['dbconfig'];
612
613
614 ///////////////////////////////////////////////////////////////////////////////
615 ////    UPGRADE PREP
616 prepSystemForUpgradeSilent();
617
618 //repair tabledictionary.ext.php file if needed
619 repairTableDictionaryExtFile();
620
621 $unzip_dir = clean_path("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp");
622 $install_file = clean_path("{$cwd}/{$sugar_config['upload_dir']}upgrades/patch/".basename($argv[1]));
623
624 $_SESSION['unzip_dir'] = $unzip_dir;
625 $_SESSION['install_file'] = $install_file;
626 $_SESSION['zip_from_dir'] = $zip_from_dir;
627 if(is_dir($unzip_dir.'/scripts'))
628 {
629         rmdir_recursive($unzip_dir.'/scripts');
630 }
631 if(is_file($unzip_dir.'/manifest.php'))
632 {
633         rmdir_recursive($unzip_dir.'/manifest.php');
634 }
635 mkdir_recursive($unzip_dir);
636 if(!is_dir($unzip_dir)) {
637         echo "\n{$unzip_dir} is not an available directory\nFAILURE\n";
638         fwrite(STDERR,"\n{$unzip_dir} is not an available directory\nFAILURE\n");
639         exit(1);
640 }
641
642 unzip($argv[1], $unzip_dir);
643 // mimic standard UW by copy patch zip to appropriate dir
644 copy($argv[1], $install_file);
645 ////    END UPGRADE PREP
646 ///////////////////////////////////////////////////////////////////////////////
647
648 ///////////////////////////////////////////////////////////////////////////////
649 ////    UPGRADE UPGRADEWIZARD
650
651 $zipBasePath = clean_path("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp/{$zip_from_dir}");
652 $uwFiles = findAllFiles(clean_path("{$zipBasePath}/modules/UpgradeWizard"), array());
653 $destFiles = array();
654
655 foreach($uwFiles as $uwFile) {
656         $destFile = clean_path(str_replace($zipBasePath, $cwd, $uwFile));
657         copy($uwFile, $destFile);
658 }
659 require_once('modules/UpgradeWizard/uw_utils.php'); // must upgrade UW first
660 removeSilentUpgradeVarsCache(); // Clear the silent upgrade vars - Note: Any calls to these functions within this file are removed here
661 logThis("*** SILENT UPGRADE INITIATED.", $path);
662 logThis("*** UpgradeWizard Upgraded  ", $path);
663
664 if(function_exists('set_upgrade_vars')){
665         set_upgrade_vars();
666 }
667
668 if($configOptions['db_type'] == 'mysql'){
669         //Change the db wait_timeout for this session
670         $que ="select @@wait_timeout";
671         $result = $db->query($que);
672         $tb = $db->fetchByAssoc($result);
673         logThis('Wait Timeout before change ***** '.$tb['@@wait_timeout'] , $path);
674         $query ="set wait_timeout=28800";
675         $db->query($query);
676         $result = $db->query($que);
677         $ta = $db->fetchByAssoc($result);
678         logThis('Wait Timeout after change ***** '.$ta['@@wait_timeout'] , $path);
679 }
680
681 ////    END UPGRADE UPGRADEWIZARD
682 ///////////////////////////////////////////////////////////////////////////////
683
684 ///////////////////////////////////////////////////////////////////////////////
685 ////    MAKE SURE PATCH IS COMPATIBLE
686 if(is_file("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp/manifest.php")) {
687         // provides $manifest array
688         include("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp/manifest.php");
689         if(!isset($manifest)) {
690                 fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
691             exit(1);
692         } else {
693                 copy("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp/manifest.php", "{$cwd}/{$sugar_config['upload_dir']}upgrades/patch/{$zip_from_dir}-manifest.php");
694
695                 $error = validate_manifest($manifest);
696                 if(!empty($error)) {
697                         $error = strip_tags(br2nl($error));
698                         fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
699                         exit(1);
700                 }
701         }
702 } else {
703         fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file.  Cannot continue.\n\n");
704         exit(1);
705 }
706
707 $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');
708 $_SESSION['upgrade_from_flavor'] = $manifest['name'];
709
710 global $sugar_config;
711 global $sugar_version;
712 global $sugar_flavor;
713
714 ////    END MAKE SURE PATCH IS COMPATIBLE
715 ///////////////////////////////////////////////////////////////////////////////
716
717 ///////////////////////////////////////////////////////////////////////////////
718 ////    RUN SILENT UPGRADE
719 ob_start();
720 set_time_limit(0);
721 if(file_exists('ModuleInstall/PackageManager/PackageManagerDisplay.php')) {
722         require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php');
723 }
724
725         $parserFiles = array();
726
727 if(file_exists(clean_path("{$zipBasePath}/include/SugarFields"))) {
728         $parserFiles = findAllFiles(clean_path("{$zipBasePath}/include/SugarFields"), $parserFiles);
729 }
730  //$cwd = clean_path(getcwd());
731 foreach($parserFiles as $file) {
732         $srcFile = clean_path($file);
733         //$targetFile = clean_path(getcwd() . '/' . $srcFile);
734     if (strpos($srcFile,".svn") !== false) {
735           //do nothing
736     }
737     else{
738     $targetFile = str_replace(clean_path($zipBasePath), $cwd, $srcFile);
739
740     if(!file_exists(dirname($targetFile))) 
741     {
742                 logThis("Create directory " . dirname($targetFile), $path);
743         mkdir_recursive(str_replace($argv[3], '', dirname($targetFile))); // make sure the directory exists
744         }
745
746         if(!file_exists($targetFile))
747          {
748                 //logThis('Copying file to destination: ' . $targetFile, $path);
749                 if(!copy($srcFile, $targetFile)) {
750                         logThis('*** ERROR: could not copy file: ' . $targetFile, $path);
751                 } else {
752                         $copiedFiles[] = $targetFile;
753                 }
754         } else {
755                 //logThis('Skipping file: ' . $targetFile, $path);
756                 //$skippedFiles[] = $targetFile;
757         }
758    }
759  }
760         //copy minimum required files including sugar_file_utils.php
761         if(file_exists("{$zipBasePath}/include/utils/sugar_file_utils.php")){
762                 $destFile = clean_path(str_replace($zipBasePath, $cwd, "{$zipBasePath}/include/utils/sugar_file_utils.php"));
763                 copy("{$zipBasePath}/include/utils/sugar_file_utils.php", $destFile);
764         }
765         if(file_exists('include/utils/sugar_file_utils.php')){
766         require_once('include/utils/sugar_file_utils.php');
767     }
768
769 /*
770 $errors = preflightCheck();
771 if((count($errors) == 1)) { // only diffs
772         logThis('file preflight check passed successfully.', $path);
773 }
774 else{
775         fwrite(STDERR,"\nThe user doesn't have sufficient permissions to write to database'.\n\n");
776         exit(1);
777 }
778 */
779 //If version less than 500 then look for modules to be upgraded
780 if(function_exists('set_upgrade_vars')){
781         set_upgrade_vars();
782 }
783 //Initialize the session variables. If upgrade_progress.php is already created
784 //look for session vars there and restore them
785 if(function_exists('initialize_session_vars')){
786         initialize_session_vars();
787 }
788
789 if(!didThisStepRunBefore('preflight')){
790         set_upgrade_progress('preflight','in_progress');
791         //Quickcreatedefs on the basis of editviewdefs
792     if(substr($sugar_version,0,1) >= 5){
793         updateQuickCreateDefs();
794         }
795         set_upgrade_progress('preflight','done');
796 }
797 ////////////////COMMIT PROCESS BEGINS///////////////////////////////////////////////////////////////
798 ////    MAKE BACKUPS OF TARGET FILES
799
800 if(!didThisStepRunBefore('commit')){
801         set_upgrade_progress('commit','in_progress','commit','in_progress');
802         if(!didThisStepRunBefore('commit','commitMakeBackupFiles')){
803                 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','in_progress');
804                 $errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
805                 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','done');
806         }
807
808         //Need to make sure we have the matching copy of SetValueAction for static/instance method matching
809     if(file_exists("include/Expressions/Actions/SetValueAction.php")){
810         require_once("include/Expressions/Actions/SetValueAction.php");
811     }
812
813         ///////////////////////////////////////////////////////////////////////////////
814         ////    HANDLE PREINSTALL SCRIPTS
815         if(empty($errors)) {
816                 $file = "{$unzip_dir}/".constant('SUGARCRM_PRE_INSTALL_FILE');
817
818                 if(is_file($file)) {
819                         include($file);
820                         if(!didThisStepRunBefore('commit','pre_install')){
821                                 set_upgrade_progress('commit','in_progress','pre_install','in_progress');
822                                 pre_install();
823                                 set_upgrade_progress('commit','in_progress','pre_install','done');
824                         }
825                 }
826         }
827
828         //Clean smarty from cache
829         if(is_dir($GLOBALS['sugar_config']['cache_dir'].'smarty')){
830                 $allModFiles = array();
831                 $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'smarty',$allModFiles);
832            foreach($allModFiles as $file){
833                 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
834                 if(file_exists($file)){
835                                 unlink($file);
836                 }
837            }
838         }
839
840                 //Also add the three-way merge here. The idea is after the 451 html files have
841                 //been converted run the 3-way merge. If 500 then just run the 3-way merge
842                 if(file_exists('modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
843                     set_upgrade_progress('end','in_progress','threewaymerge','in_progress');
844                     require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php');
845                     $merger = new SugarMerge($zipBasePath);
846                     $merger->mergeAll();
847                     set_upgrade_progress('end','in_progress','threewaymerge','done');
848                 }
849         ///////////////////////////////////////////////////////////////////////////////
850         ////    COPY NEW FILES INTO TARGET INSTANCE
851
852      if(!didThisStepRunBefore('commit','commitCopyNewFiles')){
853                         set_upgrade_progress('commit','in_progress','commitCopyNewFiles','in_progress');
854                         $split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
855                         $copiedFiles = $split['copiedFiles'];
856                         $skippedFiles = $split['skippedFiles'];
857                         set_upgrade_progress('commit','in_progress','commitCopyNewFiles','done');
858          }
859         require_once(clean_path($unzip_dir.'/scripts/upgrade_utils.php'));
860         $new_sugar_version = getUpgradeVersion();
861     $origVersion = substr(preg_replace("/[^0-9]/", "", $sugar_version),0,3);
862     $destVersion = substr(preg_replace("/[^0-9]/", "", $new_sugar_version),0,3);
863     $siv_varset_1 = setSilentUpgradeVar('origVersion', $origVersion);
864     $siv_varset_2 = setSilentUpgradeVar('destVersion', $destVersion);
865     $siv_write    = writeSilentUpgradeVars();
866     if(!$siv_varset_1 || !$siv_varset_2 || !$siv_write){
867         logThis("Error with silent upgrade variables: origVersion write success is ({$siv_varset_1}) ".
868                         "-- destVersion write success is ({$siv_varset_2}) -- ".
869                         "writeSilentUpgradeVars success is ({$siv_write}) -- ".
870                         "path to cache dir is ({$GLOBALS['sugar_config']['cache_dir']})", $path);
871     }
872      require_once('modules/DynamicFields/templates/Fields/TemplateText.php');
873         ///////////////////////////////////////////////////////////////////////////////
874     ///    RELOAD NEW DEFINITIONS
875     global $ACLActions, $beanList, $beanFiles;
876     include('modules/ACLActions/actiondefs.php');
877     include('include/modules.php');
878         /////////////////////////////////////////////
879
880     if (!function_exists("inDeveloperMode")) {
881         //this function was introduced from tokyo in the file include/utils.php, so when upgrading from 5.1x and 5.2x we should declare the this function
882         function inDeveloperMode()
883         {
884             return isset($GLOBALS['sugar_config']['developerMode']) && $GLOBALS['sugar_config']['developerMode'];
885         }
886     }
887         ///////////////////////////////////////////////////////////////////////////////
888         ////    HANDLE POSTINSTALL SCRIPTS
889         if(empty($errors)) {
890                 logThis('Starting post_install()...', $path);
891
892                 $trackerManager = TrackerManager::getInstance();
893         $trackerManager->pause();
894         $trackerManager->unsetMonitors();
895
896                 if(!didThisStepRunBefore('commit','post_install')){
897                         $file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
898                         if(is_file($file)) {
899                                 //set_upgrade_progress('commit','in_progress','post_install','in_progress');
900                                 $progArray['post_install']='in_progress';
901                                 post_install_progress($progArray,'set');
902                                     global $moduleList;
903                                         include($file);
904                                         post_install();
905                                 // cn: only run conversion if admin selects "Sugar runs SQL"
906                                 if(!empty($_SESSION['allTables']) && $_SESSION['schema_change'] == 'sugar')
907                                         executeConvertTablesSql($db->dbType, $_SESSION['allTables']);
908                                 //set process to done
909                                 $progArray['post_install']='done';
910                                 //set_upgrade_progress('commit','in_progress','post_install','done');
911                                 post_install_progress($progArray,'set');
912                         }
913                 }
914             //clean vardefs
915                 logThis('Performing UWrebuild()...', $path);
916                 ob_start();
917                         @UWrebuild();
918                 ob_end_clean();
919                 logThis('UWrebuild() done.', $path);
920
921                 logThis('begin check default permissions .', $path);
922                 checkConfigForPermissions();
923             logThis('end check default permissions .', $path);
924
925             logThis('begin check logger settings .', $path);
926                 checkLoggerSettings();
927             logThis('begin check logger settings .', $path);
928
929             logThis('begin check lead conversion settings .', $path);
930             checkLeadConversionSettings();
931             logThis('end check lead conversion settings .', $path);
932
933             logThis('begin check resource settings .', $path);
934                         checkResourceSettings();
935                 logThis('begin check resource settings .', $path);
936
937
938                 require("sugar_version.php");
939                 require('config.php');
940                 global $sugar_config;
941
942                 if($ce_to_pro_ent){
943                         if(isset($sugar_config['sugarbeet']))
944                         {
945                             //$sugar_config['sugarbeet'] is only set in COMM
946                             unset($sugar_config['sugarbeet']);
947                         }
948                     if(isset($sugar_config['disable_team_access_check']))
949                         {
950                             //$sugar_config['disable_team_access_check'] is a runtime configration,
951                             //no need to write to config.php
952                             unset($sugar_config['disable_team_access_check']);
953                         }
954                         if(!merge_passwordsetting($sugar_config, $sugar_version)) {
955                                 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
956                                 $errors[] = 'Could not write config.php!';
957                         }
958
959                 }
960
961                 logThis('Set default_theme to Sugar', $path);
962                 $sugar_config['default_theme'] = 'Sugar';
963
964                 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
965             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
966             $errors[] = 'Could not write config.php!';
967         }
968
969         logThis('Set default_max_tabs to 7', $path);
970                 $sugar_config['default_max_tabs'] = '7';
971
972                 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
973             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
974             $errors[] = 'Could not write config.php!';
975         }
976
977                 logThis('Upgrade the sugar_version', $path);
978                 $sugar_config['sugar_version'] = $sugar_version;
979                 if($destVersion == $origVersion)
980                         require('config.php');
981         if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
982             logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
983             $errors[] = 'Could not write config.php!';
984         }
985
986                 logThis('post_install() done.', $path);
987         }
988
989         ///////////////////////////////////////////////////////////////////////////////
990         ////    REGISTER UPGRADE
991         if(empty($errors)) {
992                 logThis('Registering upgrade with UpgradeHistory', $path);
993                 if(!didThisStepRunBefore('commit','upgradeHistory')){
994                         set_upgrade_progress('commit','in_progress','upgradeHistory','in_progress');
995                         $file_action = "copied";
996                         // if error was encountered, script should have died before now
997                         $new_upgrade = new UpgradeHistory();
998                         $new_upgrade->filename = $install_file;
999                         $new_upgrade->md5sum = md5_file($install_file);
1000                         $new_upgrade->name = $zip_from_dir;
1001                         $new_upgrade->description = $manifest['description'];
1002                         $new_upgrade->type = 'patch';
1003                         $new_upgrade->version = $sugar_version;
1004                         $new_upgrade->status = "installed";
1005                         $new_upgrade->manifest = (!empty($_SESSION['install_manifest']) ? $_SESSION['install_manifest'] : '');
1006
1007                         if($new_upgrade->description == null){
1008                                 $new_upgrade->description = "Silent Upgrade was used to upgrade the instance";
1009                         }
1010                         else{
1011                                 $new_upgrade->description = $new_upgrade->description." Silent Upgrade was used to upgrade the instance.";
1012                         }
1013                    $new_upgrade->save();
1014                    set_upgrade_progress('commit','in_progress','upgradeHistory','done');
1015                    set_upgrade_progress('commit','done','commit','done');
1016                 }
1017           }
1018
1019         //Clean modules from cache
1020                 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'smarty')){
1021                         $allModFiles = array();
1022                         $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'smarty',$allModFiles);
1023                    foreach($allModFiles as $file){
1024                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1025                         if(file_exists($file)){
1026                                         unlink($file);
1027                         }
1028                    }
1029                 }
1030    //delete cache/modules before rebuilding the relations
1031         //Clean modules from cache
1032                 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'modules')){
1033                         $allModFiles = array();
1034                         $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'modules',$allModFiles);
1035                    foreach($allModFiles as $file){
1036                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1037                         if(file_exists($file)){
1038                                         unlink($file);
1039                         }
1040                    }
1041                 }
1042
1043                 //delete cache/themes
1044                 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'themes')){
1045                         $allModFiles = array();
1046                         $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'themes',$allModFiles);
1047                    foreach($allModFiles as $file){
1048                         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1049                         if(file_exists($file)){
1050                                         unlink($file);
1051                         }
1052                    }
1053                 }
1054         ob_start();
1055         if(!isset($_REQUEST['silent'])){
1056                 $_REQUEST['silent'] = true;
1057         }
1058         else if(isset($_REQUEST['silent']) && $_REQUEST['silent'] != true){
1059                 $_REQUEST['silent'] = true;
1060         }
1061
1062          //logThis('Checking for leads_assigned_user relationship and if not found then create.', $path);
1063         @createMissingRels();
1064          //logThis('Checked for leads_assigned_user relationship.', $path);
1065         ob_end_clean();
1066         //// run fix on dropdown lists that may have been incorrectly named
1067     //fix_dropdown_list();
1068 }
1069
1070 set_upgrade_progress('end','in_progress','end','in_progress');
1071 /////////////////////////Old Logger settings///////////////////////////////////////
1072 ///////////////////////////////////////////////////////////////////////////////
1073
1074 if(function_exists('deleteCache')){
1075         set_upgrade_progress('end','in_progress','deleteCache','in_progress');
1076         @deleteCache();
1077         set_upgrade_progress('end','in_progress','deleteCache','done');
1078 }
1079
1080 ///////////////////////////////////////////////////////////////////////////////
1081 ////    HANDLE REMINDERS
1082 if(empty($errors)) {
1083         commitHandleReminders($skippedFiles, $path);
1084 }
1085
1086 if(file_exists(clean_path(getcwd()).'/original451files')){
1087         rmdir_recursive(clean_path(getcwd()).'/original451files');
1088 }
1089
1090 require_once('modules/Administration/Administration.php');
1091 $admin = new Administration();
1092 $admin->saveSetting('system','adminwizard',1);
1093
1094 logThis('Upgrading user preferences start .', $path);
1095 if(function_exists('upgradeUserPreferences')){
1096    upgradeUserPreferences();
1097 }
1098 logThis('Upgrading user preferences finish .', $path);
1099
1100
1101 require_once('modules/Administration/upgrade_custom_relationships.php');
1102 upgrade_custom_relationships();
1103
1104 if($ce_to_pro_ent)
1105 {
1106         //check to see if there are any new files that need to be added to systems tab
1107         //retrieve old modules list
1108         logThis('check to see if new modules exist',$path);
1109         $oldModuleList = array();
1110         $newModuleList = array();
1111         include($argv[3].'/include/modules.php');
1112         $oldModuleList = $moduleList;
1113         include('include/modules.php');
1114         $newModuleList = $moduleList;
1115
1116         //include tab controller
1117         require_once('modules/MySettings/TabController.php');
1118         $newTB = new TabController();
1119
1120         //make sure new modules list has a key we can reference directly
1121         $newModuleList = $newTB->get_key_array($newModuleList);
1122         $oldModuleList = $newTB->get_key_array($oldModuleList);
1123
1124         //iterate through list and remove commonalities to get new modules
1125         foreach ($newModuleList as $remove_mod){
1126             if(in_array($remove_mod, $oldModuleList)){
1127                 unset($newModuleList[$remove_mod]);
1128             }
1129         }
1130
1131         $must_have_modules= array(
1132                           'Activities'=>'Activities',
1133                   'Calendar'=>'Calendar',
1134                   'Reports' => 'Reports',
1135                           'Quotes' => 'Quotes',
1136                           'Products' => 'Products',
1137                           'Forecasts' => 'Forecasts',
1138                           'Contracts' => 'Contracts',
1139                           'KBDocuments' => 'KBDocuments'
1140         );
1141         $newModuleList = array_merge($newModuleList,$must_have_modules);
1142
1143         //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
1144         logThis('new modules to add are '.var_export($newModuleList,true),$path);
1145
1146         //grab the existing system tabs
1147         $tabs = $newTB->get_system_tabs();
1148
1149         //add the new tabs to the array
1150         foreach($newModuleList as $nm ){
1151           $tabs[$nm] = $nm;
1152         }
1153
1154         //now assign the modules to system tabs
1155         $newTB->set_system_tabs($tabs);
1156         logThis('module tabs updated',$path);
1157 }
1158
1159 //Also set the tracker settings if  flavor conversion ce->pro or ce->ent
1160 if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
1161         if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){
1162             $_REQUEST['upgradeWizard'] = true;
1163             ob_start();
1164                         include('include/Smarty/internals/core.write_file.php');
1165                 ob_end_clean();
1166                 $db =& DBManagerFactory::getInstance();
1167                 if($ce_to_pro_ent){
1168                 //Also set license information
1169                 $admin = new Administration();
1170                         $category = 'license';
1171                         $value = 0;
1172                         $admin->saveSetting($category, 'users', $value);
1173                         $key = array('num_lic_oc','key','expire_date');
1174                         $value = '';
1175                         foreach($key as $k){
1176                                 $admin->saveSetting($category, $k, $value);
1177                         }
1178                 }
1179         }
1180 }
1181
1182         $phpErrors = ob_get_contents();
1183         ob_end_clean();
1184         logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
1185
1186         if(count($errors) > 0) {
1187                 foreach($errors as $error) {
1188                         logThis("****** SilentUpgrade ERROR: {$error}", $path);
1189                 }
1190                 echo "FAILED\n";
1191         }
1192
1193
1194 } else {
1195 //ELSE if DCE_INSTANCE
1196 echo "RUNNING DCE UPGRADE\n";
1197
1198 } //END of big if-else block for DCE_INSTANCE
1199
1200
1201 /**
1202  * repairTableDictionaryExtFile
1203  * 
1204  * There were some scenarios in 6.0.x whereby the files loaded in the extension tabledictionary.ext.php file 
1205  * did not exist.  This would cause warnings to appear during the upgrade.  As a result, this
1206  * function scans the contents of tabledictionary.ext.php and then remove entries where the file does exist.
1207  */
1208 function repairTableDictionaryExtFile()
1209 {
1210         $tableDictionaryExtDirs = array('custom/Extension/application/Ext/TableDictionary', 'custom/application/Ext/TableDictionary');
1211         
1212         foreach($tableDictionaryExtDirs as $tableDictionaryExt)
1213         {
1214         
1215                 if(is_dir($tableDictionaryExt) && is_writable($tableDictionaryExt)){
1216                         $dir = dir($tableDictionaryExt);
1217                         while(($entry = $dir->read()) !== false)
1218                         {
1219                                 $entry = $tableDictionaryExt . '/' . $entry;
1220                                 if(is_file($entry) && preg_match('/\.php$/i', $entry) && is_writeable($entry))
1221                                 {
1222                         
1223                                                 if(function_exists('sugar_fopen'))
1224                                                 {
1225                                                         $fp = @sugar_fopen($entry, 'r');
1226                                                 } else {
1227                                                         $fp = fopen($entry, 'r');
1228                                                 }                       
1229                                                 
1230                                                 
1231                                             if($fp)
1232                                         {
1233                                              $altered = false;
1234                                              $contents = '';
1235                                                      
1236                                              while($line = fgets($fp))
1237                                                      {
1238                                                         if(preg_match('/\s*include\s*\(\s*[\'|\"](.*?)[\"|\']\s*\)\s*;/', $line, $match))
1239                                                         {
1240                                                            if(!file_exists($match[1]))
1241                                                            {
1242                                                               $altered = true;
1243                                                            } else {
1244                                                                   $contents .= $line;
1245                                                            }
1246                                                         } else {
1247                                                            $contents .= $line;
1248                                                         }
1249                                                      }
1250                                                      
1251                                                      fclose($fp); 
1252                                         }
1253                                         
1254                                         
1255                                             if($altered)
1256                                             {
1257                                                         if(function_exists('sugar_fopen'))
1258                                                         {
1259                                                                 $fp = @sugar_fopen($entry, 'w');
1260                                                         } else {
1261                                                                 $fp = fopen($entry, 'w');
1262                                                         }                       
1263                                             
1264                                                         if($fp && fwrite($fp, $contents))
1265                                                         {
1266                                                                 fclose($fp);
1267                                                         }
1268                                             }                                   
1269                                 } //if
1270                         } //while
1271                 } //if
1272         }
1273 }
1274
1275 ?>