]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UpgradeWizard/silentUpgrade_step2.php
Release 6.5.0
[Github/sugarcrm.git] / modules / UpgradeWizard / silentUpgrade_step2.php
1 <?php
2
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2012 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  //Bug 24890, 24892. default_permissions not written to config.php. Following function checks and if
49  //no found then adds default_permissions to the config file.
50  function checkConfigForPermissions(){
51      if(file_exists(getcwd().'/config.php')){
52          require(getcwd().'/config.php');
53      }
54      global $sugar_config;
55      if(!isset($sugar_config['default_permissions'])){
56              $sugar_config['default_permissions'] = array (
57                      'dir_mode' => 02770,
58                      'file_mode' => 0660,
59                      'user' => '',
60                      'group' => '',
61              );
62          ksort($sugar_config);
63          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
64                 //writing to the file
65                 }
66      }
67 }
68
69 function checkLoggerSettings(){
70         if(file_exists(getcwd().'/config.php')){
71          require(getcwd().'/config.php');
72      }
73     global $sugar_config;
74         if(!isset($sugar_config['logger'])){
75             $sugar_config['logger'] =array (
76                         'level'=>'fatal',
77                     'file' =>
78                      array (
79                       'ext' => '.log',
80                       'name' => 'sugarcrm',
81                       'dateFormat' => '%c',
82                       'maxSize' => '10MB',
83                       'maxLogs' => 10,
84                       'suffix' => '', // bug51583, change default suffix to blank for backwards comptability
85                     ),
86                   );
87                  ksort($sugar_config);
88          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
89                 //writing to the file
90                 }
91          }
92 }
93
94 function checkResourceSettings(){
95         if(file_exists(getcwd().'/config.php')){
96          require(getcwd().'/config.php');
97      }
98     global $sugar_config;
99         if(!isset($sugar_config['resource_management'])){
100           $sugar_config['resource_management'] =
101                   array (
102                     'special_query_limit' => 50000,
103                     'special_query_modules' =>
104                     array (
105                       0 => 'Reports',
106                       1 => 'Export',
107                       2 => 'Import',
108                       3 => 'Administration',
109                       4 => 'Sync',
110                     ),
111                     'default_limit' => 1000,
112                   );
113                  ksort($sugar_config);
114          if(is_writable('config.php') && write_array_to_file("sugar_config", $sugar_config,'config.php')) {
115                 //writing to the file
116                 }
117         }
118 }
119
120
121 function verifyArguments($argv,$usage_regular){
122     $upgradeType = '';
123     $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
124     if(isset($argv[3])) {
125         if(is_dir($argv[3])) {
126             $cwd = $argv[3];
127             chdir($cwd);
128         } else {
129             echo "*******************************************************************************\n";
130             echo "*** ERROR: 3rd parameter must be a valid directory.  Tried to cd to [ {$argv[3]} ].\n";
131             exit(1);
132         }
133     }
134
135     //check if this is an instance
136     if(is_file("{$cwd}/include/entryPoint.php")) {
137         //this should be a regular sugar install
138         $upgradeType = constant('SUGARCRM_INSTALL');
139         //check if this is a valid zip file
140         if(!is_file($argv[1])) { // valid zip?
141             echo "*******************************************************************************\n";
142             echo "*** ERROR: First argument must be a full path to the patch file. Got [ {$argv[1]} ].\n";
143             echo $usage_regular;
144             echo "FAILURE\n";
145             exit(1);
146         }
147         if(count($argv) < 5) {
148             echo "*******************************************************************************\n";
149             echo "*** ERROR: Missing required parameters.  Received ".count($argv)." argument(s), require 5.\n";
150             echo $usage_regular;
151             echo "FAILURE\n";
152             exit(1);
153         }
154     }
155     else {
156         //this should be a regular sugar install
157         echo "*******************************************************************************\n";
158         echo "*** ERROR: Tried to execute in a non-SugarCRM root directory.\n";
159         exit(1);
160     }
161
162     if(isset($argv[7]) && file_exists($argv[7].'SugarTemplateUtilties.php')){
163         require_once($argv[7].'SugarTemplateUtilties.php');
164     }
165
166     return $upgradeType;
167 }
168
169 ////    END UTILITIES THAT MUST BE LOCAL :(
170 ///////////////////////////////////////////////////////////////////////////////
171
172 function rebuildRelations($pre_path = '')
173 {
174         $_REQUEST['silent'] = true;
175         include($pre_path.'modules/Administration/RebuildRelationship.php');
176         $_REQUEST['upgradeWizard'] = true;
177         include($pre_path.'modules/ACL/install_actions.php');
178 }
179
180 // only run from command line
181 if(isset($_SERVER['HTTP_USER_AGENT'])) {
182         fwrite(STDERR,'This utility may only be run from the command line or command prompt.');
183         exit(1);
184 }
185 //Clean_string cleans out any file  passed in as a parameter
186 $_SERVER['PHP_SELF'] = 'silentUpgrade.php';
187
188
189 ///////////////////////////////////////////////////////////////////////////////
190 ////    USAGE
191 $usage_regular =<<<eoq2
192 Usage: php.exe -f silentUpgrade.php [upgradeZipFile] [logFile] [pathToSugarInstance] [admin-user]
193
194 On Command Prompt Change directory to where silentUpgrade.php resides. Then type path to
195 php.exe followed by -f silentUpgrade.php and the arguments.
196
197 Example:
198     [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
199
200 Arguments:
201     upgradeZipFile                       : Upgrade package file.
202     logFile                              : Silent Upgarde log file.
203     pathToSugarInstance                  : Sugar Instance instance being upgraded.
204     admin-user                           : admin user performing the upgrade
205 eoq2;
206 ////    END USAGE
207 ///////////////////////////////////////////////////////////////////////////////
208
209
210
211 ///////////////////////////////////////////////////////////////////////////////
212 ////    STANDARD REQUIRED SUGAR INCLUDES AND PRESETS
213 if(!defined('sugarEntry')) define('sugarEntry', true);
214
215 $_SESSION = array();
216 $_SESSION['schema_change'] = 'sugar'; // we force-run all SQL
217 $_SESSION['silent_upgrade'] = true;
218 $_SESSION['step'] = 'silent'; // flag to NOT try redirect to 4.5.x upgrade wizard
219
220 $_REQUEST = array();
221 $_REQUEST['addTaskReminder'] = 'remind';
222
223
224 define('SUGARCRM_INSTALL', 'SugarCRM_Install');
225 define('DCE_INSTANCE', 'DCE_Instance');
226
227 global $cwd;
228 $cwd = getcwd(); // default to current, assumed to be in a valid SugarCRM root dir.
229
230 $upgradeType = verifyArguments($argv,$usage_regular);
231
232 $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
233 $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
234
235 require_once('include/entryPoint.php');
236 require_once('modules/UpgradeWizard/uw_utils.php');
237 require_once('include/utils/zip_utils.php');
238 require_once('include/utils/sugar_file_utils.php');
239 require_once('include/SugarObjects/SugarConfig.php');
240 global $sugar_config;
241 $isDCEInstance = false;
242 $errors = array();
243
244         require('config.php');
245         if(isset($argv[3])) {
246                 if(is_dir($argv[3])) {
247                         $cwd = $argv[3];
248                         chdir($cwd);
249                 }
250         }
251
252         require_once("{$cwd}/sugar_version.php"); // provides $sugar_version & $sugar_flavor
253
254         global $sugar_config;
255         $configOptions = $sugar_config['dbconfig'];
256
257     $GLOBALS['log']     = LoggerManager::getLogger('SugarCRM');
258         $patchName              = basename($argv[1]);
259         $zip_from_dir   = substr($patchName, 0, strlen($patchName) - 4); // patch folder name (minus ".zip")
260         $path                   = $argv[2]; // custom log file, if blank will use ./upgradeWizard.log
261     $db                         = &DBManagerFactory::getInstance();
262         $UWstrings              = return_module_language('en_us', 'UpgradeWizard');
263         $adminStrings   = return_module_language('en_us', 'Administration');
264     $app_list_strings = return_app_list_strings_language('en_us');
265         $mod_strings    = array_merge($adminStrings, $UWstrings);
266         $subdirs                = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
267         global $unzip_dir;
268     $license_accepted = false;
269     if(isset($argv[5]) && (strtolower($argv[5])=='yes' || strtolower($argv[5])=='y')){
270         $license_accepted = true;
271          }
272         //////////////////////////////////////////////////////////////////////////////
273         //Adding admin user to the silent upgrade
274
275         $current_user = new User();
276         if(isset($argv[4])) {
277            //if being used for internal upgrades avoid admin user verification
278            $user_name = $argv[4];
279            $q = "select id from users where user_name = '" . $user_name . "' and is_admin=1";
280            $result = $GLOBALS['db']->query($q, false);
281            $logged_user = $GLOBALS['db']->fetchByAssoc($result);
282            if(isset($logged_user['id']) && $logged_user['id'] != null){
283                 //do nothing
284             $current_user->retrieve($logged_user['id']);
285            }
286            else{
287                 echo "Not an admin user in users table. Please provide an admin user\n";
288                 exit(1);
289            }
290         }
291         else {
292                 echo "*******************************************************************************\n";
293                 echo "*** ERROR: 4th parameter must be a valid admin user.\n";
294                 echo $usage;
295                 echo "FAILURE\n";
296                 exit(1);
297         }
298
299 /////retrieve admin user
300
301 $unzip_dir = sugar_cached("upgrades/temp");
302 $install_file = $sugar_config['upload_dir']."/upgrades/patch/".basename($argv[1]);
303 sugar_mkdir($sugar_config['upload_dir']."/upgrades/patch", 0775, true);
304
305 $_SESSION['unzip_dir'] = $unzip_dir;
306 $_SESSION['install_file'] = $install_file;
307 $_SESSION['zip_from_dir'] = $zip_from_dir;
308
309 mkdir_recursive($unzip_dir);
310 if(!is_dir($unzip_dir)) {
311         fwrite(STDERR,"\n{$unzip_dir} is not an available directory\nFAILURE\n");
312     exit(1);
313 }
314 unzip($argv[1], $unzip_dir);
315 // mimic standard UW by copy patch zip to appropriate dir
316 copy($argv[1], $install_file);
317 ////    END UPGRADE PREP
318 ///////////////////////////////////////////////////////////////////////////////
319
320
321 if(function_exists('set_upgrade_vars')){
322         set_upgrade_vars();
323 }
324
325 ///////////////////////////////////////////////////////////////////////////////
326 ////    RUN SILENT UPGRADE
327 ob_start();
328 set_time_limit(0);
329
330 ///    RELOAD NEW DEFINITIONS
331 global $ACLActions, $beanList, $beanFiles;
332
333 require_once('modules/Trackers/TrackerManager.php');
334 $trackerManager = TrackerManager::getInstance();
335 $trackerManager->pause();
336 $trackerManager->unsetMonitors();
337
338 include('modules/ACLActions/actiondefs.php');
339 include('include/modules.php');
340
341 require_once('modules/Administration/upgrade_custom_relationships.php');
342 upgrade_custom_relationships();
343
344 logThis('Upgrading user preferences start .', $path);
345 if(function_exists('upgradeUserPreferences')){
346    upgradeUserPreferences();
347 }
348 logThis('Upgrading user preferences finish .', $path);
349
350 // clear out the theme cache
351 if(is_dir($GLOBALS['sugar_config']['cache_dir'].'themes')){
352     $allModFiles = array();
353     $allModFiles = findAllFiles($GLOBALS['sugar_config']['cache_dir'].'themes',$allModFiles);
354     foreach($allModFiles as $file){
355         //$file_md5_ref = str_replace(clean_path(getcwd()),'',$file);
356         if(file_exists($file)){
357             unlink($file);
358         }
359     }
360 }
361
362 // re-minify the JS source files
363 $_REQUEST['root_directory'] = getcwd();
364 $_REQUEST['js_rebuild_concat'] = 'rebuild';
365 require_once('jssource/minify.php');
366
367 //Add the cache cleaning here.
368 if(function_exists('deleteCache'))
369 {
370         logThis('Call deleteCache', $path);
371         @deleteCache();
372 }
373
374 // creating full text search logic hooks
375 // this will be merged into application/Ext/LogicHooks/logichooks.ext.php
376 // when rebuild_extensions is called
377 logThis(' Writing FTS hooks');
378 if (!function_exists('createFTSLogicHook')) {
379     $customFileLoc = create_custom_directory('Extension/application/Ext/LogicHooks/SugarFTSHooks.php');
380     $fp = sugar_fopen($customFileLoc, 'wb');
381     $contents = <<<CIA
382 <?php
383 if (!isset(\$hook_array) || !is_array(\$hook_array)) {
384     \$hook_array = array();
385 }
386 if (!isset(\$hook_array['after_save']) || !is_array(\$hook_array['after_save'])) {
387     \$hook_array['after_save'] = array();
388 }
389 \$hook_array['after_save'][] = array(1, 'fts', 'include/SugarSearchEngine/SugarSearchEngineQueueManager.php', 'SugarSearchEngineQueueManager', 'populateIndexQueue');
390 CIA;
391
392     fwrite($fp,$contents);
393     fclose($fp);
394 } else {
395     createFTSLogicHook('Extension/application/Ext/LogicHooks/SugarFTSHooks.php');
396 }
397
398 //First repair the databse to ensure it is up to date with the new vardefs/tabledefs
399 logThis('About to repair the database.', $path);
400 //Use Repair and rebuild to update the database.
401 global $dictionary;
402 require_once("modules/Administration/QuickRepairAndRebuild.php");
403 $rac = new RepairAndClear();
404 $rac->clearVardefs();
405 $rac->rebuildExtensions();
406 //bug: 44431 - defensive check to ensure the method exists since upgrades to 6.2.0 may not have this method define yet.
407 if(method_exists($rac, 'clearExternalAPICache'))
408 {
409     $rac->clearExternalAPICache();
410 }
411
412 $repairedTables = array();
413 foreach ($beanFiles as $bean => $file) {
414         if(file_exists($file)){
415                 unset($GLOBALS['dictionary'][$bean]);
416                 require_once($file);
417                 $focus = new $bean ();
418                 if(empty($focus->table_name) || isset($repairedTables[$focus->table_name])) {
419                    continue;
420                 }
421
422                 if (($focus instanceOf SugarBean)) {
423                         if(!isset($repairedTables[$focus->table_name]))
424                         {
425                                 $sql = $GLOBALS['db']->repairTable($focus, true);
426                 if(trim($sql) != '')
427                 {
428                                     logThis('Running sql:' . $sql, $path);
429                 }
430                                 $repairedTables[$focus->table_name] = true;
431                         }
432
433                         //Check to see if we need to create the audit table
434                     if($focus->is_AuditEnabled() && !$focus->db->tableExists($focus->get_audit_table_name())){
435                logThis('Creating audit table:' . $focus->get_audit_table_name(), $path);
436                        $focus->create_audit_table();
437             }
438                 }
439         }
440 }
441
442 unset ($dictionary);
443 include ("{$argv[3]}/modules/TableDictionary.php");
444 foreach ($dictionary as $meta) {
445         $tablename = $meta['table'];
446
447         if(isset($repairedTables[$tablename])) {
448            continue;
449         }
450
451         $fielddefs = $meta['fields'];
452         $indices = $meta['indices'];
453         $sql = $GLOBALS['db']->repairTableParams($tablename, $fielddefs, $indices, true);
454         if(!empty($sql)) {
455             logThis($sql, $path);
456             $repairedTables[$tablename] = true;
457         }
458
459 }
460
461 logThis('database repaired', $path);
462
463 logThis('Start rebuild relationships.', $path);
464 @rebuildRelations();
465 logThis('End rebuild relationships.', $path);
466
467 include("$unzip_dir/manifest.php");
468 $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');
469 $origVersion = getSilentUpgradeVar('origVersion');
470 if(!$origVersion){
471     global $silent_upgrade_vars_loaded;
472     logThis("Error retrieving silent upgrade var for origVersion: cache dir is {$GLOBALS['sugar_config']['cache_dir']} -- full cache for \$silent_upgrade_vars_loaded is ".var_export($silent_upgrade_vars_loaded, true), $path);
473 }
474
475
476 if($ce_to_pro_ent) {
477         //add the global team if it does not exist
478         $globalteam = new Team();
479         $globalteam->retrieve('1');
480         require_once($unzip_dir.'/'.$zip_from_dir.'/modules/Administration/language/en_us.lang.php');
481         if(isset($globalteam->name)){
482                 echo 'Global '.$mod_strings['LBL_UPGRADE_TEAM_EXISTS'].'<br>';
483                 logThis(" Finish Building Global Team", $path);
484         }else{
485                 $globalteam->create_team("Global", $mod_strings['LBL_GLOBAL_TEAM_DESC'], $globalteam->global_team);
486         }
487
488         logThis(" Start Building private teams", $path);
489
490     upgradeModulesForTeam();
491     logThis(" Finish Building private teams", $path);
492
493     logThis(" Start Building the team_set and team_sets_teams", $path);
494     upgradeModulesForTeamsets();
495     logThis(" Finish Building the team_set and team_sets_teams", $path);
496
497         logThis(" Start modules/Administration/upgradeTeams.php", $path);
498         include('modules/Administration/upgradeTeams.php');
499         logThis(" Finish modules/Administration/upgradeTeams.php", $path);
500
501     if(check_FTS()){
502         $GLOBALS['db']->full_text_indexing_setup();
503     }
504 }
505
506
507 /*
508 */
509
510 //bug: 37214 - merge config_si.php settings if available
511 logThis('Begin merge_config_si_settings', $path);
512 merge_config_si_settings(true, '', '', $path);
513 logThis('End merge_config_si_settings', $path);
514
515 //Upgrade connectors
516 logThis('Begin upgrade_connectors', $path);
517 upgrade_connectors();
518 logThis('End upgrade_connectors', $path);
519
520 // Enable the InsideView connector by default
521 if($origVersion < '621' && function_exists('upgradeEnableInsideViewConnector')) {
522     logThis("Looks like we need to enable the InsideView connector\n",$path);
523     upgradeEnableInsideViewConnector($path);
524 }
525
526
527 //bug: 36845 - ability to provide global search support for custom modules
528 /*
529 */
530
531 //Upgrade system displayed tabs and subpanels
532 if(function_exists('upgradeDisplayedTabsAndSubpanels'))
533 {
534         upgradeDisplayedTabsAndSubpanels($origVersion);
535 }
536
537 //Unlink files that have been removed
538 if(function_exists('unlinkUpgradeFiles'))
539 {
540         unlinkUpgradeFiles($origVersion);
541 }
542
543 if(function_exists('rebuildSprites') && function_exists('imagecreatetruecolor'))
544 {
545     rebuildSprites(true);
546 }
547
548 //Run repairUpgradeHistoryTable
549 if($origVersion < '650' && function_exists('repairUpgradeHistoryTable'))
550 {
551     repairUpgradeHistoryTable();
552 }
553
554 ///////////////////////////////////////////////////////////////////////////////
555 ////    TAKE OUT TRASH
556 if(empty($errors)) {
557         set_upgrade_progress('end','in_progress','unlinkingfiles','in_progress');
558         logThis('Taking out the trash, unlinking temp files.', $path);
559         unlinkUWTempFiles();
560         removeSilentUpgradeVarsCache();
561         logThis('Taking out the trash, done.', $path);
562 }
563
564 ///////////////////////////////////////////////////////////////////////////////
565 ////    RECORD ERRORS
566
567 $phpErrors = ob_get_contents();
568 ob_end_clean();
569 logThis("**** Potential PHP generated error messages: {$phpErrors}", $path);
570
571 if(count($errors) > 0) {
572         foreach($errors as $error) {
573                 logThis("****** SilentUpgrade ERROR: {$error}", $path);
574         }
575         echo "FAILED\n";
576 } else {
577         logThis("***** SilentUpgrade completed successfully.", $path);
578         echo "********************************************************************\n";
579         echo "*************************** SUCCESS*********************************\n";
580         echo "********************************************************************\n";
581         echo "******** If your pre-upgrade Leads data is not showing  ************\n";
582         echo "******** Or you see errors in detailview subpanels  ****************\n";
583         echo "************* In order to resolve them  ****************************\n";
584         echo "******** Log into application as Administrator  ********************\n";
585         echo "******** Go to Admin panel  ****************************************\n";
586         echo "******** Run Repair -> Rebuild Relationships  **********************\n";
587         echo "********************************************************************\n";
588 }
589
590
591 ?>