]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - data/Relationships/One2MBeanRelationship.php
Release 6.5.16
[Github/sugarcrm.git] / data / Relationships / One2MBeanRelationship.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-2013 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/One2MRelationship.php");
40
41 /**
42  * Represents a one to many relationship that is table based.
43  * @api
44  */
45 class One2MBeanRelationship extends One2MRelationship
46 {
47     //Type is read in sugarbean to determine query construction
48     var $type = "one-to-many";
49
50     public function __construct($def)
51     {
52         parent::__construct($def);
53     }
54
55     /**
56      * @param  $lhs SugarBean left side bean to add to the relationship.
57      * @param  $rhs SugarBean right side bean to add to the relationship.
58      * @param  $additionalFields key=>value pairs of fields to save on the relationship
59      * @return boolean true if successful
60      */
61     public function add($lhs, $rhs, $additionalFields = array())
62     {
63         // test to see if the relationship exist if the relationship between the two beans
64         // exist then we just fail out with false as we don't want to re-trigger this
65         // the save and such as it causes problems with the related() in sugarlogic
66         if($this->relationship_exists($lhs, $rhs) && !empty($GLOBALS['resavingRelatedBeans'])) return false;
67
68         $lhsLinkName = $this->lhsLink;
69         $rhsLinkName = $this->rhsLink;
70
71         //Since this is bean based, we know updating the RHS's field will overwrite any old value,
72         //But we need to use delete to make sure custom logic is called correctly
73         if ($rhs->load_relationship($rhsLinkName))
74         {
75             $oldLink = $rhs->$rhsLinkName;
76             $prevRelated = $oldLink->getBeans(null);
77             foreach($prevRelated as $oldLHS)
78             {
79                 if ($oldLHS->id != $lhs->id)
80                     $this->remove($oldLHS, $rhs, false);
81             }
82         }
83
84         //Make sure we load the current relationship state to the LHS link
85         if ((isset($lhs->$lhsLinkName) && is_a($lhs->$lhsLinkName, "Link2")) || $lhs->load_relationship($lhsLinkName)) {
86             $lhs->$lhsLinkName->load();
87         }
88
89         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
90         {
91             $this->callBeforeAdd($lhs, $rhs);
92             $this->callBeforeAdd($rhs, $lhs);
93         }
94
95         $this->updateFields($lhs, $rhs, $additionalFields);
96
97         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
98         {
99             //Need to call save to update the bean as the relationship is saved on the main table
100             //We don't want to create a save loop though, so make sure we aren't already in the middle of saving this bean
101             SugarRelationship::addToResaveList($rhs);
102
103             $this->updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName);
104
105             $this->callAfterAdd($lhs, $rhs);
106             $this->callAfterAdd($rhs, $lhs);
107         }
108
109         //One2MBean relationships require that the RHS bean be saved or else the relationship will not be saved.
110         //If we aren't already in a relationship save, intitiate a save now.
111         if (empty($GLOBALS['resavingRelatedBeans']))
112             SugarRelationship::resaveRelatedBeans();
113         
114         return true;
115     }
116
117     protected function updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName)
118     {
119         if (isset($lhs->$lhsLinkName))
120             $lhs->$lhsLinkName->addBean($rhs);
121         //RHS only has one bean ever, so we don't need to preload the relationship
122         if (isset($rhs->$rhsLinkName))
123             $rhs->$rhsLinkName->beans = array($lhs->id => $lhs);
124     }
125
126     protected function updateFields($lhs, $rhs, $additionalFields)
127     {
128         //Now update the RHS bean's ID field
129         $rhsID = $this->def['rhs_key'];
130         $rhs->$rhsID = $lhs->id;
131         foreach($additionalFields as $field => $val)
132         {
133             $rhs->$field = $val;
134         }
135         //Update role fields
136         if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
137         {
138             $roleField = $this->def["relationship_role_column"];
139             $rhs->$roleField = $this->def["relationship_role_column_value"];
140         }
141     }
142
143     public function remove($lhs, $rhs, $save = true)
144     {
145         $rhsID = $this->def['rhs_key'];
146
147         //If this relationship has already been removed, we can just return
148         if ($rhs->$rhsID != $lhs->id)
149             return false;
150
151         $rhs->$rhsID = '';
152
153         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
154         {
155             $this->callBeforeDelete($lhs, $rhs);
156             $this->callBeforeDelete($rhs, $lhs);
157         }
158
159         if ($save && !$rhs->deleted)
160         {
161             $rhs->in_relationship_update = TRUE;
162             $rhs->save();
163         }
164
165         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
166         {
167             $this->callAfterDelete($lhs, $rhs);
168             $this->callAfterDelete($rhs, $lhs);
169         }
170
171         return true;
172     }
173
174     /**
175      * @param  $link Link2 loads the relationship for this link.
176      * @return void
177      */
178     public function load($link, $params = array())
179     {
180         $relatedModule = $link->getSide() == REL_LHS ? $this->def['rhs_module'] : $this->def['lhs_module'];
181         $rows = array();
182         //The related bean ID is stored on the RHS table.
183         //If the link is RHS, just grab it from the focus.
184         if ($link->getSide() == REL_RHS)
185         {
186             $rhsID = $this->def['rhs_key'];
187             $id = $link->getFocus()->$rhsID;
188             if (!empty($id))
189             {
190                 $rows[$id] = array('id' => $id);
191             }
192         }
193         else //If the link is LHS, we need to query to get the full list and load all the beans.
194         {
195             $db = DBManagerFactory::getInstance();
196             $query = $this->getQuery($link, $params);
197             if (empty($query))
198             {
199                 $GLOBALS['log']->fatal("query for {$this->name} was empty when loading from   {$this->lhsLink}\n");
200                 return array("rows" => array());
201             }
202             $result = $db->query($query);
203             while ($row = $db->fetchByAssoc($result, FALSE))
204             {
205                 $id = $row['id'];
206                 $rows[$id] = $row;
207             }
208         }
209
210         return array("rows" => $rows);
211     }
212
213     public function getQuery($link, $params = array())
214     {
215         //There was an old signature with $return_as_array as the second parameter. We should respect this if $params is true
216         if ($params === true){
217             $params = array("return_as_array" => true);
218         }
219
220         if ($link->getSide() == REL_RHS) {
221             return false;
222         }
223         else
224         {
225             $lhsKey = $this->def['lhs_key'];
226             $rhsTable = $this->def['rhs_table'];
227             $rhsTableKey = "{$rhsTable}.{$this->def['rhs_key']}";
228             $deleted = !empty($params['deleted']) ? 1 : 0;
229             $where = "WHERE $rhsTableKey = '{$link->getFocus()->$lhsKey}' AND {$rhsTable}.deleted=$deleted";
230
231             //Check for role column
232             if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
233             {
234                 $roleField = $this->def["relationship_role_column"];
235                 $roleValue = $this->def["relationship_role_column_value"];
236                 $where .= " AND $rhsTable.$roleField = '$roleValue'";
237             }
238
239             //Add any optional where clause
240             if (!empty($params['where'])){
241                 $add_where = is_string($params['where']) ? $params['where'] : "$rhsTable." . $this->getOptionalWhereClause($params['where']);
242                 if (!empty($add_where))
243                     $where .= " AND $add_where";
244             }
245
246             $from = $this->def['rhs_table'];
247
248             if (empty($params['return_as_array'])) {
249                 //Limit is not compatible with return_as_array
250                 $query = "SELECT id FROM $from $where";
251                 if (!empty($params['limit']) && $params['limit'] > 0) {
252                     $offset = isset($params['offset']) ? $params['offset'] : 0;
253                     $query = DBManagerFactory::getInstance()->limitQuery($query, $offset, $params['limit'], false, "", false);
254                 }
255                 return $query;
256             }
257             else
258             {
259                 return array(
260                     'select' => "SELECT {$this->def['rhs_table']}.id",
261                     'from' => "FROM {$this->def['rhs_table']}",
262                     'where' => $where,
263                 );
264             }
265         }
266     }
267
268     public function getJoin($link, $params = array(), $return_array = false)
269     {
270         $linkIsLHS = $link->getSide() == REL_LHS;
271         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
272         if (!$linkIsLHS)
273             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
274         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
275         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
276         $targetTableWithAlias = $targetTable;
277         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
278         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
279         $join = '';
280
281         //Set up any table aliases required
282         if ( ! empty($params['join_table_alias']))
283         {
284             $targetTableWithAlias = $targetTable. " ".$params['join_table_alias'];
285             $targetTable = $params['join_table_alias'];
286         }
287
288         //First join the relationship table
289         $join .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
290         //Next add any role filters
291                . $this->getRoleWhere(($linkIsLHS) ? $targetTable : $startingTable) . "\n";
292
293         if($return_array){
294             return array(
295                 'join' => $join,
296                 'type' => $this->type,
297                 'rel_key' => $targetKey,
298                 'join_tables' => array($targetTable),
299                 'where' => "",
300                 'select' => "$targetTable.id",
301             );
302         }
303         return $join;
304     }
305
306     public function getSubpanelQuery($link, $params = array(), $return_array = false)
307     {
308
309         $linkIsLHS = $link->getSide() == REL_RHS;
310         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
311         if (!$linkIsLHS)
312             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
313         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
314         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
315         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
316         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
317         $query = '';
318
319         $alias = empty($params['join_table_alias']) ? "{$link->name}_rel": $params['join_table_alias'];
320         $alias = $GLOBALS['db']->getValidDBName($alias, false, 'alias');
321
322         $tableInRoleFilter = "";
323         if (
324             (
325                 $startingTable == "meetings"
326                 || $startingTable == "notes"
327                 || $startingTable == "tasks"
328                 || $startingTable == "calls"
329                 || $startingTable == "emails"
330             )
331             &&
332             (
333                 $targetTable == "meetings"
334                 || $targetTable == "notes"
335                 || $targetTable == "tasks"
336                 || $targetTable == "calls"
337             )
338             && substr($alias, 0, 12 + strlen($targetTable)) == $targetTable . "_activities_"
339         )
340         {
341             $tableInRoleFilter = $linkIsLHS ? $alias : $startingTable;
342         }
343         
344         //Set up any table aliases required
345         $targetTableWithAlias = "$targetTable $alias";
346         $targetTable = $alias;
347
348         $query .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
349         //Next add any role filters
350                . $this->getRoleWhere($tableInRoleFilter) . "\n";
351
352         if (!empty($params['return_as_array'])) {
353             $return_array = true;
354         }
355
356         if($return_array){
357             return array(
358                 'join' => $query,
359                 'type' => $this->type,
360                 'rel_key' => $targetKey,
361                 'join_tables' => array($targetTable),
362                 'where' => "WHERE $startingTable.$startingKey='{$link->focus->id}'",
363                 'select' => " ",
364             );
365         }
366         return $query;
367
368     }
369
370     /**
371      * Check to see if the relationship already exist.
372      *
373      * If it does return true otherwise return false
374      *
375      * @param SugarBean $lhs        Left hand side of the relationship
376      * @param SugarBean $rhs        Right hand side of the relationship
377      * @return boolean
378      */
379     public function relationship_exists($lhs, $rhs)
380     {
381         // we need the key that is stored on the rhs to compare tok
382         $lhsIDName = $this->def['rhs_key'];
383
384         return (isset($rhs->fetched_row[$lhsIDName]) && $rhs->$lhsIDName == $rhs->fetched_row[$lhsIDName] && $rhs->$lhsIDName == $lhs->id);
385     }
386
387     public function getRelationshipTable()
388     {
389         if (isset($this->def['table']))
390             return $this->def['table'];
391         else
392             return $this->def['rhs_table'];
393     }
394 }