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.
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.
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
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
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.
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.
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 ********************************************************************************/
39 require_once("data/Relationships/SugarRelationship.php");
42 * Represents a many to many relationship that is table based.
45 class M2MRelationship extends SugarRelationship
47 var $type = "many-to-many";
49 public function __construct($def)
52 $this->name = $def['name'];
54 $lhsModule = $def['lhs_module'];
55 $this->lhsLinkDef = $this->getLinkedDefForModuleByRelationship($lhsModule);
56 $this->lhsLink = $this->lhsLinkDef['name'];
58 $rhsModule = $def['rhs_module'];
59 $this->rhsLinkDef = $this->getLinkedDefForModuleByRelationship($rhsModule);
60 $this->rhsLink = $this->rhsLinkDef['name'];
62 $this->self_referencing = $lhsModule == $rhsModule;
66 * Find the link entry for a particular relationship and module.
71 public function getLinkedDefForModuleByRelationship($module)
73 $results = VardefManager::getLinkFieldForRelationship( $module, BeanFactory::getObjectName($module), $this->name);
74 //Only a single link was found
75 if( isset($results['name']) )
79 //Multiple links with same relationship name
80 else if( is_array($results) )
82 $GLOBALS['log']->error("Warning: Multiple links found for relationship {$this->name} within module {$module}");
83 return $this->getMostAppropriateLinkedDefinition($results);
92 * Find the most 'appropriate' link entry for a relationship/module in which there are multiple link entries with the
93 * same relationship name.
98 protected function getMostAppropriateLinkedDefinition($links)
100 //First priority is to find a link name that matches the relationship name
101 foreach($links as $link)
103 if( isset($link['name']) && $link['name'] == $this->name )
108 //Next would be a relationship that has a side defined
109 foreach($links as $link)
111 if( isset($link['id_name']))
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}");
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
126 public function add($lhs, $rhs, $additionalFields = array())
128 $lhsLinkName = $this->lhsLink;
129 $rhsLinkName = $this->rhsLink;
131 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
133 $lhsClass = get_class($lhs);
134 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName in $lhsClass");
137 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
139 $rhsClass = get_class($rhs);
140 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName in $rhsClass");
144 $lhs->$lhsLinkName->addBean($rhs);
145 $rhs->$rhsLinkName->addBean($lhs);
147 $this->callBeforeAdd($lhs, $rhs, $lhsLinkName);
148 $this->callBeforeAdd($rhs, $lhs, $rhsLinkName);
150 //Many to many has no additional logic, so just add a new row to the table and notify the beans.
151 $dataToInsert = $this->getRowToInsert($lhs, $rhs, $additionalFields);
153 $this->addRow($dataToInsert);
155 if ($this->self_referencing)
156 $this->addSelfReferencing($lhs, $rhs, $additionalFields);
158 $lhs->$lhsLinkName->addBean($rhs);
159 $rhs->$rhsLinkName->addBean($lhs);
161 $this->callAfterAdd($lhs, $rhs, $lhsLinkName);
162 $this->callAfterAdd($rhs, $lhs, $rhsLinkName);
165 protected function getRowToInsert($lhs, $rhs, $additionalFields = array())
168 "id" => create_guid(),
169 $this->def['join_key_lhs'] => $lhs->id,
170 $this->def['join_key_rhs'] => $rhs->id,
171 'date_modified' => TimeDate::getInstance()->nowDb(),
176 if (!empty($this->def['relationship_role_column']) && !empty($this->def['relationship_role_column_value']) && !$this->ignore_role_filter )
178 $row[$this->relationship_role_column] = $this->relationship_role_column_value;
181 if (!empty($this->def['fields']))
183 foreach($this->def['fields'] as $fieldDef)
185 if (!empty($fieldDef['name']) && !isset($row[$fieldDef['name']]) && !empty($fieldDef['default']))
187 $row[$fieldDef['name']] = $fieldDef['default'];
191 if (!empty($additionalFields))
193 $row = array_merge($row, $additionalFields);
200 * Adds the reversed version of this relationship to the table so that it can be accessed from either side equally
203 * @param array $additionalFields
206 protected function addSelfReferencing($lhs, $rhs, $additionalFields = array())
208 if ($rhs->id != $lhs->id)
210 $dataToInsert = $this->getRowToInsert($rhs, $lhs, $additionalFields);
211 $this->addRow($dataToInsert);
215 public function remove($lhs, $rhs)
217 if(!($lhs instanceof SugarBean) || !($rhs instanceof SugarBean)) {
218 $GLOBALS['log']->fatal("LHS and RHS must be beans");
221 $lhsLinkName = $this->lhsLink;
222 $rhsLinkName = $this->rhsLink;
224 if (!($lhs instanceof SugarBean)) {
225 $GLOBALS['log']->fatal("LHS is not a SugarBean object");
228 if (!($rhs instanceof SugarBean)) {
229 $GLOBALS['log']->fatal("RHS is not a SugarBean object");
232 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
234 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName");
237 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
239 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName");
243 if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
245 if ($lhs->$lhsLinkName instanceof Link2)
247 $lhs->$lhsLinkName->load();
248 $this->callBeforeDelete($lhs, $rhs, $lhsLinkName);
251 if ($rhs->$rhsLinkName instanceof Link2)
253 $rhs->$rhsLinkName->load();
254 $this->callBeforeDelete($rhs, $lhs, $rhsLinkName);
258 $dataToRemove = array(
259 $this->def['join_key_lhs'] => $lhs->id,
260 $this->def['join_key_rhs'] => $rhs->id
263 $this->removeRow($dataToRemove);
265 if ($this->self_referencing)
266 $this->removeSelfReferencing($lhs, $rhs);
268 if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
270 if ($lhs->$lhsLinkName instanceof Link2)
272 $lhs->$lhsLinkName->load();
273 $this->callAfterDelete($lhs, $rhs, $lhsLinkName);
276 if ($rhs->$rhsLinkName instanceof Link2)
278 $rhs->$rhsLinkName->load();
279 $this->callAfterDelete($rhs, $lhs, $rhsLinkName);
285 * Removes the reversed version of this relationship
288 * @param array $additionalFields
291 protected function removeSelfReferencing($lhs, $rhs, $additionalFields = array())
293 if ($rhs->id != $lhs->id)
295 $dataToRemove = array(
296 $this->def['join_key_lhs'] => $rhs->id,
297 $this->def['join_key_rhs'] => $lhs->id
299 $this->removeRow($dataToRemove);
304 * @param $link Link2 loads the relationship for this link.
307 public function load($link, $params = array())
309 $db = DBManagerFactory::getInstance();
310 $query = $this->getQuery($link, $params);
311 $result = $db->query($query);
313 $idField = $link->getSide() == REL_LHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
314 while ($row = $db->fetchByAssoc($result, FALSE))
316 if (empty($row['id']) && empty($row[$idField]))
318 $id = empty($row['id']) ? $row[$idField] : $row['id'];
321 return array("rows" => $rows);
324 protected function linkIsLHS($link) {
325 return $link->getSide() == REL_LHS;
328 public function getQuery($link, $params = array())
330 if ($this->linkIsLHS($link)) {
331 $knownKey = $this->def['join_key_lhs'];
332 $targetKey = $this->def['join_key_rhs'];
333 $relatedSeed = BeanFactory::getBean($this->getRHSModule());
334 if (!empty($params['where']))
335 $whereTable = (empty($params['right_join_table_alias']) ? $relatedSeed->table_name : $params['right_join_table_alias']);
339 $knownKey = $this->def['join_key_rhs'];
340 $targetKey = $this->def['join_key_lhs'];
341 $relatedSeed = BeanFactory::getBean($this->getLHSModule());
342 if (!empty($params['where']))
343 $whereTable = (empty($params['left_join_table_alias']) ? $relatedSeed->table_name : $params['left_join_table_alias']);
345 $rel_table = $this->getRelationshipTable();
347 $where = "$rel_table.$knownKey = '{$link->getFocus()->id}'" . $this->getRoleWhere();
349 //Add any optional where clause
350 if (!empty($params['where'])){
351 $add_where = is_string($params['where']) ? $params['where'] : "$whereTable." . $this->getOptionalWhereClause($params['where']);
352 if (!empty($add_where))
353 $where .= " AND $rel_table.$targetKey=$whereTable.id AND $add_where";
356 $deleted = !empty($params['deleted']) ? 1 : 0;
358 if (!empty($params['where']))
359 $from .= ", $whereTable";
361 if (empty($params['return_as_array'])) {
362 $query = "SELECT $targetKey id FROM $from WHERE $where AND $rel_table.deleted=$deleted";
363 //Limit is not compatible with return_as_array
364 if (!empty($params['limit']) && $params['limit'] > 0) {
365 $offset = isset($params['offset']) ? $params['offset'] : 0;
366 $query = DBManagerFactory::getInstance()->limitQuery($query, $offset, $params['limit'], false, "", false);
373 'select' => "SELECT $targetKey id",
374 'from' => "FROM $from",
375 'where' => "WHERE $where AND $rel_table.deleted=$deleted",
380 public function getJoin($link, $params = array(), $return_array = false)
382 $linkIsLHS = $link->getSide() == REL_LHS;
384 $startingTable = (empty($params['left_join_table_alias']) ? $link->getFocus()->table_name : $params['left_join_table_alias']);
386 $startingTable = (empty($params['right_join_table_alias']) ? $link->getFocus()->table_name : $params['right_join_table_alias']);
389 $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
390 $startingJoinKey = $linkIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
391 $joinTable = $this->getRelationshipTable();
392 $joinTableWithAlias = $joinTable;
393 $joinKey = $linkIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
394 $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
395 $targetTableWithAlias = $targetTable;
396 $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
397 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
401 //Set up any table aliases required
402 if (!empty($params['join_table_link_alias']))
404 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
405 $joinTable = $params['join_table_link_alias'];
407 if ( ! empty($params['join_table_alias']))
409 $targetTableWithAlias = $targetTable . " ". $params['join_table_alias'];
410 $targetTable = $params['join_table_alias'];
413 $join1 = "$startingTable.$startingKey=$joinTable.$startingJoinKey";
414 $join2 = "$targetTable.$targetKey=$joinTable.$joinKey";
418 //First join the relationship table
419 $join .= "$join_type $joinTableWithAlias ON $join1 AND $joinTable.deleted=0\n"
420 //Next add any role filters
421 . $this->getRoleWhere($joinTable) . "\n"
422 //Then finally join the related module's table
423 . "$join_type $targetTableWithAlias ON $join2 AND $targetTable.deleted=0\n";
428 'type' => $this->type,
429 'rel_key' => $joinKey,
430 'join_tables' => array($joinTable, $targetTable),
432 'select' => "$targetTable.id",
435 return $join . $where;
439 * Similar to getQuery or Get join, except this time we are starting from the related table and
440 * searching for items with id's matching the $link->focus->id
442 * @param array $params
443 * @param bool $return_array
444 * @return String|Array
446 public function getSubpanelQuery($link, $params = array(), $return_array = false)
448 $targetIsLHS = $link->getSide() == REL_RHS;
449 $startingTable = $targetIsLHS ? $this->def['lhs_table'] : $this->def['rhs_table'];;
450 $startingKey = $targetIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
451 $startingJoinKey = $targetIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
452 $joinTable = $this->getRelationshipTable();
453 $joinTableWithAlias = $joinTable;
454 $joinKey = $targetIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
455 $targetKey = $targetIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
456 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
460 //Set up any table aliases required
461 if (!empty($params['join_table_link_alias']))
463 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
464 $joinTable = $params['join_table_link_alias'];
467 $where = "$startingTable.$startingKey=$joinTable.$startingJoinKey AND $joinTable.$joinKey='{$link->getFocus()->$targetKey}'";
469 //Check if we should ignore the role filter.
470 $ignoreRole = !empty($params['ignore_role']);
472 //First join the relationship table
473 $query .= "$join_type $joinTableWithAlias ON $where AND $joinTable.deleted=0\n"
474 //Next add any role filters
475 . $this->getRoleWhere($joinTable, $ignoreRole) . "\n";
477 if (!empty($params['return_as_array'])) {
478 $return_array = true;
483 'type' => $this->type,
484 'rel_key' => $joinKey,
485 'join_tables' => array($joinTable),
494 protected function getRoleFilterForJoin()
497 if (!empty($this->relationship_role_column) && !$this->ignore_role_filter)
499 $ret .= " AND ".$this->getRelationshipTable().'.'.$this->relationship_role_column;
501 if (empty($this->relationship_role_column_value))
505 $ret.= "='".$this->relationship_role_column_value."'";
517 public function relationship_exists($lhs, $rhs)
519 $query = "SELECT id FROM {$this->getRelationshipTable()} WHERE {$this->join_key_lhs} = '{$lhs->id}' AND {$this->join_key_rhs} = '{$rhs->id}'";
521 //Roles can allow for multiple links between two records with different roles
522 $query .= $this->getRoleWhere() . " and deleted = 0";
524 return $GLOBALS['db']->getOne($query);
528 * @return Array - set of fields that uniquely identify an entry in this relationship
530 protected function getAlternateKeyFields()
532 $fields = array($this->join_key_lhs, $this->join_key_rhs);
534 //Roles can allow for multiple links between two records with different roles
535 if (!empty($this->def['relationship_role_column']) && !$this->ignore_role_filter)
537 $fields[] = $this->relationship_role_column;
543 public function getRelationshipTable()
545 if (!empty($this->def['table']))
546 return $this->def['table'];
547 else if(!empty($this->def['join_table']))
548 return $this->def['join_table'];
553 public function getFields()
555 if (!empty($this->def['fields']))
556 return $this->def['fields'];
558 "id" => array('name' => 'id'),
559 'date_modified' => array('name' => 'date_modified'),
560 'modified_user_id' => array('name' => 'modified_user_id'),
561 'created_by' => array('name' => 'created_by'),
562 $this->def['join_key_lhs'] => array('name' => $this->def['join_key_lhs']),
563 $this->def['join_key_rhs'] => array('name' => $this->def['join_key_rhs'])
565 if (!empty($this->def['relationship_role_column']))
567 $fields[$this->def['relationship_role_column']] = array("name" => $this->def['relationship_role_column']);
569 $fields['deleted'] = array('name' => 'deleted');