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