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