]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - data/Relationships/M2MRelationship.php
Release 6.3.1
[Github/sugarcrm.git] / data / Relationships / M2MRelationship.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 require_once("data/Relationships/SugarRelationship.php");
40
41 /**
42  * Represents a many to many relationship that is table based.
43  */
44 class M2MRelationship extends SugarRelationship 
45 {
46     var $type = "many-to-many";
47
48     public function __construct($def)
49     {
50         $this->def = $def;
51         $this->name = $def['name'];
52
53         $lhsModule = $def['lhs_module'];
54         $this->lhsLinkDef = $this->getLinkedDefForModuleByRelationship($lhsModule);
55         $this->lhsLink = $this->lhsLinkDef['name'];
56
57         $rhsModule = $def['rhs_module'];
58         $this->rhsLinkDef = $this->getLinkedDefForModuleByRelationship($rhsModule);
59         $this->rhsLink = $this->rhsLinkDef['name'];
60
61         $this->self_referencing = $lhsModule == $rhsModule;
62     }
63
64     /**
65      * Find the link entry for a particular relationship and module.
66      *
67      * @param $module
68      * @return array|bool
69      */
70     public function getLinkedDefForModuleByRelationship($module)
71     {
72         $results = VardefManager::getLinkFieldForRelationship( $module, BeanFactory::getObjectName($module), $this->name);
73         //Only a single link was found
74         if( isset($results['name']) )
75         {
76             return $results;
77         }
78         //Multiple links with same relationship name
79         else if( is_array($results) )
80         {
81             $GLOBALS['log']->error("Warning: Multiple links found for relationship {$this->name} within module {$module}");
82             return $this->getMostAppropriateLinkedDefinition($results);
83         }
84         else
85         {
86             return FALSE;
87         }
88     }
89
90     /**
91      * Find the most 'appropriate' link entry for a relationship/module in which there are multiple link entries with the
92      * same relationship name.
93      *
94      * @param $links
95      * @return bool
96      */
97     protected function getMostAppropriateLinkedDefinition($links)
98     {
99         //First priority is to find a link name that matches the relationship name
100         foreach($links as $link)
101         {
102             if( isset($link['name']) && $link['name'] == $this->name )
103             {
104                 return $link;
105             }
106         }
107         //Next would be a relationship that has a side defined
108         foreach($links as $link)
109         {
110             if( isset($link['id_name']))
111             {
112                 return $link;
113             }
114         }
115         //Unable to find an appropriate link, guess and use the first one
116         $GLOBALS['log']->error("Unable to determine best appropriate link for relationship {$this->name}");
117         return $links[0];
118     }
119     /**
120      * @param  $lhs SugarBean left side bean to add to the relationship.
121      * @param  $rhs SugarBean right side bean to add to the relationship.
122      * @param  $additionalFields key=>value pairs of fields to save on the relationship
123      * @return boolean true if successful
124      */
125     public function add($lhs, $rhs, $additionalFields = array())
126     {
127         $lhsLinkName = $this->lhsLink;
128         $rhsLinkName = $this->rhsLink;
129
130         if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
131         {
132             $lhsClass = get_class($lhs);
133             $GLOBALS['log']->fatal("could not load LHS $lhsLinkName in $lhsClass");
134             return false;
135         }
136         if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
137         {
138             $rhsClass = get_class($rhs);
139             $GLOBALS['log']->fatal("could not load RHS $rhsLinkName in $rhsClass");
140             return false;
141         }
142
143         //Many to many has no additional logic, so just add a new row to the table and notify the beans.
144         $dataToInsert = $this->getRowToInsert($lhs, $rhs, $additionalFields);
145
146         $this->addRow($dataToInsert);
147
148         if ($this->self_referencing)
149             $this->addSelfReferencing($lhs, $rhs, $additionalFields);
150
151             $lhs->$lhsLinkName->addBean($rhs);
152             $rhs->$rhsLinkName->addBean($lhs);
153
154             $this->callAfterAdd($lhs, $rhs, $lhsLinkName);
155             $this->callAfterAdd($rhs, $lhs, $rhsLinkName);
156     }
157
158     protected function getRowToInsert($lhs, $rhs, $additionalFields = array())
159     {
160         $row = array(
161             "id" => create_guid(),
162             $this->def['join_key_lhs'] => $lhs->id,
163             $this->def['join_key_rhs'] => $rhs->id,
164             'date_modified' => TimeDate::getInstance()->getNow()->asDb(),
165             'deleted' => 0,
166         );
167
168
169         if (!empty($this->def['relationship_role_column']) && !empty($this->def['relationship_role_column_value']) && !$this->ignore_role_filter )
170         {
171             $row[$this->relationship_role_column] = $this->relationship_role_column_value;
172         }
173
174         if (!empty($this->def['fields']))
175         {
176             foreach($this->def['fields'] as $fieldDef)
177             {
178                 if (!empty($fieldDef['name']) && !isset($row[$fieldDef['name']]) && !empty($fieldDef['default']))
179                 {
180                     $row[$fieldDef['name']] = $fieldDef['default'];
181                 }
182             }
183         }
184         if (!empty($additionalFields))
185         {
186             $row = array_merge($row, $additionalFields);
187         }
188
189         return $row;
190     }
191
192     /**
193      * Adds the reversed version of this relationship to the table so that it can be accessed from either side equally
194      * @param $lhs
195      * @param $rhs
196      * @param array $additionalFields
197      * @return void
198      */
199     protected function addSelfReferencing($lhs, $rhs, $additionalFields = array())
200     {
201         if ($rhs->id != $lhs->id)
202         {
203             $dataToInsert = $this->getRowToInsert($rhs, $lhs, $additionalFields);
204             $this->addRow($dataToInsert);
205         }
206     }
207
208     public function remove($lhs, $rhs)
209     {
210         $lhsLinkName = $this->lhsLink;
211         $rhsLinkName = $this->rhsLink;
212
213         if (!($lhs instanceof SugarBean)) {
214             $GLOBALS['log']->fatal("LHS is not a SugarBean object");
215             return false;
216         }
217         if (!($rhs instanceof SugarBean)) {
218             $GLOBALS['log']->fatal("RHS is not a SugarBean object");
219             return false;
220         }
221         if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
222         {
223             $GLOBALS['log']->fatal("could not load LHS $lhsLinkName");
224             return false;
225         }
226         if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
227         {
228             $GLOBALS['log']->fatal("could not load RHS $rhsLinkName");
229             return false;
230         }
231
232         $dataToRemove = array(
233             $this->def['join_key_lhs'] => $lhs->id,
234             $this->def['join_key_rhs'] => $rhs->id
235         );
236
237         $this->removeRow($dataToRemove);
238
239         if ($this->self_referencing)
240             $this->removeSelfReferencing($lhs, $rhs);
241
242         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
243         {
244             if ($lhs->$lhsLinkName instanceof Link2)
245             {
246                 $lhs->$lhsLinkName->load();
247                 $this->callAfterDelete($lhs, $rhs, $lhsLinkName);
248             }
249
250             if ($rhs->$rhsLinkName instanceof Link2)
251             {
252                 $rhs->$rhsLinkName->load();
253                 $this->callAfterDelete($rhs, $lhs, $rhsLinkName);
254             }
255         }
256     }
257
258     /**
259      * Removes the reversed version of this relationship
260      * @param $lhs
261      * @param $rhs
262      * @param array $additionalFields
263      * @return void
264      */
265     protected function removeSelfReferencing($lhs, $rhs, $additionalFields = array())
266     {
267         if ($rhs->id != $lhs->id)
268         {
269             $dataToRemove = array(
270                 $this->def['join_key_lhs'] => $rhs->id,
271                 $this->def['join_key_rhs'] => $lhs->id
272             );
273             $this->removeRow($dataToRemove);
274         }
275     }
276
277     /**
278      * @param  $link Link2 loads the relationship for this link.
279      * @return void
280      */
281     public function load($link)
282     {
283         $db = DBManagerFactory::getInstance();
284         $query = $this->getQuery($link);
285         $result = $db->query($query);
286         $rows = Array();
287         $idField = $link->getSide() == REL_LHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
288         while ($row = $db->fetchByAssoc($result))
289         {
290             if (empty($row['id']) && empty($row[$idField]))
291                 continue;
292             $id = empty($row['id']) ? $row[$idField] : $row['id'];
293             $rows[$id] = $row;
294         }
295         return array("rows" => $rows);
296     }
297
298     public function getQuery($link, $params = array())
299     {
300         if ($link->getSide() == REL_LHS) {
301             $knownKey = $this->def['join_key_lhs'];
302             $targetKey = $this->def['join_key_rhs'];
303         }
304         else
305         {
306             $knownKey = $this->def['join_key_rhs'];
307             $targetKey = $this->def['join_key_lhs'];
308         }
309         $rel_table = $this->getRelationshipTable();
310
311         $where = "$rel_table.$knownKey = '{$link->getFocus()->id}'" . $this->getRoleWhere();
312
313         if (empty($params['return_as_array'])) {
314             return "SELECT $targetKey id FROM $rel_table WHERE $where AND deleted=0";
315         }
316         else
317         {
318             return array(
319                 'select' => "SELECT $targetKey id",
320                 'from' => "FROM $rel_table",
321                 'where' => "WHERE $where AND $rel_table.deleted=0",
322             );
323         }
324     }
325
326     public function getJoin($link, $params = array(), $return_array = false)
327     {
328         $linkIsLHS = $link->getSide() == REL_LHS;
329         if ($linkIsLHS) {
330             $startingTable = (empty($params['left_join_table_alias']) ? $link->getFocus()->table_name : $params['left_join_table_alias']);
331         } else {
332             $startingTable = (empty($params['right_join_table_alias']) ? $link->getFocus()->table_name : $params['right_join_table_alias']);
333         }
334
335         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
336         $startingJoinKey = $linkIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
337         $joinTable = $this->getRelationshipTable();
338         $joinTableWithAlias = $joinTable;
339         $joinKey = $linkIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
340         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
341         $targetTableWithAlias = $targetTable;
342         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
343         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
344
345         $join = '';
346
347         //Set up any table aliases required
348         if (!empty($params['join_table_link_alias']))
349         {
350             $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
351             $joinTable = $params['join_table_link_alias'];
352         }
353         if ( ! empty($params['join_table_alias']))
354         {
355             $targetTableWithAlias = $targetTable . " ". $params['join_table_alias'];
356             $targetTable = $params['join_table_alias'];
357         }
358
359         $join1 = "$startingTable.$startingKey=$joinTable.$startingJoinKey";
360         $join2 = "$targetTable.$targetKey=$joinTable.$joinKey";
361         $where = "";
362
363
364         //First join the relationship table
365         $join .= "$join_type $joinTableWithAlias ON $join1 AND $joinTable.deleted=0\n"
366         //Next add any role filters
367                . $this->getRoleWhere($joinTable) . "\n"
368         //Then finally join the related module's table
369                . "$join_type $targetTableWithAlias ON $join2 AND $targetTable.deleted=0\n";
370
371         if($return_array){
372             return array(
373                 'join' => $join,
374                 'type' => $this->type,
375                 'rel_key' => $joinKey,
376                 'join_tables' => array($joinTable, $targetTable),
377                 'where' => $where,
378                 'select' => "$targetTable.id",
379             );
380         }
381         return $join . $where;
382     }
383
384     /**
385      * Similar to getQuery or Get join, except this time we are starting from the related table and
386      * searching for items with id's matching the $link->focus->id
387      * @param  $link
388      * @param array $params
389      * @param bool $return_array
390      * @return String|Array
391      */
392     public function getSubpanelQuery($link, $params = array(), $return_array = false)
393     {
394         $targetIsLHS = $link->getSide() == REL_RHS;
395         $startingTable = $targetIsLHS ? $this->def['lhs_table'] : $this->def['rhs_table'];;
396         $startingKey = $targetIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
397         $startingJoinKey = $targetIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
398         $joinTable = $this->getRelationshipTable();
399         $joinTableWithAlias = $joinTable;
400         $joinKey = $targetIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
401         $targetKey = $targetIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
402         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
403
404         $query = '';
405
406         //Set up any table aliases required
407         if (!empty($params['join_table_link_alias']))
408         {
409             $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
410             $joinTable = $params['join_table_link_alias'];
411         }
412
413         $where = "$startingTable.$startingKey=$joinTable.$startingJoinKey AND $joinTable.$joinKey='{$link->getFocus()->$targetKey}'";
414
415         //Check if we should ignore the role fileter;
416         $ignoreRole = !empty($params['ignore_role']);
417
418         //First join the relationship table
419         $query .= "$join_type $joinTableWithAlias ON $where AND $joinTable.deleted=0\n"
420         //Next add any role filters
421                . $this->getRoleWhere($joinTable, $ignoreRole) . "\n";
422
423         if (!empty($params['return_as_array'])) {
424             $return_array = true;
425         }
426         if($return_array){
427             return array(
428                 'join' => $query,
429                 'type' => $this->type,
430                 'rel_key' => $joinKey,
431                 'join_tables' => array($joinTable),
432                 'where' => "",
433                 'select' => " ",
434             );
435         }
436         return $query;
437
438     }
439
440     protected function getRoleFilterForJoin()
441     {
442         $ret = "";
443         if (!empty($this->relationship_role_column) && !$this->ignore_role_filter)
444         {
445             $ret .= " AND ".$this->getRelationshipTable().'.'.$this->relationship_role_column;
446             //role column value.
447             if (empty($this->relationship_role_column_value))
448             {
449                 $ret.=' IS NULL';
450             } else {
451                 $ret.= "='".$this->relationship_role_column_value."'";
452             }
453             $ret.= "\n";
454         }
455         return $ret;
456     }
457
458     /**
459      * @param  $lhs
460      * @param  $rhs
461      * @return bool
462      */
463     public function relationship_exists($lhs, $rhs)
464     {
465         $query = "SELECT * FROM {$this->getRelationshipTable()} WHERE {$this->join_key_lhs} = {$lhs->id} AND {$this->join_key_rhs} = {$rhs->id}";
466
467         //Roles can allow for multiple links between two records with different roles
468         $query .= $this->getRoleWhere() . " and deleted = 0";
469
470         $result = DBManagerFactory::getInstance()->query($query);
471         $row = $this->_db->fetchByAssoc($result);
472
473         if ($row == null) {
474             return false;
475         }
476         else {
477             return $row['id'];
478         }
479     }
480
481     /**
482      * @return Array - set of fields that uniquely identify an entry in this relationship
483      */
484     protected function getAlternateKeyFields()
485     {
486         $fields = array($this->join_key_lhs, $this->join_key_rhs);
487
488         //Roles can allow for multiple links between two records with different roles
489         if (!empty($this->def['relationship_role_column']) && !$this->ignore_role_filter)
490         {
491             $fields[] = $this->relationship_role_column;
492         }
493
494         return $fields;
495     }
496
497     public function getRelationshipTable()
498     {
499         if (!empty($this->def['table']))
500             return $this->def['table'];
501         else if(!empty($this->def['join_table']))
502             return $this->def['join_table'];
503
504         return false;
505     }
506
507     public function getFields()
508     {
509         if (!empty($this->def['fields']))
510             return $this->def['fields'];
511         $fields = array(
512             "id" => array('name' => 'id'),
513             'date_modified' => array('name' => 'date_modified'),
514             'modified_user_id' => array('name' => 'modified_user_id'),
515             'created_by' => array('name' => 'created_by'),
516             $this->def['join_key_lhs'] => array('name' => $this->def['join_key_lhs']),
517             $this->def['join_key_rhs'] => array('name' => $this->def['join_key_rhs'])
518         );
519         if (!empty($this->def['relationship_role_column']))
520         {
521             $fields[$this->def['relationship_role_column']] = array("name" => $this->def['relationship_role_column']);
522         }
523         $fields['deleted'] = array('name' => 'deleted');
524
525         return $fields;
526     }
527
528 }