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 //rebuild all relationships...
149 function rebuildRelations($pre_path = ''){
150 $_REQUEST['silent'] = true;
151 include($pre_path.'modules/Administration/RebuildRelationship.php');
152 $_REQUEST['upgradeWizard'] = true;
153 include($pre_path.'modules/ACL/install_actions.php');
156 function createMissingRels(){
157 $relForObjects = array('leads'=>'Leads','campaigns'=>'Campaigns','prospects'=>'Prospects');
158 foreach($relForObjects as $relObjName=>$relModName){
160 $guid = create_guid();
161 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_assigned_user'";
162 $result= $GLOBALS['db']->query($query, true);
164 $a = $GLOBALS['db']->fetchByAssoc($result);
165 if($GLOBALS['db']->checkError()){
168 if(!isset($a['id']) && empty($a['id']) ){
169 $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)
170 VALUES ('{$guid}', '{$relObjName}_assigned_user','Users','users','id','{$relModName}','{$relObjName}','assigned_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
171 $GLOBALS['db']->query($qRel);
172 if($GLOBALS['db']->checkError()){
177 $guid = create_guid();
178 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_modified_user'";
179 $result= $GLOBALS['db']->query($query, true);
180 if($GLOBALS['db']->checkError()){
184 $a = $GLOBALS['db']->fetchByAssoc($result);
185 if(!isset($a['id']) && empty($a['id']) ){
186 $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)
187 VALUES ('{$guid}', '{$relObjName}_modified_user','Users','users','id','{$relModName}','{$relObjName}','modified_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
188 $GLOBALS['db']->query($qRel);
189 if($GLOBALS['db']->checkError()){
194 $guid = create_guid();
195 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
196 $result= $GLOBALS['db']->query($query, true);
198 $a = $GLOBALS['db']->fetchByAssoc($result);
199 if(!isset($a['id']) && empty($a['id']) ){
200 $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)
201 VALUES ('{$guid}', '{$relObjName}_created_by','Users','users','id','{$relModName}','{$relObjName}','created_by',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
202 $GLOBALS['db']->query($qRel);
203 if($GLOBALS['db']->checkError()){
208 //Also add tracker perf relationship
213 * This function will merge password default settings into config file
214 * @param $sugar_config
215 * @param $sugar_version
216 * @return bool true if successful
218 function merge_passwordsetting($sugar_config, $sugar_version) {
219 $passwordsetting_defaults = array(
220 'passwordsetting' => array (
221 'SystemGeneratedPasswordON' => '',
222 'generatepasswordtmpl' => '',
223 'lostpasswordtmpl' => '',
224 'forgotpasswordON' => false,
225 'linkexpiration' => '1',
226 'linkexpirationtime' => '30',
227 'linkexpirationtype' => '1',
228 'systexpiration' => '0',
229 'systexpirationtime' => '',
230 'systexpirationtype' => '0',
231 'systexpirationlogin' => '',
236 $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
238 // need to override version with default no matter what
239 $sugar_config['sugar_version'] = $sugar_version;
241 ksort( $sugar_config );
243 if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
251 function addDefaultModuleRoles($defaultRoles = array()) {
252 foreach($defaultRoles as $roleName=>$role){
253 foreach($role as $category=>$actions){
254 foreach($actions as $name=>$access_override){
255 $query = "SELECT * FROM acl_actions WHERE name='$name' AND category = '$category' AND acltype='$roleName' AND deleted=0 ";
256 $result = $GLOBALS['db']->query($query);
257 //only add if an action with that name and category don't exist
258 $row=$GLOBALS['db']->fetchByAssoc($result);
260 $guid = create_guid();
261 $currdate = gmdate($GLOBALS['timedate']->get_db_date_time_format());
262 $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')";
263 $GLOBALS['db']->query($query);
264 if($GLOBALS['db']->checkError()){
273 function verifyArguments($argv,$usage_dce,$usage_regular){
275 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
276 if(isset($argv[3])) {
277 if(is_dir($argv[3])) {
281 echo "*******************************************************************************\n";
282 echo "*** ERROR: 3rd parameter must be a valid directory. Tried to cd to [ {$argv[3]} ].\n";
287 //check if this is an instance
288 if(is_file("{$cwd}/ini_setup.php")){
289 // this is an instance
290 $upgradeType = constant('DCE_INSTANCE');
291 //now that this is dce instance we want to make sure that there are
293 if(count($argv) < 7) {
294 echo "*******************************************************************************\n";
295 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 7.\n";
300 // this is an instance
301 if(!is_dir($argv[1])) { // valid directory . template path?
302 echo "*******************************************************************************\n";
303 echo "*** ERROR: First argument must be a full path to the template. Got [ {$argv[1]} ].\n";
309 else if(is_file("{$cwd}/include/entryPoint.php")) {
310 //this should be a regular sugar install
311 $upgradeType = constant('SUGARCRM_INSTALL');
312 //check if this is a valid zip file
313 if(!is_file($argv[1])) { // valid zip?
314 echo "*******************************************************************************\n";
315 echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
320 if(count($argv) < 5) {
321 echo "*******************************************************************************\n";
322 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 5.\n";
329 //this should be a regular sugar install
330 echo "*******************************************************************************\n";
331 echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
335 if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
336 require_once($argv[7].'SugarTemplateUtilties.php');
342 function upgradeDCEFiles($argv,$instanceUpgradePath){
343 //copy and update following files from upgrade package
344 $upgradeTheseFiles = array('cron.php','download.php','index.php','install.php','soap.php','sugar_version.php','vcal_server.php');
345 foreach($upgradeTheseFiles as $file){
346 $srcFile = clean_path("{$instanceUpgradePath}/$file");
347 $destFile = clean_path("{$argv[3]}/$file");
348 if(file_exists($srcFile)){
349 if(!is_dir(dirname($destFile))) {
350 mkdir_recursive(dirname($destFile)); // make sure the directory exists
352 copy_recursive($srcFile,$destFile);
353 $_GET['TEMPLATE_PATH'] = $destFile;
354 $_GET['CONVERT_FILE_ONLY'] = true;
355 if(!class_exists('TemplateConverter')){
356 include($argv[7].'templateConverter.php');
358 TemplateConverter::convertFile($_GET['TEMPLATE_PATH']);
368 function threeWayMerge(){
369 //using threeway merge apis
371 //// END UTILITIES THAT MUST BE LOCAL :(
372 ///////////////////////////////////////////////////////////////////////////////
375 // only run from command line
376 if(isset($_SERVER['HTTP_USER_AGENT'])) {
377 fwrite(STDERR, 'This utility may only be run from the command line or command prompt.');
380 //Clean_string cleans out any file passed in as a parameter
381 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
384 ///////////////////////////////////////////////////////////////////////////////
387 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
389 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
390 php.exe followed by -f silentUpgrade.php and the arguments.
393 [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
394 [Old Template path] [skipdbupgrade] [exitOrContinue]
397 New Template Path or Upgrade Package : Upgrade package name. Template2 (upgrade to)location.
398 silentupgrade.log : Silent Upgarde log file.
399 Sugar451e/DCE : Sugar or DCE Instance instance being upgraded.
400 Old Template path : Template1 (upgrade from) Instance is being upgraded.
401 skipDBupgrade : If set to Yes then silentupgrade will only upgrade files. Default is No.
402 exitOnConflicts : If set to No and conflicts are found then Upgrade continues. Default Yes.
403 pathToDCEClient : This is path to to DCEClient directory
407 $usage_regular =<<<eoq2
408 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
410 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
411 php.exe followed by -f silentUpgrade.php and the arguments.
414 [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
417 upgradeZipFile : Upgrade package file.
418 logFile : Silent Upgarde log file.
419 pathToSugarInstance : Sugar Instance instance being upgraded.
420 admin-user : admin user performing the upgrade
423 ///////////////////////////////////////////////////////////////////////////////
427 ///////////////////////////////////////////////////////////////////////////////
428 //// STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
429 if(!defined('sugarEntry')) define('sugarEntry', true);
432 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
433 $_SESSION['silent_upgrade'] = true;
434 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
437 $_REQUEST['addTaskReminder'] = 'remind';
440 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
441 define('DCE_INSTANCE', 'DCE_Instance');
444 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
446 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
448 ///////////////////////////////////////////////////////////////////////////////
449 ////// Verify that all the arguments are appropriately placed////////////////
451 ///////////////////////////////////////////////////////////////////////////////
452 //// PREP LOCALLY USED PASSED-IN VARS & CONSTANTS
453 //$GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
454 //require_once('/var/www/html/eddy/sugarnode/SugarTemplateUtilities.php');
456 $path = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
457 //$db = &DBManagerFactory::getInstance(); //<---------
460 //$UWstrings = return_module_language('en_us', 'UpgradeWizard');
461 //$adminStrings = return_module_language('en_us', 'Administration');
462 //$mod_strings = array_merge($adminStrings, $UWstrings);
463 $subdirs = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
465 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
467 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
468 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
469 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
470 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
475 echo "********************************************************************\n";
476 echo "***************This Upgrade process may take sometime***************\n";
477 echo "********************************************************************\n";
480 global $sugar_config;
481 $isDCEInstance = false;
485 if($upgradeType == constant('DCE_INSTANCE')){
486 //$instanceUpgradePath = "{$argv[1]}/DCEUpgrade/{$zip_from_dir}";
487 //$instanceUpgradePath = "{$argv[1]}";
488 include ("ini_setup.php");
490 //get new template path for use in later processing
491 $dceupgrade_pos = strpos($argv[1], '/DCEUpgrade');
492 $newtemplate_path = substr($argv[1], 0, $dceupgrade_pos);
494 require("{$argv[4]}/sugar_version.php");
495 global $sugar_version;
497 //load up entrypoint from original template
498 require_once("{$argv[4]}/include/entryPoint.php");
499 require_once("{$argv[4]}/include/utils/zip_utils.php");
500 require_once("{$argv[4]}/modules/Administration/UpgradeHistory.php");
501 // We need to run the silent upgrade as the admin user,
502 global $current_user;
503 $current_user = new User();
504 $current_user->retrieve('1');
506 //This is DCE instance
507 global $sugar_config;
508 global $sugar_version;
509 // require_once("{$cwd}/sugar_version.php"); //provides instance version, flavor etc..
510 //provides instance version, flavor etc..
511 $isDCEInstance = true;
512 prepSystemForUpgradeSilent();
514 /////retrieve admin user
515 $configOptions = $sugar_config['dbconfig'];
517 $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
518 $db = &DBManagerFactory::getInstance();
519 ///////////////////////////////////////////////////////////////////////////////
520 //// MAKE SURE PATCH IS COMPATIBLE
522 if(is_file("{$argv[1]}/manifest.php")) {
523 // provides $manifest array
524 include("{$argv[1]}/manifest.php");
526 //If Instance then the files will be accessed from Template/DCEUpgrade folder
528 if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
529 $zip_from_dir = $manifest['copy_files']['from_dir'];
531 $instanceUpgradePath = "{$argv[1]}/{$zip_from_dir}";
532 global $instancePath;
533 $instancePath = $instanceUpgradePath;
534 $_SESSION['instancePath'] = $instancePath;
535 if(file_exists("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php")){
536 require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
539 require_once("{$argv[4]}/modules/UpgradeWizard/uw_utils.php");
541 if(function_exists('set_upgrade_vars')){
544 if(is_file("$argv[1]/manifest.php")) {
545 // provides $manifest array
546 //include("$instanceUpgradePath/manifest.php");
547 if(!isset($manifest)) {
548 fwrite(STDERR, "\nThe patch did not contain a proper manifest.php file. Cannot continue.\n\n");
551 $error = validate_manifest($manifest);
553 $error = strip_tags(br2nl($error));
554 fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
559 fwrite(STDERR, "\nThe patch did not contain a proper manifest.php file. Cannot continue.\n\n");
563 $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');
564 $_SESSION['upgrade_from_flavor'] = $manifest['name'];
566 //get the latest uw_utils.php
567 // require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
568 logThis("*** SILENT DCE UPGRADE INITIATED.", $path);
569 logThis("*** UpgradeWizard Upgraded ", $path);
570 $_SESSION['sugar_version_file'] = '';
571 $srcFile = clean_path("{$instanceUpgradePath}/sugar_version.php");
572 if(file_exists($srcFile)) {
573 logThis('Save the version file in session variable', $path);
574 $_SESSION['sugar_version_file'] = $srcFile;
579 //check exit on conflicts
580 $exitOnConflict = 'yes'; //default
581 if($argv[5] != null && !empty($argv[5])){
582 if(strtolower($argv[5]) == 'no'){
583 $exitOnConflict = 'no'; //override
586 if($exitOnConflict == 'yes'){
587 $customFiles = array();
588 $customFiles = findAllFiles(clean_path("{$argv[3]}/custom"), $customFiles);
589 if($customFiles != null){
590 logThis("*** **************************** ****", $path);
591 logThis("*** START LOGGING CUSTOM FILES ****", $path);
592 $existsCustomFile = false;
593 foreach($customFiles as $file) {
594 $srcFile = clean_path($file);
595 //$targetFile = clean_path(getcwd() . '/' . $srcFile);
596 if (strpos($srcFile,".svn") !== false) {
600 $existsCustomFile = true;
601 //log the custom file in
602 logThis($file, $path);
605 logThis("*** END LOGGING CUSTOM FILES ****", $path);
606 logThis("*** **************************** ****", $path);
607 if($existsCustomFile){
608 echo 'Stop and Exit Upgrade. There are customized files. Take a look in the upgrade log';
609 logThis("Stop and Exit Upgrade. There are customized files. Take a look in the upgrade log", $path);
613 upgradeDCEFiles($argv,$instanceUpgradePath);
617 //copy and update following files from upgrade package
618 upgradeDCEFiles($argv,$instanceUpgradePath);
622 //copy and update following files from upgrade package
623 upgradeDCEFiles($argv,$instanceUpgradePath);
627 $unzip_dir = $argv[1];
628 $_SESSION['unzip_dir'] = $unzip_dir;
631 } //END OF BIG if block
634 ///////////////////////////////////////////////////////////////////////////////
636 $phpErrors = ob_get_contents();
638 logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
640 if(count($errors) > 0) {
641 foreach($errors as $error) {
642 logThis("****** SilentUpgrade ERROR: {$error}", $path);