2 if (! defined ( 'sugarEntry' ) || ! sugarEntry)
3 die ( 'Not A Valid Entry Point' ) ;
5 /*********************************************************************************
6 * SugarCRM Community Edition is a customer relationship management program developed by
7 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
9 * This program is free software; you can redistribute it and/or modify it under
10 * the terms of the GNU Affero General Public License version 3 as published by the
11 * Free Software Foundation with the addition of the following permission added
12 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
13 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
14 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16 * This program is distributed in the hope that it will be useful, but WITHOUT
17 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
18 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
21 * You should have received a copy of the GNU Affero General Public License along with
22 * this program; if not, see http://www.gnu.org/licenses or write to the Free
23 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
26 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
27 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
29 * The interactive user interfaces in modified source and object code versions
30 * of this program must display Appropriate Legal Notices, as required under
31 * Section 5 of the GNU Affero General Public License version 3.
33 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
34 * these Appropriate Legal Notices must retain the display of the "Powered by
35 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
36 * technical reasons, the Appropriate Legal Notices must display the words
37 * "Powered by SugarCRM".
38 ********************************************************************************/
42 * Abstract class for managing a set of Relationships
43 * The Relationships we're managing consist of metadata about relationships, rather than relationship implementations used by the application
44 * Relationships defined here are implemented by the build() method to become a relationship that the application can use
45 * Note that the modules/Relationships/Relationship.php contains some methods that look similar; remember though that the methods in that file are acting on implemented relationships, not the metadata that we deal with here
47 class AbstractRelationships
50 static $methods = array (
51 'Labels' => 'language' ,
52 'RelationshipMetaData' => 'relationships' ,
53 'SubpanelDefinitions' => 'layoutdefs' ,
54 'Vardefs' => 'vardefs' ,
55 'FieldsToLayouts' => 'layoutfields',
57 static $activities = array ( 'calls' => 'Calls' , 'meetings' => 'Meetings' , 'notes' => 'Notes' , 'tasks' => 'Tasks' , 'emails' => 'Emails' ) ;
59 protected $relationships = array ( ) ; // array containing all the AbstractRelationship objects that are in this set of relationships
60 protected $moduleName ;
63 * Find all deployed modules that can participate in a relationship
64 * Return a list of modules with associated subpanels
65 * @param boolean $includeActivitiesSubmodules True if the list should include Calls, Meetings etc; false if they should be replaced by the parent, Activities
66 * @return array Array of [$module][$subpanel]
68 static function findRelatableModules ($includeActivitiesSubmodules = true)
70 $relatableModules = array ( ) ;
72 // add in activities automatically if required
73 $relatableModules [ 'Activities' ] [ 'default' ] = translate( 'LBL_DEFAULT' ) ;
75 // find all deployed modules
76 require_once 'modules/ModuleBuilder/Module/StudioBrowser.php' ;
77 $browser = new StudioBrowser() ;
78 $browser->loadRelatableModules();
79 reset($browser->modules) ;
81 while ( list( $moduleName , $module ) = each($browser->modules) )
83 // do not include the submodules of Activities as already have the parent...
84 if (! $includeActivitiesSubmodules && in_array ( $module->module, self::$activities ))
87 $relatableModules [ $module->module ] = $module->getProvidedSubpanels() ;
90 return $relatableModules ;
94 static function validSubpanel ($filename)
96 if (! file_exists ( $filename ))
100 return (isset ( $subpanel_layout ) && (isset ( $subpanel_layout [ 'top_buttons' ] ) && isset ( $subpanel_layout [ 'list_fields' ] ))) ;
104 * Get a list of all relationships (which have not been deleted)
105 * @return array Array of relationship names, ready for use in get()
107 function getRelationshipList ()
110 foreach ( $this->relationships as $name => $relationship )
112 if (! $relationship->deleted ())
113 $list [ $name ] = $name ;
119 * Get a relationship by name
120 * @param string $relationshipName The unique name for this relationship, as returned by $relationship->getName()
121 * @return AbstractRelationship or false if $relationshipName is not in this set of relationships
123 function get ($relationshipName)
125 if (isset ( $this->relationships [ $relationshipName ] ))
127 return $this->relationships [ $relationshipName ] ;
133 * Construct a relationship from the information in the $_REQUEST array
134 * If a relationship_name is provided, and that relationship is not read only, then modify the existing relationship, overriding the definition with any AbstractRelationship::$definitionkeys entries set in the $_REQUEST
135 * Otherwise, create and add a new relationship with the information in the $_REQUEST
136 * @return AbstractRelationship
138 function addFromPost ()
140 $definition = array ( ) ;
142 require_once 'modules/ModuleBuilder/parsers/relationships/AbstractRelationship.php' ;
143 foreach ( AbstractRelationship::$definitionKeys as $key )
145 if (! empty ( $_REQUEST [ $key ] ))
147 $definition [ $key ] = ($key == 'relationship_type') ? AbstractRelationship::parseRelationshipType ( $_REQUEST [ $key ] ) : $_REQUEST [ $key ] ;
151 // if this is a change to an existing relationship, and it is not readonly, then delete the old one
152 if (! empty ( $_REQUEST [ 'relationship_name' ] ))
154 if ($relationship = $this->get ( $_REQUEST [ 'relationship_name' ] ))
156 unset( $definition[ 'relationship_name' ] ) ; // in case the related modules have changed; this name is probably no longer appropriate
157 if (! $relationship->readonly ())
158 $this->delete ( $_REQUEST [ 'relationship_name' ] ) ;
162 $newRelationship = RelationshipFactory::newRelationship ( $definition ) ;
163 // TODO: error handling in case we get a badly formed definition and hence relationship
164 $this->add ( $newRelationship ) ;
165 return $newRelationship ;
169 * Add a relationship to the set
170 * @param AbstractRelationship $relationship The relationship to add
172 function add ($relationship)
174 $name = $this->getUniqueName ( $relationship ) ;
175 $relationship->setName ( $name ) ;
176 $this->relationships [ $name ] = $relationship ;
180 * Load a set of relationships from a file
181 * The saved relationships are stored as AbstractRelationship objects, which isn't the same as the old MBRelationships definition
182 * @param string $basepath Base directory in which to store the relationships information
183 * @return Array of AbstractRelationship objects
185 protected function _load ($basepath)
187 $GLOBALS [ 'log' ]->info ( get_class ( $this ) . ": loading relationships from " . $basepath . '/relationships.php' ) ;
188 $objects = array ( ) ;
189 if (file_exists ( $basepath . '/relationships.php' ))
191 include ($basepath . '/relationships.php') ;
192 foreach ( $relationships as $name => $definition )
194 // update any pre-5.1 relationships to the new definitions
195 // we do this here, rather than when upgrading from 5.0 to 5.1, as modules exported from MB in 5.0 may be loaded into 5.1 at any time
196 // note also that since these definitions are only found in the relationships.php working file they only occur for deployed or exported modules, not published then loaded modules
197 $definition = $this->_updateRelationshipDefinition( $definition ) ;
198 $relationship = RelationshipFactory::newRelationship ( $definition ) ;
199 // make sure it has a unique name
200 if (! isset( $definition [ 'relationship_name' ] ) )
202 $name = $this->getUniqueName ( $relationship ) ;
203 $relationship->setName ( $name ) ;
205 $objects [ $name ] = $relationship ;
212 * Save the set of relationships to a file
213 * @param string $basepath Base directory in which to store the relationships information
215 protected function _save ($relationships , $basepath)
217 $GLOBALS [ 'log' ]->info ( get_class ( $this ) . ": saving relationships to " . $basepath . '/relationships.php' ) ;
218 $header = file_get_contents ( 'modules/ModuleBuilder/MB/header.php' ) ;
220 $definitions = array ( ) ;
222 foreach ( $relationships as $relationship )
224 // if (! $relationship->readonly ())
225 $definitions [ $relationship->getName () ] = $relationship->getDefinition () ;
228 mkdir_recursive ( $basepath ) ;
229 // replace any existing relationships.php
230 write_array_to_file ( 'relationships', $definitions, $basepath . '/relationships.php', 'w', $header ) ;
234 * Return all known deployed relationships
235 * All are set to read-only - the assumption for now is that we can't directly modify a deployed relationship
236 * However, if it was created through this AbstractRelationships class a modifiable version will be held in the relationships working file,
237 * and that one will override the readonly version in load()
239 * TODO: currently we ignore the value of the 'reverse' field in the relationships definition. This is safe to do as only one
240 * relationship (products-products) uses it (and there it makes no difference from our POV) and we don't use it when creating new ones
241 * @return array Array of $relationshipName => $relationshipDefinition as an array
243 protected function getDeployedRelationships ()
246 $db = DBManagerFactory::getInstance () ;
247 $query = "SELECT * FROM relationships WHERE deleted = 0" ;
248 $result = $db->query ( $query ) ;
249 while ( $row = $db->fetchByAssoc ( $result ) )
251 // set this relationship to readonly
252 $row [ 'readonly' ] = true ;
253 $relationships [ $row [ 'relationship_name' ] ] = $row ;
256 return $relationships ;
260 * Get a name for this relationship that is unique across all of the relationships we are aware of
261 * We make the name unique by simply adding on a suffix until we achieve uniqueness
262 * @param AbstractRelationship The relationship object
263 * @return string A globally unique relationship name
265 protected function getUniqueName ($relationship)
267 $allRelationships = $this->getRelationshipList () ;
268 $basename = $relationship->getName () ;
270 if (empty ( $basename ))
272 // start off with the proposed name being simply lhs_module_rhs_module
273 $definition = $relationship->getDefinition () ;
274 $basename = strtolower ( $definition [ 'lhs_module' ] . '_' . $definition [ 'rhs_module' ] ) ;
279 while ( isset ( $allRelationships [ $name ] ) )
281 $name = $basename . "_" . ( string ) ($suffix ++) ;
287 * Translate the set of relationship objects into files that the Module Loader can work with
288 * @param string $basepath Pathname of the directory to contain the build
289 * @param string $installDefPrefix Pathname prefix for the installdefs, for example for ModuleBuilder use "<basepath>/SugarModules"
290 * @param array $relationships Relationships to implement
292 protected function build ($basepath , $installDefPrefix , $relationships )
294 global $sugar_config;
295 // keep the relationships data separate from any other build data by ading /relationships to the basepath
296 $basepath .= '/relationships' ;
298 $installDefs = array ( ) ;
299 $compositeAdded = false ;
300 foreach ( self::$methods as $method => $key )
302 $buildMethod = 'build' . $method ;
303 $saveMethod = 'save' . $method ;
305 foreach ( $relationships as $name => $relationship )
307 if (! ($relationship->readonly () || $relationship->deleted ()))
309 if (method_exists ( $relationship, $buildMethod ) && method_exists ( $this, $saveMethod ))
311 $metadata = $relationship->$buildMethod () ;
313 if (count ( $metadata ) > 0) // don't clutter up the filesystem with empty files...
315 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . ": BUILD is running METHOD $saveMethod" ) ;
316 $installDef = $this->$saveMethod ( $basepath, $installDefPrefix, $name, $metadata ) ;
318 // some save methods (e.g., saveRelateFieldDefinition) handle the installDefs internally and so return null
321 if (! is_null ( $installDef ))
323 foreach ( $installDef as $moduleName => $def )
325 $installDefs [ $key ] [ ] = $def ;
335 return $installDefs ;
339 * SAVE methods called during the build to translate the metadata provided by each relationship into files for the module installer
340 * Note that the installer expects only one file for each module in each section of the manifest - multiple files result in only the last one being implemented!
344 * Add a set of labels to the module
345 * @param string $basepath Basepath location for this module
346 * @param $installDefPrefix Pathname prefix for the installdefs, for example for ModuleBuilder use "<basepath>/SugarModules"
347 * @param string $relationshipName Name of this relationship (for uniqueness)
348 * @param array $labelDefinitions Array of System label => Display label pairs
349 * @return null Nothing to be added to the installdefs for an undeployed module
351 protected function saveLabels ($basepath , $installDefPrefix , $relationshipName , $labelDefinitions)
353 global $sugar_config;
355 mkdir_recursive ( "$basepath/language" ) ;
357 $headerString = "<?php\n//THIS FILE IS AUTO GENERATED, DO NOT MODIFY\n" ;
358 $installDefs = array ( ) ;
359 foreach ( $labelDefinitions as $definition )
361 $mod_strings = array();
362 $app_list_strings = array();
364 $out = $headerString;
366 $filename = "{$basepath}/language/{$definition['module']}.php" ;
368 if (file_exists ( $filename ))
372 //Check for app strings
373 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveLabels(): saving the following to {$filename}"
374 . print_r ( $definition, true ) ) ;
375 if ($definition['module'] == 'application') {
376 $app_list_strings[$definition [ 'system_label' ]] = $definition [ 'display_label' ];
377 foreach ($app_list_strings as $key => $val)
378 $out .= override_value_to_string_recursive2('app_list_strings', $key, $val);
380 $mod_strings[ $definition [ 'system_label' ]] = $definition [ 'display_label' ];
381 foreach ($mod_strings as $key => $val)
382 $out .= override_value_to_string_recursive2('mod_strings', $key, $val);
385 $fh = fopen ( $filename, 'w' ) ;
386 fputs ( $fh, $out, strlen ( $out ) ) ;
390 foreach($sugar_config['languages'] as $lk => $lv)
392 $installDefs [ $definition [ 'module' ] . "_$lk" ] = array (
393 'from' => "{$installDefPrefix}/relationships/language/{$definition [ 'module' ]}.php" ,
394 'to_module' => $definition [ 'module' ] ,
399 /* do not use the following write_array_to_file method to write the label file -
400 * module installer appends each of the label files together (as it does for all files)
401 * into a combined label file and so the last $mod_strings is the only one received by the application */
402 // write_array_to_file ( 'mod_strings', array ( $definition [ 'system_label' ] => $definition [ 'display_label' ] ), $filename, "a" ) ;
405 return $installDefs ;
409 * Translate a set of relationship metadata definitions into files for the Module Loader
410 * @param string $basepath Basepath location for this module
411 * @param $installDefPrefix Pathname prefix for the installdefs, for example for ModuleBuilder use "<basepath>/SugarModules"
412 * @param string $relationshipName Name of this relationship (for uniqueness)
413 * @param array $relationshipMetaData Set of metadata definitions in the form $relationshipMetaData[$relationshipName]
414 * @return array $installDefs Set of new installDefs
416 protected function saveRelationshipMetaData ($basepath , $installDefPrefix , $relationshipName , $relationshipMetaData)
418 mkdir_recursive ( "$basepath/relationships" ) ;
420 $installDefs = array ( ) ;
421 list ( $rhs_module, $properties ) = each ( $relationshipMetaData ) ;
422 $filename = "$basepath/relationships/{$relationshipName}MetaData.php" ;
423 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveRelationshipMetaData(): saving the following to {$filename}" . print_r ( $properties, true ) ) ;
424 write_array_to_file ( 'dictionary["' . $relationshipName . '"]', $properties, "{$filename}", 'w' ) ;
425 $installDefs [ $relationshipName ] = array ( /*'module' => $rhs_module , 'module_vardefs' => "<basepath>/Vardefs/{$relationshipName}.php" ,*/ 'meta_data' => "{$installDefPrefix}/relationships/relationships/{$relationshipName}MetaData.php" ) ;
427 return $installDefs ;
431 * Translate a set of subpanelDefinitions into files for the Module Loader
432 * @param string $basepath Basepath location for this module
433 * @param $installDefPrefix Pathname prefix for the installdefs, for example for ModuleBuilder use "<basepath>/SugarModules"
434 * @param array $subpanelDefinitions Set of subpanel definitions in the form $subpanelDefinitions[$for_module][]
435 * @return array $installDefs Set of new installDefs
437 protected function saveSubpanelDefinitions ($basepath , $installDefPrefix , $relationshipName , $subpanelDefinitions)
439 mkdir_recursive ( "$basepath/layoutdefs/" ) ;
441 foreach ( $subpanelDefinitions as $moduleName => $definitions )
443 $filename = "$basepath/layoutdefs/{$relationshipName}_{$moduleName}.php" ;
444 $subpanelVarname = 'layout_defs["' . $moduleName . '"]["subpanel_setup"]';
446 foreach ( $definitions as $definition )
448 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveSubpanelDefinitions(): saving the following to {$filename}" . print_r ( $definition, true ) ) ;
449 if (empty($definition ['get_subpanel_data']) || $definition ['subpanel_name'] == 'history' || $definition ['subpanel_name'] == 'activities') {
450 $definition ['get_subpanel_data'] = $definition ['subpanel_name'];
452 $out .= override_value_to_string($subpanelVarname, strtolower ( $definition [ 'get_subpanel_data' ] ), $definition) . "\n";
455 $out = "<?php\n // created: " . date('Y-m-d H:i:s') . "\n" . $out;
456 sugar_file_put_contents($filename, $out);
459 $installDefs [ $moduleName ] = array ( 'from' => "{$installDefPrefix}/relationships/layoutdefs/{$relationshipName}_{$moduleName}.php" , 'to_module' => $moduleName ) ;
461 return $installDefs ;
466 * Translate a set of linkFieldDefinitions into files for the Module Loader
467 * Note that the Module Loader will only accept one entry in the vardef section of the Manifest for each module
468 * This means that we cannot simply build a file for each relationship as relationships that involve the same module will end up overwriting each other when installed
469 * So we have to append the vardefs for each relationship to a single file for each module
470 * @param string $basepath Basepath location for this module
471 * @param $installDefPrefix Pathname prefix for the installdefs, for example for ModuleBuilder use "<basepath>/SugarModules"
472 * @param string $relationshipName Name of this relationship (for uniqueness)
473 * @param array $linkFieldDefinitions Set of link field definitions in the form $linkFieldDefinitions[$for_module]
474 * @return array $installDefs Set of new installDefs
476 protected function saveVardefs ($basepath , $installDefPrefix , $relationshipName , $vardefs)
478 mkdir_recursive ( "$basepath/vardefs/" ) ;
479 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveVardefs(): vardefs =" . print_r ( $vardefs, true ) ) ;
481 foreach ( $vardefs as $moduleName => $definitions )
483 // find this module's Object name - the object name, not the module name, is used as the key in the vardefs...
484 if (isset ( $GLOBALS [ 'beanList' ] [ $moduleName ] ))
486 $module = get_module_info ( $moduleName ) ;
487 $object = $module->object_name ;
490 $object = $moduleName ;
493 $relName = $moduleName;
494 foreach ( $definitions as $definition )
496 if (!empty($definition['relationship']))
498 $relName = $definition['relationship'];
503 $filename = "$basepath/vardefs/{$relName}_{$moduleName}.php" ;
505 $out = "<?php\n// created: " . date('Y-m-d H:i:s') . "\n";
506 foreach ( $definitions as $definition )
508 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveVardefs(): saving the following to {$filename}" . print_r ( $definition, true ) ) ;
509 $out .= '$dictionary["' . $object . '"]["fields"]["' . $definition [ 'name' ] . '"] = '
510 . var_export_helper($definition) . ";\n";
512 file_put_contents($filename, $out);
514 $installDefs [ $moduleName ] = array (
515 'from' => "{$installDefPrefix}/relationships/vardefs/{$relName}_{$moduleName}.php" ,
516 'to_module' => $moduleName
520 $GLOBALS [ 'log' ]->debug ( get_class ( $this ) . "->saveVardefs(): installDefs =" . print_r ( $installDefs, true ) ) ;
522 return $installDefs ;
527 * Determine if we're dealing with a deployed or undeployed module based on the name
528 * Undeployed modules are those known to ModuleBuilder; the twist is that the deployed names of modulebuilder modules are keyname_modulename not packagename_modulename
529 * and ModuleBuilder doesn't have any accessor methods based around keys, so we must convert keynames to packagenames
530 * @param $deployedName Name of the module in the deployed form - that is, keyname_modulename or modulename
531 * @return array ('moduleName'=>name, 'packageName'=>package) if undeployed, ('moduleName'=>name) if deployed
533 static function parseDeployedModuleName ($deployedName)
535 require_once 'modules/ModuleBuilder/MB/ModuleBuilder.php' ;
536 $mb = new ModuleBuilder ( ) ;
539 $moduleName = $deployedName ;
541 foreach ( $mb->getPackageList () as $name )
543 // convert the keyName into a packageName, needed for checking to see if this is really an undeployed module, or just a module with a _ in the name...
544 $package = $mb->getPackage ( $name ) ; // seem to need to call getPackage twice to get the key correctly... TODO: figure out why...
545 $key = $mb->getPackage ( $name )->key ;
546 if (strlen ( $key ) < strlen ( $deployedName ))
548 $position = stripos ( $deployedName, $key ) ;
549 $moduleName = trim( substr( $deployedName , strlen($key) ) , '_' ); //use trim rather than just assuming that _ is between packageName and moduleName in the deployedName
550 if ( $position !== false && $position == 0 && (isset ( $mb->packages [ $name ]->modules [ $moduleName ] )))
552 $packageName = $name ;
558 if (! empty ( $packageName ))
560 return array ( 'moduleName' => $moduleName , 'packageName' => $packageName ) ;
563 return array ( 'moduleName' => $deployedName ) ;