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 //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);
147 $this->addRow($dataToInsert);
149 if ($this->self_referencing)
150 $this->addSelfReferencing($lhs, $rhs, $additionalFields);
152 $lhs->$lhsLinkName->addBean($rhs);
153 $rhs->$rhsLinkName->addBean($lhs);
155 $this->callAfterAdd($lhs, $rhs, $lhsLinkName);
156 $this->callAfterAdd($rhs, $lhs, $rhsLinkName);
159 protected function getRowToInsert($lhs, $rhs, $additionalFields = 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(),
170 if (!empty($this->def['relationship_role_column']) && !empty($this->def['relationship_role_column_value']) && !$this->ignore_role_filter )
172 $row[$this->relationship_role_column] = $this->relationship_role_column_value;
175 if (!empty($this->def['fields']))
177 foreach($this->def['fields'] as $fieldDef)
179 if (!empty($fieldDef['name']) && !isset($row[$fieldDef['name']]) && !empty($fieldDef['default']))
181 $row[$fieldDef['name']] = $fieldDef['default'];
185 if (!empty($additionalFields))
187 $row = array_merge($row, $additionalFields);
194 * Adds the reversed version of this relationship to the table so that it can be accessed from either side equally
197 * @param array $additionalFields
200 protected function addSelfReferencing($lhs, $rhs, $additionalFields = array())
202 if ($rhs->id != $lhs->id)
204 $dataToInsert = $this->getRowToInsert($rhs, $lhs, $additionalFields);
205 $this->addRow($dataToInsert);
209 public function remove($lhs, $rhs)
211 if(!($lhs instanceof SugarBean) || !($rhs instanceof SugarBean)) {
212 $GLOBALS['log']->fatal("LHS and RHS must be beans");
215 $lhsLinkName = $this->lhsLink;
216 $rhsLinkName = $this->rhsLink;
218 if (!($lhs instanceof SugarBean)) {
219 $GLOBALS['log']->fatal("LHS is not a SugarBean object");
222 if (!($rhs instanceof SugarBean)) {
223 $GLOBALS['log']->fatal("RHS is not a SugarBean object");
226 if (empty($lhs->$lhsLinkName) && !$lhs->load_relationship($lhsLinkName))
228 $GLOBALS['log']->fatal("could not load LHS $lhsLinkName");
231 if (empty($rhs->$rhsLinkName) && !$rhs->load_relationship($rhsLinkName))
233 $GLOBALS['log']->fatal("could not load RHS $rhsLinkName");
237 $dataToRemove = array(
238 $this->def['join_key_lhs'] => $lhs->id,
239 $this->def['join_key_rhs'] => $rhs->id
242 $this->removeRow($dataToRemove);
244 if ($this->self_referencing)
245 $this->removeSelfReferencing($lhs, $rhs);
247 if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
249 if ($lhs->$lhsLinkName instanceof Link2)
251 $lhs->$lhsLinkName->load();
252 $this->callAfterDelete($lhs, $rhs, $lhsLinkName);
255 if ($rhs->$rhsLinkName instanceof Link2)
257 $rhs->$rhsLinkName->load();
258 $this->callAfterDelete($rhs, $lhs, $rhsLinkName);
264 * Removes the reversed version of this relationship
267 * @param array $additionalFields
270 protected function removeSelfReferencing($lhs, $rhs, $additionalFields = array())
272 if ($rhs->id != $lhs->id)
274 $dataToRemove = array(
275 $this->def['join_key_lhs'] => $rhs->id,
276 $this->def['join_key_rhs'] => $lhs->id
278 $this->removeRow($dataToRemove);
283 * @param $link Link2 loads the relationship for this link.
286 public function load($link, $params = array())
288 $db = DBManagerFactory::getInstance();
289 $query = $this->getQuery($link, $params);
290 $result = $db->query($query);
292 $idField = $link->getSide() == REL_LHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
293 while ($row = $db->fetchByAssoc($result, FALSE))
295 if (empty($row['id']) && empty($row[$idField]))
297 $id = empty($row['id']) ? $row[$idField] : $row['id'];
300 return array("rows" => $rows);
303 protected function linkIsLHS($link) {
304 return $link->getSide() == REL_LHS;
307 public function getQuery($link, $params = array())
309 if ($this->linkIsLHS($link)) {
310 $knownKey = $this->def['join_key_lhs'];
311 $targetKey = $this->def['join_key_rhs'];
312 $relatedSeed = BeanFactory::getBean($this->getRHSModule());
313 if (!empty($params['where']))
314 $whereTable = (empty($params['right_join_table_alias']) ? $relatedSeed->table_name : $params['right_join_table_alias']);
318 $knownKey = $this->def['join_key_rhs'];
319 $targetKey = $this->def['join_key_lhs'];
320 $relatedSeed = BeanFactory::getBean($this->getLHSModule());
321 if (!empty($params['where']))
322 $whereTable = (empty($params['left_join_table_alias']) ? $relatedSeed->table_name : $params['left_join_table_alias']);
324 $rel_table = $this->getRelationshipTable();
326 $where = "$rel_table.$knownKey = '{$link->getFocus()->id}'" . $this->getRoleWhere();
328 //Add any optional where clause
329 if (!empty($params['where'])){
330 $add_where = is_string($params['where']) ? $params['where'] : "$whereTable." . $this->getOptionalWhereClause($params['where']);
331 if (!empty($add_where))
332 $where .= " AND $rel_table.$targetKey=$whereTable.id AND $add_where";
335 $deleted = !empty($params['deleted']) ? 1 : 0;
337 if (!empty($params['where']))
338 $from .= ", $whereTable";
340 if (empty($params['return_as_array'])) {
341 $query = "SELECT $targetKey id FROM $from WHERE $where AND $rel_table.deleted=$deleted";
342 //Limit is not compatible with return_as_array
343 if (!empty($params['limit']) && $params['limit'] > 0) {
344 $offset = isset($params['offset']) ? $params['offset'] : 0;
345 $query = DBManagerFactory::getInstance()->limitQuery($query, $offset, $params['limit'], false, "", false);
352 'select' => "SELECT $targetKey id",
353 'from' => "FROM $from",
354 'where' => "WHERE $where AND $rel_table.deleted=$deleted",
359 public function getJoin($link, $params = array(), $return_array = false)
361 $linkIsLHS = $link->getSide() == REL_LHS;
363 $startingTable = (empty($params['left_join_table_alias']) ? $link->getFocus()->table_name : $params['left_join_table_alias']);
365 $startingTable = (empty($params['right_join_table_alias']) ? $link->getFocus()->table_name : $params['right_join_table_alias']);
368 $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
369 $startingJoinKey = $linkIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
370 $joinTable = $this->getRelationshipTable();
371 $joinTableWithAlias = $joinTable;
372 $joinKey = $linkIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
373 $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
374 $targetTableWithAlias = $targetTable;
375 $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
376 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
380 //Set up any table aliases required
381 if (!empty($params['join_table_link_alias']))
383 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
384 $joinTable = $params['join_table_link_alias'];
386 if ( ! empty($params['join_table_alias']))
388 $targetTableWithAlias = $targetTable . " ". $params['join_table_alias'];
389 $targetTable = $params['join_table_alias'];
392 $join1 = "$startingTable.$startingKey=$joinTable.$startingJoinKey";
393 $join2 = "$targetTable.$targetKey=$joinTable.$joinKey";
397 //First join the relationship table
398 $join .= "$join_type $joinTableWithAlias ON $join1 AND $joinTable.deleted=0\n"
399 //Next add any role filters
400 . $this->getRoleWhere($joinTable) . "\n"
401 //Then finally join the related module's table
402 . "$join_type $targetTableWithAlias ON $join2 AND $targetTable.deleted=0\n";
407 'type' => $this->type,
408 'rel_key' => $joinKey,
409 'join_tables' => array($joinTable, $targetTable),
411 'select' => "$targetTable.id",
414 return $join . $where;
418 * Similar to getQuery or Get join, except this time we are starting from the related table and
419 * searching for items with id's matching the $link->focus->id
421 * @param array $params
422 * @param bool $return_array
423 * @return String|Array
425 public function getSubpanelQuery($link, $params = array(), $return_array = false)
427 $targetIsLHS = $link->getSide() == REL_RHS;
428 $startingTable = $targetIsLHS ? $this->def['lhs_table'] : $this->def['rhs_table'];;
429 $startingKey = $targetIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
430 $startingJoinKey = $targetIsLHS ? $this->def['join_key_lhs'] : $this->def['join_key_rhs'];
431 $joinTable = $this->getRelationshipTable();
432 $joinTableWithAlias = $joinTable;
433 $joinKey = $targetIsLHS ? $this->def['join_key_rhs'] : $this->def['join_key_lhs'];
434 $targetKey = $targetIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
435 $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
439 //Set up any table aliases required
440 if (!empty($params['join_table_link_alias']))
442 $joinTableWithAlias = $joinTable . " ". $params['join_table_link_alias'];
443 $joinTable = $params['join_table_link_alias'];
446 $where = "$startingTable.$startingKey=$joinTable.$startingJoinKey AND $joinTable.$joinKey='{$link->getFocus()->$targetKey}'";
448 //Check if we should ignore the role filter.
449 $ignoreRole = !empty($params['ignore_role']);
451 //First join the relationship table
452 $query .= "$join_type $joinTableWithAlias ON $where AND $joinTable.deleted=0\n"
453 //Next add any role filters
454 . $this->getRoleWhere($joinTable, $ignoreRole) . "\n";
456 if (!empty($params['return_as_array'])) {
457 $return_array = true;
462 'type' => $this->type,
463 'rel_key' => $joinKey,
464 'join_tables' => array($joinTable),
473 protected function getRoleFilterForJoin()
476 if (!empty($this->relationship_role_column) && !$this->ignore_role_filter)
478 $ret .= " AND ".$this->getRelationshipTable().'.'.$this->relationship_role_column;
480 if (empty($this->relationship_role_column_value))
484 $ret.= "='".$this->relationship_role_column_value."'";
496 public function relationship_exists($lhs, $rhs)
498 $query = "SELECT id FROM {$this->getRelationshipTable()} WHERE {$this->join_key_lhs} = '{$lhs->id}' AND {$this->join_key_rhs} = '{$rhs->id}'";
500 //Roles can allow for multiple links between two records with different roles
501 $query .= $this->getRoleWhere() . " and deleted = 0";
503 return $GLOBALS['db']->getOne($query);
507 * @return Array - set of fields that uniquely identify an entry in this relationship
509 protected function getAlternateKeyFields()
511 $fields = array($this->join_key_lhs, $this->join_key_rhs);
513 //Roles can allow for multiple links between two records with different roles
514 if (!empty($this->def['relationship_role_column']) && !$this->ignore_role_filter)
516 $fields[] = $this->relationship_role_column;
522 public function getRelationshipTable()
524 if (!empty($this->def['table']))
525 return $this->def['table'];
526 else if(!empty($this->def['join_table']))
527 return $this->def['join_table'];
532 public function getFields()
534 if (!empty($this->def['fields']))
535 return $this->def['fields'];
537 "id" => array('name' => 'id'),
538 'date_modified' => array('name' => 'date_modified'),
539 'modified_user_id' => array('name' => 'modified_user_id'),
540 'created_by' => array('name' => 'created_by'),
541 $this->def['join_key_lhs'] => array('name' => $this->def['join_key_lhs']),
542 $this->def['join_key_rhs'] => array('name' => $this->def['join_key_rhs'])
544 if (!empty($this->def['relationship_role_column']))
546 $fields[$this->def['relationship_role_column']] = array("name" => $this->def['relationship_role_column']);
548 $fields['deleted'] = array('name' => 'deleted');