]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - data/Relationships/One2MBeanRelationship.php
Release 6.4.1
[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)) 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         $this->updateFields($lhs, $rhs, $additionalFields);
89
90
91         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
92         {
93             //Need to call save to update the bean as the relationship is saved on the main table
94             //We don't want to create a save loop though, so make sure we aren't already in the middle of saving this bean
95             SugarRelationship::addToResaveList($rhs);
96
97             $this->updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName);
98
99             $this->callAfterAdd($lhs, $rhs);
100             $this->callAfterAdd($rhs, $lhs);
101         }
102     }
103
104     protected function updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName)
105     {
106         if (isset($lhs->$lhsLinkName))
107             $lhs->$lhsLinkName->addBean($rhs);
108         //RHS only has one bean ever, so we don't need to preload the relationship
109         if (isset($rhs->$rhsLinkName))
110             $rhs->$rhsLinkName->beans = array($lhs->id => $lhs);
111     }
112
113     protected function updateFields($lhs, $rhs, $additionalFields)
114     {
115         //Now update the RHS bean's ID field
116         $rhsID = $this->def['rhs_key'];
117         $rhs->$rhsID = $lhs->id;
118         foreach($additionalFields as $field => $val)
119         {
120             $rhs->$field = $val;
121         }
122         //Update role fields
123         if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
124         {
125             $roleField = $this->def["relationship_role_column"];
126             $rhs->$roleField = $this->def["relationship_role_column_value"];
127         }
128     }
129
130     public function remove($lhs, $rhs, $save = true)
131     {
132         $rhsID = $this->def['rhs_key'];
133
134         //If this relationship has already been removed, we can just return
135         if ($rhs->$rhsID != $lhs->id)
136             return;
137
138         $rhs->$rhsID = '';
139
140         if ($save && !$rhs->deleted)
141         {
142             $rhs->in_relationship_update = TRUE;
143             $rhs->save();
144         }
145
146         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
147         {
148             $this->callAfterDelete($lhs, $rhs);
149             $this->callAfterDelete($rhs, $lhs);
150         }
151     }
152
153     /**
154      * @param  $link Link2 loads the relationship for this link.
155      * @return void
156      */
157     public function load($link)
158     {
159         $relatedModule = $link->getSide() == REL_LHS ? $this->def['rhs_module'] : $this->def['lhs_module'];
160         $rows = array();
161         //The related bean ID is stored on the RHS table.
162         //If the link is RHS, just grab it from the focus.
163         if ($link->getSide() == REL_RHS)
164         {
165             $rhsID = $this->def['rhs_key'];
166             $id = $link->getFocus()->$rhsID;
167             if (!empty($id))
168             {
169                 $rows[$id] = array('id' => $id);
170             }
171         }
172         else //If the link is LHS, we need to query to get the full list and load all the beans.
173         {
174             $db = DBManagerFactory::getInstance();
175             $query = $this->getQuery($link);
176             if (empty($query))
177             {
178                 echo ("query for {$this->name} was empty when loading from {$this->lhsLink}\n");
179             }
180             $result = $db->query($query);
181             while ($row = $db->fetchByAssoc($result))
182             {
183                 $id = $row['id'];
184                 $rows[$id] = $row;
185             }
186         }
187
188         return array("rows" => $rows);
189     }
190
191     public function getQuery($link, $return_as_array = false)
192     {
193
194         if ($link->getSide() == REL_RHS) {
195             return false;
196         }
197         else
198         {
199             $lhsKey = $this->def['lhs_key'];
200             $rhsTable = $this->def['rhs_table'];
201             $rhsTableKey = "{$rhsTable}.{$this->def['rhs_key']}";
202             $where = "WHERE $rhsTableKey = '{$link->getFocus()->$lhsKey}' AND {$rhsTable}.deleted=0";
203             //Check for role column
204             if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
205             {
206                 $roleField = $this->def["relationship_role_column"];
207                 $roleValue = $this->def["relationship_role_column_value"];
208                 $where .= " AND $rhsTable.$roleField = '$roleValue'";
209             }
210             if (!$return_as_array) {
211                 return "SELECT id FROM {$this->def['rhs_table']} $where";
212             }
213             else
214             {
215                 return array(
216                     'select' => "SELECT {$this->def['rhs_table']}.id",
217                     'from' => "FROM {$this->def['rhs_table']}",
218                     'where' => $where,
219                 );
220             }
221         }
222     }
223
224     public function getJoin($link, $params = array(), $return_array = false)
225     {
226         $linkIsLHS = $link->getSide() == REL_LHS;
227         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
228         if (!$linkIsLHS)
229             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
230         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
231         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
232         $targetTableWithAlias = $targetTable;
233         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
234         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
235         $join = '';
236
237         //Set up any table aliases required
238         if ( ! empty($params['join_table_alias']))
239         {
240             $targetTableWithAlias = $targetTable. " ".$params['join_table_alias'];
241             $targetTable = $params['join_table_alias'];
242         }
243
244         //First join the relationship table
245         $join .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
246         //Next add any role filters
247                . $this->getRoleWhere(($linkIsLHS) ? $targetTable : $startingTable) . "\n";
248
249         if($return_array){
250             return array(
251                 'join' => $join,
252                 'type' => $this->type,
253                 'rel_key' => $targetKey,
254                 'join_tables' => array($targetTable),
255                 'where' => "",
256                 'select' => "$targetTable.id",
257             );
258         }
259         return $join;
260     }
261
262     public function getSubpanelQuery($link, $params = array(), $return_array = false)
263     {
264
265         $linkIsLHS = $link->getSide() == REL_RHS;
266         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
267         if (!$linkIsLHS)
268             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
269         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
270         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
271         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
272         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
273         $query = '';
274
275         $alias = empty($params['join_table_alias']) ? "{$link->name}_rel": $params['join_table_alias'];
276         $alias = $GLOBALS['db']->getValidDBName($alias, false, 'alias');
277
278         //Set up any table aliases required
279         $targetTableWithAlias = "$targetTable $alias";
280         $targetTable = $alias;
281
282         $query .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
283         //Next add any role filters
284                . $this->getRoleWhere() . "\n";
285
286         if($return_array){
287             return array(
288                 'join' => $query,
289                 'type' => $this->type,
290                 'rel_key' => $targetKey,
291                 'join_tables' => array($targetTable),
292                 'where' => "WHERE $startingTable.$startingKey='{$link->focus->id}'",
293                 'select' => " ",
294             );
295         }
296         return $query;
297
298     }
299
300     /**
301      * Check to see if the relationship already exist.
302      *
303      * If it does return true otherwise return false
304      *
305      * @param SugarBean $lhs        Left hand side of the relationship
306      * @param SugarBean $rhs        Right hand side of the relationship
307      * @return boolean
308      */
309     public function relationship_exists($lhs, $rhs)
310     {
311         // we need the key that is stored on the rhs to compare tok
312         $lhsIDName = $this->def['rhs_key'];
313
314         return (isset($rhs->fetched_row[$lhsIDName]) && $rhs->$lhsIDName == $rhs->fetched_row[$lhsIDName] && $rhs->$lhsIDName == $lhs->id);
315     }
316
317     public function getRelationshipTable()
318     {
319         if (isset($this->def['table']))
320             return $this->def['table'];
321         else
322             return $this->def['rhs_table'];
323     }
324 }