]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - ModuleInstall/ModuleInstaller.php
Release 6.5.0
[Github/sugarcrm.git] / ModuleInstall / ModuleInstaller.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
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  * ModuleInstaller - takes an installation package from files in the custom/Extension/X directories, and moves them into custom/X to install them.
41  * If a directory has multiple files they are concatenated together.
42  * Relevant directories (X) are Layoutdefs, Vardefs, Include (bean stuff), Language, TableDictionary (relationships)
43  *
44  * Installation steps that involve more than just copying files:
45  * 1. installing custom fields - calls bean->custom_fields->addField
46  * 2. installing relationships - calls createTableParams to build the relationship table, and createRelationshipMeta to add the relationship to the relationship table
47  * 3. rebuilding the relationships - at almost the last step in install(), calls modules/Administration/RebuildRelationship.php
48  * 4. repair indices - uses "modules/Administration/RepairIndex.php";
49  */
50
51
52
53 require_once('include/utils/progress_bar_utils.php');
54
55 require_once('ModuleInstall/ModuleScanner.php');
56 define('DISABLED_PATH', 'Disabled');
57
58 class ModuleInstaller{
59         var $modules = array();
60         var $silent = false;
61         var $base_dir  = '';
62         var $modulesInPackage = array();
63         public $disabled_path = DISABLED_PATH;
64
65         function ModuleInstaller(){
66                 $this->ms = new ModuleScanner();
67                 $this->modules = get_module_dir_list();
68                 $this->db = & DBManagerFactory::getInstance();
69         include("ModuleInstall/extensions.php");
70         $this->extensions = $extensions;
71         }
72
73    /*
74     * ModuleInstaller->install includes the manifest.php from the base directory it has been given. If it has been asked to do an upgrade it checks to see if there is
75     * an upgrade_manifest defined in the manifest; if not it errors. It then adds the bean into the custom/Extension/application/Ext/Include/<module>.php - sets beanList, beanFiles
76     * and moduleList - and then calls ModuleInstaller->merge_files('Ext/Include', 'modules.ext.php', '', true) to merge the individual module files into a combined file
77     * /custom/Extension/application/Ext/Include/modules.ext.php (which now contains a list of all $beanList, $beanFiles and $moduleList for all extension modules) -
78     * this file modules.ext.php is included at the end of modules.php.
79     *
80     * Finally it runs over a list of defined tasks; then install_beans, then install_custom_fields, then clear the Vardefs, run a RepairAndClear, then finally call rebuild_relationships.
81     */
82         function install($base_dir, $is_upgrade = false, $previous_version = ''){
83                 if(defined('TEMPLATE_URL'))SugarTemplateUtilities::disableCache();
84                 if(!empty($GLOBALS['sugar_config']['moduleInstaller']['packageScan'])){
85                         $this->ms->scanPackage($base_dir);
86                         if($this->ms->hasIssues()){
87                                 $this->ms->displayIssues();
88                                 sugar_cleanup(true);
89                         }
90                 }
91
92         // workaround for bug 45812 - refresh vardefs cache before unpacking to avoid partial vardefs in cache
93         global $beanList;
94         foreach ($this->modules as $module_name) {
95             if (!empty($beanList[$module_name])) {
96                 $objectName = BeanFactory::getObjectName($module_name);
97                 VardefManager::loadVardef($module_name, $objectName);
98             }
99         }
100
101                 global $app_strings, $mod_strings;
102                 $this->base_dir = $base_dir;
103                 $total_steps = 5; //minimum number of steps with no tasks
104                 $current_step = 0;
105                 $tasks = array(
106                         'pre_execute',
107                         'install_copy',
108                     'install_extensions',
109                         'install_images',
110                         'install_dcactions',
111                         'install_dashlets',
112                         'install_connectors',
113                         'install_layoutfields',
114                         'install_relationships',
115             'enable_manifest_logichooks',
116                         'post_execute',
117                         'reset_opcodes',
118                 );
119
120                 $total_steps += count($tasks);
121                 if(file_exists($this->base_dir . '/manifest.php')){
122                                 if(!$this->silent){
123                                         $current_step++;
124                                         display_progress_bar('install', $current_step, $total_steps);
125                                         echo '<div id ="displayLoglink" ><a href="#" onclick="document.getElementById(\'displayLog\').style.display=\'\'">'
126                                                 .$app_strings['LBL_DISPLAY_LOG'].'</a> </div><div id="displayLog" style="display:none">';
127                                 }
128
129                                 include($this->base_dir . '/manifest.php');
130                                 if($is_upgrade && !empty($previous_version)){
131                                         //check if the upgrade path exists
132                                         if(!empty($upgrade_manifest)){
133                                                 if(!empty($upgrade_manifest['upgrade_paths'])){
134                                                         if(!empty($upgrade_manifest['upgrade_paths'][$previous_version])){
135                                                                 $installdefs =  $upgrade_manifest['upgrade_paths'][$previous_version];
136                                                         }else{
137                                                                 $errors[] = 'No Upgrade Path Found in manifest.';
138                                                                 $this->abort($errors);
139                                                         }//fi
140                                                 }//fi
141                                         }//fi
142                                 }//fi
143                                 $this->id_name = $installdefs['id'];
144                                 $this->installdefs = $installdefs;
145                                 if(!$this->silent){
146                                         $current_step++;
147                                         update_progress_bar('install', $current_step, $total_steps);
148                                 }
149
150                                 foreach($tasks as $task){
151                                         $this->$task();
152                                         if(!$this->silent){
153                                                 $current_step++;
154                                                 update_progress_bar('install', $current_step, $total_steps);
155                                         }
156                                 }
157                                 $this->install_beans($this->installed_modules);
158                                 if(!$this->silent){
159                                         $current_step++;
160                                         update_progress_bar('install', $total_steps, $total_steps);
161                                 }
162                                 if(isset($installdefs['custom_fields'])){
163                                         $this->log(translate('LBL_MI_IN_CUSTOMFIELD'));
164                                         $this->install_custom_fields($installdefs['custom_fields']);
165                                 }
166                                 if(!$this->silent){
167                                         $current_step++;
168                                         update_progress_bar('install', $current_step, $total_steps);
169                                         echo '</div>';
170                                 }
171                                 if(!$this->silent){
172                                         $current_step++;
173                                         update_progress_bar('install', $current_step, $total_steps);
174                                         echo '</div>';
175                                 }
176                                 $selectedActions = array(
177                         'clearTpls',
178                         'clearJsFiles',
179                         'clearDashlets',
180                         'clearVardefs',
181                         'clearJsLangFiles',
182                         'rebuildAuditTables',
183                         'repairDatabase',
184                 );
185                                 VardefManager::clearVardef();
186                                 global $beanList, $beanFiles, $moduleList;
187                                 if (file_exists('custom/application/Ext/Include/modules.ext.php'))
188                                 {
189                                     include('custom/application/Ext/Include/modules.ext.php');
190                                 }
191                                 require_once("modules/Administration/upgrade_custom_relationships.php");
192                 upgrade_custom_relationships($this->installed_modules);
193                                 $this->rebuild_all(true);
194                                 require_once('modules/Administration/QuickRepairAndRebuild.php');
195                                 $rac = new RepairAndClear();
196                                 $rac->repairAndClearAll($selectedActions, $this->installed_modules,true, false);
197                                 $this->rebuild_relationships();
198                                 UpdateSystemTabs('Add',$this->tab_modules);
199                 //Clear out all the langauge cache files.
200                 clearAllJsAndJsLangFilesWithoutOutput();
201                 $cache_key = 'app_list_strings.'.$GLOBALS['current_language'];
202                 sugar_cache_clear($cache_key );
203                 sugar_cache_reset();
204
205                                 //clear the unified_search_module.php file
206                     require_once('modules/Home/UnifiedSearchAdvanced.php');
207                     UnifiedSearchAdvanced::unlinkUnifiedSearchModulesFile();
208
209                                 $this->log('<br><b>' . translate('LBL_MI_COMPLETE') . '</b>');
210                 }else{
211                         die("No \$installdefs Defined In $this->base_dir/manifest.php");
212                 }
213
214         }
215
216         function install_user_prefs($module, $hide_from_user=false){
217                 UserPreference::updateAllUserPrefs('display_tabs', $module, '', true, !$hide_from_user);
218                 UserPreference::updateAllUserPrefs('hide_tabs', $module, '', true, $hide_from_user);
219                 UserPreference::updateAllUserPrefs('remove_tabs', $module, '', true, $hide_from_user);
220         }
221         function uninstall_user_prefs($module){
222                 UserPreference::updateAllUserPrefs('display_tabs', $module, '', true, true);
223                 UserPreference::updateAllUserPrefs('hide_tabs', $module, '', true, true);
224                 UserPreference::updateAllUserPrefs('remove_tabs', $module, '', true, true);
225         }
226
227         function pre_execute(){
228                 require_once($this->base_dir . '/manifest.php');
229                 if(isset($this->installdefs['pre_execute']) && is_array($this->installdefs['pre_execute'])){
230                         foreach($this->installdefs['pre_execute'] as $includefile){
231                                 require_once(str_replace('<basepath>', $this->base_dir, $includefile));
232                         }
233                 }
234         }
235
236         function post_execute(){
237                 require_once($this->base_dir . '/manifest.php');
238                 if(isset($this->installdefs['post_execute']) && is_array($this->installdefs['post_execute'])){
239                         foreach($this->installdefs['post_execute'] as $includefile){
240                                 require_once(str_replace('<basepath>', $this->base_dir, $includefile));
241                         }
242                 }
243         }
244
245         function pre_uninstall(){
246                 require_once($this->base_dir . '/manifest.php');
247                 if(isset($this->installdefs['pre_uninstall']) && is_array($this->installdefs['pre_uninstall'])){
248                         foreach($this->installdefs['pre_uninstall'] as $includefile){
249                                 require_once(str_replace('<basepath>', $this->base_dir, $includefile));
250                         }
251                 }
252         }
253
254         function post_uninstall(){
255                 require_once($this->base_dir . '/manifest.php');
256                 if(isset($this->installdefs['post_uninstall']) && is_array($this->installdefs['post_uninstall'])){
257                         foreach($this->installdefs['post_uninstall'] as $includefile){
258                                 require_once(str_replace('<basepath>', $this->base_dir, $includefile));
259                         }
260                 }
261         }
262
263         /*
264      * ModuleInstaller->install_copy gets the copy section of installdefs in the manifest and calls copy_path to copy each path (file or directory) to its final location
265      * (specified as from and to in the manifest), replacing <basepath> by the base_dir value passed in to install.
266      */
267         function install_copy(){
268                 if(isset($this->installdefs['copy'])){
269                         /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:11 PM */
270                         $backup_path = clean_path( remove_file_extension(urldecode(hashToFile($_REQUEST['install_file'])))."-restore" );
271                         /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
272                         foreach($this->installdefs['copy'] as $cp){
273                                 $GLOBALS['log']->debug("Copying ..." . $cp['from'].  " to " .$cp['to'] );
274                                 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:11 PM */
275                                 //$this->copy_path($cp['from'], $cp['to']);
276                                 $this->copy_path($cp['from'], $cp['to'], $backup_path);
277                                 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
278                         }
279                         //here we should get the module list again as we could have copied something to the modules dir
280                         $this->modules = get_module_dir_list();
281                 }
282         }
283         function uninstall_copy(){
284                 if(!empty($this->installdefs['copy'])){
285                                         foreach($this->installdefs['copy'] as $cp){
286                                                 $cp['to'] = clean_path(str_replace('<basepath>', $this->base_dir, $cp['to']));
287                                                 $cp['from'] = clean_path(str_replace('<basepath>', $this->base_dir, $cp['from']));
288                                                 $GLOBALS['log']->debug('Unlink ' . $cp['to']);
289                                 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:11 PM */
290                                                 //rmdir_recursive($cp['to']);
291
292                                                 $backup_path = clean_path( remove_file_extension(urldecode(hashToFile($_REQUEST['install_file'])))."-restore/".$cp['to'] );
293                                                 $this->uninstall_new_files($cp, $backup_path);
294                                                 $this->copy_path($backup_path, $cp['to'], $backup_path, true);
295                                 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
296                                         }
297                                         $backup_path = clean_path( remove_file_extension(urldecode(hashToFile($_REQUEST['install_file'])))."-restore");
298                                         if(file_exists($backup_path))
299                                                 rmdir_recursive($backup_path);
300                                 }
301         }
302
303
304         /**
305          * Removes any files that were added by the loaded module. If the files already existed prior to install
306          * it will be handled by copy_path with the uninstall parameter.
307          *
308          */
309         function uninstall_new_files($cp, $backup_path){
310                 $zip_files = $this->dir_get_files($cp['from'],$cp['from']);
311                 $backup_files = $this->dir_get_files($backup_path, $backup_path);
312                 foreach($zip_files as $k=>$v){
313                         //if it's not a backup then it is probably a new file but we'll check that it is not in the md5.files first
314                         if(!isset($backup_files[$k])){
315                                 $to = $cp['to'] . $k;
316                                 //if it's not a sugar file then we remove it otherwise we can't restor it
317                                 if(!$this->ms->sugarFileExists($to)){
318                                         $GLOBALS['log']->debug('ModuleInstaller[uninstall_new_file] deleting file ' . $to);
319                                         if(file_exists($to)) {
320                                             unlink($to);
321                                         }
322                                 }else{
323                                         $GLOBALS['log']->fatal('ModuleInstaller[uninstall_new_file] Could not remove file ' . $to . ' as no backup file was found to restore to');
324                                 }
325                         }
326                 }
327                 //lets check if the directory is empty if it is we will delete it as well
328                 $files_remaining = $this->dir_file_count($cp['to']);
329                 if(file_exists($cp['to']) && $files_remaining == 0){
330                         $GLOBALS['log']->debug('ModuleInstaller[uninstall_new_file] deleting directory ' . $cp['to']);
331                         rmdir_recursive($cp['to']);
332                 }
333
334         }
335
336         /**
337          * Get directory where module's extensions go
338          * @param string $module Module name
339          */
340     public function getExtDir($module)
341     {
342             if($module == 'application') {
343             return "custom/Extension/application/Ext";
344         } else {
345                         return "custom/Extension/modules/$module/Ext";
346         }
347     }
348
349         /**
350          * Install file(s) into Ext/ part
351          * @param string $section Name of the install file section
352          * @param string $extname Name in Ext directory
353          * @param string $module This extension belongs to a specific module
354          */
355         public function installExt($section, $extname, $module = '')
356         {
357         if(isset($this->installdefs[$section])){
358                         $this->log(sprintf(translate("LBL_MI_IN_EXT"), $section));
359                         foreach($this->installdefs[$section] as $item){
360                             if(isset($item['from'])) {
361                                     $from = str_replace('<basepath>', $this->base_dir, $item['from']);
362                             } else {
363                                 $from = '';
364                             }
365                                 if(!empty($module)) {
366                                     $item['to_module'] = $module;
367                                 }
368                                 $GLOBALS['log']->debug("Installing section $section from $from for " .$item['to_module'] );
369                 if($item['to_module'] == 'application') {
370                     $path = "custom/Extension/application/Ext/$extname";
371                 } else {
372                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/$extname";
373                 }
374                                 if(!file_exists($path)){
375                                         mkdir_recursive($path, true);
376                                 }
377                                 if(isset($item["name"])) {
378                                     $target = $item["name"];
379                                 } else if (!empty($from)){
380                     $target = basename($from, ".php");
381                 } else {
382                                     $target = $this->id_name;
383                                 }
384                                 if(!empty($from)) {
385                                     copy_recursive($from , "$path/$target.php");
386                                 }
387                         }
388                 }
389         }
390
391         /**
392          * Uninstall file(s) into Ext/ part
393          * @param string $section Name of the install file section
394          * @param string $extname Name in Ext directory
395          * @param string $module This extension belongs to a specific module
396          */
397         public function uninstallExt($section, $extname, $module = '')
398         {
399         if(isset($this->installdefs[$section])){
400                         $this->log(sprintf(translate("LBL_MI_UN_EXT"), $section));
401                         foreach($this->installdefs[$section] as $item){
402                             if(isset($item['from'])) {
403                                     $from = str_replace('<basepath>', $this->base_dir, $item['from']);
404                             } else {
405                                 $from = '';
406                             }
407                             if(!empty($module)) {
408                                     $item['to_module'] = $module;
409                                 }
410                                 $GLOBALS['log']->debug("Uninstalling section $section from $from for " .$item['to_module'] );
411                 if($item['to_module'] == 'application') {
412                     $path = "custom/Extension/application/Ext/$extname";
413                 } else {
414                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/$extname";
415                 }
416                                 if(isset($item["name"])) {
417                                     $target = $item["name"];
418                                 } else if (!empty($from)){
419                     $target = basename($from, ".php");
420                 } else {
421                                     $target = $this->id_name;
422                                 }
423                                 $disabled_path = $path.'/'.DISABLED_PATH;
424                                 if (file_exists("$path/$target.php")) {
425                                     rmdir_recursive("$path/$target.php");
426                 } else if (file_exists("$disabled_path/$target.php")) {
427                     rmdir_recursive("$disabled_path/$target.php");
428                                 } else if (!empty($from) && file_exists($path . '/'. basename($from))) {
429                                     rmdir_recursive( $path . '/'. basename($from));
430                 } else if (!empty($from) && file_exists($disabled_path . '/'. basename($from))) {
431                                         rmdir_recursive( $disabled_path . '/'. basename($from));
432                                 }
433                     }
434             }
435         }
436
437         /**
438      * Rebuild generic extension
439      * @param string $ext Extension directory
440      * @param string $filename Target filename
441      */
442         public function rebuildExt($ext, $filename)
443         {
444             $this->log(translate('LBL_MI_REBUILDING') . " $ext...");
445                         $this->merge_files("Ext/$ext/", $filename);
446         }
447
448         /**
449          * Disable generic extension
450          * @param string $section Install file section name
451          * @param string $extname Extension directory
452          * @param string $module This extension belongs to a specific module
453          */
454         public function disableExt($section, $extname, $module = '')
455         {
456                 if(isset($this->installdefs[$section])) {
457                         foreach($this->installdefs[$section] as $item) {
458                             if(isset($item['from'])) {
459                                     $from = str_replace('<basepath>', $this->base_dir, $item['from']);
460                             } else {
461                                 $from = '';
462                             }
463                                 if(!empty($module)) {
464                                     $item['to_module'] = $module;
465                                 }
466                                 $GLOBALS['log']->debug("Disabling $extname ... from $from for " .$item['to_module']);
467                 if($item['to_module'] == 'application') {
468                     $path = "custom/Extension/application/Ext/$extname";
469                 } else {
470                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/$extname";
471                 }
472                                 if(isset($item["name"])) {
473                                     $target = $item["name"];
474                                 } else if (!empty($from)){
475                     $target = basename($from, ".php");
476                 }else {
477                                     $target = $this->id_name;
478                                 }
479                                 $disabled_path = $path.'/'.DISABLED_PATH;
480                 if (file_exists("$path/$target.php")) {
481                                         mkdir_recursive($disabled_path, true);
482                                         rename("$path/$target.php", "$disabled_path/$target.php");
483                                 } else if (!empty($from) && file_exists($path . '/'. basename($from))) {
484                                         mkdir_recursive($disabled_path, true);
485                                     rename( $path . '/'. basename($from), $disabled_path.'/'. basename($from));
486                                 }
487                         }
488                 }
489         }
490
491         /**
492          * Enable generic extension
493          * @param string $section Install file section name
494          * @param string $extname Extension directory
495          * @param string $module This extension belongs to a specific module
496          */
497         public function enableExt($section, $extname, $module = '')
498         {
499                 if(isset($this->installdefs[$section])) {
500                         foreach($this->installdefs[$section] as $item) {
501                             if(isset($item['from'])) {
502                                     $from = str_replace('<basepath>', $this->base_dir, $item['from']);
503                             } else {
504                                 $from = '';
505                             }
506                             if(!empty($module)) {
507                                     $item['to_module'] = $module;
508                                 }
509                                 $GLOBALS['log']->debug("Enabling $extname ... from $from for " .$item['to_module']);
510
511                 if($item['to_module'] == 'application') {
512                     $path = "custom/Extension/application/Ext/$extname";
513                 } else {
514                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/$extname";
515                 }
516                                 if(isset($item["name"])) {
517                                     $target = $item["name"];
518                                 } else if (!empty($from)){
519                     $target = basename($from, ".php");
520                 } else {
521                                     $target = $this->id_name;
522                                 }
523                                 if(!file_exists($path)) {
524                                     mkdir_recursive($path, true);
525                                 }
526                 $disabled_path = $path.'/'.DISABLED_PATH;
527                                 if (file_exists("$disabled_path/$target.php")) {
528                                         rename("$disabled_path/$target.php",  "$path/$target.php");
529                                 }
530                                 if (!empty($from) && file_exists($disabled_path . '/'. basename($from))) {
531                                         rename($disabled_path.'/'. basename($from),  $path . '/'. basename($from));
532                                 }
533                         }
534                 }
535     }
536
537         public function install_extensions()
538         {
539             foreach($this->extensions as $extname => $ext) {
540                 $install = "install_$extname";
541                 if(method_exists($this, $install)) {
542                     // non-standard function
543                 $this->$install();
544                 } else {
545                     if(!empty($ext["section"])) {
546                         $module = isset($ext['module'])?$ext['module']:'';
547                         $this->installExt($ext["section"], $ext["extdir"], $module);
548                     }
549                 }
550             }
551             $this->rebuild_extensions();
552         }
553
554         public function uninstall_extensions()
555         {
556             foreach($this->extensions as $extname => $ext) {
557                 $func = "uninstall_$extname";
558                 if(method_exists($this, $func)) {
559                     // non-standard function
560                 $this->$func();
561                 } else {
562                     if(!empty($ext["section"])) {
563                         $module = isset($ext['module'])?$ext['module']:'';
564                         $this->uninstallExt($ext["section"], $ext["extdir"], $module);
565                     }
566                 }
567             }
568             $this->rebuild_extensions();
569         }
570
571         public function rebuild_extensions()
572         {
573             foreach($this->extensions as $extname => $ext) {
574                 $func = "rebuild_$extname";
575                 if(method_exists($this, $func)) {
576                     // non-standard function
577                 $this->$func();
578                 } else {
579                 $this->rebuildExt($ext["extdir"], $ext["file"]);
580                 }
581             }
582         }
583
584         public function disable_extensions()
585         {
586             foreach($this->extensions as $extname => $ext) {
587                 $func = "disable_$extname";
588                 if(method_exists($this, $func)) {
589                     // non-standard install
590                 $this->$func();
591                 } else {
592                     if(!empty($ext["section"])) {
593                         $module = isset($ext['module'])?$ext['module']:'';
594                         $this->disableExt($ext["section"], $ext["extdir"], $module);
595                     }
596                 }
597             }
598             $this->rebuild_extensions();
599         }
600
601         public function enable_extensions()
602         {
603             foreach($this->extensions as $extname => $ext) {
604                 $func = "enable_$extname";
605                 if(method_exists($this, $func)) {
606                     // non-standard install
607                 $this->$func();
608                 } else {
609                     if(!empty($ext["section"])) {
610                         $module = isset($ext['module'])?$ext['module']:'';
611                         $this->enableExt($ext["section"], $ext["extdir"], $module);
612                     }
613                 }
614             }
615             $this->rebuild_extensions();
616         }
617
618         function install_dashlets()
619         {
620         if(isset($this->installdefs['dashlets'])){
621                         foreach($this->installdefs['dashlets'] as $cp){
622                                 $this->log(translate('LBL_MI_IN_DASHLETS') . $cp['name']);
623                                 $cp['from'] = str_replace('<basepath>', $this->base_dir, $cp['from']);
624                                 $path = 'custom/modules/Home/Dashlets/' . $cp['name'] . '/';
625                                 $GLOBALS['log']->debug("Installing Dashlet " . $cp['name'] . "..." . $cp['from'] );
626                                 if(!file_exists($path)){
627                                         mkdir_recursive($path, true);
628                                 }
629                                 copy_recursive($cp['from'] , $path);
630                         }
631                         include('modules/Administration/RebuildDashlets.php');
632
633                 }
634         }
635
636         function uninstall_dashlets(){
637         if(isset($this->installdefs['dashlets'])){
638                         foreach($this->installdefs['dashlets'] as $cp){
639                                 $this->log(translate('LBL_MI_UN_DASHLETS') . $cp['name']);
640                                 $path = 'custom/modules/Home/Dashlets/' . $cp['name'];
641                                 $GLOBALS['log']->debug('Unlink ' .$path);
642                                 if (file_exists($path))
643                                         rmdir_recursive($path);
644                         }
645                         include('modules/Administration/RebuildDashlets.php');
646                 }
647         }
648
649
650         function install_images(){
651         if(isset($this->installdefs['image_dir'])){
652                         $this->log( translate('LBL_MI_IN_IMAGES') );
653                         $this->copy_path($this->installdefs['image_dir'] , 'custom/themes');
654
655                 }
656         }
657
658         function install_dcactions(){
659                 if(isset($this->installdefs['dcaction'])){
660                         $this->log(translate('LBL_MI_IN_MENUS'));
661                         foreach($this->installdefs['dcaction'] as $action){
662                                 $action['from'] = str_replace('<basepath>', $this->base_dir, $action['from']);
663                                 $GLOBALS['log']->debug("Installing DCActions ..." . $action['from']);
664                                 $path = 'custom/Extension/application/Ext/DashletContainer/Containers';
665                                 if(!file_exists($path)){
666                                         mkdir_recursive($path, true);
667                                 }
668                                 copy_recursive($action['from'] , $path . '/'. $this->id_name . '.php');
669                         }
670                         $this->rebuild_dashletcontainers();
671                 }
672         }
673
674         function uninstall_dcactions(){
675         if(isset($this->installdefs['dcaction'])){
676                         $this->log(translate('LBL_MI_UN_MENUS'));
677                         foreach($this->installdefs['dcaction'] as $action){
678                                 $action['from'] = str_replace('<basepath>', $this->base_dir, $action['from']);
679                                 $GLOBALS['log']->debug("Uninstalling DCActions ..." . $action['from'] );
680                                 $path = 'custom/Extension/application/Ext/DashletContainer/Containers';
681                                 if (sugar_is_file($path . '/'. $this->id_name . '.php', 'w'))
682                                 {
683                                         rmdir_recursive( $path . '/'. $this->id_name . '.php');
684                                 }
685                                 else if (sugar_is_file($path . '/'. DISABLED_PATH . '/'. $this->id_name . '.php', 'w'))
686                                 {
687                                         rmdir_recursive( $path . '/'. DISABLED_PATH . '/'. $this->id_name . '.php');
688                                 }
689                         }
690                         $this->rebuild_dashletcontainers();
691                 }
692         }
693
694         function install_connectors(){
695         if(isset($this->installdefs['connectors'])){
696                 foreach($this->installdefs['connectors'] as $cp){
697                                 $this->log(translate('LBL_MI_IN_CONNECTORS') . $cp['name']);
698                                 $dir = str_replace('_','/',$cp['name']);
699                                 $cp['connector'] = str_replace('<basepath>', $this->base_dir, $cp['connector']);
700                                 $source_path = 'custom/modules/Connectors/connectors/sources/' . $dir. '/';
701                                 $GLOBALS['log']->debug("Installing Connector " . $cp['name'] . "..." . $cp['connector'] );
702                                 if(!file_exists($source_path)){
703                                         mkdir_recursive($source_path, true);
704                                 }
705                                 copy_recursive($cp['connector'] , $source_path);
706
707                                 //Install optional formatter code if it is specified
708                                 if(!empty($cp['formatter'])) {
709                                         $cp['formatter'] = str_replace('<basepath>', $this->base_dir, $cp['formatter']);
710                                         $formatter_path = 'custom/modules/Connectors/connectors/formatters/' . $dir. '/';
711                                         if(!file_exists($formatter_path)){
712                                                 mkdir_recursive($formatter_path, true);
713                                         }
714                                         copy_recursive($cp['formatter'] , $formatter_path);
715                                 }
716                         }
717                         require_once('include/connectors/utils/ConnectorUtils.php');
718                         ConnectorUtils::installSource($cp['name']);
719                 }
720
721         }
722         function uninstall_connectors(){
723         if(isset($this->installdefs['connectors'])){
724                 foreach($this->installdefs['connectors'] as $cp){
725                                 $this->log(translate('LBL_MI_UN_CONNECTORS') . $cp['name']);
726                                 $dir = str_replace('_','/',$cp['name']);
727                                 $source_path = 'custom/modules/Connectors/connectors/sources/' . $dir;
728                                 $formatter_path = 'custom/modules/Connectors/connectors/formatters/' . $dir;
729                                 $GLOBALS['log']->debug('Unlink ' .$source_path);
730                                 rmdir_recursive($source_path);
731                                 rmdir_recursive($formatter_path);
732                         }
733                         require_once('include/connectors/utils/ConnectorUtils.php');
734                         //ConnectorUtils::getConnectors(true);
735                         ConnectorUtils::uninstallSource($cp['name']);
736                 }
737         }
738
739         function install_vardef($from, $to_module)
740         {
741                         $GLOBALS['log']->debug("Installing Vardefs ..." . $from .  " for " .$to_module);
742                         $path = 'custom/Extension/modules/' . $to_module. '/Ext/Vardefs';
743                         if($to_module == 'application'){
744                                 $path ='custom/Extension/' . $to_module. '/Ext/Vardefs';
745                         }
746                         if(!file_exists($path)){
747                                 mkdir_recursive($path, true);
748                         }
749                         copy_recursive($from , $path.'/'. basename($from));
750         }
751
752         function install_layoutdef($from, $to_module){
753                         $GLOBALS['log']->debug("Installing Layout Defs ..." . $from .  " for " .$to_module);
754                         $path = 'custom/Extension/modules/' . $to_module. '/Ext/Layoutdefs';
755                         if($to_module == 'application'){
756                                 $path ='custom/Extension/' . $to_module. '/Ext/Layoutdefs';
757                         }
758                         if(!file_exists($path)){
759                                 mkdir_recursive($path, true);
760                         }
761                         copy_recursive($from , $path.'/'. basename($from));
762         }
763
764     // Non-standard - needs special rebuild call
765         function install_languages()
766         {
767         $languages = array();
768         if(isset($this->installdefs['language']))
769         {
770             $this->log(translate('LBL_MI_IN_LANG') );
771             foreach($this->installdefs['language'] as $packs)
772             {
773                 $modules[]=$packs['to_module'];
774                 $languages[$packs['language']] = $packs['language'];
775                                 $packs['from'] = str_replace('<basepath>', $this->base_dir, $packs['from']);
776                                 $GLOBALS['log']->debug("Installing Language Pack ..." . $packs['from']  .  " for " .$packs['to_module']);
777                             $path = 'custom/Extension/modules/' . $packs['to_module']. '/Ext/Language';
778                                 if($packs['to_module'] == 'application'){
779                                     $path ='custom/Extension/' . $packs['to_module']. '/Ext/Language';
780                                 }
781
782                                 if(!file_exists($path)){
783                                     mkdir_recursive($path, true);
784                 }
785                                 copy_recursive($packs['from'] , $path.'/'.$packs['language'].'.'. $this->id_name . '.php');
786                         }
787                         $this->rebuild_languages($languages, $modules);
788
789                 }
790         }
791
792     // Non-standard, needs special rebuild
793         function uninstall_languages(){
794         $languages = array();
795                                 if(isset($this->installdefs['language'])){
796                                         $this->log(translate('LBL_MI_UN_LANG') );
797                                         foreach($this->installdefs['language'] as $packs){
798                                                 $modules[]=$packs['to_module'];
799                                                 $languages[$packs['language']] = $packs['language'];
800                                                 $packs['from'] = str_replace('<basepath>', $this->base_dir, $packs['from']);
801                                                 $GLOBALS['log']->debug("Uninstalling Language Pack ..." . $packs['from']  .  " for " .$packs['to_module']);
802                                                 $path = 'custom/Extension/modules/' . $packs['to_module']. '/Ext/Language';
803                                                 if($packs['to_module'] == 'application'){
804                                                         $path ='custom/Extension/' . $packs['to_module']. '/Ext/Language';
805                                                 }
806                                                 if (sugar_is_file($path.'/'.$packs['language'].'.'. $this->id_name . '.php', 'w')) {
807                                                         rmdir_recursive( $path.'/'.$packs['language'].'.'. $this->id_name . '.php');
808                                                 } else if (sugar_is_file($path.'/'.DISABLED_PATH.'/'.$packs['language'].'.'. $this->id_name . '.php', 'w')) {
809                                                         rmdir_recursive($path.'/'.DISABLED_PATH.'/'.$packs['language'].'.'. $this->id_name . '.php', 'w');
810                                                 }
811                                         }
812                                         $this->rebuild_languages($languages, $modules);
813
814                                 }
815         }
816
817     // Non-standard, needs special rebuild
818         public function disable_languages()
819         {
820                 if(isset($this->installdefs['language'])) {
821                     $languages = $modules = array();
822                         foreach($this->installdefs['language'] as $item) {
823                                 $from = str_replace('<basepath>', $this->base_dir, $item['from']);
824                                 $GLOBALS['log']->debug("Disabling Language {$item['language']}... from $from for " .$item['to_module']);
825                                 $modules[]=$item['to_module'];
826                                 $languages[$item['language']] = $item['language'];
827                                 if($item['to_module'] == 'application') {
828                     $path = "custom/Extension/application/Ext/Language";
829                 } else {
830                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/Language";
831                 }
832                                 if(isset($item["name"])) {
833                                     $target = $item["name"];
834                                 } else {
835                                     $target = $this->id_name;
836                                 }
837                                 $target = "{$item['language']}.$target";
838
839                                 $disabled_path = $path.'/'.DISABLED_PATH;
840                 if (file_exists("$path/$target.php")) {
841                                         mkdir_recursive($disabled_path, true);
842                                         rename("$path/$target.php", "$disabled_path/$target.php");
843                                 } else if (file_exists($path . '/'. basename($from))) {
844                                         mkdir_recursive($disabled_path, true);
845                                     rename( $path . '/'. basename($from), $disabled_path.'/'. basename($from));
846                                 }
847                         }
848                         $this->rebuild_languages($languages, $modules);
849                 }
850         }
851
852     // Non-standard, needs special rebuild
853         public function enable_languages()
854         {
855                 if(isset($this->installdefs['language'])) {
856                         foreach($this->installdefs['language'] as $item) {
857                                 $from = str_replace('<basepath>', $this->base_dir, $item['from']);
858                                 $GLOBALS['log']->debug("Enabling Language {$item['language']}... from $from for " .$item['to_module']);
859                                 $modules[]=$item['to_module'];
860                                 $languages[$item['language']] = $item['language'];
861                                 if(!empty($module)) {
862                                     $item['to_module'] = $module;
863                                 }
864
865                 if($item['to_module'] == 'application') {
866                     $path = "custom/Extension/application/Ext/Language";
867                 } else {
868                                     $path = "custom/Extension/modules/{$item['to_module']}/Ext/Language";
869                 }
870                                 if(isset($item["name"])) {
871                                     $target = $item["name"];
872                                 } else {
873                                     $target = $this->id_name;
874                                 }
875                                 $target = "{$item['language']}.$target";
876
877                                 if(!file_exists($path)) {
878                                     mkdir_recursive($path, true);
879                                 }
880                 $disabled_path = $path.'/'.DISABLED_PATH;
881                                 if (file_exists("$disabled_path/$target.php")) {
882                                         rename("$disabled_path/$target.php",  "$path/$target.php");
883                                 }
884                                 if (file_exists($disabled_path . '/'. basename($from))) {
885                                         rename($disabled_path.'/'. basename($from),  $path . '/'. basename($from));
886                                 }
887                         }
888                         $this->rebuild_languages($languages, $modules);
889                 }
890     }
891
892     // Functions for adding and removing logic hooks from uploaded files
893     // Since one class/file can be used by multiple logic hooks, I'm not going to touch the file labeled in the logic_hook entry
894     /* The module hook definition should look like this:
895      $installdefs = array(
896      ... blah blah ...
897          'logic_hooks' => array(
898              array('module'      => 'Accounts',
899                    'hook'        => 'after_save',
900                    'order'       => 99,
901                    'description' => 'Account sample logic hook',
902                    'file'        => 'modules/Sample/sample_account_logic_hook_file.php',
903                    'class'       => 'SampleLogicClass',
904                    'function'    => 'accountAfterSave',
905              ),
906          ),
907      ... blah blah ...
908      );
909      */
910     function enable_manifest_logichooks() {
911         if(empty($this->installdefs['logic_hooks']) || !is_array($this->installdefs['logic_hooks'])) {
912            return;
913         }
914
915
916
917         foreach($this->installdefs['logic_hooks'] as $hook ) {
918             check_logic_hook_file($hook['module'], $hook['hook'], array($hook['order'], $hook['description'],  $hook['file'], $hook['class'], $hook['function']));
919         }
920     }
921
922     function disable_manifest_logichooks() {
923         if(empty($this->installdefs['logic_hooks']) || !is_array($this->installdefs['logic_hooks'])) {
924             return;
925         }
926
927         foreach($this->installdefs['logic_hooks'] as $hook ) {
928             remove_logic_hook($hook['module'], $hook['hook'], array($hook['order'], $hook['description'],  $hook['file'], $hook['class'], $hook['function']));
929         }
930     }
931
932 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
933         function copy_path($from, $to, $backup_path='', $uninstall=false){
934         //function copy_path($from, $to){
935 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
936                 $to = str_replace('<basepath>', $this->base_dir, $to);
937
938                 if(!$uninstall) {
939                 $from = str_replace('<basepath>', $this->base_dir, $from);
940                 $GLOBALS['log']->debug('Copy ' . $from);
941                 }
942                 else {
943                         $from = str_replace('<basepath>', $backup_path, $from);
944                         //$GLOBALS['log']->debug('Restore ' . $from);
945                 }
946                 $from = clean_path($from);
947                 $to = clean_path($to);
948
949                 $dir = dirname($to);
950                 //there are cases where if we need to create a directory in the root directory
951                 if($dir == '.' && is_dir($from)){
952                         $dir = $to;
953                 }
954                 if(!sugar_is_dir($dir, 'instance'))
955                         mkdir_recursive($dir, true);
956 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
957                 if(empty($backup_path)) {
958 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
959                 if(!copy_recursive($from, $to)){
960                         die('Failed to copy ' . $from. ' ' . $to);
961                 }
962 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
963                 }
964                 elseif(!$this->copy_recursive_with_backup($from, $to, $backup_path, $uninstall)){
965                         die('Failed to copy ' . $from. ' to ' . $to);
966                 }
967 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:22:18 PM */
968         }
969
970         function install_custom_fields($fields){
971                 global $beanList, $beanFiles;
972                 include('include/modules.php');
973                 require_once('modules/DynamicFields/FieldCases.php');
974                 foreach($fields as $field){
975                         $installed = false;
976                         if(isset($beanList[ $field['module']])){
977                                 $class = $beanList[ $field['module']];
978                 if(!isset($field['ext4']))$field['ext4'] = '';
979                 if(!isset($field['mass_update']))$field['mass_update'] = 0;
980                 if(!isset($field['duplicate_merge']))$field['duplicate_merge'] = 0;
981                 if(!isset($field['help']))$field['help'] = '';
982
983                 //Merge contents of the sugar field extension if we copied one over
984                 if (file_exists("custom/Extension/modules/{$field['module']}/Ext/Vardefs/sugarfield_{$field['name']}.php"))
985                 {
986                     $dictionary = array();
987                     include ("custom/Extension/modules/{$field['module']}/Ext/Vardefs/sugarfield_{$field['name']}.php");
988                     $obj = BeanFactory::getObjectName($field['module']);
989                     if (!empty($dictionary[$obj]['fields'][$field['name']])) {
990                         $field = array_merge($dictionary[$obj]['fields'][$field['name']], $field);
991                     }
992                 }
993
994                 if(file_exists($beanFiles[$class])){
995                                         require_once($beanFiles[$class]);
996                                         $mod = new $class();
997                                         $installed = true;
998                                         $fieldObject = get_widget($field['type']);
999                                         $fieldObject->populateFromRow($field);
1000                                         $mod->custom_fields->use_existing_labels =  true;
1001                                         $mod->custom_fields->addFieldObject($fieldObject);
1002                                 }
1003                         }
1004                         if(!$installed){
1005                                 $GLOBALS['log']->debug('Could not install custom field ' . $field['name'] . ' for module ' .  $field['module'] . ': Module does not exist');
1006                         }
1007                 }
1008         }
1009
1010         function uninstall_custom_fields($fields){
1011                 global $beanList, $beanFiles;
1012                 require_once('modules/DynamicFields/DynamicField.php');
1013                 $dyField = new DynamicField();
1014
1015                 foreach($fields as $field){
1016                         $class = $beanList[ $field['module']];
1017                         if(file_exists($beanFiles[$class])){
1018                                         require_once($beanFiles[$class]);
1019                                         $mod = new $class();
1020                                         $dyField->bean = $mod;
1021                                         $dyField->module = $field['module'];
1022                                         $dyField->deleteField($field['name']);
1023                         }
1024                 }
1025         }
1026
1027         /*
1028      * ModuleInstaller->install_relationships calls install_relationship for every file included in the module package that defines a relationship, and then
1029      * writes a custom/Extension/application/Ext/TableDictionary/$module.php file containing an include_once for every relationship metadata file passed to install_relationship.
1030      * Next it calls install_vardef and install_layoutdef. Finally, it rebuilds the vardefs and layoutdefs (by calling merge_files as usual), and then calls merge_files to merge
1031      * everything in 'Ext/TableDictionary/' into 'tabledictionary.ext.php'
1032      */
1033     function install_relationships ()
1034     {
1035         if (isset ( $this->installdefs [ 'relationships' ] ))
1036         {
1037             $this->log ( translate ( 'LBL_MI_IN_RELATIONSHIPS' ) ) ;
1038             $str = "<?php \n //WARNING: The contents of this file are auto-generated\n" ;
1039             $save_table_dictionary = false ;
1040
1041             if (! file_exists ( "custom/Extension/application/Ext/TableDictionary" ))
1042             {
1043                 mkdir_recursive ( "custom/Extension/application/Ext/TableDictionary", true ) ;
1044             }
1045
1046             foreach ( $this->installdefs [ 'relationships' ] as $key => $relationship )
1047             {
1048                 $filename = basename ( $relationship [ 'meta_data' ] ) ;
1049                 $this->copy_path ( $relationship [ 'meta_data' ], 'custom/metadata/' . $filename ) ;
1050                 $this->install_relationship ( 'custom/metadata/' . $filename ) ;
1051                 $save_table_dictionary = true ;
1052
1053                 if (! empty ( $relationship [ 'module_vardefs' ] ))
1054                 {
1055                     $relationship [ 'module_vardefs' ] = str_replace ( '<basepath>', $this->base_dir, $relationship [ 'module_vardefs' ] ) ;
1056                     $this->install_vardef ( $relationship [ 'module_vardefs' ], $relationship [ 'module' ] ) ;
1057                 }
1058
1059                 if (! empty ( $relationship [ 'module_layoutdefs' ] ))
1060                 {
1061                     $relationship [ 'module_layoutdefs' ] = str_replace ( '<basepath>', $this->base_dir, $relationship [ 'module_layoutdefs' ] ) ;
1062                     $this->install_layoutdef ( $relationship [ 'module_layoutdefs' ], $relationship [ 'module' ] ) ;
1063                 }
1064
1065                 $relName = strpos($filename, "MetaData") !== false ? substr($filename, 0, strlen($filename) - 12) : $filename;
1066                 $out = sugar_fopen ( "custom/Extension/application/Ext/TableDictionary/$relName.php", 'w' ) ;
1067                 fwrite ( $out, $str . "include('custom/metadata/$filename');\n\n?>" ) ;
1068                 fclose ( $out ) ;
1069             }
1070
1071
1072
1073
1074             Relationship::delete_cache();
1075             $this->rebuild_vardefs () ;
1076             $this->rebuild_layoutdefs () ;
1077             if ($save_table_dictionary)
1078             {
1079                 $this->rebuild_tabledictionary () ;
1080             }
1081             require_once("data/Relationships/RelationshipFactory.php");
1082             SugarRelationshipFactory::deleteCache();
1083         }
1084     }
1085
1086         /*
1087      * Install_relationship obtains a set of relationship definitions from the filename passed in as a parameter.
1088      * For each definition it calls db->createTableParams to build the relationships table if it does not exist,
1089      * and SugarBean::createRelationshipMeta to add the relationship into the 'relationships' table.
1090      */
1091         function install_relationship($file)
1092         {
1093                 $_REQUEST['moduleInstaller'] = true;
1094                 if(!file_exists($file))
1095                 {
1096                         $GLOBALS['log']->debug( 'File does not exists : '.$file);
1097                         return;
1098                 }
1099                 include($file);
1100                 $rel_dictionary = $dictionary;
1101                 foreach ($rel_dictionary as $rel_name => $rel_data)
1102             {
1103                 $table = ''; // table is actually optional
1104                 // check if we have a table definition - not all relationships require a join table
1105             if ( isset( $rel_data[ 'table' ] ) )
1106             {
1107                 $table = $rel_data[ 'table' ];
1108
1109                 if(!$this->db->tableExists($table))
1110                 {
1111                     $this->db->createTableParams($table, $rel_data[ 'fields' ], $rel_data[ 'indices' ]);
1112                 }
1113             }
1114
1115             if(!$this->silent)
1116                 $GLOBALS['log']->debug("Processing relationship meta for ". $rel_name."...");
1117             SugarBean::createRelationshipMeta($rel_name, $this->db,$table,$rel_dictionary,'');
1118             Relationship::delete_cache();
1119             if(!$this->silent)
1120                 $GLOBALS['log']->debug( 'done<br>');
1121         }
1122         }
1123
1124         function install_layoutfields() {
1125                  if (!empty ( $this->installdefs [ 'layoutfields' ] ))
1126                  {
1127                         foreach ( $this->installdefs [ 'layoutfields' ] as $fieldSet )
1128             {
1129                                 if (!empty($fieldSet['additional_fields']))
1130                                 {
1131                                         $this->addFieldsToLayout($fieldSet['additional_fields']);
1132                                 }
1133             }
1134                  }
1135         }
1136
1137         function uninstall_layoutfields() {
1138                  if (!empty ( $this->installdefs [ 'layoutfields' ] ))
1139                  {
1140                         foreach ( $this->installdefs [ 'layoutfields' ] as $fieldSet )
1141             {
1142                                 if (!empty($fieldSet['additional_fields']))
1143                                 {
1144                                         $this->removeFieldsFromLayout($fieldSet['additional_fields']);
1145                                 }
1146             }
1147                  }
1148         }
1149
1150         function uninstall_relationship($file, $rel_dictionary = null){
1151         if ($rel_dictionary == null)
1152                 {
1153                         if(!file_exists($file)){
1154                                 $GLOBALS['log']->debug( 'File does not exists : '.$file);
1155                                 return;
1156                         }
1157                         include($file);
1158                         $rel_dictionary = $dictionary;
1159                 }
1160
1161                 foreach ($rel_dictionary as $rel_name => $rel_data)
1162                 {
1163                         if (!empty($rel_data['table'])){
1164                                 $table = $rel_data['table'];
1165                         }
1166                         else{
1167                                 $table = ' One-to-Many ';
1168                         }
1169
1170                         if ($this->db->tableExists($table) && isset($GLOBALS['mi_remove_tables']) && $GLOBALS['mi_remove_tables'])
1171                         {
1172                                 SugarBean::removeRelationshipMeta($rel_name, $this->db,$table,$rel_dictionary,'');
1173                                 $this->db->dropTableName($table);
1174                                 if(!$this->silent) $this->log( translate('LBL_MI_UN_RELATIONSHIPS_DROP') . $table);
1175                         }
1176
1177                         //Delete Layout defs
1178                         // check to see if we have any vardef or layoutdef entries to remove - must have a relationship['module'] parameter if we do
1179                         if (!isset($rel_data[ 'module' ]))
1180                                 $mods = array(
1181                                         $rel_data['relationships'][$rel_name]['lhs_module'],
1182                                         $rel_data['relationships'][$rel_name]['rhs_module'],
1183                                 );
1184                         else
1185                                 $mods = array($rel_data[ 'module' ]);
1186
1187                         $filename = "$rel_name.php";
1188
1189                         foreach($mods as $mod) {
1190                                 if ($mod != 'application' )  {
1191                                         $basepath = "custom/Extension/modules/$mod/Ext/";
1192                                 } else {
1193                                         $basepath = "custom/Extension/application/Ext/";
1194                                 }
1195
1196                                 foreach (array($filename , "custom" . $filename, $rel_name ."_". $mod. ".php") as $fn) {
1197                                         //remove any vardefs
1198                                         $path = $basepath . "Vardefs/$fn" ;
1199                                         if (file_exists( $path ))
1200                                                 rmdir_recursive( $path );
1201
1202                                         //remove any layoutdefs
1203                                         $path = $basepath . "Layoutdefs/$fn" ;
1204                                         if( file_exists( $path ))
1205                                         {
1206                                                 rmdir_recursive( $path );
1207                                         }
1208                                 }
1209                         }
1210
1211                         foreach (array($filename , "custom" . $filename, $rel_name ."_". $mod. ".php") as $fn) {
1212                                 // remove the table dictionary extension
1213                                 if ( file_exists("custom/Extension/application/Ext/TableDictionary/$fn"))
1214                                     unlink("custom/Extension/application/Ext/TableDictionary/$fn");
1215
1216                                 if (file_exists("custom/metadata/{$rel_name}MetaData.php"))
1217                                         unlink( "custom/metadata/{$rel_name}MetaData.php" );
1218                         }
1219                 }
1220         }
1221
1222         function uninstall_relationships($include_studio_relationships = false){
1223                 $relationships = array();
1224
1225                 //Find and remove studio created relationships.
1226                 global $beanList, $beanFiles, $dictionary;
1227                 //Load up the custom relationship definitions.
1228                 if(file_exists('custom/application/Ext/TableDictionary/tabledictionary.ext.php')){
1229                         include('custom/application/Ext/TableDictionary/tabledictionary.ext.php');
1230                 }
1231                 //Find all the relatioships/relate fields involving this module.
1232                 $rels_to_remove = array();
1233                 foreach($beanList as $mod => $bean) {
1234                         //Some modules like cases have a bean name that doesn't match the object name
1235                         $bean = BeanFactory::getObjectName($mod);
1236             VardefManager::loadVardef($mod, $bean);
1237                         //We can skip modules that are in this package as they will be removed anyhow
1238                         if (!in_array($mod, $this->modulesInPackage) && !empty($dictionary[$bean]) && !empty($dictionary[$bean]['fields']))
1239                         {
1240                                 $field_defs = $dictionary[$bean]['fields'];
1241                                 foreach($field_defs as $field => $def)
1242                                 {
1243                                         //Weed out most fields first
1244                                         if (isset ($def['type']))
1245                                         {
1246                                                 //Custom relationships created in the relationship editor
1247                                                 if ($def['type'] == "link" && !empty($def['relationship']) && !empty($dictionary[$def['relationship']]))
1248                                                 {
1249                                                         $rel_name = $def['relationship'];
1250
1251                                                         $rel_def = $dictionary[$rel_name]['relationships'][$rel_name];
1252
1253                                                         //Check against mods to be removed.
1254                                                         foreach($this->modulesInPackage as $removed_mod) {
1255                                                                 if ($rel_def['lhs_module'] == $removed_mod || $rel_def['rhs_module'] == $removed_mod )
1256                                                                 {
1257                                                                         $dictionary[$rel_name]['from_studio'] = true;
1258                                                                         $relationships[$rel_name] = $dictionary[$rel_name];
1259                                                                 }
1260                                                         }
1261                                                 }
1262                                                 //Custom "relate" fields created in studio also need to be removed
1263                                                 if ($def['type'] == 'relate' && isset($def['module'])) {
1264                                                         foreach($this->modulesInPackage as $removed_mod) {
1265                                                                 if ($def['module'] == $removed_mod)
1266                                                                 {
1267                                                                         require_once 'modules/ModuleBuilder/Module/StudioModule.php' ;
1268                                                                         $studioMod = new StudioModule ( $mod );
1269                                                                         $studioMod->removeFieldFromLayouts( $field );
1270                                                                         if (isset($def['custom_module'])) {
1271                                                                                 require_once ('modules/DynamicFields/DynamicField.php') ;
1272                                                                                 require_once ($beanFiles [ $bean ]) ;
1273                                                                                 $seed = new $bean ( ) ;
1274                                                                                 $df = new DynamicField ( $mod ) ;
1275                                                                                 $df->setup ( $seed ) ;
1276                                                                                 //Need to load the entire field_meta_data for some field types
1277                                                                                 $field_obj = $df->getFieldWidget($mod, $field);
1278                                                                                 $field_obj->delete ( $df ) ;
1279                                                                         }
1280                                                                 }
1281                                                         }
1282                                                 }
1283                                         }
1284                                 }
1285                         }
1286                 }
1287
1288
1289
1290                 $this->uninstall_relationship(null, $relationships);
1291
1292                 if(isset($this->installdefs['relationships'])) {
1293                         $relationships = $this->installdefs['relationships'];
1294                         $this->log(translate('LBL_MI_UN_RELATIONSHIPS') );
1295                         foreach($relationships as $relationship)
1296                         {
1297                                 // remove the metadata entry
1298                                 $filename = basename ( $relationship['meta_data'] );
1299                                 $pathname = (file_exists("custom/metadata/$filename")) ? "custom/metadata/$filename" : "metadata/$filename" ;
1300                                 if(isset($GLOBALS['mi_remove_tables']) && $GLOBALS['mi_remove_tables'])
1301                                 $this->uninstall_relationship( $pathname );
1302                                 if (file_exists($pathname))
1303                                         unlink( $pathname );
1304                         }
1305                 }
1306
1307                 if (file_exists("custom/Extension/application/Ext/TableDictionary/{$this->id_name}.php"))
1308                         unlink("custom/Extension/application/Ext/TableDictionary/{$this->id_name}.php");
1309                 Relationship::delete_cache();
1310                 $this->rebuild_tabledictionary();
1311         }
1312
1313
1314
1315
1316         function uninstall($base_dir){
1317                 if(defined('TEMPLATE_URL'))SugarTemplateUtilities::disableCache();
1318                 global $app_strings;
1319                 $total_steps = 5; //min steps with no tasks
1320                 $current_step = 0;
1321                 $this->base_dir = $base_dir;
1322                 $tasks = array(
1323                         'pre_uninstall',
1324                         'uninstall_relationships',
1325                         'uninstall_copy',
1326                         'uninstall_dcactions',
1327                         'uninstall_dashlets',
1328                         'uninstall_connectors',
1329                         'uninstall_layoutfields',
1330                     'uninstall_extensions',
1331                         'disable_manifest_logichooks',
1332                         'post_uninstall',
1333                 );
1334                 $total_steps += count($tasks); //now the real number of steps
1335                 if(file_exists($this->base_dir . '/manifest.php')){
1336                                 if(!$this->silent){
1337                                         $current_step++;
1338                                         display_progress_bar('install', $current_step, $total_steps);
1339                                         echo '<div id ="displayLoglink" ><a href="#" onclick="toggleDisplay(\'displayLog\')">'.$app_strings['LBL_DISPLAY_LOG'].'</a> </div><div id="displayLog" style="display:none">';
1340                                 }
1341
1342                                 global $moduleList;
1343                                 include($this->base_dir . '/manifest.php');
1344                                 $this->installdefs = $installdefs;
1345                                 $this->id_name = $this->installdefs['id'];
1346                                 $installed_modules = array();
1347                                 if(isset($this->installdefs['beans'])){
1348                                         foreach($this->installdefs['beans'] as $bean){
1349
1350                                                 $installed_modules[] = $bean['module'];
1351                                                 $this->uninstall_user_prefs($bean['module']);
1352                                         }
1353                                         $this->modulesInPackage = $installed_modules;
1354                                         $this->uninstall_beans($installed_modules);
1355                                         $this->uninstall_customizations($installed_modules);
1356                                         if(!$this->silent){
1357                                                 $current_step++;
1358                                                 update_progress_bar('install', $total_steps, $total_steps);
1359                                         }
1360                                 }
1361                                 if(!$this->silent){
1362                                         $current_step++;
1363                                         update_progress_bar('install', $current_step, $total_steps);
1364                                 }
1365                                 foreach($tasks as $task){
1366                                         $this->$task();
1367                                         if(!$this->silent){
1368                                                 $current_step++;
1369                                                 update_progress_bar('install', $current_step, $total_steps);
1370                                         }
1371                                 }
1372                                 if(isset($installdefs['custom_fields']) && (isset($GLOBALS['mi_remove_tables']) && $GLOBALS['mi_remove_tables'])){
1373                                         $this->log(translate('LBL_MI_UN_CUSTOMFIELD'));
1374                                         $this->uninstall_custom_fields($installdefs['custom_fields']);
1375                                 }
1376                                 if(!$this->silent){
1377                                         $current_step++;
1378                                         update_progress_bar('install', $current_step, $total_steps);
1379                                         echo '</div>';
1380                                 }
1381                                 //since we are passing $silent = true to rebuildAll() in that method it will set $this->silent = true, so
1382                                 //we need to save the setting to set it back after rebuildAll() completes.
1383                                 $silentBak = $this->silent;
1384                                 $this->rebuild_all(true);
1385                                 $this->silent = $silentBak;
1386
1387                                 //#27877, If the request from MB redeploy a custom module , we will not remove the ACL actions for this package.
1388                                 if( !isset($_REQUEST['action']) || $_REQUEST['action']!='DeployPackage' ){
1389                                         $this->remove_acl_actions();
1390                                 }
1391                                 //end
1392
1393                                 if(!$this->silent){
1394                                         $current_step++;
1395                                         update_progress_bar('install', $current_step, $total_steps);
1396                                         echo '</div>';
1397                                 }
1398
1399                                 UpdateSystemTabs('Restore',$installed_modules);
1400
1401                     //clear the unified_search_module.php file
1402                     require_once('modules/Home/UnifiedSearchAdvanced.php');
1403                     UnifiedSearchAdvanced::unlinkUnifiedSearchModulesFile();
1404
1405                                 $this->log('<br><b>' . translate('LBL_MI_COMPLETE') . '</b>');
1406                                 if(!$this->silent){
1407                                         update_progress_bar('install', $total_steps, $total_steps);
1408                                 }
1409                 }else{
1410                         die("No manifest.php Defined In $this->base_dir/manifest.php");
1411                 }
1412         }
1413
1414         function rebuild_languages($languages = array(), $modules="")
1415         {
1416             foreach($languages as $language=>$value){
1417                                 $this->log(translate('LBL_MI_REBUILDING') . " Language...$language");
1418                                 $this->merge_files('Ext/Language/', $language.'.lang.ext.php', $language);
1419                     if($modules!=""){
1420                         foreach($modules as $module){
1421                                 LanguageManager::clearLanguageCache($module, $language);
1422                         }
1423                     }
1424                         }
1425                         sugar_cache_reset();
1426         }
1427
1428         function rebuild_vardefs()
1429         {
1430             $this->rebuildExt("Vardefs", 'vardefs.ext.php');
1431                 sugar_cache_reset();
1432         }
1433
1434         function rebuild_dashletcontainers(){
1435             $this->log(translate('LBL_MI_REBUILDING') . " DC Actions...");
1436                         $this->merge_files('Ext/DashletContainer/Containers/', 'dcactions.ext.php');
1437         }
1438
1439         function rebuild_tabledictionary()
1440         {
1441             $this->rebuildExt("TableDictionary", 'tabledictionary.ext.php');
1442         }
1443
1444         function rebuild_relationships() {
1445         if(!$this->silent) echo translate('LBL_MI_REBUILDING') . ' Relationships';
1446                 $_REQUEST['silent'] = true;
1447                 global $beanFiles;
1448                 include('include/modules.php');
1449                 include("modules/Administration/RebuildRelationship.php");
1450         }
1451
1452         function remove_acl_actions() {
1453                 global $beanFiles, $beanList, $current_user;
1454                 include('include/modules.php');
1455                 include("modules/ACL/remove_actions.php");
1456         }
1457
1458         /**
1459          * Wrapper call to modules/Administration/RepairIndex.php
1460          */
1461         function repair_indices() {
1462                 global $current_user,$beanFiles,$dictionary;
1463                 $this->log(translate('LBL_MI_REPAIR_INDICES'));
1464                 $_REQUEST['silent'] = true; // local var flagging echo'd output in repair script
1465                 $_REQUEST['mode'] = 'execute'; // flag to just go ahead and run the script
1466                 include("modules/Administration/RepairIndex.php");
1467         }
1468
1469         /**
1470          * Rebuilds the extension files found in custom/Extension
1471          * @param boolean $silent
1472          */
1473         function rebuild_all($silent=false){
1474                 if(defined('TEMPLATE_URL'))SugarTemplateUtilities::disableCache();
1475                 $this->silent=$silent;
1476                 global $sugar_config;
1477
1478                 //Check for new module extensions
1479                 $this->rebuild_modules();
1480
1481                 $this->rebuild_languages($sugar_config['languages']);
1482                 $this->rebuild_extensions();
1483                 $this->rebuild_dashletcontainers();
1484                 $this->rebuild_relationships();
1485                 $this->rebuild_tabledictionary();
1486         $this->reset_opcodes();
1487                 sugar_cache_reset();
1488         }
1489
1490         /*
1491      * ModuleInstaller->merge_files runs over the list of all modules already installed in /modules. For each $module it reads the contents of every file in
1492      * custom/Extension/modules/$module/<path> (_override files last) and concatenates them to custom/modules/$module/<path>/<file>.
1493      * Then it does the same thing in custom/Extension/application/<path>, concatenating those files and copying the result to custom/application/<path>/<file>
1494      */
1495         function merge_files($path, $name, $filter = '', $application = false){
1496                 if(!$application){
1497                 $GLOBALS['log']->debug( get_class($this)."->merge_files() : merging module files in custom/Extension/modules/<module>/$path to custom/modules/<module>/$path$name");
1498                 foreach($this->modules as $module){
1499                                 //$GLOBALS['log']->debug("Merging Files for: ".$module);
1500                                 //$GLOBALS['log']->debug("Merging Files for path: ".$path);
1501                                 $extension = "<?php \n //WARNING: The contents of this file are auto-generated\n";
1502                                 $extpath = "modules/$module/$path";
1503                                 $module_install  = 'custom/Extension/'.$extpath;
1504                                 $shouldSave = false;
1505                                 if(is_dir($module_install)){
1506                                         $dir = dir($module_install);
1507                                         $shouldSave = true;
1508                                         $override = array();
1509                                         while($entry = $dir->read()){
1510                                                 if((empty($filter) || substr_count($entry, $filter) > 0) && is_file($module_install.'/'.$entry)
1511                                                   && $entry != '.' && $entry != '..' && strtolower(substr($entry, -4)) == ".php")
1512                                                 {
1513                                                      if (substr($entry, 0, 9) == '_override') {
1514                                                         $override[] = $entry;
1515                                                     } else {
1516                                                             $file = file_get_contents($module_install . '/' . $entry);
1517                                                             $GLOBALS['log']->debug(get_class($this)."->merge_files(): found {$module_install}{$entry}") ;
1518                                                             $extension .= "\n". str_replace(array('<?php', '?>', '<?PHP', '<?'), array('','', '' ,'') , $file);
1519                                                     }
1520                                                 }
1521                                         }
1522                                         foreach ($override as $entry) {
1523                         $file = file_get_contents($module_install . '/' . $entry);
1524                         $extension .= "\n". str_replace(array('<?php', '?>', '<?PHP', '<?'), array('','', '' ,'') , $file);
1525                                         }
1526                                 }
1527                                 $extension .= "\n?>";
1528
1529                                 if($shouldSave){
1530                                         if(!file_exists("custom/$extpath")) {
1531                                             mkdir_recursive("custom/$extpath", true);
1532                                     }
1533                                         $out = sugar_fopen("custom/$extpath/$name", 'w');
1534                                         fwrite($out,$extension);
1535                                         fclose($out);
1536                                 }else{
1537                                         if(file_exists("custom/$extpath/$name")){
1538                                                 unlink("custom/$extpath/$name");
1539                                         }
1540                                 }
1541                         }
1542
1543                 }
1544
1545                 $GLOBALS['log']->debug("Merging application files for $name in $path");
1546                 //Now the application stuff
1547                 $extension = "<?php \n //WARNING: The contents of this file are auto-generated\n";
1548                 $extpath = "application/$path";
1549                 $module_install  = 'custom/Extension/'.$extpath;
1550                 $shouldSave = false;
1551                                         if(is_dir($module_install)){
1552                                                 $dir = dir($module_install);
1553                                                 while($entry = $dir->read()){
1554                                                                 $shouldSave = true;
1555                                                                 if((empty($filter) || substr_count($entry, $filter) > 0) && is_file($module_install.'/'.$entry)
1556                                                                   && $entry != '.' && $entry != '..' && strtolower(substr($entry, -4)) == ".php")
1557                                                                 {
1558                                                                         $file = file_get_contents($module_install . '/' . $entry);
1559                                                                         $extension .= "\n". str_replace(array('<?php', '?>', '<?PHP', '<?'), array('','', '' ,'') , $file);
1560                                                                 }
1561                                                 }
1562                                         }
1563                                         $extension .= "\n?>";
1564                                         if($shouldSave){
1565                                                 if(!file_exists("custom/$extpath")){
1566                                                         mkdir_recursive("custom/$extpath", true);
1567                                                 }
1568                                                 $out = sugar_fopen("custom/$extpath/$name", 'w');
1569                                                 fwrite($out,$extension);
1570                                                 fclose($out);
1571                                         }else{
1572                                         if(file_exists("custom/$extpath/$name")){
1573                                                 unlink("custom/$extpath/$name");
1574                                         }
1575                                 }
1576
1577 }
1578
1579     function install_modules()
1580     {
1581             $this->installed_modules = array();
1582                 $this->tab_modules = array();
1583         if(isset($this->installdefs['beans'])){
1584                         $str = "<?php \n //WARNING: The contents of this file are auto-generated\n";
1585                         foreach($this->installdefs['beans'] as $bean){
1586                                 if(!empty($bean['module']) && !empty($bean['class']) && !empty($bean['path'])){
1587                                         $module = $bean['module'];
1588                                         $class = $bean['class'];
1589                                         $path = $bean['path'];
1590
1591                                         $str .= "\$beanList['$module'] = '$class';\n";
1592                                         $str .= "\$beanFiles['$class'] = '$path';\n";
1593                                         if($bean['tab']){
1594                                                 $str .= "\$moduleList[] = '$module';\n";
1595                                                 $this->install_user_prefs($module, empty($bean['hide_by_default']));
1596                                                 $this->tab_modules[] = $module;
1597                                         }else{
1598                                                 $str .= "\$modules_exempt_from_availability_check['$module'] = '$module';\n";
1599                                                 $str .= "\$report_include_modules['$module'] = '$module';\n";
1600                                                 $str .= "\$modInvisList[] = '$module';\n";
1601                                         }
1602                                     $this->installed_modules[] = $module;
1603                                 }else{
1604                                                 $errors[] = 'Bean array not well defined.';
1605                                                 $this->abort($errors);
1606                                 }
1607                         }
1608                         $str.= "\n?>";
1609                         if(!file_exists("custom/Extension/application/Ext/Include")){
1610                                 mkdir_recursive("custom/Extension/application/Ext/Include", true);
1611                         }
1612                         file_put_contents("custom/Extension/application/Ext/Include/{$this->id_name}.php", $str);
1613         }
1614     }
1615
1616     /*
1617      * ModuleInstaller->install_beans runs through the list of beans given, instantiates each bean, calls bean->create_tables, and then calls SugarBean::createRelationshipMeta for the
1618      * bean/module.
1619      */
1620         function install_beans($beans){
1621         include('include/modules.php');
1622                 foreach($beans as $bean){
1623                         $this->log( translate('LBL_MI_IN_BEAN') . " $bean");
1624                         if(isset($beanList[$bean])){
1625                                 $class = $beanList[$bean];
1626                                 if(file_exists($beanFiles[$class])){
1627                                         require_once($beanFiles[$class]);
1628                                         $mod = new $class();
1629                                         //#30273
1630                                         if(is_subclass_of($mod, 'SugarBean')  && $mod->disable_vardefs == false ){
1631                                                 $GLOBALS['log']->debug( "Creating Tables Bean : $bean");
1632                                                 $mod->create_tables();
1633                                                 SugarBean::createRelationshipMeta($mod->getObjectName(), $mod->db,$mod->table_name,'',$mod->module_dir);    
1634                                         }
1635                                 }else{
1636                                         $GLOBALS['log']->debug( "File Does Not Exist:" . $beanFiles[$class] );
1637                                 }
1638                         }
1639                 }
1640         }
1641
1642                 function uninstall_beans($beans){
1643                 include('include/modules.php');
1644         foreach($beans as $bean){
1645                         $this->log( translate('LBL_MI_UN_BEAN') . " $bean");
1646                         if(isset($beanList[$bean])){
1647                                 $class = $beanList[$bean];
1648
1649                                 if(file_exists($beanFiles[$class])){
1650                                         require_once($beanFiles[$class]);
1651                                         $mod = new $class();
1652
1653                                         if(is_subclass_of($mod, 'SugarBean')){
1654                                                 $GLOBALS['log']->debug( "Drop Tables : $bean");
1655                                                 if(isset($GLOBALS['mi_remove_tables']) && $GLOBALS['mi_remove_tables'])
1656                                                         $mod->drop_tables();
1657                                         }
1658                                 }else{
1659                                         $GLOBALS['log']->debug( "File Does Not Exist:" . $beanFiles[$class] );
1660                                 }
1661                         }
1662                 }
1663         }
1664
1665         /**
1666          * Remove any customizations made within Studio while the module was installed.
1667          */
1668         function uninstall_customizations($beans){
1669         foreach($beans as $bean){
1670                         $dirs = array(
1671                                 'custom/modules/' . $bean,
1672                                 'custom/Extension/modules/' . $bean,
1673                 'custom/working/modules/' . $bean
1674                         );
1675                 foreach($dirs as $dir)
1676                 {
1677                                 if(is_dir($dir)){
1678                                         rmdir_recursive($dir);
1679                                 }
1680                 }
1681                 }
1682         }
1683
1684         function log($str){
1685                 $GLOBALS['log']->debug('ModuleInstaller:'. $str);
1686                 if(!$this->silent){
1687                         echo $str . '<br>';
1688                 }
1689         }
1690
1691 /* BEGIN - RESTORE POINT - by MR. MILK August 31, 2005 02:15:18 PM      */
1692 function copy_recursive_with_backup( $source, $dest, $backup_path, $uninstall=false ) {
1693         if(is_file($source)) {
1694             if($uninstall) {
1695                     $GLOBALS['log']->debug("Restoring ... " . $source.  " to " .$dest );
1696                     if(copy( $source, $dest)) {
1697                             if(is_writable($dest))
1698                                 sugar_touch( $dest, filemtime($source) );
1699                         return(unlink($source));
1700                 }
1701                     else {
1702                         $GLOBALS['log']->debug( "Can't restore file: " . $source );
1703                         return true;
1704                 }
1705             }
1706             else {
1707                         if(file_exists($dest)) {
1708                                 $rest = clean_path($backup_path."/$dest");
1709                                 if( !is_dir(dirname($rest)) )
1710                                         mkdir_recursive(dirname($rest), true);
1711
1712                                 $GLOBALS['log']->debug("Backup ... " . $dest.  " to " .$rest );
1713                                 if(copy( $dest, $rest)) {
1714                                         if(is_writable($rest))
1715                                                 sugar_touch( $rest, filemtime($dest) );
1716                                 }
1717                                 else {
1718                                         $GLOBALS['log']->debug( "Can't backup file: " . $dest );
1719                                 }
1720                         }
1721                         return( copy( $source, $dest ) );
1722                 }
1723     }
1724     elseif(!is_dir($source)) {
1725             if($uninstall) {
1726                         if(is_file($dest))
1727                                 return(unlink($dest));
1728                         else {
1729                                 //don't do anything we already cleaned up the files using uninstall_new_files
1730                                 return true;
1731                         }
1732                 }
1733                 else
1734                         return false;
1735         }
1736
1737     if( !is_dir($dest) && !$uninstall){
1738         sugar_mkdir( $dest );
1739     }
1740
1741     $status = true;
1742
1743     $d = dir( $source );
1744     while( $f = $d->read() ){
1745         if( $f == "." || $f == ".." ){
1746             continue;
1747         }
1748         $status &= $this->copy_recursive_with_backup( "$source/$f", "$dest/$f", $backup_path, $uninstall );
1749     }
1750     $d->close();
1751     return( $status );
1752 }
1753
1754 private function dir_get_files($path, $base_path){
1755         $files = array();
1756         if(!is_dir($path))return $files;
1757         $d = dir($path);
1758         while ($e = $d->read()){
1759                 //ignore invisible files . .. ._MACOSX
1760                 if(substr($e, 0, 1) == '.')continue;
1761                 if(is_file($path . '/' . $e))$files[str_replace($base_path , '', $path . '/' . $e)] = str_replace($base_path , '', $path . '/' . $e);
1762                 if(is_dir($path . '/' . $e))$files = array_merge($files, $this->dir_get_files($path . '/' . $e, $base_path));
1763         }
1764         $d->close();
1765         return $files;
1766
1767 }
1768
1769 private function dir_file_count($path){
1770         //if its a file then it has at least 1 file in the directory
1771         if(is_file($path)) return 1;
1772         if(!is_dir($path)) return 0;
1773         $d = dir($path);
1774         $count = 0;
1775         while ($e = $d->read()){
1776                 //ignore invisible files . .. ._MACOSX
1777                 if(substr($e, 0, 1) == '.')continue;
1778                 if(is_file($path . '/' . $e))$count++;
1779                 if(is_dir($path . '/' . $e))$count += $this->dir_file_count($path . '/' . $e);
1780         }
1781         $d->close();
1782         return $count;
1783
1784
1785 }
1786 /* END - RESTORE POINT - by MR. MILK August 31, 2005 02:15:34 PM */
1787
1788
1789         /**
1790          * Static function which allows a module developer to abort their progress, pass in an array of errors and
1791          * redirect back to the main module loader page
1792          *
1793          * @param errors        an array of error messages which will be displayed on the
1794          *                                      main module loader page once it is loaded.
1795          */
1796         function abort($errors = array()){
1797                 //set the errors onto the session so we can display them one the moduler loader page loads
1798                 $_SESSION['MODULEINSTALLER_ERRORS'] = $errors;
1799                 echo '<META HTTP-EQUIV="Refresh" content="0;url=index.php?module=Administration&action=UpgradeWizard&view=module">';
1800                 die();
1801                 //header('Location: index.php?module=Administration&action=UpgradeWizard&view=module');
1802         }
1803
1804         /**
1805          * Return the set of errors stored in the SESSION
1806          *
1807          * @return an array of errors
1808          */
1809         function getErrors(){
1810                 if(!empty($_SESSION['MODULEINSTALLER_ERRORS'])){
1811                         $errors = $_SESSION['MODULEINSTALLER_ERRORS'];
1812                         unset($_SESSION['MODULEINSTALLER_ERRORS']);
1813                         return $errors;
1814                 }
1815                 else
1816                         return null;
1817         }
1818
1819         /*
1820      * Add any fields to the DetailView and EditView of the appropriate modules
1821      * Only add into deployed modules, as addFieldsToUndeployedLayouts has done this already for undeployed modules (and the admin might have edited the layouts already)
1822      * @param array $layoutAdditions  An array of module => fieldname
1823      * return null
1824      */
1825         function addFieldsToLayout($layoutAdditions) {
1826         require_once 'modules/ModuleBuilder/parsers/views/GridLayoutMetaDataParser.php' ;
1827
1828         // these modules either lack editviews/detailviews or use custom mechanisms for the editview/detailview.
1829         // In either case, we don't want to attempt to add a relate field to them
1830         // would be better if GridLayoutMetaDataParser could handle this gracefully, so we don't have to maintain this list here
1831         $invalidModules = array ( 'emails' , 'kbdocuments' ) ;
1832
1833         foreach ( $layoutAdditions as $deployedModuleName => $fieldName )
1834         {
1835             if ( ! in_array( strtolower ( $deployedModuleName ) , $invalidModules ) )
1836             {
1837                 foreach ( array ( MB_EDITVIEW , MB_DETAILVIEW ) as $view )
1838                 {
1839                     $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . ": adding $fieldName to $view layout for module $deployedModuleName" ) ;
1840                     $parser = new GridLayoutMetaDataParser ( $view, $deployedModuleName ) ;
1841                     $parser->addField ( array ( 'name' => $fieldName ) ) ;
1842                     $parser->handleSave ( false ) ;
1843                 }
1844             }
1845         }
1846
1847         }
1848
1849         function removeFieldsFromLayout($layoutAdditions) {
1850         require_once 'modules/ModuleBuilder/parsers/views/GridLayoutMetaDataParser.php' ;
1851
1852         // these modules either lack editviews/detailviews or use custom mechanisms for the editview/detailview.
1853         // In either case, we don't want to attempt to add a relate field to them
1854         // would be better if GridLayoutMetaDataParser could handle this gracefully, so we don't have to maintain this list here
1855         $invalidModules = array ( 'emails' , 'kbdocuments' ) ;
1856
1857         foreach ( $layoutAdditions as $deployedModuleName => $fieldName )
1858         {
1859             if ( ! in_array( strtolower ( $deployedModuleName ) , $invalidModules ) )
1860             {
1861                 foreach ( array ( MB_EDITVIEW , MB_DETAILVIEW ) as $view )
1862                 {
1863                     $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . ": adding $fieldName to $view layout for module $deployedModuleName" ) ;
1864                     $parser = new GridLayoutMetaDataParser ( $view, $deployedModuleName ) ;
1865                     $parser->removeField ( $fieldName ) ;
1866                     $parser->handleSave ( false ) ;
1867                 }
1868             }
1869         }
1870
1871         }
1872
1873         ///////////////////
1874         //********** DISABLE/ENABLE FUNCTIONS
1875         ///////////////////
1876         function enable($base_dir, $is_upgrade = false, $previous_version = ''){
1877                 global $app_strings;
1878                 $this->base_dir = $base_dir;
1879                 $total_steps = 3; //minimum number of steps with no tasks
1880                 $current_step = 0;
1881                 $tasks = array(
1882                                                                 'enable_copy',
1883                                                                 'enable_dashlets',
1884                                                                 'enable_relationships',
1885                                         'enable_extensions',
1886                                         'enable_manifest_logichooks',
1887                                                                 'reset_opcodes',
1888                 );
1889                 $total_steps += count($tasks);
1890                 if(file_exists($this->base_dir . '/manifest.php')){
1891                                 if(!$this->silent){
1892                                         $current_step++;
1893                                         display_progress_bar('install', $current_step, $total_steps);
1894                                         echo '<div id ="displayLoglink" ><a href="#" onclick="toggleDisplay(\'displayLog\')">'.$app_strings['LBL_DISPLAY_LOG'].'</a> </div><div id="displayLog" style="display:none">';
1895                                 }
1896
1897                                 require_once($this->base_dir . '/manifest.php');
1898                                 if($is_upgrade && !empty($previous_version)){
1899                                         //check if the upgrade path exists
1900                                         if(!empty($upgrade_manifest)){
1901                                                 if(!empty($upgrade_manifest['upgrade_paths'])){
1902                                                         if(!empty($upgrade_manifest['upgrade_paths'][$previous_version])){
1903                                                                 $installdefs =  $upgrade_manifest['upgrade_paths'][$previous_version];
1904                                                         }else{
1905                                                                 $errors[] = 'No Upgrade Path Found in manifest.';
1906                                                                 $this->abort($errors);
1907                                                         }//fi
1908                                                 }//fi
1909                                         }//fi
1910                                 }//fi
1911                                 $this->id_name = $installdefs['id'];
1912                                 $this->installdefs = $installdefs;
1913                                 $installed_modules = array();
1914                                 if(isset($installdefs['beans'])){
1915                                         foreach($this->installdefs['beans'] as $bean){
1916                                                 $installed_modules[] = $bean['module'];
1917                                         }
1918                                 }
1919                                 if(!$this->silent){
1920                                         $current_step++;
1921                                         update_progress_bar('install', $current_step, $total_steps);
1922                                 }
1923
1924                                 foreach($tasks as $task){
1925                                         $this->$task();
1926                                         if(!$this->silent){
1927                                                 $current_step++;
1928                                                 update_progress_bar('install', $current_step, $total_steps);
1929                                         }
1930                                 }
1931
1932                                 if(!$this->silent){
1933                                         $current_step++;
1934                                         update_progress_bar('install', $current_step, $total_steps);
1935                                         echo '</div>';
1936                                 }
1937                                 UpdateSystemTabs('Add',$installed_modules);
1938                                 $GLOBALS['log']->debug('Complete');
1939
1940                 }else{
1941                         die("No \$installdefs Defined In $this->base_dir/manifest.php");
1942                 }
1943
1944         }
1945         function disable($base_dir){
1946                 global $app_strings;
1947                 $total_steps = 3; //min steps with no tasks
1948                 $current_step = 0;
1949                 $this->base_dir = $base_dir;
1950                 $tasks = array(
1951                                                         'disable_copy',
1952                                                         'disable_dashlets',
1953                                                         'disable_relationships',
1954                                     'disable_extensions',
1955                                                         'disable_manifest_logichooks',
1956                                                         'reset_opcodes',
1957                                                         );
1958                 $total_steps += count($tasks); //now the real number of steps
1959                 if(file_exists($this->base_dir . '/manifest.php')){
1960                                 if(!$this->silent){
1961                                         $current_step++;
1962                                         display_progress_bar('install', $current_step, $total_steps);
1963                                         echo '<div id ="displayLoglink" ><a href="#" onclick="toggleDisplay(\'displayLog\')">'.$app_strings['LBL_DISPLAY_LOG'].'</a> </div><div id="displayLog" style="display:none">';
1964                                 }
1965
1966                                 require_once($this->base_dir . '/manifest.php');
1967                                 $this->installdefs = $installdefs;
1968                                 $this->id_name = $this->installdefs['id'];
1969                                 $installed_modules = array();
1970                                 if(isset($this->installdefs['beans'])){
1971                                         foreach($this->installdefs['beans'] as $bean){
1972                                                 $installed_modules[] = $bean['module'];
1973                                         }
1974                                 }
1975                                 if(!$this->silent){
1976                                         $current_step++;
1977                                         update_progress_bar('install', $current_step, $total_steps);
1978                                 }
1979                                 foreach($tasks as $task){
1980                                         $this->$task();
1981                                         if(!$this->silent){
1982                                                 $current_step++;
1983                                                 update_progress_bar('install', $current_step, $total_steps);
1984                                         }
1985                                 }
1986                                 if(!$this->silent){
1987                                         $current_step++;
1988                                         update_progress_bar('install', $current_step, $total_steps);
1989                                         echo '</div>';
1990                                 }
1991                         UpdateSystemTabs('Restore',$installed_modules);
1992
1993                 }else{
1994                         die("No manifest.php Defined In $this->base_dir/manifest.php");
1995                 }
1996         }
1997
1998         function enable_vardef($to_module)
1999         {
2000             $this->enableExt("vardefs", "Vardefs", $to_module);
2001         }
2002
2003         function enable_layoutdef($to_module)
2004         {
2005             $this->enableExt("layoutdefs", "Layoutdefs", $to_module);
2006         }
2007
2008         function enable_relationships(){
2009                 if(isset($this->installdefs['relationships'])){
2010                         $str = "<?php \n //WARNING: The contents of this file are auto-generated\n";
2011                         $save_table_dictionary = false;
2012                         foreach($this->installdefs['relationships'] as $relationship){
2013                 $filename       =basename($relationship['meta_data']);
2014
2015                                 $save_table_dictionary  = true;
2016                                 $str .= "include_once('metadata/$filename');\n";
2017                                 if (empty($relationship['module']))
2018                                     continue;
2019
2020                                 if(!empty($relationship['module_vardefs'])){
2021                                         $this->enable_vardef($relationship['module']);
2022                                 }
2023                                 if(!empty($relationship['module_layoutdefs'])){
2024                                         $this->enable_layoutdef($relationship['module']);
2025                                 }
2026                         }
2027                         $this->rebuild_vardefs();
2028                         $this->rebuild_layoutdefs();
2029                         if($save_table_dictionary){
2030                                 if(!file_exists("custom/Extension/application/Ext/TableDictionary")){
2031                                         mkdir_recursive("custom/Extension/application/Ext/TableDictionary", true);
2032                                 }
2033                                 if (file_exists("custom/Extension/application/Ext/TableDictionary/".DISABLED_PATH."/$this->id_name.php"))
2034                                    rename("custom/Extension/application/Ext/TableDictionary/".DISABLED_PATH."/$this->id_name.php", "custom/Extension/application/Ext/TableDictionary/$this->id_name.php");
2035                                 $this->rebuild_tabledictionary();
2036                         }
2037                 }
2038         }
2039
2040         function disable_relationships($action = 'disable'){
2041                 if(isset($this->installdefs['relationships'])){
2042                         foreach($this->installdefs['relationships'] as $relationship){
2043                                 $filename = basename($relationship['meta_data']);
2044                 $relName = substr($filename, -12) == "MetaData.php" ? substr($filename,0,strlen($filename) - 12) : "";
2045                                 if (empty($relationship['module']) && empty($relName))
2046                         continue;
2047
2048                                 //remove the vardefs
2049                                 if (empty($relName))
2050                                         $path = 'custom/Extension/modules/' . $relationship['module']. '/Ext/Vardefs';
2051                                 if(!empty($relationship['module']) && $relationship['module'] == 'application'){
2052                                         $path ='custom/Extension/' . $relationship['module']. '/Ext/Vardefs';
2053                                 }
2054                                 if(!empty($relationship['module_vardefs']) && file_exists($path . '/'. $this->id_name . '.php')){
2055                                         mkdir_recursive($path . '/'.DISABLED_PATH, true);
2056                                         rename( $path . '/'. $this->id_name . '.php', $path . '/'.DISABLED_PATH.'/'. $this->id_name . '.php');
2057                                 }
2058                                 //remove the layoutdefs
2059                                 if ( !empty($relationship['module']) ) {
2060                     $path = 'custom/Extension/modules/' . $relationship['module']. '/Ext/Layoutdefs';
2061                     if($relationship['module'] == 'application'){
2062                         $path ='custom/Extension/' . $relationship['module']. '/Ext/Layoutdefs';
2063                     }
2064                                 }
2065
2066                                 if(!empty($relationship['module_layoutdefs']) && file_exists($path . '/'. $this->id_name . '.php')){
2067                                         mkdir_recursive($path . '/'.DISABLED_PATH, true);
2068                                         rename( $path . '/'. $this->id_name . '.php', $path . '/'.DISABLED_PATH.'/'. $this->id_name . '.php');
2069                                 }
2070
2071                         }
2072                         if(file_exists("custom/Extension/application/Ext/TableDictionary/$this->id_name.php")){
2073                                 mkdir_recursive("custom/Extension/application/Ext/TableDictionary/".DISABLED_PATH, true);
2074                                 rename("custom/Extension/application/Ext/TableDictionary/$this->id_name.php", "custom/Extension/application/Ext/TableDictionary/".DISABLED_PATH."/$this->id_name.php");
2075                         }
2076                         $this->rebuild_tabledictionary();
2077                         $this->rebuild_vardefs();
2078                         $this->rebuild_layoutdefs();
2079                 }
2080         }
2081
2082         function enable_dashlets(){
2083                 if(isset($this->installdefs['dashlets'])){
2084                         foreach($this->installdefs['dashlets'] as $cp){
2085                                 $cp['from'] = str_replace('<basepath>', $this->base_dir, $cp['from']);
2086                                 $path = 'custom/modules/Home/Dashlets/' . $cp['name'] . '/';
2087                                 $disabled_path = 'custom/modules/Home/'.DISABLED_PATH.'Dashlets/' . $cp['name'];
2088                                 $GLOBALS['log']->debug("Enabling Dashlet " . $cp['name'] . "..." . $cp['from'] );
2089                                 if (file_exists($disabled_path))
2090                                 {
2091                                         rename($disabled_path,  $path);
2092                                 }
2093                         }
2094                         include('modules/Administration/RebuildDashlets.php');
2095
2096                 }
2097         }
2098
2099         function disable_dashlets(){
2100                 if(isset($this->installdefs['dashlets'])){
2101                                         foreach($this->installdefs['dashlets'] as $cp){
2102                                                 $path = 'custom/modules/Home/Dashlets/' . $cp['name'];
2103                                                 $disabled_path = 'custom/modules/Home/'.DISABLED_PATH.'Dashlets/' . $cp['name'];
2104                                                 $GLOBALS['log']->debug('Disabling ' .$path);
2105                                                 if (file_exists($path))
2106                                                 {
2107                                                         mkdir_recursive('custom/modules/Home/'.DISABLED_PATH.'Dashlets/', true);
2108                                                         rename( $path, $disabled_path);
2109                                                 }
2110                                         }
2111                                         include('modules/Administration/RebuildDashlets.php');
2112                                 }
2113         }
2114
2115         function enable_copy(){
2116                 //copy files back onto file system. first perform md5 check to determine if anything has been modified
2117                 //here we should just go through the files in the -restore directory and copy those back
2118                 if(isset($GLOBALS['mi_overwrite_files']) && $GLOBALS['mi_overwrite_files']){
2119                         if(!empty($this->installdefs['copy'])){
2120                                 foreach($this->installdefs['copy'] as $cp){
2121                                         $cp['to'] = clean_path(str_replace('<basepath>', $this->base_dir, $cp['to']));
2122                                         $backup_path = clean_path( remove_file_extension(urldecode(hashToFile($_REQUEST['install_file'])))."-restore/".$cp['to'] );
2123
2124                                         //check if this file exists in the -restore directory
2125                                         if(file_exists($backup_path)){
2126                                                 //since the file exists, then we want do an md5 of the install version and the file system version
2127                                                 //if(is_file($backup_path) && md5_file($backup_path) == md5_file($cp['to'])){
2128                                                         //since the files are the same then we can safely move back from the -restore
2129                                                         //directory into the file system
2130                                                         $GLOBALS['log']->debug("ENABLE COPY:: FROM: ".$cp['from']. " TO: ".$cp['to']);
2131                                                         $this->copy_path($cp['from'], $cp['to']);
2132                                                 /*}else{
2133                                                         //since they are not equal then we need to prompt the user
2134                                                 }*/
2135                                         }//fi
2136                                 }//rof
2137                         }//fi
2138                 }//fi
2139         }
2140
2141         function disable_copy(){
2142                 //when we disable we want to copy the -restore files back into the file system
2143                 //but we should check the version in the module install against the version on the file system
2144                 //if they match then we can copy the file back, but otherwise we should ask the user.
2145
2146 //              $GLOBALS['log']->debug('ModuleInstaller.php->disable_copy()');
2147                 if(isset($GLOBALS['mi_overwrite_files']) && $GLOBALS['mi_overwrite_files']){
2148 //              $GLOBALS['log']->debug('ModuleInstaller.php->disable_copy():mi_overwrite_files=true');
2149                         if(!empty($this->installdefs['copy'])){
2150 //                              $GLOBALS['log']->debug('ModuleInstaller.php->disable_copy(): installdefs not empty');
2151                                 foreach($this->installdefs['copy'] as $cp){
2152                                         $cp['to'] = clean_path(str_replace('<basepath>', $this->base_dir, $cp['to']));
2153                                         $backup_path = clean_path( remove_file_extension(urldecode(hashToFile($_REQUEST['install_file'])))."-restore/".$cp['to'] ); // bug 16966 tyoung - replaced missing assignment to $backup_path
2154                                         //check if this file exists in the -restore directory
2155 //                                      $GLOBALS['log']->debug("ModuleInstaller.php->disable_copy(): backup_path=".$backup_path);
2156                                         if(file_exists($backup_path)){
2157                                                 //since the file exists, then we want do an md5 of the install version and the file system version
2158                                                 $from = str_replace('<basepath>', $this->base_dir, $cp['from']);
2159
2160                                                 //if(is_file($from) && md5_file($from) == md5_file($cp['to'])){
2161                                                         //since the files are the same then we can safely move back from the -restore
2162                                                         //directory into the file system
2163                                                         $GLOBALS['log']->debug("DISABLE COPY:: FROM: ".$backup_path. " TO: ".$cp['to']);
2164                                                         $this->copy_path($backup_path, $cp['to']);
2165                                                 /*}else{
2166                                                         //since they are not equal then we need to prompt the user
2167                                                 }*/
2168                                         }//fi
2169                                 }//rof
2170                         }//fi
2171                 }//fi
2172         }
2173
2174         public function reset_opcodes()
2175     {
2176         /* Bug 39354 - added function_exists check. Not optimal fix, but safe nonetheless.
2177          * This is for the upgrade to 6.1 from pre 6.1, since the utils files haven't been updated to 6.1 when this is called,
2178          * but this file has been updated to 6.1
2179          */
2180         if(function_exists('sugar_clean_opcodes')){
2181             sugar_clean_opcodes();
2182         }
2183     }
2184
2185     /**
2186      * BC implementation to provide specific calls to extensions
2187      */
2188     public function __call($name, $args)
2189     {
2190         $nameparts = explode('_', $name);
2191         // name is something_something
2192         if(count($nameparts) == 2 && isset($this->extensions[$nameparts[1]])) {
2193             $ext = $this->extensions[$nameparts[1]];
2194             switch($nameparts[0]) {
2195                 case 'enable':
2196                     return $this->enableExt($ext['section'], $ext['extdir']);
2197                 case 'disable':
2198                     return $this->disableExt($ext['section'], $ext['extdir']);
2199                 case 'install':
2200                     return $this->installExt($ext['section'], $ext['extdir']);
2201                 case 'uninstall':
2202                     return $this->uninstallExt($ext['section'], $ext['extdir']);
2203                 case 'rebuild':
2204                     return $this->rebuildExt($ext['extdir'], $ext['file']);
2205             }
2206         }
2207         sugar_die("Unknown method ModuleInstaller::$name called");
2208     }
2209
2210 }
2211
2212     function UpdateSystemTabs($action, $installed_modules){
2213         require_once("modules/MySettings/TabController.php");
2214         $controller = new TabController();
2215         $isSystemTabsInDB = $controller->is_system_tabs_in_db();
2216         if ($isSystemTabsInDB && !empty($installed_modules))
2217         {
2218             global $moduleList;
2219             switch ($action)
2220             {
2221                 case 'Restore' :
2222                     $currentTabs = $controller->get_system_tabs();
2223                     foreach ($installed_modules as $module)
2224                     {
2225                         if(in_array($module, $currentTabs)){
2226                             unset($currentTabs[$module]);
2227                         }
2228                     }
2229                     $controller->set_system_tabs($currentTabs);;
2230                     break;
2231                 case 'Add' :
2232                     $currentTabs = $controller->get_system_tabs();
2233                     foreach ($installed_modules as $module)
2234                     {
2235                         if(!in_array($module, $currentTabs)){
2236                             $currentTabs[$module] = $module;
2237                         }
2238                     }
2239                     $controller->set_system_tabs($currentTabs);
2240                 default:
2241                     break;
2242             }
2243     }
2244
2245 }