3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 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("upload://upgrades/{$subdir}")) {
56 mkdir_recursive("upload://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',
111 'suffix' => '', // bug51583, change default suffix to blank for backwards comptability
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(!isset($a['id']) && empty($a['id']) ){
166 $qRel = "INSERT INTO relationships (id,relationship_name, lhs_module, lhs_table, lhs_key, rhs_module, rhs_table, rhs_key, join_table, join_key_lhs, join_key_rhs, relationship_type, relationship_role_column, relationship_role_column_value, reverse, deleted)
167 VALUES ('{$guid}', '{$relObjName}_assigned_user','Users','users','id','{$relModName}','{$relObjName}','assigned_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
168 $GLOBALS['db']->query($qRel);
171 $guid = create_guid();
172 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_modified_user'";
173 $result= $GLOBALS['db']->query($query, true);
175 $a = $GLOBALS['db']->fetchByAssoc($result);
176 if(!isset($a['id']) && empty($a['id']) ){
177 $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)
178 VALUES ('{$guid}', '{$relObjName}_modified_user','Users','users','id','{$relModName}','{$relObjName}','modified_user_id',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
179 $GLOBALS['db']->query($qRel);
182 $guid = create_guid();
183 $query = "SELECT id FROM relationships WHERE relationship_name = '{$relObjName}_created_by'";
184 $result= $GLOBALS['db']->query($query, true);
186 $a = $GLOBALS['db']->fetchByAssoc($result);
187 if(!isset($a['id']) && empty($a['id']) ){
188 $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)
189 VALUES ('{$guid}', '{$relObjName}_created_by','Users','users','id','{$relModName}','{$relObjName}','created_by',NULL,NULL,NULL,'one-to-many',NULL,NULL,'0','0')";
190 $GLOBALS['db']->query($qRel);
193 //Also add tracker perf relationship
198 * This function will merge password default settings into config file
199 * @param $sugar_config
200 * @param $sugar_version
201 * @return bool true if successful
203 function merge_passwordsetting($sugar_config, $sugar_version) {
204 $passwordsetting_defaults = array(
205 'passwordsetting' => array (
206 'SystemGeneratedPasswordON' => '',
207 'generatepasswordtmpl' => '',
208 'lostpasswordtmpl' => '',
209 'forgotpasswordON' => false,
210 'linkexpiration' => '1',
211 'linkexpirationtime' => '30',
212 'linkexpirationtype' => '1',
213 'systexpiration' => '0',
214 'systexpirationtime' => '',
215 'systexpirationtype' => '0',
216 'systexpirationlogin' => '',
221 $sugar_config = sugarArrayMerge($passwordsetting_defaults, $sugar_config );
223 // need to override version with default no matter what
224 $sugar_config['sugar_version'] = $sugar_version;
226 ksort( $sugar_config );
228 if( write_array_to_file( "sugar_config", $sugar_config, "config.php" ) ){
236 function addDefaultModuleRoles($defaultRoles = array()) {
237 foreach($defaultRoles as $roleName=>$role){
238 foreach($role as $category=>$actions){
239 foreach($actions as $name=>$access_override){
240 $query = "SELECT * FROM acl_actions WHERE name='$name' AND category = '$category' AND acltype='$roleName' AND deleted=0 ";
241 $result = $GLOBALS['db']->query($query);
242 //only add if an action with that name and category don't exist
243 $row=$GLOBALS['db']->fetchByAssoc($result);
245 $guid = create_guid();
246 $currdate = gmdate($GLOBALS['timedate']->get_db_date_time_format());
247 $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')";
248 $GLOBALS['db']->query($query);
255 function verifyArguments($argv,$usage_dce,$usage_regular){
257 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
258 if(isset($argv[3])) {
259 if(is_dir($argv[3])) {
263 echo "*******************************************************************************\n";
264 echo "*** ERROR: 3rd parameter must be a valid directory. Tried to cd to [ {$argv[3]} ].\n";
269 //check if this is an instance
270 if(is_file("{$cwd}/ini_setup.php")){
271 // this is an instance
272 $upgradeType = constant('DCE_INSTANCE');
273 //now that this is dce instance we want to make sure that there are
275 if(count($argv) < 7) {
276 echo "*******************************************************************************\n";
277 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 7.\n";
282 // this is an instance
283 if(!is_dir($argv[1])) { // valid directory . template path?
284 echo "*******************************************************************************\n";
285 echo "*** ERROR: First argument must be a full path to the template. Got [ {$argv[1]} ].\n";
291 else if(is_file("{$cwd}/include/entryPoint.php")) {
292 //this should be a regular sugar install
293 $upgradeType = constant('SUGARCRM_INSTALL');
294 //check if this is a valid zip file
295 if(!is_file($argv[1])) { // valid zip?
296 echo "*******************************************************************************\n";
297 echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
302 if(count($argv) < 5) {
303 echo "*******************************************************************************\n";
304 echo "*** ERROR: Missing required parameters. Received ".count($argv)." argument(s), require 5.\n";
311 //this should be a regular sugar install
312 echo "*******************************************************************************\n";
313 echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
317 if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
318 require_once($argv[7].'SugarTemplateUtilties.php');
324 function upgradeDCEFiles($argv,$instanceUpgradePath){
325 //copy and update following files from upgrade package
326 $upgradeTheseFiles = array('cron.php','download.php','index.php','install.php','soap.php','sugar_version.php','vcal_server.php');
327 foreach($upgradeTheseFiles as $file){
328 $srcFile = clean_path("{$instanceUpgradePath}/$file");
329 $destFile = clean_path("{$argv[3]}/$file");
330 if(file_exists($srcFile)){
331 if(!is_dir(dirname($destFile))) {
332 mkdir_recursive(dirname($destFile)); // make sure the directory exists
334 copy_recursive($srcFile,$destFile);
335 $_GET['TEMPLATE_PATH'] = $destFile;
336 $_GET['CONVERT_FILE_ONLY'] = true;
337 if(!class_exists('TemplateConverter')){
338 include($argv[7].'templateConverter.php');
340 TemplateConverter::convertFile($_GET['TEMPLATE_PATH']);
350 function threeWayMerge(){
351 //using threeway merge apis
353 //// END UTILITIES THAT MUST BE LOCAL :(
354 ///////////////////////////////////////////////////////////////////////////////
357 // only run from command line
358 if(isset($_SERVER['HTTP_USER_AGENT'])) {
359 fwrite(STDERR, 'This utility may only be run from the command line or command prompt.');
362 //Clean_string cleans out any file passed in as a parameter
363 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
366 ///////////////////////////////////////////////////////////////////////////////
369 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance]
371 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
372 php.exe followed by -f silentUpgrade.php and the arguments.
375 [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
376 [Old Template path] [skipdbupgrade] [exitOrContinue]
379 New Template Path or Upgrade Package : Upgrade package name. Template2 (upgrade to)location.
380 silentupgrade.log : Silent Upgarde log file.
381 Sugar451e/DCE : Sugar or DCE Instance instance being upgraded.
382 Old Template path : Template1 (upgrade from) Instance is being upgraded.
383 skipDBupgrade : If set to Yes then silentupgrade will only upgrade files. Default is No.
384 exitOnConflicts : If set to No and conflicts are found then Upgrade continues. Default Yes.
385 pathToDCEClient : This is path to to DCEClient directory
389 $usage_regular =<<<eoq2
390 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
392 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
393 php.exe followed by -f silentUpgrade.php and the arguments.
396 [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
399 upgradeZipFile : Upgrade package file.
400 logFile : Silent Upgarde log file.
401 pathToSugarInstance : Sugar Instance instance being upgraded.
402 admin-user : admin user performing the upgrade
405 ///////////////////////////////////////////////////////////////////////////////
409 ///////////////////////////////////////////////////////////////////////////////
410 //// STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
411 if(!defined('sugarEntry')) define('sugarEntry', true);
414 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
415 $_SESSION['silent_upgrade'] = true;
416 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
419 $_REQUEST['addTaskReminder'] = 'remind';
422 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
423 define('DCE_INSTANCE', 'DCE_Instance');
426 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
428 $upgradeType = verifyArguments($argv,$usage_dce,$usage_regular);
430 ///////////////////////////////////////////////////////////////////////////////
431 ////// Verify that all the arguments are appropriately placed////////////////
433 ///////////////////////////////////////////////////////////////////////////////
434 //// PREP LOCALLY USED PASSED-IN VARS & CONSTANTS
435 //$GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
436 //require_once('/var/www/html/eddy/sugarnode/SugarTemplateUtilities.php');
438 $path = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
439 //$db = &DBManagerFactory::getInstance(); //<---------
442 //$UWstrings = return_module_language('en_us', 'UpgradeWizard');
443 //$adminStrings = return_module_language('en_us', 'Administration');
444 //$mod_strings = array_merge($adminStrings, $UWstrings);
445 $subdirs = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
447 //$_REQUEST['zip_from_dir'] = $zip_from_dir;
449 define('SUGARCRM_PRE_INSTALL_FILE', 'scripts/pre_install.php');
450 define('SUGARCRM_POST_INSTALL_FILE', 'scripts/post_install.php');
451 define('SUGARCRM_PRE_UNINSTALL_FILE', 'scripts/pre_uninstall.php');
452 define('SUGARCRM_POST_UNINSTALL_FILE', 'scripts/post_uninstall.php');
457 echo "********************************************************************\n";
458 echo "***************This Upgrade process may take sometime***************\n";
459 echo "********************************************************************\n";
462 global $sugar_config;
463 $isDCEInstance = false;
467 if($upgradeType == constant('DCE_INSTANCE')){
468 //$instanceUpgradePath = "{$argv[1]}/DCEUpgrade/{$zip_from_dir}";
469 //$instanceUpgradePath = "{$argv[1]}";
470 include ("ini_setup.php");
472 //get new template path for use in later processing
473 $dceupgrade_pos = strpos($argv[1], '/DCEUpgrade');
474 $newtemplate_path = substr($argv[1], 0, $dceupgrade_pos);
476 require("{$argv[4]}/sugar_version.php");
477 global $sugar_version;
479 //load up entrypoint from original template
480 require_once("{$argv[4]}/include/entryPoint.php");
481 require_once("{$argv[4]}/include/utils/zip_utils.php");
482 require_once("{$argv[4]}/modules/Administration/UpgradeHistory.php");
483 // We need to run the silent upgrade as the admin user,
484 global $current_user;
485 $current_user = new User();
486 $current_user->retrieve('1');
488 //This is DCE instance
489 global $sugar_config;
490 global $sugar_version;
491 // require_once("{$cwd}/sugar_version.php"); //provides instance version, flavor etc..
492 //provides instance version, flavor etc..
493 $isDCEInstance = true;
494 prepSystemForUpgradeSilent();
496 /////retrieve admin user
497 $configOptions = $sugar_config['dbconfig'];
499 $GLOBALS['log'] = LoggerManager::getLogger('SugarCRM');
500 $db = &DBManagerFactory::getInstance();
501 ///////////////////////////////////////////////////////////////////////////////
502 //// MAKE SURE PATCH IS COMPATIBLE
504 if(is_file("{$argv[1]}/manifest.php")) {
505 // provides $manifest array
506 include("{$argv[1]}/manifest.php");
508 //If Instance then the files will be accessed from Template/DCEUpgrade folder
510 if( isset( $manifest['copy_files']['from_dir'] ) && $manifest['copy_files']['from_dir'] != "" ){
511 $zip_from_dir = $manifest['copy_files']['from_dir'];
513 $instanceUpgradePath = "{$argv[1]}/{$zip_from_dir}";
514 global $instancePath;
515 $instancePath = $instanceUpgradePath;
516 $_SESSION['instancePath'] = $instancePath;
517 if(file_exists("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php")){
518 require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
521 require_once("{$argv[4]}/modules/UpgradeWizard/uw_utils.php");
523 if(function_exists('set_upgrade_vars')){
526 if(is_file("$argv[1]/manifest.php")) {
527 // provides $manifest array
528 //include("$instanceUpgradePath/manifest.php");
529 if(!isset($manifest)) {
530 fwrite(STDERR, "\nThe patch did not contain a proper manifest.php file. Cannot continue.\n\n");
533 $error = validate_manifest($manifest);
535 $error = strip_tags(br2nl($error));
536 fwrite(STDERR,"\n{$error}\n\nFAILURE\n");
541 fwrite(STDERR, "\nThe patch did not contain a proper manifest.php file. Cannot continue.\n\n");
545 $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');
546 $_SESSION['upgrade_from_flavor'] = $manifest['name'];
548 //get the latest uw_utils.php
549 // require_once("{$instanceUpgradePath}/modules/UpgradeWizard/uw_utils.php");
550 logThis("*** SILENT DCE UPGRADE INITIATED.", $path);
551 logThis("*** UpgradeWizard Upgraded ", $path);
552 $_SESSION['sugar_version_file'] = '';
553 $srcFile = clean_path("{$instanceUpgradePath}/sugar_version.php");
554 if(file_exists($srcFile)) {
555 logThis('Save the version file in session variable', $path);
556 $_SESSION['sugar_version_file'] = $srcFile;
561 //check exit on conflicts
562 $exitOnConflict = 'yes'; //default
563 if($argv[5] != null && !empty($argv[5])){
564 if(strtolower($argv[5]) == 'no'){
565 $exitOnConflict = 'no'; //override
568 if($exitOnConflict == 'yes'){
569 $customFiles = array();
570 $customFiles = findAllFiles(clean_path("{$argv[3]}/custom"), $customFiles);
571 if($customFiles != null){
572 logThis("*** **************************** ****", $path);
573 logThis("*** START LOGGING CUSTOM FILES ****", $path);
574 $existsCustomFile = false;
575 foreach($customFiles as $file) {
576 $srcFile = clean_path($file);
577 //$targetFile = clean_path(getcwd() . '/' . $srcFile);
578 if (strpos($srcFile,".svn") !== false) {
582 $existsCustomFile = true;
583 //log the custom file in
584 logThis($file, $path);
587 logThis("*** END LOGGING CUSTOM FILES ****", $path);
588 logThis("*** **************************** ****", $path);
589 if($existsCustomFile){
590 echo 'Stop and Exit Upgrade. There are customized files. Take a look in the upgrade log';
591 logThis("Stop and Exit Upgrade. There are customized files. Take a look in the upgrade log", $path);
595 upgradeDCEFiles($argv,$instanceUpgradePath);
599 //copy and update following files from upgrade package
600 upgradeDCEFiles($argv,$instanceUpgradePath);
604 //copy and update following files from upgrade package
605 upgradeDCEFiles($argv,$instanceUpgradePath);
609 $unzip_dir = $argv[1];
610 $_SESSION['unzip_dir'] = $unzip_dir;
613 } //END OF BIG if block
616 ///////////////////////////////////////////////////////////////////////////////
618 $phpErrors = ob_get_contents();
620 logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
622 if(count($errors) > 0) {
623 foreach($errors as $error) {
624 logThis("****** SilentUpgrade ERROR: {$error}", $path);