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