]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - ModuleInstall/PackageManager/PackageManager.php
Release 6.5.0
[Github/sugarcrm.git] / ModuleInstall / PackageManager / PackageManager.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
38 define("CREDENTIAL_CATEGORY", "ml");
39 define("CREDENTIAL_USERNAME", "username");
40 define("CREDENTIAL_PASSWORD", "password");
41
42 require_once('include/nusoap/nusoap.php');
43 require_once('include/utils/zip_utils.php');
44 require_once('ModuleInstall/PackageManager/PackageManagerDisplay.php');
45 require_once('ModuleInstall/ModuleInstaller.php');
46 require_once('include/entryPoint.php');
47 require_once('ModuleInstall/PackageManager/PackageManagerComm.php');
48
49 class PackageManager{
50     var $soap_client;
51
52     /**
53      * Constructor: In this method we will initialize the nusoap client to point to the hearbeat server
54      */
55     function PackageManager(){
56         $this->db = DBManagerFactory::getInstance();
57         $this->upload_dir = empty($GLOBALS['sugar_config']['upload_dir']) ? 'upload' : rtrim($GLOBALS['sugar_config']['upload_dir'], '/\\');
58     }
59
60     function initializeComm(){
61
62     }
63
64     /**
65      * Obtain a promotion from SugarDepot
66      * @return string   the string from the promotion
67      */
68     function getPromotion(){
69         $name_value_list = PackageManagerComm::getPromotion();
70         if(!empty($name_value_list)){
71             $name_value_list = PackageManager::fromNameValueList($name_value_list);
72             return $name_value_list['description'];
73         }else {
74            return '';
75         }
76     }
77
78     /**
79      * Obtain a list of category/packages/releases for use within the module loader
80      */
81     function getModuleLoaderCategoryPackages($category_id = ''){
82         $filter = array();
83         $filter = array('type' => "'module', 'theme', 'langpack'");
84         $filter = PackageManager::toNameValueList($filter);
85         return PackageManager::getCategoryPackages($category_id, $filter);
86     }
87
88     /**
89      * Obtain the list of category_packages from SugarDepot
90      * @return category_packages
91      */
92     function getCategoryPackages($category_id = '', $filter = array()){
93          $results = PackageManagerComm::getCategoryPackages($category_id, $filter);
94          PackageManagerComm::errorCheck();
95          $nodes = array();
96
97         $nodes[$category_id]['packages'] = array();
98         if(!empty($results['categories'])){
99                  foreach($results['categories'] as $category){
100                     $mycat = PackageManager::fromNameValueList($category);
101                     $nodes[$mycat['id']] = array('id' => $mycat['id'], 'label' => $mycat['name'], 'description' => $mycat['description'], 'type' => 'cat', 'parent' => $mycat['parent_id']);
102                     $nodes[$mycat['id']]['packages'] = array();
103                  }
104         }
105          if(!empty($results['packages'])){
106                 $uh = new UpgradeHistory();
107                  foreach($results['packages'] as $package){
108                     $mypack = PackageManager::fromNameValueList($package);
109                     $nodes[$mypack['category_id']]['packages'][$mypack['id']] = array('id' => $mypack['id'], 'label' => $mypack['name'], 'description' => $mypack['description'], 'category_id' => $mypack['category_id'], 'type' => 'package');
110                     $releases = PackageManager::getReleases($category_id, $mypack['id'], $filter);
111                     $arr_releases = array();
112                     $nodes[$mypack['category_id']]['packages'][$mypack['id']]['releases'] = array();
113                     if(!empty($releases['packages'])){
114                             foreach($releases['packages'] as $release){
115                                  $myrelease = PackageManager::fromNameValueList($release);
116                                  //check to see if we already this one installed
117                                  $result = $uh->determineIfUpgrade($myrelease['id_name'], $myrelease['version']);
118                                  $enable = false;
119                                  if($result == true || is_array($result))
120                                          $enable = true;
121                                  $nodes[$mypack['category_id']]['packages'][$mypack['id']]['releases'][$myrelease['id']] = array('id' => $myrelease['id'], 'version' => $myrelease['version'], 'label' => $myrelease['description'], 'category_id' => $mypack['category_id'], 'package_id' => $mypack['id'], 'type' => 'release', 'enable' => $enable);
122                                 }
123                     }
124                     //array_push($nodes[$mypack['category_id']]['packages'], $package_arr);
125                  }
126          }
127          $GLOBALS['log']->debug("NODES". var_export($nodes, true));
128         return $nodes;
129     }
130
131     /**
132      * Get a list of categories from the SugarDepot
133      * @param category_id   the category id of parent to obtain
134      * @param filter        an array of filters to pass to limit the query
135      * @return array        an array of categories for display on the client
136      */
137     function getCategories($category_id, $filter = array()){
138         $nodes = array();
139         $results = PackageManagerComm::getCategories($category_id, $filter);
140         PackageManagerComm::errorCheck();
141         if(!empty($results['categories'])){
142                 foreach($results['categories'] as $category){
143                     $mycat = PackageManager::fromNameValueList($category);
144                     $nodes[] = array('id' => $mycat['id'], 'label' => $mycat['name'], 'description' => $mycat['description'], 'type' => 'cat', 'parent' => $mycat['parent_id']);
145                 }
146         }
147         return $nodes;
148     }
149
150     function getPackages($category_id, $filter = array()){
151         $nodes = array();
152         $results = PackageManagerComm::getPackages($category_id, $filter);
153         PackageManagerComm::errorCheck();
154         $packages = array();
155         //$xml = '';
156         //$xml .= '<packages>';
157         if(!empty($results['packages'])){
158                 foreach($results['packages'] as $package){
159                     $mypack = PackageManager::fromNameValueList($package);
160                     $packages[$mypack['id']] = array('package_id' => $mypack['id'], 'name' => $mypack['name'], 'description' => $mypack['description'], 'category_id' => $mypack['category_id']);
161                     $releases = PackageManager::getReleases($category_id, $mypack['id']);
162                     $arr_releases = array();
163                     foreach($releases['packages'] as $release){
164                          $myrelease = PackageManager::fromNameValueList($release);
165                          $arr_releases[$myrelease['id']]  = array('release_id' => $myrelease['id'], 'version' => $myrelease['version'], 'description' => $myrelease['description'], 'category_id' => $mypack['category_id'], 'package_id' => $mypack['id']);
166                     }
167                     $packages[$mypack['id']]['releases'] = $arr_releases;
168                 }
169         }
170         return $packages;
171     }
172
173     function getReleases($category_id, $package_id, $filter = array()){
174         $releases = PackageManagerComm::getReleases($category_id, $package_id, $filter);
175         PackageManagerComm::errorCheck();
176         return $releases;
177     }
178
179     /**
180      * Retrieve the package as specified by the $id from the heartbeat server
181      *
182      * @param category_id   the category_id to which the release belongs
183      * @param package_id    the package_id to which the release belongs
184      * @param release_id    the release_id to download
185      * @return filename - the path to which the zip file was saved
186      */
187     public function download($category_id, $package_id, $release_id)
188     {
189         $GLOBALS['log']->debug('RELEASE _ID: '.$release_id);
190         if(!empty($release_id)){
191             $filename = PackageManagerComm::addDownload($category_id, $package_id, $release_id);
192             if($filename){
193                     $GLOBALS['log']->debug('RESULT: '.$filename);
194                     PackageManagerComm::errorCheck();
195                         $filepath = PackageManagerComm::performDownload($filename);
196                         return $filepath;
197             }
198         }else{
199             return null;
200         }
201     }
202
203     /**
204      * Given the Mambo username, password, and download key attempt to authenticate, if
205      * successful then store these credentials
206      *
207      * @param username      Mambo username
208      * @param password      Mambo password
209      * @param systemname   the user's download key
210      * @return              true if successful, false otherwise
211      */
212     function authenticate($username, $password, $systemname='', $terms_checked = true){
213         PackageManager::setCredentials($username, $password, $systemname);
214         PackageManagerComm::clearSession();
215         $result = PackageManagerComm::login($terms_checked);
216         if(is_array($result))
217                 return $result;
218         else
219                 return true;
220     }
221
222     function setCredentials($username, $password, $systemname){
223
224         $admin = new Administration();
225         $admin->retrieveSettings();
226          $admin->saveSetting(CREDENTIAL_CATEGORY, CREDENTIAL_USERNAME, $username);
227          $admin->saveSetting(CREDENTIAL_CATEGORY, CREDENTIAL_PASSWORD, $password);
228          if(!empty($systemname)){
229                 $admin->saveSetting('system', 'name', $systemname);
230          }
231     }
232
233     function getCredentials(){
234
235         $admin = new Administration();
236         $admin->retrieveSettings(CREDENTIAL_CATEGORY, true);
237         $credentials = array();
238         $credentials['username'] = '';
239         $credentials['password'] = '';
240                 $credentials['system_name'] = '';
241         if(!empty($admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME])){
242            $credentials['username'] = $admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME];
243         }
244         if(!empty($admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_USERNAME])){
245            $credentials['password'] = $admin->settings[CREDENTIAL_CATEGORY.'_'.CREDENTIAL_PASSWORD];
246         }
247         if(!empty($admin->settings['system_name'])){
248            $credentials['system_name'] = $admin->settings['system_name'];
249         }
250         return $credentials;
251     }
252
253     function getTermsAndConditions(){
254         return PackageManagerComm::getTermsAndConditions();
255
256     }
257
258     /**
259      * Retrieve documentation for the given release or package
260      *
261      * @param package_id        the specified package to retrieve documentation
262      * @param release_id        the specified release to retrieve documentation
263      *
264      * @return documents
265      */
266     function getDocumentation($package_id, $release_id){
267          if(!empty($release_id) || !empty($package_id)){
268             $documents = PackageManagerComm::getDocumentation($package_id, $release_id);
269             return $documents;
270         }else{
271             return null;
272         }
273     }
274
275     /**
276      * Grab the list of installed modules and send that list to the depot.
277      * The depot will then send back a list of modules that need to be updated
278      */
279     function checkForUpdates(){
280         $lists = $this->buildInstalledReleases(array('module'), true);
281                 $updates = array();
282                 if(!empty($lists)){
283                         $updates = PackageManagerComm::checkForUpdates($lists);
284                 }//fi
285                 return $updates;
286     }
287
288      ////////////////////////////////////////////////////////
289      /////////// HELPER FUNCTIONS
290     function toNameValueList($array){
291                 $list = array();
292                 foreach($array as $name=>$value){
293                         $list[] = array('name'=>$name, 'value'=>$value);
294                 }
295                 return $list;
296         }
297
298         function toNameValueLists($arrays){
299                 $lists = array();
300                 foreach($arrays as $array){
301                         $lists[] = PackageManager::toNameValueList($array);
302                 }
303                 return $lists;
304         }
305
306      function fromNameValueList($nvl){
307         $array = array();
308         foreach($nvl as $list){
309             $array[$list['name']] = $list['value'];
310         }
311         return $array;
312     }
313
314     function buildInstalledReleases($types = array('module')){
315         //1) get list of installed modules
316                 $installeds = $this->getInstalled($types);
317                 $releases = array();
318                 foreach($installeds as $installed){
319                         $releases[] = array('name' => $installed->name, 'id_name' => $installed->id_name, 'version' => $installed->version, 'filename' => $installed->filename, 'type' => $installed->type);
320                 }
321
322                 $lists = array();
323                 $name_value_list = array();
324                 if(!empty($releases)){
325                         $lists = $this->toNameValueLists($releases);
326                 }//fi
327                 return $lists;
328     }
329
330     function buildPackageXML($package, $releases = array()){
331         $xml = '<package>';
332         $xml .= '<package_id>'.$package['id'].'</package_id>';
333         $xml .= '<name>'.$package['name'].'</name>';
334         $xml .= '<description>'.$package['description'].'</description>';
335         if(!empty($releases)){
336              $xml .= '<releases>';
337              foreach($releases['packages'] as $release){
338
339                  $myrelease = PackageManager::fromNameValueList($release);
340                  $xml .= '<release>';
341                  $xml .= '<release_id>'.$myrelease['id'].'</release_id>';
342                  $xml .= '<version>'.$myrelease['version'].'</version>';
343                  $xml .= '<description>'.$myrelease['description'].'</description>';
344                  $xml .= '<package_id>'.$package['id'].'</package_id>';
345                  $xml .= '<category_id>'.$package['category_id'].'</category_id>';
346                  $xml .= '</release>';
347              }
348              $xml .= '</releases>';
349         }
350         $xml .= '</package>';
351         return $xml;
352     }
353
354     //////////////////////////////////////////////////////////////////////
355     /////////// INSTALL SECTION
356     function extractFile( $zip_file, $file_in_zip, $base_tmp_upgrade_dir){
357         $my_zip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
358         unzip_file( $zip_file, $file_in_zip, $my_zip_dir );
359         return( "$my_zip_dir/$file_in_zip" );
360     }
361
362     function extractManifest( $zip_file,$base_tmp_upgrade_dir ) {
363         global $sugar_config;
364         $base_upgrade_dir       = $this->upload_dir."/upgrades";
365         $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
366         return $this->extractFile( $zip_file, "manifest.php",$base_tmp_upgrade_dir );
367     }
368
369     function validate_manifest( $manifest ){
370     // takes a manifest.php manifest array and validates contents
371     global $subdirs;
372     global $sugar_version;
373     global $sugar_flavor;
374     global $mod_strings;
375
376     if( !isset($manifest['type']) ){
377         die($mod_strings['ERROR_MANIFEST_TYPE']);
378     }
379     $type = $manifest['type'];
380     $GLOBALS['log']->debug("Getting InstallType");
381     if( $this->getInstallType( "/$type/" ) == "" ){
382         $GLOBALS['log']->debug("Error with InstallType".$type);
383         die($mod_strings['ERROR_PACKAGE_TYPE']. ": '" . $type . "'." );
384     }
385     $GLOBALS['log']->debug("Passed with InstallType");
386     if( isset($manifest['acceptable_sugar_versions']) ){
387             $version_ok = false;
388             $matches_empty = true;
389             if( isset($manifest['acceptable_sugar_versions']['exact_matches']) ){
390                 $matches_empty = false;
391                 foreach( $manifest['acceptable_sugar_versions']['exact_matches'] as $match ){
392                     if( $match == $sugar_version ){
393                         $version_ok = true;
394                     }
395                 }
396             }
397             if( !$version_ok && isset($manifest['acceptable_sugar_versions']['regex_matches']) ){
398                 $matches_empty = false;
399                 foreach( $manifest['acceptable_sugar_versions']['regex_matches'] as $match ){
400                     if( preg_match( "/$match/", $sugar_version ) ){
401                         $version_ok = true;
402                     }
403                 }
404             }
405
406             if( !$matches_empty && !$version_ok ){
407                 die( $mod_strings['ERROR_VERSION_INCOMPATIBLE'] . $sugar_version );
408             }
409         }
410
411      if( isset($manifest['acceptable_sugar_flavors']) && sizeof($manifest['acceptable_sugar_flavors']) > 0 ){
412             $flavor_ok = false;
413             foreach( $manifest['acceptable_sugar_flavors'] as $match ){
414                 if( $match == $sugar_flavor ){
415                     $flavor_ok = true;
416                 }
417             }
418             if( !$flavor_ok ){
419                 //die( $mod_strings['ERROR_FLAVOR_INCOMPATIBLE'] . $sugar_flavor );
420             }
421         }
422     }
423
424     function getInstallType( $type_string ){
425         // detect file type
426         global $subdirs;
427         $subdirs = array('full', 'langpack', 'module', 'patch', 'theme', 'temp');
428
429
430         foreach( $subdirs as $subdir ){
431             if( preg_match( "#/$subdir/#", $type_string ) ){
432                 return( $subdir );
433             }
434         }
435         // return empty if no match
436         return( "" );
437     }
438
439     function performSetup($tempFile, $view = 'module', $display_messages = true){
440         global $sugar_config,$mod_strings;
441         $base_filename = urldecode($tempFile);
442         $GLOBALS['log']->debug("BaseFileName: ".$base_filename);
443         $base_upgrade_dir       = $this->upload_dir.'/upgrades';
444         $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
445         $manifest_file = $this->extractManifest( $base_filename,$base_tmp_upgrade_dir);
446          $GLOBALS['log']->debug("Manifest: ".$manifest_file);
447         if($view == 'module')
448             $license_file = $this->extractFile($base_filename, 'LICENSE.txt', $base_tmp_upgrade_dir);
449         if(is_file($manifest_file)){
450             $GLOBALS['log']->debug("VALIDATING MANIFEST". $manifest_file);
451             require_once( $manifest_file );
452             $this->validate_manifest($manifest );
453             $upgrade_zip_type = $manifest['type'];
454             $GLOBALS['log']->debug("VALIDATED MANIFEST");
455             // exclude the bad permutations
456             if( $view == "module" ){
457                 if ($upgrade_zip_type != "module" && $upgrade_zip_type != "theme" && $upgrade_zip_type != "langpack"){
458                     $this->unlinkTempFiles();
459                     if($display_messages)
460                         die($mod_strings['ERR_UW_NOT_ACCEPTIBLE_TYPE']);
461                 }
462             }elseif( $view == "default" ){
463                 if($upgrade_zip_type != "patch" ){
464                     $this->unlinkTempFiles();
465                     if($display_messages)
466                         die($mod_strings['ERR_UW_ONLY_PATCHES']);
467                 }
468             }
469
470             $base_filename = preg_replace( "#\\\\#", "/", $base_filename );
471             $base_filename = basename( $base_filename );
472             mkdir_recursive( "$base_upgrade_dir/$upgrade_zip_type" );
473             $target_path = "$base_upgrade_dir/$upgrade_zip_type/$base_filename";
474             $target_manifest = remove_file_extension( $target_path ) . "-manifest.php";
475
476             if( isset($manifest['icon']) && $manifest['icon'] != "" ){
477                 $icon_location = $this->extractFile( $tempFile ,$manifest['icon'], $base_tmp_upgrade_dir );
478                 $path_parts = pathinfo( $icon_location );
479                 copy( $icon_location, remove_file_extension( $target_path ) . "-icon." . $path_parts['extension'] );
480             }
481
482             if( copy( $tempFile , $target_path ) ){
483                 copy( $manifest_file, $target_manifest );
484                 if($display_messages)
485                     $messages = '<script>ajaxStatus.flashStatus("' .$base_filename.$mod_strings['LBL_UW_UPLOAD_SUCCESS'] . ', 5000");</script>';
486             }else{
487                 if($display_messages)
488                         $messages = '<script>ajaxStatus.flashStatus("' .$mod_strings['ERR_UW_UPLOAD_ERROR'] . ', 5000");</script>';
489             }
490         }//fi
491         else{
492             $this->unlinkTempFiles();
493             if($display_messages)
494                 die($mod_strings['ERR_UW_NO_MANIFEST']);
495         }
496         if(isset($messages))
497             return $messages;
498     }
499
500     function unlinkTempFiles() {
501         global $sugar_config;
502         @unlink($_FILES['upgrade_zip']['tmp_name']);
503         @unlink("upload://".$_FILES['upgrade_zip']['name']);
504     }
505
506     function performInstall($file, $silent=true){
507         global $sugar_config;
508         global $mod_strings;
509         global $current_language;
510         $base_upgrade_dir       = $this->upload_dir.'/upgrades';
511         $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
512         if(!file_exists($base_tmp_upgrade_dir)){
513             mkdir_recursive($base_tmp_upgrade_dir, true);
514         }
515
516         $GLOBALS['log']->debug("INSTALLING: ".$file);
517         $mi = new ModuleInstaller();
518         $mi->silent = $silent;
519         $mod_strings = return_module_language($current_language, "Administration");
520              $GLOBALS['log']->debug("ABOUT TO INSTALL: ".$file);
521         if(preg_match("#.*\.zip\$#", $file)) {
522              $GLOBALS['log']->debug("1: ".$file);
523             // handle manifest.php
524             $target_manifest = remove_file_extension( $file ) . '-manifest.php';
525             include($target_manifest);
526             $GLOBALS['log']->debug("2: ".$file);
527             $unzip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
528             unzip($file, $unzip_dir );
529             $GLOBALS['log']->debug("3: ".$unzip_dir);
530             $id_name = $installdefs['id'];
531                         $version = $manifest['version'];
532                         $uh = new UpgradeHistory();
533                         $previous_install = array();
534                 if(!empty($id_name) & !empty($version))
535                         $previous_install = $uh->determineIfUpgrade($id_name, $version);
536                 $previous_version = (empty($previous_install['version'])) ? '' : $previous_install['version'];
537                 $previous_id = (empty($previous_install['id'])) ? '' : $previous_install['id'];
538
539             if(!empty($previous_version)){
540                 $mi->install($unzip_dir, true, $previous_version);
541             }else{
542                 $mi->install($unzip_dir);
543             }
544             $GLOBALS['log']->debug("INSTALLED: ".$file);
545             $new_upgrade = new UpgradeHistory();
546             $new_upgrade->filename      = $file;
547             $new_upgrade->md5sum        = md5_file($file);
548             $new_upgrade->type          = $manifest['type'];
549             $new_upgrade->version       = $manifest['version'];
550             $new_upgrade->status        = "installed";
551             //$new_upgrade->author        = $manifest['author'];
552             $new_upgrade->name          = $manifest['name'];
553             $new_upgrade->description   = $manifest['description'];
554             $new_upgrade->id_name               = $id_name;
555                         $serial_manifest = array();
556                         $serial_manifest['manifest'] = (isset($manifest) ? $manifest : '');
557                         $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : '');
558                         $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : '');
559                         $new_upgrade->manifest          = base64_encode(serialize($serial_manifest));
560             //$new_upgrade->unique_key    = (isset($manifest['unique_key'])) ? $manifest['unique_key'] : '';
561             $new_upgrade->save();
562                     //unlink($file);
563         }//fi
564     }
565
566     function performUninstall($name){
567         $uh = new UpgradeHistory();
568         $uh->name = $name;
569         $uh->id_name = $name;
570         $found = $uh->checkForExisting($uh);
571         if($found != null){
572
573                 global $sugar_config;
574                 global $mod_strings;
575                 global $current_language;
576                 $base_upgrade_dir       = $this->upload_dir.'/upgrades';
577                 $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
578                 if(!isset($GLOBALS['mi_remove_tables']))$GLOBALS['mi_remove_tables'] = true;
579                 $unzip_dir = mk_temp_dir( $base_tmp_upgrade_dir );
580                 unzip($found->filename, $unzip_dir );
581                 $mi = new ModuleInstaller();
582                 $mi->silent = true;
583                 $mi->uninstall( "$unzip_dir");
584                 $found->delete();
585                 unlink(remove_file_extension( $found->filename ) . '-manifest.php');
586                 unlink($found->filename);
587         }
588     }
589
590     function getUITextForType( $type ){
591         if( $type == "full" ){
592             return( "Full Upgrade" );
593         }
594         if( $type == "langpack" ){
595             return( "Language Pack" );
596         }
597         if( $type == "module" ){
598             return( "Module" );
599         }
600         if( $type == "patch" ){
601             return( "Patch" );
602         }
603         if( $type == "theme" ){
604             return( "Theme" );
605         }
606     }
607
608     function getImageForType( $type ){
609
610         $icon = "";
611         switch( $type ){
612             case "full":
613                 $icon = SugarThemeRegistry::current()->getImage("Upgrade", "" ,null,null,'.gif', "Upgrade");
614
615                 break;
616             case "langpack":
617                 $icon = SugarThemeRegistry::current()->getImage("LanguagePacks", "",null,null,'.gif',"Language Packs" );
618
619                 break;
620             case "module":
621                 $icon = SugarThemeRegistry::current()->getImage("ModuleLoader", "" ,null,null,'.gif', "Module Loader");
622
623                 break;
624             case "patch":
625                 $icon = SugarThemeRegistry::current()->getImage("PatchUpgrades", "",null,null,'.gif', "Patch Upgrades" );
626
627                 break;
628             case "theme":
629                 $icon = SugarThemeRegistry::current()->getImage("Themes", "",null,null,'.gif', "Themes" );
630
631                 break;
632             default:
633                 break;
634         }
635         return( $icon );
636     }
637
638     function getPackagesInStaging($view = 'module'){
639         global $sugar_config;
640         global $current_language;
641         $uh = new UpgradeHistory();
642         $base_upgrade_dir       = "upload://upgrades";
643         $uContent = findAllFiles( $base_upgrade_dir, array() , false, 'zip');
644         $upgrade_contents = array();
645         $content_values = array_values($uContent);
646         $alreadyProcessed = array();
647         foreach($content_values as $val){
648                 if(empty($alreadyProcessed[$val])){
649                         $upgrade_contents[] = $val;
650                         $alreadyProcessed[$val] = true;
651                 }
652         }
653
654         $upgrades_available = 0;
655         $packages = array();
656         $mod_strings = return_module_language($current_language, "Administration");
657         foreach($upgrade_contents as $upgrade_content) {
658             if(!preg_match('#.*\.zip$#', strtolower($upgrade_content)) || preg_match("#.*./zips/.*#", strtolower($upgrade_content))) {
659                 continue;
660             }
661
662             $the_base = basename($upgrade_content);
663             $the_md5 = md5_file($upgrade_content);
664             $md5_matches = $uh->findByMd5($the_md5);
665                 $file_install = $upgrade_content;
666             if(empty($md5_matches))
667             {
668                 $target_manifest = remove_file_extension( $upgrade_content ) . '-manifest.php';
669                 if(file_exists($target_manifest)) {
670                         require_once($target_manifest);
671         
672                         $name = empty($manifest['name']) ? $upgrade_content : $manifest['name'];
673                         $version = empty($manifest['version']) ? '' : $manifest['version'];
674                         $published_date = empty($manifest['published_date']) ? '' : $manifest['published_date'];
675                         $icon = '';
676                         $description = empty($manifest['description']) ? 'None' : $manifest['description'];
677                         $uninstallable = empty($manifest['is_uninstallable']) ? 'No' : 'Yes';
678                         $type = $this->getUITextForType( $manifest['type'] );
679                         $manifest_type = $manifest['type'];
680                         $dependencies = array();
681                         if( isset( $manifest['dependencies']) ){
682                                         $dependencies    = $manifest['dependencies'];
683                                         }
684                 }
685
686                                 //check dependencies first
687                                 if(!empty($dependencies)) {
688                                         $uh = new UpgradeHistory();
689                                         $not_found = $uh->checkDependencies($dependencies);
690                                         if(!empty($not_found) && count($not_found) > 0){
691                                                         $file_install = 'errors_'.$mod_strings['ERR_UW_NO_DEPENDENCY']."[".implode(',', $not_found)."]";
692                                         }
693                                 }
694
695                 if($view == 'default' && $manifest_type != 'patch') {
696                     continue;
697                 }
698
699                 if($view == 'module'
700                     && $manifest_type != 'module' && $manifest_type != 'theme' && $manifest_type != 'langpack') {
701                     continue;
702                 }
703
704                 if(empty($manifest['icon'])) {
705                     $icon = $this->getImageForType( $manifest['type'] );
706                 } else {
707                     $path_parts = pathinfo( $manifest['icon'] );
708                     $icon = "<img src=\"" . remove_file_extension( $upgrade_content ) . "-icon." . $path_parts['extension'] . "\">";
709                 }
710
711                 $upgrades_available++;
712
713                 $packages[] = array('name' => $name, 'version' => $version, 'published_date' => $published_date,
714                         'description' => $description, 'uninstallable' =>$uninstallable, 'type' => $type,
715                         'file' => fileToHash($upgrade_content), 'file_install' => fileToHash($upgrade_content), 'unFile' => fileToHash($upgrade_content));
716             }//fi
717         }//rof
718         return $packages;
719     }
720
721     function getLicenseFromFile($file){
722         global $sugar_config;
723         $base_upgrade_dir       = $this->upload_dir.'/upgrades';
724         $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
725         $license_file = $this->extractFile($file, 'LICENSE.txt', $base_tmp_upgrade_dir);
726         if(is_file($license_file)){
727             $contents = file_get_contents($license_file);
728             return $contents;
729         }else{
730             return null;
731         }
732     }
733
734     /**
735      * Run the query to obtain the list of installed types as specified by the type param
736      *
737      * @param type      an array of types you would like to search for
738      *                          type options include (theme, langpack, module, patch)
739      *
740      * @return an array of installed upgrade_history objects
741      */
742     function getInstalled($types = array('module')){
743         $uh = new UpgradeHistory();
744         $in = "";
745         for($i = 0; $i < count($types); $i++){
746                 $in .= "'".$types[$i]."'";
747                 if(($i+1) < count($types)){
748                         $in .= ",";
749                 }
750         }
751         $query = "SELECT * FROM ".$uh->table_name."      WHERE type IN (".$in.")";
752         return $uh->getList($query);
753     }
754
755     function getinstalledPackages($types = array('module', 'langpack')){
756         global $sugar_config;
757         $installeds = $this->getInstalled($types);
758         $packages = array();
759         $upgrades_installed = 0;
760         $uh = new UpgradeHistory();
761         $base_upgrade_dir       = $this->upload_dir.'/upgrades';
762         $base_tmp_upgrade_dir   = "$base_upgrade_dir/temp";
763         foreach($installeds as $installed)
764                 {
765                         $populate = false;
766                         $filename = from_html($installed->filename);
767                         $date_entered = $installed->date_entered;
768                         $type = $installed->type;
769                         $version = $installed->version;
770                         $uninstallable = false;
771                         $link = "";
772                         $description = $installed->description;
773                         $name = $installed->name;
774                         $enabled = true;
775                         $enabled_string = 'ENABLED';
776                         //if the name is empty then we should try to pull from manifest and populate upgrade_history_table
777                         if(empty($name)){
778                                 $populate = true;
779                         }
780                         $upgrades_installed++;
781                         switch($type)
782                         {
783                                 case "theme":
784                                 case "langpack":
785                                 case "module":
786                                 case "patch":
787                                         if($populate){
788                                                 $manifest_file = $this->extractManifest($filename, $base_tmp_upgrade_dir);
789                                                 require_once($manifest_file);
790                                                 $GLOBALS['log']->info("Filling in upgrade_history table");
791                                                 $populate = false;
792                                                 if( isset( $manifest['name'] ) ){
793                                                 $name = $manifest['name'];
794                                                 $installed->name = $name;
795                                                 }
796                                                 if( isset( $manifest['description'] ) ){
797                                                     $description = $manifest['description'];
798                                                     $installed->description = $description;
799                                                 }
800                                                 if(isset($installdefs) && isset( $installdefs['id'] ) ){
801                                                     $id_name  = $installdefs['id'];
802                                                     $installed->id_name = $id_name;
803                                                 }
804
805                                                 $serial_manifest = array();
806                                                 $serial_manifest['manifest'] = (isset($manifest) ? $manifest : '');
807                                                 $serial_manifest['installdefs'] = (isset($installdefs) ? $installdefs : '');
808                                                 $serial_manifest['upgrade_manifest'] = (isset($upgrade_manifest) ? $upgrade_manifest : '');
809                                                 $installed->manifest = base64_encode(serialize($serial_manifest));
810                                                 $installed->save();
811                                         }else{
812                                                 $serial_manifest = unserialize(base64_decode($installed->manifest));
813                                                 $manifest = $serial_manifest['manifest'];
814                                         }
815                                         if(($upgrades_installed==0 || $uh->UninstallAvailable($installeds, $installed))
816                                                 && is_file($filename) && !empty($manifest['is_uninstallable']))
817                                         {
818                                                 $uninstallable = true;
819                                         }
820                                         $enabled = $installed->enabled;
821                                         if(!$enabled)
822                                                 $enabled_string = 'DISABLED';
823                                         $file_uninstall = $filename;
824                                         if(!$uninstallable){
825                                                 $file_uninstall = 'UNINSTALLABLE';
826                                                 $enabled_string = 'UNINSTALLABLE';
827                                         } else {
828                                                 $file_uninstall = fileToHash( $file_uninstall );
829                                         }
830
831                                 $packages[] = array(
832                                     'name' => $name,
833                                     'version' => $version,
834                                     'type' => $type,
835                                     'published_date' => $date_entered,
836                                     'description' => $description,
837                                     'uninstallable' =>$uninstallable,
838                                     'file_install' =>  $file_uninstall ,
839                                     'file' =>  fileToHash($filename),
840                                     'enabled' => $enabled_string
841                                 );
842                                 break;
843                                 default:
844                                 break;
845                         }
846
847                 }//rof
848                 return $packages;
849     }
850  }
851 ?>