]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/ModuleBuilder/MB/MBPackage.php
Release 6.5.6
[Github/sugarcrm.git] / modules / ModuleBuilder / MB / MBPackage.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37 require_once('modules/ModuleBuilder/MB/MBModule.php');
38
39 class MBPackage{
40     var $name;
41     var $is_uninstallable = true;
42     var $description = '';
43     var $has_images = true;
44     var $modules = array();
45     var $date_modified = '';
46     var $author = '';
47     var $key = '';
48     var $readme='';
49     function MBPackage($name){
50         $this->name = $name;
51         $this->load();
52         
53     }
54     function loadModules($force=false){
55         if(!file_exists(MB_PACKAGE_PATH . '/' . $this->name .'/modules'))return;
56         $d = dir(MB_PACKAGE_PATH . '/' . $this->name .'/modules');
57         while($e = $d->read()){
58             if(substr($e, 0, 1) != '.' && is_dir(MB_PACKAGE_PATH . '/'. $this->name. '/modules/' . $e)){
59                 $this->getModule($e, $force);
60             }
61         }
62     }
63     
64     /**
65      * Loads the translated module titles from the selected language into.
66      * Will override currently loaded string to reflect undeployed label changes.
67      * $app_list_strings
68      * @return 
69      * @param $languge String language identifyer
70      */
71     function loadModuleTitles($languge = '') 
72     {
73         if (empty($language))
74         {
75             $language = $GLOBALS['current_language'];
76         }
77         global $app_list_strings;
78         $packLangFilePath = $this->getPackageDir() . "/language/application/" . $language . ".lang.php";
79         if (file_exists($packLangFilePath))
80         {
81             
82             require($packLangFilePath);
83         }
84     }
85     
86     /**
87      * @param $name
88      * @param bool $force
89      * @return MBModule
90      */
91     function getModule($name, $force=true){
92         if(!$force && !empty($this->modules[$name]))
93             return $this->modules[$name];
94
95         $path = $this->getPackageDir();
96         $this->modules[$name] = new MBModule($name, $path, $this->name, $this->key);
97
98         return $this->modules[$name];
99     }
100
101     /**
102      * Returns an MBModule by the given full name (package key + module name)
103      * if it exists in this package
104      *
105      * @param string $name
106      * @return MBModule
107      */
108     public function getModuleByFullName($name){
109         foreach($this->modules as $mname => $module) {
110             if ($this->key . "_" . $mname == $name)
111                 return $module;
112         }
113     }
114     
115     function deleteModule($name){
116         $this->modules[$name]->delete();
117         unset($this->modules[$name]);
118     }
119     
120 function getManifest($version_specific = false, $for_export = false){
121     //If we are exporting the package, we must ensure a different install key
122     $pre = $for_export ? MB_EXPORTPREPEND : "";
123     $date = TimeDate::getInstance()->nowDb();
124     $time = time();
125     $this->description = to_html($this->description);
126     $is_uninstallable = ($this->is_uninstallable ? true : false);
127     if($GLOBALS['sugar_flavor'] == 'CE') {
128         $flavors = array('CE','PRO','ENT');
129     } else {
130         $flavors = array($GLOBALS['sugar_flavor']);
131     }
132     $version = (!empty($version_specific))?$GLOBALS['sugar_version']:'';
133
134     // Build an array and use var_export to build this file
135     $manifest = array(
136         array('acceptable_sugar_versions' => array($version)),
137         array('acceptable_sugar_flavors' => $flavors),
138         'readme' => $this->readme,
139         'key' => $this->key,
140         'author' => $this->author,
141         'description' => $this->description,
142         'icon' => '',
143         'is_uninstallable' => $is_uninstallable,
144         'name' => $pre.$this->name,
145         'published_date' => $date,
146         'type' => 'module',
147         'version' => $time,
148         'remove_tables' => 'prompt',
149     );
150         
151               
152
153     $header = file_get_contents('modules/ModuleBuilder/MB/header.php');
154     
155     return $header."\n// THIS CONTENT IS GENERATED BY MBPackage.php\n".'$manifest = '.var_export_helper($manifest).";\n\n";
156 /*
157     return  <<<EOQ
158     $header
159     \$manifest = array (
160          'acceptable_sugar_versions' => 
161           array (
162             $version
163           ),
164           'acceptable_sugar_flavors' =>
165           array(
166             $flavor
167           ),
168           'readme'=>'$this->readme',
169           'key'=>'$this->key',
170           'author' => '$this->author',
171           'description' => '$this->description',
172           'icon' => '',
173           'is_uninstallable' => $is_uninstallable,
174           'name' => '$pre$this->name',
175           'published_date' => '$date',
176           'type' => 'module',
177           'version' => '$time',
178           'remove_tables' => 'prompt',
179           );
180 EOQ;
181 */
182 }
183     
184 function buildInstall($path){
185     $installdefs = array ('id' => $this->name,
186         'beans'=>array(),
187         'layoutdefs'=>array(),
188         'relationships'=>array(),
189     );
190     if($this->has_images){
191         $installdefs['image_dir'] = '<basepath>/icons'; 
192     }
193     foreach(array_keys($this->modules) as $module){
194         $this->modules[$module]->build($path);
195         $this->modules[$module]->addInstallDefs($installdefs);
196     }
197     $this->path = $this->getPackageDir(); 
198     if(file_exists($this->path . '/language')){
199         $d= dir($this->path . '/language');
200         while($e = $d->read()){
201             $lang_path = $this->path .'/language/' . $e;
202             if(substr($e, 0, 1) != '.' && is_dir($lang_path)){
203                 $f = dir($lang_path);
204                 while($g = $f->read()){
205                     if(substr($g, 0, 1) != '.' && is_file($lang_path.'/'. $g)){
206                         $lang = substr($g, 0, strpos($g, '.'));
207                         $installdefs['language'][] = array(
208                         'from'=> '<basepath>/SugarModules/language/'.$e . '/'. $g,
209                         'to_module'=> $e,
210                         'language'=> $lang  
211                         );
212                     }
213                 }
214             }
215         }
216             
217         copy_recursive( $this->path . '/language/', $path . '/language/');
218         $icon_path = $path . '/../icons/default/images/';
219         mkdir_recursive($icon_path);
220         copy_recursive($this->path . '/icons/', $icon_path);
221     }
222     return "\n".'$installdefs = ' . var_export_helper($installdefs). ';';
223
224 }
225     
226     function getPackageDir(){
227         return MB_PACKAGE_PATH . '/' . $this->name;
228     }
229     
230     function getBuildDir(){
231         return MB_PACKAGE_BUILD . DIRECTORY_SEPARATOR . $this->name;
232     }
233     
234     function getZipDir(){
235         return $this->getPackageDir() . '/zips';
236     }
237     
238     
239     function load(){
240         $path = $this->getPackageDir();
241         if(file_exists($path .'/manifest.php')){
242             require($path . '/manifest.php');
243             if(!empty($manifest)){
244                 $this->date_modified = $manifest['published_date'];
245                 $this->is_uninstallable = $manifest['is_uninstallable'];
246                 $this->author = $manifest['author'];
247                 $this->key = $manifest['key'];
248                 $this->description = $manifest['description'];
249                 if(!empty($manifest['readme']))
250                     $this->readme = $manifest['readme'];
251             }
252         }
253         $this->loadModules(true);
254     }
255
256     function save(){
257         $path = $this->getPackageDir();
258         if(mkdir_recursive($path)){
259             //Save all the modules when we save a package
260             $this->updateModulesMetaData(true);
261             sugar_file_put_contents_atomic($path .'/manifest.php', $this->getManifest());
262         }
263     }
264     
265     function build($export=true, $clean = false){
266         $this->loadModules();
267         require_once('include/utils/zip_utils.php');
268         $package_path = $this->getPackageDir();
269         $path = $this->getBuildDir() . '/SugarModules';
270         if($clean && file_exists($path))rmdir_recursive($path);
271         if(mkdir_recursive($path)){
272             
273             $manifest = $this->getManifest().$this->buildInstall($path);
274             $fp = sugar_fopen($this->getBuildDir() .'/manifest.php', 'w');
275             fwrite($fp, $manifest);
276             fclose($fp);
277             
278         }
279         if(file_exists('modules/ModuleBuilder/MB/LICENSE.txt')){
280             copy('modules/ModuleBuilder/MB/LICENSE.txt', $this->getBuildDir() . '/LICENSE.txt');
281         }else if(file_exists('LICENSE.txt')){
282             copy('LICENSE.txt', $this->getBuildDir() . '/LICENSE.txt');
283         }
284         $package_dir = $this->getPackageDir();
285         $date = date('Y_m_d_His');
286         $zipDir = $this->getZipDir();
287         if(!file_exists($zipDir))mkdir_recursive($zipDir);
288         $cwd = getcwd();
289         chdir($this->getBuildDir());
290         zip_dir('.',$cwd . '/'. $zipDir. '/'. $this->name. $date. '.zip');
291         chdir($cwd);
292         if($export){
293             header('Location:' . $zipDir. '/'. $this->name. $date. '.zip');
294         }
295         return array(
296             'zip'=>$zipDir. '/'. $this->name. $date. '.zip',
297             'manifest'=>$this->getBuildDir(). '/manifest.php',
298             'name'=>$this->name. $date,
299             );
300     }
301     
302     
303     function getNodes(){
304         $this->loadModules();
305         $node = array('name'=>$this->name, 'action'=>'module=ModuleBuilder&action=package&package=' . $this->name, 'children'=>array());
306         foreach(array_keys($this->modules) as $module){
307             $node['children'][] = $this->modules[$module]->getNodes();
308         }
309         return $node;
310     }
311     
312     function populateFromPost(){
313         $this->description = trim($_REQUEST['description']);
314         $this->author = trim($_REQUEST['author']);
315         $this->key = trim($_REQUEST['key']);
316         $this->readme = trim($_REQUEST['readme']);
317     }
318     
319     function rename($new_name){
320         $old= $this->getPackageDir();
321         $this->name = $new_name;
322         $new = $this->getPackageDir();
323         if(file_exists($new)){
324             return false;   
325         }
326         if(rename($old, $new)){
327             return true;
328         }
329             
330         return false;
331     }
332     
333     function updateModulesMetaData($save=false){
334             foreach(array_keys($this->modules) as $module){
335                 $old_name = $this->modules[$module]->key_name;
336                 $this->modules[$module]->key_name = $this->key . '_' . $this->modules[$module]->name;
337                 $this->modules[$module]->renameMetaData($this->modules[$module]->getModuleDir(), $old_name);
338                 $this->modules[$module]->renameLanguageFiles($this->modules[$module]->getModuleDir());
339                 if($save)$this->modules[$module]->save();
340             }
341         
342     }
343     
344     function copy($new_name){
345         $old= $this->getPackageDir();
346         
347         $count = 0;
348         $this->name = $new_name;
349         $new= $this->getPackageDir();
350         while(file_exists($new)){
351             $count++;
352             $this->name = $new_name . $count;
353             $new= $this->getPackageDir();
354         }
355         
356         $new = $this->getPackageDir();
357         if(copy_recursive($old, $new)){
358             $this->updateModulesMetaData();
359             return true;
360         }
361         return false;
362         
363     }
364     
365     function delete(){
366         return rmdir_recursive($this->getPackageDir());
367     }
368     
369     
370         //creation of the installdefs[] array for the manifest when exporting customizations
371     function customBuildInstall($modules, $path, $extensions = array()){
372         $columns=$this->getColumnsName();
373         $installdefs = array ('id' => $this->name, 'relationships' => array());
374         $include_path="$path/SugarModules/include/language";
375         if(file_exists($include_path) && is_dir($include_path)){
376             $dd= dir($include_path);
377             while($gg = $dd->read()){
378                 if(substr($gg, 0, 1) != '.' && is_file($include_path . '/' . $gg)){
379                     $lang = substr($gg, 0, strpos($gg, '.'));
380                     $installdefs['language'][] = array(
381                     'from'=> '<basepath>/SugarModules/include/language/'. $gg,
382                     'to_module'=> 'application',
383                     'language'=>$lang    
384                     );
385                 }
386             }
387         }
388         
389         foreach($modules as $value){
390             $custom_module = $this->getCustomModules($value);
391             foreach($custom_module as $va){
392                 if ($va == 'language'){
393                     $this->getLanguageManifestForModule($value, $installdefs);
394                     $this->getCustomFieldsManifestForModule($value, $installdefs);
395                 }//fi
396                 if($va == 'metadata'){
397                     $this->getCustomMetadataManifestForModule($value, $installdefs);
398                 }//fi
399             }//foreach
400             $relationshipsMetaFiles = $this->getCustomRelationshipsMetaFilesByModuleName($value, true, true);
401             if($relationshipsMetaFiles)
402             {
403                 foreach ($relationshipsMetaFiles as $file)
404                 {
405                     $installdefs['relationships'][] = array('meta_data' => str_replace('custom', '<basepath>', $file)); 
406                 }
407             }
408         }//foreach
409         if (is_dir($path . DIRECTORY_SEPARATOR . 'Extension'))
410         {
411             $this->getExtensionsManifestForPackage($path, $installdefs);
412         }
413         return "\n".'$installdefs = ' . var_export_helper($installdefs). ';';
414     }
415     
416     private function getLanguageManifestForModule($module, &$installdefs)
417     {
418         $lang_path = 'custom' . DIRECTORY_SEPARATOR . 'modules' . DIRECTORY_SEPARATOR . $module . DIRECTORY_SEPARATOR . 'language';
419         foreach(scandir($lang_path) as $langFile)
420         {
421                 if(substr($langFile, 0, 1) != '.' && is_file($lang_path . DIRECTORY_SEPARATOR . $langFile)){
422                     $lang = substr($langFile, 0, strpos($langFile, '.'));
423                     $installdefs['language'][] = array(
424                         'from'=> '<basepath>/SugarModules/modules/' . $module . '/language/'. $langFile,
425                         'to_module'=> $module,
426                         'language'=>$lang
427                     );
428                 }
429         }  
430     }
431     
432     private function getCustomFieldsManifestForModule($module, &$installdefs)
433     {
434         $db = DBManagerFactory::getInstance();
435         $result=$db->query("SELECT *  FROM fields_meta_data where custom_module='$module'");
436         while($row = $db->fetchByAssoc($result)){
437                 $name = $row['id'];
438                 foreach($row as $col=>$res){
439                         switch ($col) {
440                                 case 'custom_module':
441                                         $installdefs['custom_fields'][$name]['module'] = $res;
442                                         break;
443                                 case 'required':
444                                         $installdefs['custom_fields'][$name]['require_option'] = $res;
445                                         break;
446                                 case 'vname':
447                                         $installdefs['custom_fields'][$name]['label'] = $res;
448                                         break;
449                                 case 'required':
450                                         $installdefs['custom_fields'][$name]['require_option'] = $res;
451                                         break;
452                                 case 'massupdate':
453                                         $installdefs['custom_fields'][$name]['mass_update'] = $res;
454                                         break;
455                                 case 'comments':
456                                         $installdefs['custom_fields'][$name]['comments'] = $res;
457                                         break;
458                                 case 'help':
459                                         $installdefs['custom_fields'][$name]['help'] = $res;
460                                         break;
461                                 case 'len':
462                                         $installdefs['custom_fields'][$name]['max_size'] = $res;
463                                         break;
464                                 default:
465                                         $installdefs['custom_fields'][$name][$col] = $res;
466                         }//switch
467                 }//foreach
468         }//while
469     }
470     
471     private function getCustomMetadataManifestForModule($module, &$installdefs)
472     {
473         $meta_path = 'custom/modules/' . $module . '/metadata';
474         foreach(scandir($meta_path) as $meta_file)
475         {
476                 if(substr($meta_file, 0, 1) != '.' && is_file($meta_path . '/' . $meta_file)){
477                         if($meta_file == 'listviewdefs.php'){
478                                 $installdefs['copy'][] = array(
479                                 'from'=> '<basepath>/SugarModules/modules/'. $module . '/metadata/'. $meta_file,
480                                 'to'=> 'custom/modules/'. $module . '/metadata/' . $meta_file,   
481                                 );
482                         }
483                         else{
484                                 $installdefs['copy'][] = array(
485                                 'from'=> '<basepath>/SugarModules/modules/'. $module . '/metadata/'. $meta_file,
486                                 'to'=> 'custom/modules/'. $module . '/metadata/' . $meta_file,   
487                                 );
488                                 $installdefs['copy'][] = array(
489                                 'from'=> '<basepath>/SugarModules/modules/'. $module . '/metadata/'. $meta_file,
490                                 'to'=> 'custom/working/modules/'. $module . '/metadata/' . $meta_file,   
491                                 );
492                         }
493                 }
494         }
495     }
496
497     /**
498      * @todo private changed protected for testing purposes.
499      * 
500      * @param string $path
501      * @param array $installdefs link
502      */
503     protected function getExtensionsManifestForPackage($path, &$installdefs)
504     {
505         $installdefs['copy'] = array();
506         $generalPath = DIRECTORY_SEPARATOR . 'Extension' . DIRECTORY_SEPARATOR . 'modules';
507
508         $recursiveIterator = new RecursiveIteratorIterator(
509                 new RecursiveDirectoryIterator($path . $generalPath),
510                 RecursiveIteratorIterator::SELF_FIRST
511         );
512
513         /* @var $fInfo SplFileInfo */
514         foreach (new RegexIterator($recursiveIterator, "/\.php$/i") as $fInfo)
515         {
516
517             $newPath = substr($fInfo->getPathname(), strrpos($fInfo->getPathname(), $generalPath));
518
519             $installdefs['copy'][] = array(
520                 'from' => '<basepath>' . $newPath,
521                 'to' => 'custom' . $newPath
522             );
523         }
524     }
525
526     //return an array which contain the name of fields_meta_data table's columns 
527     function getColumnsName(){
528          
529         $meta = new FieldsMetaData();
530         $arr = array(); 
531          foreach($meta->getFieldDefinitions() as $key=>$value) {
532             $arr[] = $key;
533         }
534         return $arr;
535     }
536
537
538     //creation of the custom fields ZIP file (use getmanifest() and customBuildInstall() )  
539     function exportCustom($modules, $export=true, $clean = true){
540         
541         $relationshipFiles = array();
542
543         $path = $this->getBuildDir();
544         if ($clean && file_exists($path)) {
545             rmdir_recursive($path);
546         }
547         //Copy the custom files to the build dir
548         foreach ($modules as $module) {
549             $pathmod = "$path/SugarModules/modules/$module";
550             if (mkdir_recursive($pathmod)) {
551                 if (file_exists("custom/modules/$module")) {
552                     copy_recursive("custom/modules/$module", "$pathmod");
553                     //Don't include cached extension files
554                     if (is_dir("$pathmod/Ext"))
555                         rmdir_recursive("$pathmod/Ext");
556                 }
557                 //Convert modstring files to extension compatible arrays
558                 $this->convertLangFilesToExtensions("$pathmod/language");
559             }
560
561             $extensions = $this->getExtensionsList($module, $modules);
562             $relMetaFiles = $this->getCustomRelationshipsMetaFilesByModuleName($module, true);
563             $extensions = array_merge($extensions, $relMetaFiles);
564
565             foreach ($extensions as $file) {
566                 $fileInfo = new SplFileInfo($file);
567                 $trimmedPath = ltrim($fileInfo->getPath(), 'custom');
568
569                 sugar_mkdir($path . $trimmedPath, NULL, true);
570                 copy($file, $path . $trimmedPath . '/' . $fileInfo->getFilename());
571             }
572         }
573
574         $this->copyCustomDropdownValuesForModules($modules,$path);
575         if(file_exists($path)){
576             $manifest = $this->getManifest(true).$this->customBuildInstall($modules,$path);
577             sugar_file_put_contents($path .'/manifest.php', $manifest);
578         }
579         if(file_exists('modules/ModuleBuilder/MB/LICENSE.txt')){
580             copy('modules/ModuleBuilder/MB/LICENSE.txt', $path . '/LICENSE.txt');
581         }
582         else if(file_exists('LICENSE.txt')){
583             copy('LICENSE.txt', $path . '/LICENSE.txt');
584         }
585         require_once('include/utils/zip_utils.php');
586         $date = date('Y_m_d_His');
587         $zipDir = $this->getZipDir();
588         if(!file_exists($zipDir))mkdir_recursive($zipDir);
589         $cwd = getcwd();
590         chdir($this->getBuildDir());
591         zip_dir('.',$cwd . '/'. $zipDir. '/'. $this->name. $date. '.zip');
592         chdir($cwd);
593         if($clean && file_exists($this->getBuildDir()))rmdir_recursive($this->getBuildDir());
594         if($export){
595             header('Location:' . $zipDir. '/'. $this->name. $date. '.zip');
596         }
597         return $zipDir. '/'. $this->name. $date. '.zip';
598     }
599     
600     private function convertLangFilesToExtensions($langDir)
601     {
602         if (is_dir($langDir))
603         {
604             foreach(scandir($langDir) as $langFile)
605             {
606                 $mod_strings = array();
607                 if (strcasecmp(substr($langFile, -4), ".php") != 0)
608                     continue;
609                 include("$langDir/$langFile");
610                 $out = "<?php \n // created: " . date('Y-m-d H:i:s') . "\n";
611                 foreach($mod_strings as $lbl_key => $lbl_val ) 
612                 {
613                     $out .= override_value_to_string("mod_strings", $lbl_key, $lbl_val) . "\n";
614                 }
615                 $out .= "\n?>\n";
616                 sugar_file_put_contents("$langDir/$langFile", $out);
617             }
618         }
619     }
620     private function copyCustomDropdownValuesForModules($modules, $path)
621     {
622         if(file_exists("custom/include/language")){
623             if(mkdir_recursive("$path/SugarModules/include")){
624                 global $app_list_strings;
625                 $backStrings = $app_list_strings;
626                 foreach(scandir("custom/include/language") as $langFile)
627                 {
628                     $app_list_strings = array();
629                     if (strcasecmp(substr($langFile, -4), ".php") != 0)
630                        continue;
631                     include("custom/include/language/$langFile");
632                     $out = "<?php \n";
633                     $lang = substr($langFile, 0, -9);
634                     $options = $this->getCustomDropDownStringsForModules($modules, $app_list_strings); 
635                     foreach($options as $name => $arr) {
636                         $out .= override_value_to_string('app_list_strings', $name, $arr);
637                     }
638                     mkdir_recursive("$path/SugarModules/include/language/");
639                     sugar_file_put_contents("$path/SugarModules/include/language/$lang.$this->name.php", $out);
640                 }
641                 $app_list_strings = $backStrings;
642             }
643         }
644     }
645     
646     function getCustomDropDownStringsForModules($modules, $list_strings) {
647         global $beanList, $beanFiles;
648         $options = array();
649         foreach($modules as $module)
650         {
651             if (!empty($beanList[$module]))
652             {
653                 require_once($beanFiles[$beanList[$module]]);
654                 $bean = new $beanList[$module]();
655                 foreach($bean->field_defs as $field => $def) 
656                 {
657                     if (isset($def['options']) && isset($list_strings[$def['options']]))
658                     {
659                         $options[$def['options']] = $list_strings[$def['options']];
660                     }
661                 }
662             }
663         }
664         return $options;
665     }
666
667
668
669     //if $module=false : return an array with custom module and there customizations.
670     //if $module=!false : return an array with the directories of custom/module/$module.
671     function getCustomModules($module=false){
672         global $mod_strings;
673         $path='custom/modules/';
674                 $extPath = 'custom/Extension/modules/';
675         if(!file_exists($path) || !is_dir($path)){
676             return array($mod_strings['LBL_EC_NOCUSTOM'] => "");
677         }
678         else{
679             if ($module != false ){
680                 $path=$path . $module . '/';
681             }
682             $scanlisting = scandir($path);
683             $dirlisting = array();
684             foreach ($scanlisting as $value){
685                 if(is_dir($path . $value) == true && $value != '.' && $value != '..') {
686                     $dirlisting[] = $value;
687                 }
688             }
689                         if(empty($dirlisting)){
690                 return array($mod_strings['LBL_EC_NOCUSTOM'] => "");
691             }
692             if ($module == false ){
693                 foreach ($dirlisting as $value){
694                         if(!file_exists('modules/' . $value . '/metadata/studio.php'))
695                                 continue;
696                     $custommodules[$value]=$this->getCustomModules($value);
697                     foreach ($custommodules[$value] as $va){
698                         switch ($va) {
699                         case 'language':
700                                 $return[$value][$va] = $mod_strings['LBL_EC_CUSTOMFIELD'];
701                             break;
702                         case 'metadata':
703                             $return[$value][$va] = $mod_strings['LBL_EC_CUSTOMLAYOUT'];
704                             break;
705                         case 'Ext':
706                             
707                                                         $return[$value][$va] = $mod_strings['LBL_EC_CUSTOMFIELD'];
708                             break;
709                         case '':
710                             $return[$value . " " . $mod_strings['LBL_EC_EMPTYCUSTOM']] = "";
711                             break;
712                         default:
713                             $return[$value][$va] = $mod_strings['LBL_UNDEFINED'];
714                         }
715                     }
716                 }
717                 return $return;
718             }
719             else{
720                 return $dirlisting;
721             }
722         }
723     }
724         
725     /**
726      * Get _custom_ extensions for module.
727      * Default path - custom/Extension/modules/$module/Ext.
728      * 
729      * @param array $module Name.
730      * @param mixed $includeRelationships ARRAY - relationships files between $module and names in array;
731      * TRUE - with all relationships files; 
732      * @return array Paths.
733      */
734     protected function getExtensionsList($module, $includeRelationships = true)
735     {
736         if (BeanFactory::getBeanName($module) === false)
737         {
738             return array();
739         }
740         
741         $result = array();
742         $includeMask = false;
743         $extPath = sprintf('custom%1$sExtension%1$smodules%1$s' . $module . '%1$sExt', DIRECTORY_SEPARATOR);
744
745         if (is_array($includeRelationships))
746         {
747             $includeMask = array();
748             $customRels = $this->getCustomRelationshipsByModuleName($module);
749
750             $includeRelationships[] = $module;
751
752             foreach ($customRels as $k => $v)
753             {
754                 if (
755                     in_array($v->getLhsModule(), $includeRelationships) &&
756                     in_array($v->getRhsModule(), $includeRelationships)
757                 )
758                 {
759                     $includeMask[] = $k;
760                 }
761             }
762         }
763
764         $recursiveIterator = new RecursiveIteratorIterator(
765                 new RecursiveDirectoryIterator($extPath),
766                 RecursiveIteratorIterator::SELF_FIRST
767         );
768
769         /* @var $fileInfo SplFileInfo */
770         foreach ($recursiveIterator as $fileInfo)
771         {
772
773             if ($fileInfo->isFile() && !in_array($fileInfo->getPathname(), $result))
774             {
775                 if ($includeMask === false)
776                 {
777                     $result[] = $fileInfo->getPathname();
778                 } 
779                 else 
780                 {
781                     foreach ($includeMask as $v)
782                     {
783                         if (strpos($fileInfo->getFilename(), $v) !== false)
784                         {
785                             $result[] = $fileInfo->getPathname();
786                             break;
787                         }
788                     }
789                 }
790             }
791         }
792
793         return $result;
794     }
795
796     /**
797      * Returns a set of field defs for fields that will exist when this package is deployed
798      * based on the relationships in all of its modules.
799      * 
800      * @param $moduleName (module must be from whithin this package)
801      * @return array Field defs
802      */
803     function getRelationshipsForModule($moduleName) {
804         $ret = array();
805         if (isset($this->modules[$moduleName])) {
806                 $keyName = $this->modules[$moduleName]->key_name;
807                 foreach($this->modules as $mName => $module) {
808                         $rels = $module->getRelationships();
809                         $relList = $rels->getRelationshipList();
810                         foreach($relList as $rName ) {
811                             $rel = $rels->get ( $rName ) ;
812                              if ($rel->lhs_module == $keyName || $rel->rhs_module == $keyName) {
813                         $ret[$rName] =  $rel;
814                              }
815                         }
816                 }
817         }
818         return $ret; 
819     }
820     
821
822     
823     function exportProjectInstall($package, $for_export){
824         $pre = $for_export ? MB_EXPORTPREPEND : "";
825         $installdefs = array ('id' => $pre . $this->name);
826         $installdefs['copy'][] = array(
827             'from'=> '<basepath>/' . $this->name,
828             'to'=> 'custom/modulebuilder/packages/'. $this->name,   
829         );
830         return "\n".'$installdefs = ' . var_export_helper($installdefs). ';';
831
832     }
833     
834     
835     
836     function exportProject($package, $export=true, $clean = true){
837         $tmppath="custom/modulebuilder/projectTMP/";
838         if(file_exists($this->getPackageDir())){
839             if(mkdir_recursive($tmppath)){
840                 copy_recursive($this->getPackageDir(), $tmppath ."/". $this->name);
841                 $manifest = $this->getManifest(true, $export).$this->exportProjectInstall($package, $export);
842                 $fp = sugar_fopen($tmppath .'/manifest.php', 'w');
843                 fwrite($fp, $manifest);
844                 fclose($fp);
845                 if(file_exists('modules/ModuleBuilder/MB/LICENSE.txt')){
846                     copy('modules/ModuleBuilder/MB/LICENSE.txt', $tmppath . '/LICENSE.txt');
847                 }
848                 else if(file_exists('LICENSE.txt')){
849                     copy('LICENSE.txt', $tmppath . '/LICENSE.txt');
850                 }
851                 $readme_contents = $this->readme;
852                 $readmefp = sugar_fopen($tmppath.'/README.txt','w');
853                 fwrite($readmefp, $readme_contents);
854                 fclose($readmefp);
855             }
856         }
857         require_once('include/utils/zip_utils.php');
858         $date = date('Y_m_d_His');
859         $zipDir = "custom/modulebuilder/packages/ExportProjectZips";
860         if(!file_exists($zipDir))mkdir_recursive($zipDir);
861         $cwd = getcwd();
862         chdir($tmppath);
863         zip_dir('.',$cwd . '/'. $zipDir. '/project_'. $this->name. $date. '.zip');
864         chdir($cwd);
865         if($clean && file_exists($tmppath))rmdir_recursive($tmppath);
866         if($export){
867             header('Location:' . $zipDir. '/project_'. $this->name. $date. '.zip');
868         }
869         return $zipDir. '/project_'. $this->name. $date. '.zip';
870     }
871     
872     /**
873      * @param string $moduleName
874      * @param bool $lhs Return relationships where $moduleName - left module in join.
875      * @return mixed Array or false when module name is wrong.
876      */
877     protected function getCustomRelationshipsByModuleName($moduleName, $lhs = false)
878     {
879         if (BeanFactory::getBeanName($moduleName) === false)
880         {
881             return false;
882         }
883         
884         $result = array();
885         $relation = null;
886         $module = new StudioModule($moduleName);
887
888         /* @var $rel DeployedRelationships */
889         $rel = $module->getRelationships();
890
891         $relList = $rel->getRelationshipList();
892
893         foreach ($relList as $relationshipName)
894         {
895             $relation = $rel->get($relationshipName);
896
897             if ($relation->getFromStudio())
898             {
899                 if ($lhs && $relation->getLhsModule() != $moduleName)
900                 {
901                     continue;
902                 }
903                 $result[$relationshipName] = $relation;
904             }
905         }
906
907         return $result;
908     }
909     
910     /**
911      * @param string $moduleName
912      * @param bool $lhs Return relationships where $moduleName - left module in join.
913      * @param bool $metadataOnly Return only relationships metadata file.
914      * @return array
915      */
916     protected function getCustomRelationshipsMetaFilesByModuleName($moduleName, $lhs = false, $metadataOnly = false)
917     {
918         
919         $path = $metadataOnly ?
920                 'custom' . DIRECTORY_SEPARATOR . 'metadata' . DIRECTORY_SEPARATOR :
921                 'custom' . DIRECTORY_SEPARATOR;
922         $result = array();
923
924         $relationships = $this->getCustomRelationshipsByModuleName($moduleName, $lhs);
925         
926         if (!$relationships)
927         {
928             return array();
929         }
930         
931         $recursiveIterator = new RecursiveIteratorIterator(
932                 new RecursiveDirectoryIterator($path),
933                 RecursiveIteratorIterator::SELF_FIRST
934         );
935
936         /**
937          * @var $fileInfo SplFileInfo 
938          */
939         foreach ($recursiveIterator as $fileInfo)
940         {
941             if ($fileInfo->isFile() && !in_array($fileInfo->getPathname(), $result))
942             {
943                 foreach ($relationships as $k => $v)
944                 {
945
946                     if (strpos($fileInfo->getFilename(), $k) !== false)
947                     {
948                         $result[] = $fileInfo->getPathname();
949                         break;
950                     }
951                 }
952             }
953         }
954
955         return $result;
956     }
957
958     public function deleteBuild()
959     {
960         return rmdir_recursive($this->getBuildDir());
961     }
962
963 }
964
965 ?>