]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - data/Relationships/One2MBeanRelationship.php
Release 6.3.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-2011 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  */
44 class One2MBeanRelationship extends One2MRelationship
45 {
46     //Type is read in sugarbean to determine query construction
47     var $type = "one-to-many";
48
49     public function __construct($def)
50     {
51         parent::__construct($def);
52     }
53
54     /**
55      * @param  $lhs SugarBean left side bean to add to the relationship.
56      * @param  $rhs SugarBean right side bean to add to the relationship.
57      * @param  $additionalFields key=>value pairs of fields to save on the relationship
58      * @return boolean true if successful
59      */
60     public function add($lhs, $rhs, $additionalFields = array())
61     {
62         $lhsLinkName = $this->lhsLink;
63         $rhsLinkName = $this->rhsLink;
64
65         //Since this is bean based, we know updating the RHS's field will overwrite any old value,
66         //But we need to use delete to make sure custom logic is called correctly
67         if ($rhs->load_relationship($rhsLinkName))
68         {
69             $oldLink = $rhs->$rhsLinkName;
70             $prevRelated = $oldLink->getBeans(null);
71             foreach($prevRelated as $oldLHS)
72             {
73                 $this->remove($oldLHS, $rhs, false);
74             }
75         }
76
77         //Make sure we load the current relationship state to the LHS link
78         if ((isset($lhs->$lhsLinkName) && is_a($lhs->$lhsLinkName, "Link2")) || $lhs->load_relationship($lhsLinkName)) {
79             $lhs->$lhsLinkName->load();
80         }
81
82         $this->updateFields($lhs, $rhs, $additionalFields);
83
84
85         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
86         {
87             //Need to call save to update the bean as the relationship is saved on the main table
88             //We don't want to create a save loop though, so make sure we aren't already in the middle of saving this bean
89             SugarRelationship::addToResaveList($rhs);
90
91             $this->updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName);
92
93             $this->callAfterAdd($lhs, $rhs);
94             $this->callAfterAdd($rhs, $lhs);
95         }
96     }
97
98     protected function updateLinks($lhs, $lhsLinkName, $rhs, $rhsLinkName)
99     {
100         if (isset($lhs->$lhsLinkName))
101             $lhs->$lhsLinkName->addBean($rhs);
102         //RHS only has one bean ever, so we don't need to preload the relationship
103         if (isset($rhs->$rhsLinkName))
104             $rhs->$rhsLinkName->beans = array($lhs->id => $lhs);
105     }
106
107     protected function updateFields($lhs, $rhs, $additionalFields)
108     {
109         //Now update the RHS bean's ID field
110         $rhsID = $this->def['rhs_key'];
111         $rhs->$rhsID = $lhs->id;
112         foreach($additionalFields as $field => $val)
113         {
114             $rhs->$field = $val;
115         }
116         //Update role fields
117         if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
118         {
119             $roleField = $this->def["relationship_role_column"];
120             $rhs->$roleField = $this->def["relationship_role_column_value"];
121         }
122     }
123
124     public function remove($lhs, $rhs, $save = true)
125     {
126         $rhsID = $this->def['rhs_key'];
127
128         //If this relationship has already been removed, we can just return
129         if ($rhs->$rhsID != $lhs->id)
130             return;
131
132         $rhs->$rhsID = '';
133
134         if ($save && !$rhs->deleted)
135         {
136             $rhs->in_relationship_update = TRUE;
137             $rhs->save();
138         }
139         
140         if (empty($_SESSION['disable_workflow']) || $_SESSION['disable_workflow'] != "Yes")
141         {
142             $this->callAfterDelete($lhs, $rhs);
143             $this->callAfterDelete($rhs, $lhs);
144         }
145     }
146
147     /**
148      * @param  $link Link2 loads the relationship for this link.
149      * @return void
150      */
151     public function load($link)
152     {
153         $relatedModule = $link->getSide() == REL_LHS ? $this->def['rhs_module'] : $this->def['lhs_module'];
154         $rows = array();
155         //The related bean ID is stored on the RHS table.
156         //If the link is RHS, just grab it from the focus.
157         if ($link->getSide() == REL_RHS)
158         {
159             $rhsID = $this->def['rhs_key'];
160             $id = $link->getFocus()->$rhsID;
161             if (!empty($id))
162             {
163                 $rows[$id] = array('id' => $id);
164             }
165         }
166         else //If the link is LHS, we need to query to get the full list and load all the beans.
167         {
168             $db = DBManagerFactory::getInstance();
169             $query = $this->getQuery($link);
170             if (empty($query))
171             {
172                 echo ("query for {$this->name} was empty when loading from {$this->lhsLink}\n");
173             }
174             $result = $db->query($query);
175             while ($row = $db->fetchByAssoc($result))
176             {
177                 $id = $row['id'];
178                 $rows[$id] = $row;
179             }
180         }
181
182         return array("rows" => $rows);
183     }
184
185     public function getQuery($link, $return_as_array = false)
186     {
187
188         if ($link->getSide() == REL_RHS) {
189             return false;
190         }
191         else
192         {
193             $lhsKey = $this->def['lhs_key'];
194             $rhsTable = $this->def['rhs_table'];
195             $rhsTableKey = "{$rhsTable}.{$this->def['rhs_key']}";
196             $where = "WHERE $rhsTableKey = '{$link->getFocus()->$lhsKey}' AND {$rhsTable}.deleted=0";
197             //Check for role column
198             if(!empty($this->def["relationship_role_column"]) && !empty($this->def["relationship_role_column_value"]))
199             {
200                 $roleField = $this->def["relationship_role_column"];
201                 $roleValue = $this->def["relationship_role_column_value"];
202                 $where .= " AND $rhsTable.$roleField = '$roleValue'";
203             }
204             if (!$return_as_array) {
205                 return "SELECT id FROM {$this->def['rhs_table']} $where";
206             }
207             else
208             {
209                 return array(
210                     'select' => "SELECT id",
211                     'from' => "FROM {$this->def['rhs_table']}",
212                     'where' => $where,
213                 );
214             }
215         }
216     }
217
218     public function getJoin($link, $params = array(), $return_array = false)
219     {
220         $linkIsLHS = $link->getSide() == REL_LHS;
221         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
222         if (!$linkIsLHS)
223             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
224         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
225         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
226         $targetTableWithAlias = $targetTable;
227         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
228         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
229         $join = '';
230
231         //Set up any table aliases required
232         if ( ! empty($params['join_table_alias']))
233         {
234             $targetTableWithAlias = $targetTable. " ".$params['join_table_alias'];
235             $targetTable = $params['join_table_alias'];
236         }
237
238         //First join the relationship table
239         $join .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
240         //Next add any role filters
241                . $this->getRoleWhere(($linkIsLHS) ? $targetTable : $startingTable) . "\n"; 
242
243         if($return_array){
244             return array(
245                 'join' => $join,
246                 'type' => $this->type,
247                 'rel_key' => $targetKey,
248                 'join_tables' => array($targetTable),
249                 'where' => "",
250                 'select' => "$targetTable.id",
251             );
252         }
253         return $join;
254     }
255
256     public function getSubpanelQuery($link, $params = array(), $return_array = false)
257     {
258
259         $linkIsLHS = $link->getSide() == REL_RHS;
260         $startingTable = (empty($params['left_join_table_alias']) ? $this->def['lhs_table'] : $params['left_join_table_alias']);
261         if (!$linkIsLHS)
262             $startingTable = (empty($params['right_join_table_alias']) ? $this->def['rhs_table'] : $params['right_join_table_alias']);
263         $startingKey = $linkIsLHS ? $this->def['lhs_key'] : $this->def['rhs_key'];
264         $targetTable = $linkIsLHS ? $this->def['rhs_table'] : $this->def['lhs_table'];
265         $targetKey = $linkIsLHS ? $this->def['rhs_key'] : $this->def['lhs_key'];
266         $join_type= isset($params['join_type']) ? $params['join_type'] : ' INNER JOIN ';
267         $query = '';
268
269         $alias = empty($params['join_table_alias']) ? "{$link->name}_rel": $params['join_table_alias'];
270         $alias = $GLOBALS['db']->getHelper()->getValidDBName($alias, 'alias');
271
272         //Set up any table aliases required
273         $targetTableWithAlias = "$targetTable $alias";
274         $targetTable = $alias;
275
276         $query .= "$join_type $targetTableWithAlias ON $startingTable.$startingKey=$targetTable.$targetKey AND $targetTable.deleted=0\n"
277         //Next add any role filters
278                . $this->getRoleWhere() . "\n";
279
280         if($return_array){
281             return array(
282                 'join' => $query,
283                 'type' => $this->type,
284                 'rel_key' => $targetKey,
285                 'join_tables' => array($targetTable),
286                 'where' => "WHERE $startingTable.$startingKey='{$link->focus->id}'",
287                 'select' => " ",
288             );
289         }
290         return $query;
291
292     }
293
294     /**
295      * @param  $lhs
296      * @param  $rhs
297      * @return bool
298      */
299     public function relationship_exists($lhs, $rhs)
300     {
301
302         return false;
303     }
304
305     public function getRelationshipTable()
306     {
307         if (isset($this->def['table']))
308             return $this->def['table'];
309         else
310             return $this->def['rhs_table'];
311     }
312 }