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