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.
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.
44 class M2MRelationship extends SugarRelationship
46 var $type = "many-to-many";
48 public function __construct($def)
51 $this->name = $def['name'];
53 $lhsModule = $def['lhs_module'];
54 $this->lhsLinkDef = $this->getLinkedDefForModuleByRelationship($lhsModule);
55 $this->lhsLink = $this->lhsLinkDef['name'];
57 $rhsModule = $def['rhs_module'];
58 $this->rhsLinkDef = $this->getLinkedDefForModuleByRelationship($rhsModule);
59 $this->rhsLink = $this->rhsLinkDef['name'];
61 $this->self_referencing = $lhsModule == $rhsModule;
65 * Find the link entry for a particular relationship and module.
70 public function getLinkedDefForModuleByRelationship($module)
72 $results = VardefManager::getLinkFieldForRelationship( $module, BeanFactory::getObjectName($module), $this->name);
73 //Only a single link was found
74 if( isset($results['name']) )
78 //Multiple links with same relationship name
79 else if( is_array($results) )
81 $GLOBALS['log']->error("Warning: Multiple links found for relationship {$this->name} within module {$module}");
82 return $this->getMostAppropriateLinkedDefinition($results);
91 * Find the most 'appropriate' link entry for a relationship/module in which there are multiple link entries with the
92 * same relationship name.
97 protected function getMostAppropriateLinkedDefinition($links)
99 //First priority is to find a link name that matches the relationship name
100 foreach($links as $link)
102 if( isset($link['name']) && $link['name'] == $this->name )
107 //Next would be a relationship that has a side defined
108 foreach($links as $link)
110 if( isset($link['id_name']))
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}");
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
125 public function add($lhs, $rhs, $additionalFields = array())
127 $lhsLinkName = $this->lhsLink;
128 $rhsLinkName = $this->rhsLink;
130 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
132 $lhsClass = get_class($lhs);
133 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName in $lhsClass");
136 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
138 $rhsClass = get_class($rhs);
139 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName in $rhsClass");
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);
146 $this->addRow($dataToInsert);
148 if ($this->self_referencing)
149 $this->addSelfReferencing($lhs, $rhs, $additionalFields);
151 if ($lhs->$lhsLinkName->beansAreLoaded())
152 $lhs->$lhsLinkName->addBean($rhs);
153 if ($rhs->$rhsLinkName->beansAreLoaded())
154 $rhs->$rhsLinkName->addBean($lhs);
156 $this->callAfterAdd($lhs, $rhs, $lhsLinkName);
157 $this->callAfterAdd($rhs, $lhs, $rhsLinkName);
160 protected function getRowToInsert($lhs, $rhs, $additionalFields = array())
163 "id" => create_guid(),
164 $this->def['join_key_lhs'] => $lhs->id,
165 $this->def['join_key_rhs'] => $rhs->id,
166 'date_modified' => TimeDate::getInstance()->getNow()->asDb(),
171 if (!empty($this->def['relationship_role_column']) && !empty($this->def['relationship_role_column_value']) && !$this->ignore_role_filter )
173 $row[$this->relationship_role_column] = $this->relationship_role_column_value;
176 if (!empty($this->def['fields']))
178 foreach($this->def['fields'] as $fieldDef)
180 if (!empty($fieldDef['name']) && !isset($row[$fieldDef['name']]) && !empty($fieldDef['default']))
182 $row[$fieldDef['name']] = $fieldDef['default'];
186 if (!empty($additionalFields))
188 $row = array_merge($row, $additionalFields);
195 * Adds the reversed version of this relationship to the table so that it can be accessed from either side equally
198 * @param array $additionalFields
201 protected function addSelfReferencing($lhs, $rhs, $additionalFields = array())
203 if ($rhs->id != $lhs->id)
205 $dataToInsert = $this->getRowToInsert($rhs, $lhs, $additionalFields);
206 $this->addRow($dataToInsert);
210 public function remove($lhs, $rhs)
212 $lhsLinkName = $this->lhsLink;
213 $rhsLinkName = $this->rhsLink;
215 if (!($lhs instanceof SugarBean)) {
216 $GLOBALS['log']->fatal("LHS is not a SugarBean object");
219 if (!($rhs instanceof SugarBean)) {
220 $GLOBALS['log']->fatal("RHS is not a SugarBean object");
223 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
225 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName");
228 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
230 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName");
234 $dataToRemove = array(
235 $this->def['join_key_lhs'] => $lhs->id,
236 $this->def['join_key_rhs'] => $rhs->id
239 $this->removeRow($dataToRemove);
241 if ($this->self_referencing)
242 $this->removeSelfReferencing($lhs, $rhs);
244 if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
246 if ($lhs->$lhsLinkName instanceof Link2)
248 $lhs->$lhsLinkName->load();
249 $this->callAfterDelete($lhs, $rhs, $lhsLinkName);
252 if ($rhs->$rhsLinkName instanceof Link2)
254 $rhs->$rhsLinkName->load();
255 $this->callAfterDelete($rhs, $lhs, $rhsLinkName);
261 * Removes the reversed version of this relationship
264 * @param array $additionalFields
267 protected function removeSelfReferencing($lhs, $rhs, $additionalFields = array())
269 if ($rhs->id != $lhs->id)
271 $dataToRemove = array(
272 $this->def['join_key_lhs'] => $rhs->id,
273 $this->def['join_key_rhs'] => $lhs->id
275 $this->removeRow($dataToRemove);
280 * @param $link Link2 loads the relationship for this link.
283 public function load($link)
285 $db = DBManagerFactory::getInstance();
286 $query = $this->getQuery($link);
287 $result = $db->query($query);
289 $idField = $link->getSide() == REL_LHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
290 while ($row = $db->fetchByAssoc($result))
292 if (empty($row['id']) && empty($row[$idField]))
294 $id = empty($row['id']) ? $row[$idField] : $row['id'];
297 return array("rows" => $rows);
300 public function getQuery($link, $params = array())
302 if ($link->getSide() == REL_LHS) {
303 $knownKey = $this->def['join_key_lhs'];
304 $targetKey = $this->def['join_key_rhs'];
308 $knownKey = $this->def['join_key_rhs'];
309 $targetKey = $this->def['join_key_lhs'];
311 $rel_table = $this->getRelationshipTable();
313 $where = "$rel_table.$knownKey = '{$link->getFocus()->id}'" . $this->getRoleWhere();
315 if (empty($params['return_as_array'])) {
316 return "SELECT $targetKey id FROM $rel_table WHERE $where AND deleted=0";
321 'select' => "SELECT $targetKey id",
322 'from' => "FROM $rel_table",
323 'where' => "WHERE $where AND $rel_table.deleted=0",
328 public function getJoin($link, $params = array(), $return_array = false)
330 $linkIsLHS = $link->getSide() == REL_LHS;
332 $startingTable = (empty($params['left_join_table_alias']) ? $link->getFocus()->table_name : $params['left_join_table_alias']);
334 $startingTable = (empty($params['right_join_table_alias']) ? $link->getFocus()->table_name : $params['right_join_table_alias']);
337 $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
338 $startingJoinKey = $linkIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
339 $joinTable = $this->getRelationshipTable();
340 $joinTableWithAlias = $joinTable;
341 $joinKey = $linkIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
342 $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
343 $targetTableWithAlias = $targetTable;
344 $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
345 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
349 //Set up any table aliases required
350 if (!empty($params['join_table_link_alias']))
352 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
353 $joinTable = $params['join_table_link_alias'];
355 if ( ! empty($params['join_table_alias']))
357 $targetTableWithAlias = $targetTable . " ". $params['join_table_alias'];
358 $targetTable = $params['join_table_alias'];
361 $join1 = "$startingTable.$startingKey=$joinTable.$startingJoinKey";
362 $join2 = "$targetTable.$targetKey=$joinTable.$joinKey";
366 //First join the relationship table
367 $join .= "$join_type $joinTableWithAlias ON $join1 AND $joinTable.deleted=0\n"
368 //Next add any role filters
369 . $this->getRoleWhere($joinTable) . "\n"
370 //Then finally join the related module's table
371 . "$join_type $targetTableWithAlias ON $join2 AND $targetTable.deleted=0\n";
376 'type' => $this->type,
377 'rel_key' => $joinKey,
378 'join_tables' => array($joinTable, $targetTable),
380 'select' => "$targetTable.id",
383 return $join . $where;
387 * Similar to getQuery or Get join, except this time we are starting from the related table and
388 * searching for items with id's matching the $link->focus->id
390 * @param array $params
391 * @param bool $return_array
392 * @return String|Array
394 public function getSubpanelQuery($link, $params = array(), $return_array = false)
396 $targetIsLHS = $link->getSide() == REL_RHS;
397 $startingTable = $targetIsLHS ? $this->def['lhs_table'] : $this->def['rhs_table'];;
398 $startingKey = $targetIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
399 $startingJoinKey = $targetIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
400 $joinTable = $this->getRelationshipTable();
401 $joinTableWithAlias = $joinTable;
402 $joinKey = $targetIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
403 $targetKey = $targetIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
404 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
408 //Set up any table aliases required
409 if (!empty($params['join_table_link_alias']))
411 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
412 $joinTable = $params['join_table_link_alias'];
415 $where = "$startingTable.$startingKey=$joinTable.$startingJoinKey AND $joinTable.$joinKey='{$link->getFocus()->$targetKey}'";
417 //Check if we should ignore the role fileter;
418 $ignoreRole = !empty($params['ignore_role']);
420 //First join the relationship table
421 $query .= "$join_type $joinTableWithAlias ON $where AND $joinTable.deleted=0\n"
422 //Next add any role filters
423 . $this->getRoleWhere($joinTable, $ignoreRole) . "\n";
425 if (!empty($params['return_as_array'])) {
426 $return_array = true;
431 'type' => $this->type,
432 'rel_key' => $joinKey,
433 'join_tables' => array($joinTable),
442 protected function getRoleFilterForJoin()
445 if (!empty($this->relationship_role_column) && !$this->ignore_role_filter)
447 $ret .= " AND ".$this->getRelationshipTable().'.'.$this->relationship_role_column;
449 if (empty($this->relationship_role_column_value))
453 $ret.= "='".$this->relationship_role_column_value."'";
465 public function relationship_exists($lhs, $rhs)
467 $query = "SELECT * FROM {$this->getRelationshipTable()} WHERE {$this->join_key_lhs} = {$lhs->id} AND {$this->join_key_rhs} = {$rhs->id}";
469 //Roles can allow for multiple links between two records with different roles
470 $query .= $this->getRoleWhere() . " and deleted = 0";
472 $result = DBManagerFactory::getInstance()->query($query);
473 $row = $this->_db->fetchByAssoc($result);
484 * @return Array - set of fields that uniquely identify an entry in this relationship
486 protected function getAlternateKeyFields()
488 $fields = array($this->join_key_lhs, $this->join_key_rhs);
490 //Roles can allow for multiple links between two records with different roles
491 if (!empty($this->def['relationship_role_column']) && !$this->ignore_role_filter)
493 $fields[] = $this->relationship_role_column;
499 public function getRelationshipTable()
501 if (!empty($this->def['table']))
502 return $this->def['table'];
503 else if(!empty($this->def['join_table']))
504 return $this->def['join_table'];
509 public function getFields()
511 if (!empty($this->def['fields']))
512 return $this->def['fields'];
514 "id" => array('name' => 'id'),
515 'date_modified' => array('name' => 'date_modified'),
516 'modified_user_id' => array('name' => 'modified_user_id'),
517 'created_by' => array('name' => 'created_by'),
518 $this->def['join_key_lhs'] => array('name' => $this->def['join_key_lhs']),
519 $this->def['join_key_rhs'] => array('name' => $this->def['join_key_rhs'])
521 if (!empty($this->def['relationship_role_column']))
523 $fields[$this->def['relationship_role_column']] = array("name" => $this->def['relationship_role_column']);
525 $fields['deleted'] = array('name' => 'deleted');