3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
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() {
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}"));
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);
69 elseif (is_file($thedir . "/" . $children) && substr_count($children, $extension)) {
70 unlink($thedir . "/" . $children);
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');
83 if(!isset($sugar_config['default_permissions'])){
84 $sugar_config['default_permissions'] = array (
91 if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
96 function checkLoggerSettings(){
97 if(file_exists(getcwd().'/config.php')){
98 require(getcwd().'/config.php');
100 global $sugar_config;
101 if(!isset($sugar_config['logger'])){
102 $sugar_config['logger'] =array (
107 'name' => 'sugarcrm',
108 'dateFormat' => '%c',
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
121 function checkResourceSettings(){
122 if(file_exists(getcwd().'/config.php')){
123 require(getcwd().'/config.php');
125 global $sugar_config;
126 if(!isset($sugar_config['resource_management'])){
127 $sugar_config['resource_management'] =
129 'special_query_limit' => 50000,
130 'special_query_modules' =>
135 3 => 'Administration',
138 'default_limit' => 1000,
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
148 function createMissingRels(){
149 $relForObjects = array('leads'=>'Leads','campaigns'=>'Campaigns','prospects'=>'Prospects');
150 foreach($relForObjects as $relObjName=>$relModName){
152 $guid = create_guid();
153 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_assigned_user'";
154 $result= $GLOBALS['db']->query($query, true);
156 $a = $GLOBALS['db']->fetchByAssoc($result);
157 if($GLOBALS['db']->checkError()){
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()){
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()){
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()){
186 $guid = create_guid();
187 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
188 $result= $GLOBALS['db']->query($query, true);
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()){
199 $guid = create_guid();
200 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_team'";
201 $result= $GLOBALS['db']->query($query, true);
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()){
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()){
222 $a = $GLOBALS['db']->fetchByAssoc($result);
223 if($GLOBALS['db']->checkError()){
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()){
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
243 function merge_passwordsetting($sugar_config, $sugar_version) {
245 $passwordsetting_defaults = array (
246 'passwordsetting' => array (
247 'minpwdlength' => '',
248 'maxpwdlength' => '',
253 'SystemGeneratedPasswordON' => '',
254 'generatepasswordtmpl' => '',
255 'lostpasswordtmpl' => '',
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' => '',
277 $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
279 // need to override version with default no matter what
280 $sugar_config['sugar_version'] = $sugar_version;
282 ksort( $sugar_config );
284 if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
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);
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()){
314 function verifyArguments($argv,$usage_dce,$usage_regular){
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])) {
322 echo "*******************************************************************************\n";
323 echo "*** ERROR: 3rd parameter must be a valid directory. Tried to cd to [ {$argv[3]} ].\n";
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
334 if(count($argv) < 7) {
335 echo "*******************************************************************************\n";
336 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 7.\n";
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";
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";
361 if(count($argv) < 5) {
362 echo "*******************************************************************************\n";
363 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 5.\n";
370 //this should be a regular sugar install
371 echo "*******************************************************************************\n";
372 echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
376 if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
377 require_once($argv[7].'SugarTemplateUtilties.php');
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
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');
399 TemplateConverter::convertFile($_GET['TEMPLATE_PATH']);
409 function threeWayMerge(){
410 //using threeway merge apis
413 //// END UTILITIES THAT MUST BE LOCAL :(
414 ///////////////////////////////////////////////////////////////////////////////
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.');
422 //Clean_string cleans out any file passed in as a parameter
423 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
426 ///////////////////////////////////////////////////////////////////////////////
429 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
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.
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]
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
449 $usage_regular =<<<eoq2
450 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
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.
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
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
465 ///////////////////////////////////////////////////////////////////////////////
469 ///////////////////////////////////////////////////////////////////////////////
470 //// STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
471 if(!defined('sugarEntry')) define('sugarEntry', true);
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
479 $_REQUEST['addTaskReminder'] = 'remind';
482 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
483 define('DCE_INSTANCE', 'DCE_Instance');
486 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
488 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
490 ///////////////////////////////////////////////////////////////////////////////
491 ////// Verify that all the arguments are appropriately placed////////////////
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');
498 $path = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
499 //$db = &DBManagerFactory::getInstance(); //<---------
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');
507 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
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');
517 echo "********************************************************************\n";
518 echo "***************This Upgrade process may take sometime***************\n";
519 echo "********************************************************************\n";
522 global $sugar_config;
523 $isDCEInstance = false;
527 if($upgradeType != constant('DCE_INSTANCE')) {
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');
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])) {
545 require_once("{$cwd}/sugar_version.php"); // provides $sugar_version & $sugar_flavor
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
552 if($sugar_version < '5.1.0'){
553 $db = &DBManager :: getInstance();
556 $db = &DBManagerFactory::getInstance();
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');
563 $license_accepted = false;
564 if(isset($argv[5]) && (strtolower($argv[5])=='yes' || strtolower($argv[5])=='y')){
565 $license_accepted = true;
567 //////////////////////////////////////////////////////////////////////////////
568 //Adding admin user to the silent upgrade
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){
579 $current_user->retrieve($logged_user['id']);
582 echo "FAILURE: Not an admin user in users table. Please provide an admin user\n";
587 echo "*******************************************************************************\n";
588 echo "*** ERROR: 4th parameter must be a valid admin user.\n";
595 /////retrieve admin user
596 global $sugar_config;
597 $configOptions = $sugar_config['dbconfig'];
600 ///////////////////////////////////////////////////////////////////////////////
602 prepSystemForUpgradeSilent();
604 //repair tabledictionary.ext.php file if needed
605 repairTableDictionaryExtFile();
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]));
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'))
615 rmdir_recursive($unzip_dir.'/scripts');
617 if(is_file($unzip_dir.'/manifest.php'))
619 rmdir_recursive($unzip_dir.'/manifest.php');
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");
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 ///////////////////////////////////////////////////////////////////////////////
634 ///////////////////////////////////////////////////////////////////////////////
635 //// UPGRADE UPGRADEWIZARD
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();
641 foreach($uwFiles as $uwFile) {
642 $destFile = clean_path(str_replace($zipBasePath, $cwd, $uwFile));
643 copy($uwFile, $destFile);
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);
650 if(function_exists('set_upgrade_vars')){
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";
662 $result = $db->query($que);
663 $ta = $db->fetchByAssoc($result);
664 logThis('Wait Timeout after change ***** '.$ta['@@wait_timeout'] , $path);
667 //// END UPGRADE UPGRADEWIZARD
668 ///////////////////////////////////////////////////////////////////////////////
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");
679 copy("{$cwd}/{$sugar_config['upload_dir']}upgrades/temp/manifest.php", "{$cwd}/{$sugar_config['upload_dir']}upgrades/patch/{$zip_from_dir}-manifest.php");
681 $error = validate_manifest($manifest);
683 $error = strip_tags(br2nl($error));
684 fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
689 fwrite(STDERR,"\nThe patch did not contain a proper manifest.php file. Cannot continue.\n\n");
693 $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');
694 $_SESSION['upgrade_from_flavor'] = $manifest['name'];
696 global $sugar_config;
697 global $sugar_version;
698 global $sugar_flavor;
700 //// END MAKE SURE PATCH IS COMPATIBLE
701 ///////////////////////////////////////////////////////////////////////////////
703 ///////////////////////////////////////////////////////////////////////////////
704 //// RUN SILENT UPGRADE
707 if(file_exists('ModuleInstall/PackageManager/PackageManagerDisplay.php')) {
708 require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php');
711 $parserFiles = array();
713 if(file_exists(clean_path("{$zipBasePath}/include/SugarFields"))) {
714 $parserFiles = findAllFiles(clean_path("{$zipBasePath}/include/SugarFields"), $parserFiles);
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) {
724 $targetFile = str_replace(clean_path($zipBasePath), $cwd, $srcFile);
726 if(!file_exists(dirname($targetFile)))
728 logThis("Create directory " . dirname($targetFile), $path);
729 mkdir_recursive(str_replace($argv[3], '', dirname($targetFile))); // make sure the directory exists
732 if(!file_exists($targetFile))
734 //logThis('Copying file to destination: ' . $targetFile, $path);
735 if(!copy($srcFile, $targetFile)) {
736 logThis('*** ERROR: could not copy file: ' . $targetFile, $path);
738 $copiedFiles[] = $targetFile;
741 //logThis('Skipping file: ' . $targetFile, $path);
742 //$skippedFiles[] = $targetFile;
746 //copy minimum required files including sugar_file_utils.php
747 if(file_exists("{$zipBasePath}/include/utils/sugar_file_utils.php")){
748 $destFile = clean_path(str_replace($zipBasePath, $cwd, "{$zipBasePath}/include/utils/sugar_file_utils.php"));
749 copy("{$zipBasePath}/include/utils/sugar_file_utils.php", $destFile);
751 if(file_exists('include/utils/sugar_file_utils.php')){
752 require_once('include/utils/sugar_file_utils.php');
756 $errors = preflightCheck();
757 if((count($errors) == 1)) { // only diffs
758 logThis('file preflight check passed successfully.', $path);
761 fwrite(STDERR,"\nThe user doesn't have sufficient permissions to write to database'.\n\n");
765 //If version less than 500 then look for modules to be upgraded
766 if(function_exists('set_upgrade_vars')){
769 //Initialize the session variables. If upgrade_progress.php is already created
770 //look for session vars there and restore them
771 if(function_exists('initialize_session_vars')){
772 initialize_session_vars();
775 if(!didThisStepRunBefore('preflight')){
776 set_upgrade_progress('preflight','in_progress');
777 //Quickcreatedefs on the basis of editviewdefs
778 if(substr($sugar_version,0,1) >= 5){
779 updateQuickCreateDefs();
781 set_upgrade_progress('preflight','done');
783 ////////////////COMMIT PROCESS BEGINS///////////////////////////////////////////////////////////////
784 //// MAKE BACKUPS OF TARGET FILES
786 if(!didThisStepRunBefore('commit')){
787 set_upgrade_progress('commit','in_progress','commit','in_progress');
788 if(!didThisStepRunBefore('commit','commitMakeBackupFiles')){
789 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','in_progress');
790 $errors = commitMakeBackupFiles($rest_dir, $install_file, $unzip_dir, $zip_from_dir, array());
791 set_upgrade_progress('commit','in_progress','commitMakeBackupFiles','done');
794 ///////////////////////////////////////////////////////////////////////////////
795 //// HANDLE PREINSTALL SCRIPTS
797 $file = "{$unzip_dir}/".constant('SUGARCRM_PRE_INSTALL_FILE');
801 if(!didThisStepRunBefore('commit','pre_install')){
802 set_upgrade_progress('commit','in_progress','pre_install','in_progress');
804 set_upgrade_progress('commit','in_progress','pre_install','done');
809 //Clean smarty from cache
810 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'smarty')){
811 $allModFiles = array();
812 $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'smarty',$allModFiles);
813 foreach($allModFiles as $file){
814 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
815 if(file_exists($file)){
821 //Also add the three-way merge here. The idea is after the 451 html files have
822 //been converted run the 3-way merge. If 500 then just run the 3-way merge
823 if(file_exists('modules/UpgradeWizard/SugarMerge/SugarMerge.php')){
824 set_upgrade_progress('end','in_progress','threewaymerge','in_progress');
825 require_once('modules/UpgradeWizard/SugarMerge/SugarMerge.php');
826 $merger = new SugarMerge($zipBasePath);
828 set_upgrade_progress('end','in_progress','threewaymerge','done');
830 ///////////////////////////////////////////////////////////////////////////////
831 //// COPY NEW FILES INTO TARGET INSTANCE
833 if(!didThisStepRunBefore('commit','commitCopyNewFiles')){
834 set_upgrade_progress('commit','in_progress','commitCopyNewFiles','in_progress');
835 $split = commitCopyNewFiles($unzip_dir, $zip_from_dir);
836 $copiedFiles = $split['copiedFiles'];
837 $skippedFiles = $split['skippedFiles'];
838 set_upgrade_progress('commit','in_progress','commitCopyNewFiles','done');
840 require_once(clean_path($unzip_dir.'/scripts/upgrade_utils.php'));
841 $new_sugar_version = getUpgradeVersion();
842 $origVersion = substr(preg_replace("/[^0-9]/", "", $sugar_version),0,3);
843 $destVersion = substr(preg_replace("/[^0-9]/", "", $new_sugar_version),0,3);
844 $siv_varset_1 = setSilentUpgradeVar('origVersion', $origVersion);
845 $siv_varset_2 = setSilentUpgradeVar('destVersion', $destVersion);
846 $siv_write = writeSilentUpgradeVars();
847 if(!$siv_varset_1 || !$siv_varset_2 || !$siv_write){
848 logThis("Error with silent upgrade variables: origVersion write success is ({$siv_varset_1}) ".
849 "-- destVersion write success is ({$siv_varset_2}) -- ".
850 "writeSilentUpgradeVars success is ({$siv_write}) -- ".
851 "path to cache dir is ({$GLOBALS['sugar_config']['cache_dir']})", $path);
853 require_once('modules/DynamicFields/templates/Fields/TemplateText.php');
854 ///////////////////////////////////////////////////////////////////////////////
855 /// RELOAD NEW DEFINITIONS
856 global $ACLActions, $beanList, $beanFiles;
857 include('modules/ACLActions/actiondefs.php');
858 include('include/modules.php');
859 /////////////////////////////////////////////
861 if (!function_exists("inDeveloperMode")) {
862 //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
863 function inDeveloperMode()
865 return isset($GLOBALS['sugar_config']['developerMode']) && $GLOBALS['sugar_config']['developerMode'];
868 ///////////////////////////////////////////////////////////////////////////////
869 //// HANDLE POSTINSTALL SCRIPTS
871 logThis('Starting post_install()...', $path);
873 $trackerManager = TrackerManager::getInstance();
874 $trackerManager->pause();
875 $trackerManager->unsetMonitors();
877 if(!didThisStepRunBefore('commit','post_install')){
878 $file = "$unzip_dir/" . constant('SUGARCRM_POST_INSTALL_FILE');
880 //set_upgrade_progress('commit','in_progress','post_install','in_progress');
881 $progArray['post_install']='in_progress';
882 post_install_progress($progArray,'set');
886 // cn: only run conversion if admin selects "Sugar runs SQL"
887 if(!empty($_SESSION['allTables']) && $_SESSION['schema_change'] == 'sugar')
888 executeConvertTablesSql($db->dbType, $_SESSION['allTables']);
889 //set process to done
890 $progArray['post_install']='done';
891 //set_upgrade_progress('commit','in_progress','post_install','done');
892 post_install_progress($progArray,'set');
896 logThis('Performing UWrebuild()...', $path);
900 logThis('UWrebuild() done.', $path);
902 logThis('begin check default permissions .', $path);
903 checkConfigForPermissions();
904 logThis('end check default permissions .', $path);
906 logThis('begin check logger settings .', $path);
907 checkLoggerSettings();
908 logThis('begin check logger settings .', $path);
910 logThis('begin check resource settings .', $path);
911 checkResourceSettings();
912 logThis('begin check resource settings .', $path);
915 require("sugar_version.php");
916 require('config.php');
917 global $sugar_config;
920 if(isset($sugar_config['sugarbeet']))
922 //$sugar_config['sugarbeet'] is only set in COMM
923 unset($sugar_config['sugarbeet']);
925 if(isset($sugar_config['disable_team_access_check']))
927 //$sugar_config['disable_team_access_check'] is a runtime configration,
928 //no need to write to config.php
929 unset($sugar_config['disable_team_access_check']);
931 if(!merge_passwordsetting($sugar_config, $sugar_version)) {
932 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
933 $errors[] = 'Could not write config.php!';
938 logThis('Set default_theme to Sugar', $path);
939 $sugar_config['default_theme'] = 'Sugar';
941 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
942 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
943 $errors[] = 'Could not write config.php!';
946 logThis('Set default_max_tabs to 7', $path);
947 $sugar_config['default_max_tabs'] = '7';
949 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
950 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
951 $errors[] = 'Could not write config.php!';
954 logThis('Upgrade the sugar_version', $path);
955 $sugar_config['sugar_version'] = $sugar_version;
956 if($destVersion == $origVersion)
957 require('config.php');
958 if( !write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ) {
959 logThis('*** ERROR: could not write config.php! - upgrade will fail!', $path);
960 $errors[] = 'Could not write config.php!';
963 logThis('post_install() done.', $path);
966 ///////////////////////////////////////////////////////////////////////////////
967 //// REGISTER UPGRADE
969 logThis('Registering upgrade with UpgradeHistory', $path);
970 if(!didThisStepRunBefore('commit','upgradeHistory')){
971 set_upgrade_progress('commit','in_progress','upgradeHistory','in_progress');
972 $file_action = "copied";
973 // if error was encountered, script should have died before now
974 $new_upgrade = new UpgradeHistory();
975 $new_upgrade->filename = $install_file;
976 $new_upgrade->md5sum = md5_file($install_file);
977 $new_upgrade->name = $zip_from_dir;
978 $new_upgrade->description = $manifest['description'];
979 $new_upgrade->type = 'patch';
980 $new_upgrade->version = $sugar_version;
981 $new_upgrade->status = "installed";
982 $new_upgrade->manifest = (!empty($_SESSION['install_manifest']) ? $_SESSION['install_manifest'] : '');
984 if($new_upgrade->description == null){
985 $new_upgrade->description = "Silent Upgrade was used to upgrade the instance";
988 $new_upgrade->description = $new_upgrade->description." Silent Upgrade was used to upgrade the instance.";
990 $new_upgrade->save();
991 set_upgrade_progress('commit','in_progress','upgradeHistory','done');
992 set_upgrade_progress('commit','done','commit','done');
996 //Clean modules from cache
997 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'smarty')){
998 $allModFiles = array();
999 $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'smarty',$allModFiles);
1000 foreach($allModFiles as $file){
1001 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1002 if(file_exists($file)){
1007 //delete cache/modules before rebuilding the relations
1008 //Clean modules from cache
1009 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'modules')){
1010 $allModFiles = array();
1011 $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'modules',$allModFiles);
1012 foreach($allModFiles as $file){
1013 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1014 if(file_exists($file)){
1020 //delete cache/themes
1021 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'themes')){
1022 $allModFiles = array();
1023 $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'themes',$allModFiles);
1024 foreach($allModFiles as $file){
1025 //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
1026 if(file_exists($file)){
1032 if(!isset($_REQUEST['silent'])){
1033 $_REQUEST['silent'] = true;
1035 else if(isset($_REQUEST['silent']) && $_REQUEST['silent'] != true){
1036 $_REQUEST['silent'] = true;
1039 //logThis('Checking for leads_assigned_user relationship and if not found then create.', $path);
1040 @createMissingRels();
1041 //logThis('Checked for leads_assigned_user relationship.', $path);
1043 //// run fix on dropdown lists that may have been incorrectly named
1044 //fix_dropdown_list();
1047 set_upgrade_progress('end','in_progress','end','in_progress');
1048 /////////////////////////Old Logger settings///////////////////////////////////////
1049 ///////////////////////////////////////////////////////////////////////////////
1051 if(function_exists('deleteCache')){
1052 set_upgrade_progress('end','in_progress','deleteCache','in_progress');
1054 set_upgrade_progress('end','in_progress','deleteCache','done');
1057 ///////////////////////////////////////////////////////////////////////////////
1058 //// HANDLE REMINDERS
1059 if(empty($errors)) {
1060 commitHandleReminders($skippedFiles, $path);
1063 if(file_exists(clean_path(getcwd()).'/original451files')){
1064 rmdir_recursive(clean_path(getcwd()).'/original451files');
1067 require_once('modules/Administration/Administration.php');
1068 $admin = new Administration();
1069 $admin->saveSetting('system','adminwizard',1);
1071 logThis('Upgrading user preferences start .', $path);
1072 if(function_exists('upgradeUserPreferences')){
1073 upgradeUserPreferences();
1075 logThis('Upgrading user preferences finish .', $path);
1078 require_once('modules/Administration/upgrade_custom_relationships.php');
1079 upgrade_custom_relationships();
1083 //check to see if there are any new files that need to be added to systems tab
1084 //retrieve old modules list
1085 logThis('check to see if new modules exist',$path);
1086 $oldModuleList = array();
1087 $newModuleList = array();
1088 include($argv[3].'/include/modules.php');
1089 $oldModuleList = $moduleList;
1090 include('include/modules.php');
1091 $newModuleList = $moduleList;
1093 //include tab controller
1094 require_once('modules/MySettings/TabController.php');
1095 $newTB = new TabController();
1097 //make sure new modules list has a key we can reference directly
1098 $newModuleList = $newTB->get_key_array($newModuleList);
1099 $oldModuleList = $newTB->get_key_array($oldModuleList);
1101 //iterate through list and remove commonalities to get new modules
1102 foreach ($newModuleList as $remove_mod){
1103 if(in_array($remove_mod, $oldModuleList)){
1104 unset($newModuleList[$remove_mod]);
1108 $must_have_modules= array(
1109 'Activities'=>'Activities',
1110 'Calendar'=>'Calendar',
1111 'Reports' => 'Reports',
1112 'Quotes' => 'Quotes',
1113 'Products' => 'Products',
1114 'Forecasts' => 'Forecasts',
1115 'Contracts' => 'Contracts',
1116 'KBDocuments' => 'KBDocuments'
1118 $newModuleList = array_merge($newModuleList,$must_have_modules);
1120 //new modules list now has left over modules which are new to this install, so lets add them to the system tabs
1121 logThis('new modules to add are '.var_export($newModuleList,true),$path);
1123 //grab the existing system tabs
1124 $tabs = $newTB->get_system_tabs();
1126 //add the new tabs to the array
1127 foreach($newModuleList as $nm ){
1131 //now assign the modules to system tabs
1132 $newTB->set_system_tabs($tabs);
1133 logThis('module tabs updated',$path);
1136 //Also set the tracker settings if flavor conversion ce->pro or ce->ent
1137 if(isset($_SESSION['current_db_version']) && isset($_SESSION['target_db_version'])){
1138 if($_SESSION['current_db_version'] == $_SESSION['target_db_version']){
1139 $_REQUEST['upgradeWizard'] = true;
1141 include('include/Smarty/internals/core.write_file.php');
1143 $db =& DBManagerFactory::getInstance();
1145 //Also set license information
1146 $admin = new Administration();
1147 $category = 'license';
1149 $admin->saveSetting($category, 'users', $value);
1150 $key = array('num_lic_oc','key','expire_date');
1152 foreach($key as $k){
1153 $admin->saveSetting($category, $k, $value);
1159 $phpErrors = ob_get_contents();
1161 logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
1163 if(count($errors) > 0) {
1164 foreach($errors as $error) {
1165 logThis("****** SilentUpgrade ERROR: {$error}", $path);
1172 //ELSE if DCE_INSTANCE
1173 echo "RUNNING DCE UPGRADE\n";
1175 } //END of big if-else block for DCE_INSTANCE
1179 * repairTableDictionaryExtFile
1181 * There were some scenarios in 6.0.x whereby the files loaded in the extension tabledictionary.ext.php file
1182 * did not exist. This would cause warnings to appear during the upgrade. As a result, this
1183 * function scans the contents of tabledictionary.ext.php and then remove entries where the file does exist.
1185 function repairTableDictionaryExtFile()
1187 $tableDictionaryExtDirs = array('custom/Extension/application/Ext/TableDictionary', 'custom/application/Ext/TableDictionary');
1189 foreach($tableDictionaryExtDirs as $tableDictionaryExt)
1192 if(is_dir($tableDictionaryExt) && is_writable($tableDictionaryExt)){
1193 $dir = dir($tableDictionaryExt);
1194 while(($entry = $dir->read()) !== false)
1196 $entry = $tableDictionaryExt . '/' . $entry;
1197 if(is_file($entry) && preg_match('/\.php$/i', $entry) && is_writeable($entry))
1200 if(function_exists('sugar_fopen'))
1202 $fp = @sugar_fopen($entry, 'r');
1204 $fp = fopen($entry, 'r');
1213 while($line = fgets($fp))
1215 if(preg_match('/\s*include\s*\(\s*[\'|\"](.*?)[\"|\']\s*\)\s*;/', $line, $match))
1217 if(!file_exists($match[1]))
1234 if(function_exists('sugar_fopen'))
1236 $fp = @sugar_fopen($entry, 'w');
1238 $fp = fopen($entry, 'w');
1241 if($fp && fwrite($fp, $contents))