]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/ModuleBuilder/parsers/relationships/AbstractRelationship.php
Release 6.2.0
[Github/sugarcrm.git] / modules / ModuleBuilder / parsers / relationships / AbstractRelationship.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM Community Edition is a customer relationship management program developed by
5  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
6  * 
7  * This program is free software; you can redistribute it and/or modify it under
8  * the terms of the GNU Affero General Public License version 3 as published by the
9  * Free Software Foundation with the addition of the following permission added
10  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
13  * 
14  * This program is distributed in the hope that it will be useful, but WITHOUT
15  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
17  * details.
18  * 
19  * You should have received a copy of the GNU Affero General Public License along with
20  * this program; if not, see http://www.gnu.org/licenses or write to the Free
21  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
22  * 02110-1301 USA.
23  * 
24  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
26  * 
27  * The interactive user interfaces in modified source and object code versions
28  * of this program must display Appropriate Legal Notices, as required under
29  * Section 5 of the GNU Affero General Public License version 3.
30  * 
31  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32  * these Appropriate Legal Notices must retain the display of the "Powered by
33  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34  * technical reasons, the Appropriate Legal Notices must display the words
35  * "Powered by SugarCRM".
36  ********************************************************************************/
37
38
39 /*
40  * A mechanism to dynamically define new Relationships between modules
41  * This differs from the classes in modules/Relationships and data/Link in that they contain the implementation for pre-defined Relationships
42  * Those classes use the metadata in the dictionary and layout definitions to implement the relationships; this class allows you to manage and manipulate that metadata
43  */
44 class AbstractRelationship
45 {
46     
47     protected $definition ; // enough information to rebuild this relationship
48     
49
50     /*
51      * These are the elements that fully define any Relationship
52      * Any subclass of AbstractRelationship uses an array with a subset of the following keys as metadata to describe the Relationship it will implement
53      * The base set of keys are those used in the Relationships table 
54      * Defined as Public as MBRelationship uses these to read the _POST data
55      */
56     public static $definitionKeys = array ( 
57         // atttributes of this relationship - here in the definition so they are preserved across saves and loads
58         'for_activities',
59         'is_custom',
60         'from_studio',
61         'readonly' , // a readonly relationship cannot be Built by subclasses of AbstractRelationships
62         'deleted' , // a deleted relationship will not be built, and if it had been built previously the built relationship will be removed
63         'relationship_only' , // means that we won't build any UI components for this relationship - required while the Subpanel code is restricted to one subpanel only from any module, and probably useful afterwards also for developers to build relationships for new code - it's a feature!
64         // keys not found in Relationships table
65         'label' , // optional
66         'rhs_label', // optional
67         'lhs_label', // optional
68         'lhs_subpanel' , // subpanel FROM the lhs_module to display on the rhs_module detail view
69         'rhs_subpanel' , // subpanel FROM the rhs_module to display on the lhs_module detail view
70         // keys from Relationships table
71         'relationship_name' ,
72         'lhs_module' , 
73         'lhs_table' , 
74         'lhs_key' , 
75         'rhs_module' , 
76         'rhs_table' , 
77         'rhs_key' , 
78         'join_table' , 
79         'join_key_lhs' , 
80         'join_key_rhs' , 
81         'relationship_type' , 
82         'relationship_role_column' , 
83         'relationship_role_column_value' , 
84         'reverse' ) ;
85
86     /*
87      * Relationship_role_column and relationship_role_column_value:
88      * These two values define an additional condition on the relationship. If present, the value in relationship_role_column in the relationship table must equal relationship_role_column_value
89      * Any update to the relationship made using a link field tied to the relationship (as is proper) will automatically (in Link.php) add in the relationship_role_column_value
90      * The relationship table must of course contain a column with the name given in relationship_role_column
91      * 
92      * relationship_role_column and relationship_role_column_value are here implemented in a slightly less optimized form than in the standard OOB application
93      * In the OOB application, multiple relationships can, and do, share the same relationship table. Therefore, each variant of the relationship does not require its own table
94      * Here for simplicity in implementation each relationship has its own unique table. Therefore, the relationship_role_column in these tables will only contain the value relationship_role_column_value
95      * In the OOB relationships, the relationship_role_column will contain any of the relationship_role_column_values from the relationships that share the table
96      * TODO: implement this optimization
97      * 
98      */
99     
100     /*
101      * Constructor
102      * @param string $definition    Definition array for this relationship. Parameters are given in self::keys
103      */
104     function __construct ($definition)
105     {
106         // set any undefined attributes to the default value
107         foreach ( array ( 'readonly' , 'deleted' , 'relationship_only', 'for_activities', 'is_custom', 'from_studio' ) as $key )
108             if (! isset ( $definition [ $key ] ))
109                 $definition [ $key ] = false ;
110         
111         foreach ( self::$definitionKeys as $key )
112         {
113             $this->$key = isset ( $definition [ $key ] ) ? $definition [ $key ] : '' ;
114         }
115         $this->definition = $definition ;
116     }
117
118     /*
119      * Get the unique name of this relationship
120      * @return string   The unique name (actually just that given to the constructor)
121      */
122     public function getName ()
123     {
124         return isset ( $this->definition [ 'relationship_name' ] ) ? $this->definition [ 'relationship_name' ] : null ;
125     }
126
127     public function setName ($relationshipName)
128     {
129         $this->relationship_name = $this->definition [ 'relationship_name' ] = $relationshipName ;
130     }
131
132     /*
133      * Is this relationship readonly or not?
134      * @return boolean True if cannot be changed; false otherwise
135      */
136     public function readonly ()
137     {
138         return $this->definition [ 'readonly' ] ;
139     }
140
141     public function setReadonly ($set = true)
142     {
143         $this->readonly = $this->definition [ 'readonly' ] = $set ;
144     }
145
146     public function setFromStudio ()
147     {
148         $this->from_studio = $this->definition [ 'from_studio' ] = true ;
149     }
150
151     /*
152      * Has this relationship been deleted? A deleted relationship does not get built, and is no longer visible in the list of relationships
153      * @return boolean True if it has been deleted; false otherwise
154      */
155     public function deleted ()
156     {
157         return $this->definition [ 'deleted' ] ;
158     }
159
160     public function delete ()
161     {
162         $this->deleted = $this->definition [ 'deleted' ] = true ;
163     }
164     
165     
166     public function getType ()
167     {
168         return $this->relationship_type ;
169     }
170     
171     public function relationship_only ()
172     {
173         return $this->definition [ 'relationship_only' ] ;   
174     }
175     
176     public function setRelationship_only ()
177     {
178         $this->relationship_only = $this->definition [ 'relationship_only' ] = true ;
179     }
180
181     /*
182      * Get a complete description of this relationship, sufficient to pass back to a constructor to reestablish the relationship
183      * Each subclass must provide enough information in $this->definition for its constructor
184      * Used by UndeployedRelationships to save out a set of AbstractRelationship descriptions
185      * The format is the same as the schema for the Relationships table for convenience, and is defined in self::keys. That is,
186      * `relationship_name`, `lhs_module`, `lhs_table`, `lhs_key`, `rhs_module`, `rhs_table`,`rhs_key`, `join_table`, `join_key_lhs`, `join_key_rhs`, `relationship_type`, `relationship_role_column`, `relationship_role_column_value`, `reverse`,
187      * @return array    Set of parameters to pass to an AbstractRelationship constructor - must contain at least ['relationship_type']='OneToOne' or 'OneToMany' or 'ManyToMany'
188      */
189     function getDefinition ()
190     {
191         return $this->definition ;
192     }
193
194     /*
195      * BUILD methods called during the build
196      */
197     
198     /*
199      * Define the labels to be added to the module for the new relationships
200      * @return array    An array of system value => display value
201      */
202     function buildLabels ($update=false)
203     {
204         $labelDefinitions = array ( ) ;
205         if (!$this->relationship_only)
206         {
207                 if(!$this->is_custom && $update && file_exists("modules/{$this->rhs_module}/metadata/subpaneldefs.php")){
208                         include("modules/{$this->rhs_module}/metadata/subpaneldefs.php");
209                         if(isset($layout_defs[$this->rhs_module]['subpanel_setup'][strtolower($this->lhs_module)]['title_key'])){
210                                 $rightSysLabel = $layout_defs[$this->rhs_module]['subpanel_setup'][strtolower($this->lhs_module)]['title_key'];
211                         }
212                         $layout_defs = array();
213                 }
214                 if(!$this->is_custom && $update && file_exists("modules/{$this->lhs_module}/metadata/subpaneldefs.php")){
215                         include("modules/{$this->lhs_module}/metadata/subpaneldefs.php");
216                         if(isset($layout_defs[$this->lhs_module]['subpanel_setup'][strtolower($this->rhs_module)]['title_key'])){
217                                 $leftSysLabel = $layout_defs[$this->lhs_module]['subpanel_setup'][strtolower($this->rhs_module)]['title_key'];
218                         }
219                         $layout_defs = array();
220                 }
221                 $labelDefinitions [] = array (
222                         'module' => $this->rhs_module ,
223                         'system_label' => isset($rightSysLabel)?$rightSysLabel : 'LBL_' . strtoupper ( $this->relationship_name . '_FROM_' . $this->getLeftModuleSystemLabel() ) . '_TITLE' ,
224                         'display_label' => ($update && !empty($_REQUEST [ 'lhs_label' ] ))?$_REQUEST [ 'lhs_label' ] :(empty($this->lhs_label) ? translate ( $this->lhs_module ) : $this->lhs_label),
225                 ) ;
226             $labelDefinitions [] = array (
227                 'module' => $this->lhs_module ,
228                 'system_label' =>  isset($leftSysLabel)?$leftSysLabel :'LBL_' . strtoupper ( $this->relationship_name . '_FROM_' . $this->getRightModuleSystemLabel() ) . '_TITLE' ,
229                 'display_label' => ($update && !empty($_REQUEST [ 'rhs_label' ] ))?$_REQUEST [ 'rhs_label' ] :(empty($this->rhs_label) ? translate ( $this->rhs_module ) : $this->rhs_label),
230             ) ;
231         }
232         return $labelDefinitions ;
233     }
234
235         function getLeftModuleSystemLabel()
236     {
237                 if($this->lhs_module == $this->rhs_module){
238                         return $this->lhs_module.'_L';
239                 }
240                 return $this->lhs_module;
241     }
242
243     function getRightModuleSystemLabel()
244     {
245                 if($this->lhs_module == $this->rhs_module){
246                         return $this->rhs_module.'_R';
247                 }
248                 return $this->rhs_module;
249     }
250         
251     /*
252      * GET methods called by the BUILD methods of the subclasses to construct the relationship metadata
253      */
254     
255     /*
256      * Build a description of a Subpanel that can be turned into an actual Subpanel by saveSubpanelDefinition in the implementation
257      * Note that we assume that the subpanel name we are given is valid - that is, a subpanel definition by that name exists, and that a module won't have attempt to define multiple subpanels with the same name
258      * Among the elements we construct is get_subpanel_data which is used as follows in SugarBean:
259      *          $related_field_name = $this_subpanel->get_data_source_name();
260      *          $parentbean->load_relationship($related_field_name);
261      * ...where $related_field_name must be the name of a link field that references the Relationship used to obtain the subpanel data
262      * @param string $sourceModule      Name of the source module for this field
263      * @param string $relationshipName  Name of the relationship
264      * @param string $subpanelName      Name of the subpanel provided by the sourceModule
265      * @param string $titleKeyName      Name of the subpanel title , if none, we will use the module name as the subpanel title.
266      */
267     protected function getSubpanelDefinition ($relationshipName , $sourceModule , $subpanelName, $titleKeyName = '', $source = "")
268     {
269         if (empty($source)) 
270                 $source = $this->getValidDBName($relationshipName);
271         $subpanelDefinition = array ( ) ;
272         $subpanelDefinition [ 'order' ] = 100 ;
273         $subpanelDefinition [ 'module' ] = $sourceModule ;
274         $subpanelDefinition [ 'subpanel_name' ] = $subpanelName ;
275         // following two lines are required for the subpanel pagination code in ListView.php->processUnionBeans() to correctly determine the relevant field for sorting
276         $subpanelDefinition [ 'sort_order' ] = 'asc' ;
277         $subpanelDefinition [ 'sort_by' ] = 'id' ;
278                 if(!empty($titleKeyName)){
279                         $subpanelDefinition [ 'title_key' ] = 'LBL_' . strtoupper ( $relationshipName . '_FROM_' . $titleKeyName ) . '_TITLE' ;
280                 }else{
281                         $subpanelDefinition [ 'title_key' ] = 'LBL_' . strtoupper ( $relationshipName . '_FROM_' . $sourceModule ) . '_TITLE' ;
282                 }
283         $subpanelDefinition [ 'get_subpanel_data' ] = $source ;
284         $subpanelDefinition [ 'top_buttons' ] = array(
285                     array('widget_class' => "SubPanelTopButtonQuickCreate"),
286                     array('widget_class' => 'SubPanelTopSelectButton', 'mode'=>'MultiSelect')
287                 );
288         
289         return array ( $subpanelDefinition );
290     }   
291     
292
293     /*
294      * Construct a first link id field for the relationship for use in Views
295      * It is used during the save from an edit view in SugarBean->save_relationship_changes(): for each relate field, $this->$linkfieldname->add( $this->$def['id_name'] )
296      * @param string $sourceModule      Name of the source module for this field
297      * @param string $relationshipName  Name of the relationship
298      */
299     protected function getLinkFieldDefinition ($sourceModule , $relationshipName, $right_side = false, $vname = "")
300     {
301         $vardef = array ( ) ;
302
303         $vardef [ 'name' ] = $this->getValidDBName($relationshipName) ;
304         $vardef [ 'type' ] = 'link' ;
305         $vardef [ 'relationship' ] = $relationshipName ;
306         $vardef [ 'source' ] = 'non-db' ;
307         if ($right_side)
308                 $vardef [ 'side' ] = 'right' ;
309         if (!empty($vname))
310             $vardef [ 'vname' ] = $vname;
311
312         return $vardef ;
313     }
314
315     /*
316      * Construct a second link id field for the relationship for use in Views
317      * It is used in two places:
318      *    - the editview.tpl for Relate fields requires that a field with the same name as the relate field's id_name exists
319      *    - it is loaded in SugarBean->fill_in_link_field while SugarBean processes the relate fields in fill_in_relationship_fields
320      * @param string $sourceModule      Name of the source module for this field
321      * @param string $relationshipName  Name of the relationship
322      */
323     protected function getLink2FieldDefinition ($sourceModule , $relationshipName, $right_side = false,  $vname = "")
324     {
325         $vardef = array ( ) ;
326
327         $vardef [ 'name' ] = $this->getIDName( $sourceModule ) ; // must match the id_name field value in the relate field definition
328         $vardef [ 'type' ] = 'link' ;
329         $vardef [ 'relationship' ] = $relationshipName ;
330         $vardef [ 'source' ] = 'non-db' ;
331                 $vardef ['reportable'] = false;
332         if ($right_side)
333                 $vardef [ 'side' ] = 'right' ;
334         else
335                 $vardef [ 'side' ] = 'left' ;
336         if (!empty($vname))
337             $vardef [ 'vname' ] = $vname;
338
339         return $vardef ;
340     }
341
342     /*
343      * Construct a relate field for the vardefs
344      * The relate field is the element that is shown in the UI
345      * @param string $sourceModule      Name of the source module for this field
346      * @param string $relationshipName  Name of the relationship
347      * @param string $moduleType        Optional - "Types" of the module - array of SugarObject types such as "file" or "basic"
348      */
349     protected function getRelateFieldDefinition ($sourceModule , $relationshipName , $vnameLabel='')
350     {
351         $vardef = array ( ) ;
352         $vardef [ 'name' ] = $this->getValidDBName($relationshipName . "_name") ; // must end in _name for the QuickSearch code in TemplateHandler->createQuickSearchCode
353         $vardef [ 'type' ] = 'relate' ;
354
355         $vardef [ 'source' ] = 'non-db' ;
356                 if(!empty($vnameLabel)){
357                         $vardef [ 'vname' ] = 'LBL_' . strtoupper ( $relationshipName . '_FROM_' . $vnameLabel ) . '_TITLE' ;
358                 }else{
359                         $vardef [ 'vname' ] = 'LBL_' . strtoupper ( $relationshipName . '_FROM_' . $sourceModule ) . '_TITLE' ;
360                 }
361         
362         $vardef [ 'save' ] = true; // the magic value to tell SugarBean to save this relate field even though it is not listed in the $relationship_fields array
363        
364         // id_name matches the join_key_ column in the relationship table for the sourceModule - that is, the column in the relationship table containing the id of the corresponding field in the source module's table (vardef['table'])
365         $vardef [ 'id_name' ] = $this->getIDName( $sourceModule ) ;
366         
367         // link cannot match id_name otherwise the $bean->$id_name value set from the POST is overwritten by the Link object created by this 'link' entry
368         $vardef [ 'link' ] = $this->getValidDBName($relationshipName) ; // the name of the link field that points to the relationship - required for the save to function
369         $vardef [ 'table' ] = $this->getTablename( $sourceModule ) ;
370         $vardef [ 'module' ] = $sourceModule ;
371         
372         require_once 'modules/ModuleBuilder/parsers/relationships/AbstractRelationships.php' ;
373         $parsedModuleName = AbstractRelationships::parseDeployedModuleName( $sourceModule ) ;
374
375         // now determine the appropriate 'rname' field for this relate
376         // the 'rname' points to the field in source module that contains the displayable name for the record
377         // usually this is 'name' but sometimes it is not...
378         
379         $vardef [ 'rname' ] = 'name' ;
380         if ( isset( $parsedModuleName['packageName'] ) )
381         {
382             require_once 'modules/ModuleBuilder/MB/ModuleBuilder.php' ;
383             $mb = new ModuleBuilder ( ) ;
384             $module = $mb->getPackageModule ( $parsedModuleName['packageName'] , $parsedModuleName['moduleName'] ) ;
385             if (in_array( 'file' , array_keys ( $module->config [ 'templates' ] ) ) ){
386                 $vardef [ 'rname' ] = 'document_name' ;
387             }elseif(in_array ( 'person' , array_keys ( $module->config [ 'templates' ] ) ) ){
388                 $vardef [ 'db_concat_fields' ] = array( 0 =>'first_name', 1 =>'last_name') ;
389             }
390         }
391         else
392         {
393             switch ( strtolower( $sourceModule ) )
394             {
395                 case 'prospects' :
396                     $vardef [ 'rname' ] = 'account_name' ;
397                     break ;
398                 case 'documents' :
399                     $vardef [ 'rname' ] = 'document_name' ;
400                     break ;
401                 case 'kbdocuments' :
402                     $vardef [ 'rname' ] = 'kbdocument_name' ;
403                     break ;
404                 case 'leads' :
405                 case 'contacts' : 
406                     // special handling as these modules lack a name column in the database; instead 'name' refers to a non-db field that concatenates first_name and last_name
407                     // luckily, the relate field mechanism can handle this with an equivalent additional db_concat_fields entry
408                     $vardef [ 'rname' ] = 'name' ;
409                     $vardef [ 'db_concat_fields' ] = array( 0 =>'first_name', 1 =>'last_name') ;
410                     break ;
411                 default :
412                     // now see if we have any module inheriting from the 'file' template - records in file-type modules are named by the document_name field, not the usual 'name' field
413                     $object = $GLOBALS ['beanList'] [ $sourceModule ];
414                     require_once ( $GLOBALS ['beanFiles'] [ $object ] );
415                     $bean = new $object();
416                     if ( isset ( $GLOBALS [ 'dictionary' ] [ $object ] [ 'templates'] )){
417                         if(in_array ( 'file' , $GLOBALS [ 'dictionary' ] [ $object ] [ 'templates'] )){
418                                 $vardef [ 'rname' ] = 'document_name' ;
419                         }elseif(in_array ( 'person' , $GLOBALS [ 'dictionary' ] [ $object ] [ 'templates'] )){
420                                  $vardef [ 'db_concat_fields' ] = array( 0 =>'first_name', 1 =>'last_name') ;
421                         }
422                     }
423                         
424             }
425             
426         }
427             
428         return $vardef ;
429     }
430
431     /*
432      * Construct the contents of the Relationships MetaData entry in the dictionary for a generic relationship
433      * The entry we build will have three sections:
434      * 1. relationships: the relationship definition
435      * 2. table: name of the join table for this many-to-many relationship
436      * 3. fields: fields within the join table
437      * 4. indicies: indicies on the join table
438      * @param string $relationshipType  Cardinality of the relationship, for example, MB_ONETOONE or MB_ONETOMANY or MB_MANYTOMANY
439      */
440     function getRelationshipMetaData ($relationshipType)
441     {
442         $relationshipName = $this->definition [ 'relationship_name' ] ;
443         $lhs_module = $this->lhs_module ;
444         $rhs_module = $this->rhs_module ;
445         
446         $lhs_table = $this->getTablename ( $lhs_module ) ;
447         $rhs_table = $this->getTablename ( $rhs_module ) ;
448         
449         $properties = array ( ) ;
450         
451         // first define section 1, the relationship element of the metadata entry
452         
453         $rel_properties = array ( ) ;
454         $rel_properties [ 'lhs_module' ] = $lhs_module ;
455         $rel_properties [ 'lhs_table' ] = $lhs_table ;
456         $rel_properties [ 'lhs_key' ] = 'id' ;
457         $rel_properties [ 'rhs_module' ] = $rhs_module ;
458         $rel_properties [ 'rhs_table' ] = $rhs_table ;
459         $rel_properties [ 'rhs_key' ] = 'id' ;
460         
461         // because the implementation of one-to-many relationships within SugarBean does not use a join table and so requires schema changes to add a foreign key for each new relationship,
462         // we currently implement all new relationships as many-to-many regardless of the real type and enforce cardinality through the relate fields and subpanels
463         $rel_properties [ 'relationship_type' ] = MB_MANYTOMANY ;
464         // but as we need to display the true cardinality in Studio and ModuleBuilder we also record the actual relationship type
465         // this property is only used by Studio/MB
466         $properties [ 'true_relationship_type' ] = $relationshipType ;
467         if ($this->from_studio)
468             $properties [ 'from_studio' ] = true; 
469         
470         $rel_properties [ 'join_table' ] = $this->getValidDBName ( $relationshipName."_c" ) ;
471         // a and b are in case the module relates to itself
472         $rel_properties [ 'join_key_lhs' ] = $this->getJoinKeyLHS() ;
473         $rel_properties [ 'join_key_rhs' ] = $this->getJoinKeyRHS() ;
474         
475         // set the extended properties if they exist = for now, many-to-many definitions do not have to contain a role_column even if role_column_value is set; we'll just create a likely name if missing
476         if (isset ( $this->definition [ 'relationship_role_column_value' ] ))
477         {
478             if (! isset ( $this->definition [ 'relationship_role_column' ] ))
479                 $this->definition [ 'relationship_role_column' ] = 'relationship_role_column' ;
480             $rel_properties [ 'relationship_role_column' ] = $this->definition [ 'relationship_role_column' ] ;
481             $rel_properties [ 'relationship_role_column_value' ] = $this->definition [ 'relationship_role_column_value' ] ;
482         }
483         
484         $properties [ 'relationships' ] [ $relationshipName ] = $rel_properties ;
485         
486         // construct section 2, the name of the join table
487         
488         $properties [ 'table' ] = $rel_properties [ 'join_table' ] ;
489         
490         // now construct section 3, the fields in the join table
491         
492         $properties [ 'fields' ] [] = array ( 'name' => 'id' , 'type' => 'varchar' , 'len' => 36 ) ;
493         $properties [ 'fields' ] [] = array ( 'name' => 'date_modified' , 'type' => 'datetime' ) ;
494         $properties [ 'fields' ] [] = array ( 'name' => 'deleted' , 'type' => 'bool' , 'len' => '1' , 'default' => '0' , 'required' => true ) ;
495         $properties [ 'fields' ] [] = array ( 'name' => $rel_properties [ 'join_key_lhs' ] , 'type' => 'varchar' , 'len' => 36 ) ;
496         $properties [ 'fields' ] [] = array ( 'name' => $rel_properties [ 'join_key_rhs' ] , 'type' => 'varchar' , 'len' => 36 ) ;
497         if (strtolower ( $lhs_module ) == 'documents' || strtolower ( $rhs_module ) == 'documents' )
498         {
499             $properties [ 'fields' ] [] = array ( 'name' => 'document_revision_id' , 'type' => 'varchar' , 'len' => '36' ) ;
500         }
501         // if we have an extended relationship condition, then add in the corresponding relationship_role_column to the relationship (join) table
502         // for now this is restricted to extended relationships that can be specified by a varchar
503         if (isset ( $this->definition [ 'relationship_role_column_value' ] ))
504         {
505             $properties [ 'fields' ] [] = array ( 'name' => $this->definition [ 'relationship_role_column' ] , 'type' => 'varchar' ) ;
506         }
507         
508         // finally, wrap up with section 4, the indices on the join table
509         
510         $indexBase = $this->getValidDBName ( $relationshipName ) ;
511         $properties [ 'indices' ] [] = array ( 'name' => $indexBase . 'spk' , 'type' => 'primary' , 'fields' => array ( 'id' ) ) ;
512
513         switch ($relationshipType)
514         {
515             case MB_ONETOONE:
516                 $alternateKeys = array () ;
517                 $properties [ 'indices' ] [] = array ( 'name' => $indexBase . '_ida1' , 'type' => 'index' , 'fields' => array ( $rel_properties [ 'join_key_lhs' ] ) ) ;
518                 $properties [ 'indices' ] [] = array ( 'name' => $indexBase . '_idb2' , 'type' => 'index' , 'fields' => array ( $rel_properties [ 'join_key_rhs' ] ) ) ;
519                 break;
520             case MB_ONETOMANY :
521                 $alternateKeys = array ( $rel_properties [ 'join_key_rhs' ] ) ;
522                 $properties [ 'indices' ] [] = array ( 'name' => $indexBase . '_ida1' , 'type' => 'index' , 'fields' => array ( $rel_properties [ 'join_key_lhs' ] ) ) ;
523                 break;
524             default:
525                 $alternateKeys = array ( $rel_properties [ 'join_key_lhs' ] , $rel_properties [ 'join_key_rhs' ] ) ;
526         }
527         
528         if (count($alternateKeys)>0)
529             $properties [ 'indices' ] [] = array ( 'name' => $indexBase . '_alt' , 'type' => 'alternate_key' , 'fields' => $alternateKeys ) ; // type must be set to alternate_key for Link.php to correctly update an existing record rather than inserting a copy - it uses the fields in this array as the keys to check if a duplicate record already exists
530         
531         return $properties ;
532     }
533     
534     
535     /*
536      * UTILITY methods
537      */
538     
539     /*
540      * Method to build a name for a relationship between a module and an Activities submodule
541      * Used primarily in UndeployedRelationships to ensure that the subpanels we construct for Activities get their data from the correct relationships
542      * @param string $activitiesSubModuleName Name of the activities submodule, such as Tasks
543      */
544     function getActivitiesSubModuleRelationshipName ( $activitiesSubModuleName )
545     {
546         return $this->lhs_module . "_" . strtolower ( $activitiesSubModuleName ) ;
547     }
548
549     /*
550      * Return a version of $proposed that can be used as a column name in any of our supported databases
551      * Practically this means no longer than 25 characters as the smallest identifier length for our supported DBs is 30 chars for Oracle plus we add on at least four characters in some places (for indicies for example)
552      * TODO: Ideally this should reside in DBHelper as it is such a common db function...
553      * @param string $name Proposed name for the column
554      * @param string $ensureUnique 
555      * @return string Valid column name trimmed to right length and with invalid characters removed
556      */
557     static function getValidDBName ($name, $ensureUnique = false)
558     {
559
560         require_once 'modules/ModuleBuilder/parsers/constants.php' ;
561         return getValidDBName($name, $ensureUnique, MB_MAXDBIDENTIFIERLENGTH);
562     }
563
564     /*
565      * Tidy up any provided relationship type - convert all the variants of a name to the canonical type - for example, One To Many = MB_ONETOMANY
566      * @param string $type Relationship type
567      * @return string Canonical type
568      */
569     static function parseRelationshipType ($type)
570     {
571         $type = strtolower ( $type ) ;
572         $type = preg_replace ( '/[^\w]+/i', '', strtolower ( $type ) ) ;
573         $canonicalTypes = array ( ) ;
574         foreach ( array ( MB_ONETOONE , MB_ONETOMANY , MB_MANYTOMANY , MB_MANYTOONE) as $canonicalType )
575         {
576             if ($type == preg_replace ( '/[^\w]+/i', '', strtolower ( $canonicalType ) ))
577                 return $canonicalType ;
578         }
579         // ok, we give up...
580         return MB_MANYTOMANY ;
581     }
582
583     
584     function getJoinKeyLHS()
585     {
586         if (!isset($this->joinKeyLHS))
587                 $this->joinKeyLHS = $this->getValidDBName ( $this->relationship_name . $this->lhs_module . "_ida"  , true) ;
588         
589         return $this->joinKeyLHS;
590     }
591     
592     function getJoinKeyRHS()
593     {
594         if (!isset($this->joinKeyRHS))
595                 $this->joinKeyRHS = $this->getValidDBName ( $this->relationship_name . $this->rhs_module . "_idb"  , true) ;
596         
597         return $this->joinKeyRHS;
598     }
599     
600     /*
601      * Return the name of the ID field that will be used to link the subpanel, the link field and the relationship metadata
602      * @param string $sourceModule  The name of the primary module in the relationship
603      * @return string Name of the id field
604      */
605     function getIDName( $sourceModule )
606     {
607         return ($sourceModule == $this->lhs_module ) ? $this->getJoinKeyLHS() : $this->getJoinKeyRHS() ;
608     }
609     
610     /*
611      * Return the name of a module's standard (non-cstm) table in the database
612      * @param string $moduleName    Name of the module for which we are to find the table
613      * @return string Tablename
614      */
615     protected function getTablename ($moduleName)
616     {
617         // Check the moduleName exists in the beanList before calling get_module_info - Activities is the main culprit here
618         if (isset ( $GLOBALS [ 'beanList' ] [ $moduleName ] ))
619         {
620             $module = get_module_info ( $moduleName ) ;
621             return $module->table_name ;
622         }
623         return strtolower ( $moduleName ) ;
624     }
625
626     public function getTitleKey($left=false){
627                 if(!$this->is_custom && !$left && file_exists("modules/{$this->rhs_module}/metadata/subpaneldefs.php")){
628                 include("modules/{$this->rhs_module}/metadata/subpaneldefs.php");
629                 if(isset($layout_defs[$this->rhs_module]['subpanel_setup'][strtolower($this->lhs_module)]['title_key'])){
630                         return $layout_defs[$this->rhs_module]['subpanel_setup'][strtolower($this->lhs_module)]['title_key'];
631                 }
632         }else if(!$this->is_custom &&  file_exists("modules/{$this->lhs_module}/metadata/subpaneldefs.php")){
633                 include("modules/{$this->lhs_module}/metadata/subpaneldefs.php");
634                 if(isset($layout_defs[$this->lhs_module]['subpanel_setup'][strtolower($this->rhs_module)]['title_key'])){
635                         return $layout_defs[$this->lhs_module]['subpanel_setup'][strtolower($this->rhs_module)]['title_key'];
636                 }
637         }
638         
639         if($left){
640                 $titleKeyName = $this->getRightModuleSystemLabel();
641                 $sourceModule = $this->rhs_module;
642         }else{
643                 $titleKeyName = $this->getLeftModuleSystemLabel();
644                 $sourceModule = $this->lhs_module;
645         }
646         
647                 if(!empty($titleKeyName)){
648                         $title_key = 'LBL_' . strtoupper ( $this->relationship_name . '_FROM_' . $titleKeyName ) . '_TITLE' ;
649                 }else{
650                         $title_key = 'LBL_' . strtoupper ( $this->relationship_name . '_FROM_' . $sourceModule ) . '_TITLE' ;
651                 }
652                 
653                 return $title_key;
654         }
655 }