]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - json_server.php
Release 6.4.0
[Github/sugarcrm.git] / json_server.php
1 <?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37
38 require_once('soap/SoapHelperFunctions.php');
39 $GLOBALS['log']->debug("JSON_SERVER:");
40 $global_registry_var_name = 'GLOBAL_REGISTRY';
41
42 ///////////////////////////////////////////////////////////////////////////////
43 ////    SUPPORTED METHODS
44 /*
45  * ADD NEW METHODS TO THIS ARRAY:
46  * then create a function called "function json_$method($request_id, &$params)"
47  * where $method is the method name
48  */
49 $SUPPORTED_METHODS = array(
50         'retrieve',
51         'query',
52 );
53
54 /**
55  * Generic retrieve for getting data from a sugarbean
56  */
57 function json_retrieve($request_id, $params) {
58         global $current_user;
59         global $beanFiles,$beanList;
60     $json = getJSONobj();
61
62         $record = $params[0]['record'];
63
64         require_once($beanFiles[$beanList[$params[0]['module']]]);
65         $focus = new $beanList[$params[0]['module']];
66         $focus->retrieve($record);
67
68         // to get a simplified version of the sugarbean
69         $module_arr = populateBean($focus);
70
71         $response = array();
72         $response['id'] = $request_id;
73         $response['result'] = array("status"=>"success","record"=>$module_arr);
74         $json_response = $json->encode($response, true);
75         print $json_response;
76 }
77
78 function json_query($request_id, $params) {
79         global $response, $sugar_config;
80         global $beanFiles, $beanList;
81         $json = getJSONobj();
82
83         if($sugar_config['list_max_entries_per_page'] < 31)     // override query limits
84                 $sugar_config['list_max_entries_per_page'] = 31;
85
86         $args = $params[0];
87
88         //decode condition parameter values..
89         if(is_array($args['conditions'])) {
90                 foreach($args['conditions'] as $key=>$condition)        {
91                         if(!empty($condition['value'])) {
92                                 $where = $json->decode(utf8_encode($condition['value']));
93                                 // cn: bug 12693 - API change due to CSRF security changes.
94                                 $where = empty($where) ? $condition['value'] : $where;
95                                 $args['conditions'][$key]['value'] = $where;
96                         }
97                 }
98         }
99
100         $list_return = array();
101
102         if(! empty($args['module'])) {
103                 $args['modules'] = array($args['module']);
104         }
105
106         foreach($args['modules'] as $module) {
107                 require_once($beanFiles[$beanList[$module]]);
108                 $focus = new $beanList[$module];
109
110                 $query_orderby = '';
111                 if(!empty($args['order'])) {
112                         $query_orderby = preg_replace('/[^\w_.-]+/i', '', $args['order']['by']);
113                         if(!empty($args['order']['desc'])) {
114                             $query_orderby .= " DESC";
115                         } else {
116                             $query_orderby .= " ASC";
117                         }
118                 }
119
120                 $query_limit = '';
121                 if(!empty($args['limit'])) {
122                         $query_limit = (int)$args['limit'];
123                 }
124                 $query_where = construct_where($args, $focus->table_name,$module);
125                 $list_arr = array();
126                 if($focus->ACLAccess('ListView', true)) {
127                         $focus->ungreedy_count=false;
128                         $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
129                         $list_return = array_merge($list_return,$curlist['list']);
130                 }
131         }
132
133         $app_list_strings = null;
134
135         for($i = 0;$i < count($list_return);$i++) {
136                 if(isset($list_return[$i]->emailAddress) && is_object($list_return[$i]->emailAddress)) {
137                         $list_return[$i]->emailAddress->handleLegacyRetrieve($list_return[$i]);
138                 }
139
140                 $list_arr[$i]= array();
141                 $list_arr[$i]['fields']= array();
142                 $list_arr[$i]['module']= $list_return[$i]->object_name;
143
144                 foreach($args['field_list'] as $field) {
145                         // handle enums
146                         if(     (isset($list_return[$i]->field_name_map[$field]['type']) && $list_return[$i]->field_name_map[$field]['type'] == 'enum') ||
147                                 (isset($list_return[$i]->field_name_map[$field]['custom_type']) && $list_return[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
148
149                                 // get fields to match enum vals
150                                 if(empty($app_list_strings)) {
151                                         if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
152                                         else $current_language = $sugar_config['default_language'];
153                                         $app_list_strings = return_app_list_strings_language($current_language);
154                                 }
155
156                                 // match enum vals to text vals in language pack for return
157                                 if(!empty($app_list_strings[$list_return[$i]->field_name_map[$field]['options']])) {
158                                         $list_return[$i]->$field = $app_list_strings[$list_return[$i]->field_name_map[$field]['options']][$list_return[$i]->$field];
159                                 }
160                         }
161
162                         $list_arr[$i]['fields'][$field] = $list_return[$i]->$field;
163                 }
164         }
165
166
167         $response['id'] = $request_id;
168         $response['result'] = array("list"=>$list_arr);
169     $json_response = $json->encode($response, true);
170         echo $json_response;
171 }
172
173 ////    END SUPPORTED METHODS
174 ///////////////////////////////////////////////////////////////////////////////
175
176 // ONLY USED FOR MEETINGS
177 // HAS MEETING SPECIFIC CODE:
178 function populateBean(&$focus) {
179         $all_fields = $focus->column_fields;
180         // MEETING SPECIFIC
181         $all_fields = array_merge($all_fields,array('required','accept_status','name')); // need name field for contacts and users
182         //$all_fields = array_merge($focus->column_fields,$focus->additional_column_fields);
183
184         $module_arr = array();
185
186         $module_arr['module'] = $focus->object_name;
187
188         $module_arr['fields'] = array();
189
190         foreach($all_fields as $field)
191         {
192                 if(isset($focus->$field) && !is_object($focus->$field))
193                 {
194                         $focus->$field =        from_html($focus->$field);
195                         $focus->$field =        preg_replace("/\r\n/","<BR>",$focus->$field);
196                         $focus->$field =        preg_replace("/\n/","<BR>",$focus->$field);
197                         $module_arr['fields'][$field] = $focus->$field;
198                 }
199         }
200         $GLOBALS['log']->debug("JSON_SERVER:populate bean:");
201         return $module_arr;
202 }
203
204 ///////////////////////////////////////////////////////////////////////////////
205 ////    UTILS
206 function authenticate() {
207         global $sugar_config;
208
209         $user_unique_key =(isset($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : "";
210         $server_unique_key =(isset($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : "";
211
212         if($user_unique_key != $server_unique_key) {
213                 $GLOBALS['log']->debug("JSON_SERVER: user_unique_key:".$user_unique_key."!=".$server_unique_key);
214                 session_destroy();
215                 return null;
216         }
217
218         if(!isset($_SESSION['authenticated_user_id'])) {
219                 $GLOBALS['log']->debug("JSON_SERVER: authenticated_user_id NOT SET. DESTROY");
220                 session_destroy();
221                 return null;
222         }
223
224         $current_user = new User();
225
226         $result = $current_user->retrieve($_SESSION['authenticated_user_id']);
227         $GLOBALS['log']->debug("JSON_SERVER: retrieved user from SESSION");
228
229
230         if($result == null) {
231                 $GLOBALS['log']->debug("JSON_SERVER: could get a user from SESSION. DESTROY");
232                 session_destroy();
233                 return null;
234         }
235
236         return $result;
237 }
238
239 function construct_where(&$query_obj, $table='',$module=null) {
240         if(! empty($table)) {
241                 $table .= ".";
242         }
243         $cond_arr = array();
244
245         if(! is_array($query_obj['conditions'])) {
246                 $query_obj['conditions'] = array();
247         }
248
249         foreach($query_obj['conditions'] as $condition) {
250
251                 if ($condition['name']=='email1' or $condition['name']=='email2') {
252
253                         $email1_value=strtoupper($condition['value']);
254                         $email1_condition = " {$table}id in ( SELECT  er.bean_id AS id FROM email_addr_bean_rel er, " .
255                          "email_addresses ea WHERE ea.id = er.email_address_id " .
256                          "AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = '{$module}' AND email_address_caps LIKE '%{$email1_value}%' )";
257
258                  array_push($cond_arr,$email1_condition);
259                 }
260                 else {
261                         if($condition['op'] == 'contains') {
262                                 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '%".$GLOBALS['db']->quote($condition['value'])."%'";
263                         }
264                         if($condition['op'] == 'like_custom') {
265                                 $like = '';
266                                 if(!empty($condition['begin'])) $like .= $GLOBALS['db']->quote($condition['begin']);
267                                 $like .= $GLOBALS['db']->quote($condition['value']);
268                                 if(!empty($condition['end'])) $like .= $GLOBALS['db']->quote($condition['end']);
269                                 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '$like'";
270                         } else { // starts_with
271                                 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '".$GLOBALS['db']->quote($condition['value'])."%'";
272                         }
273                 }
274         }
275
276         if($table == 'users.') {
277                 $cond_arr[] = $table."status='Active'";
278         }
279
280         return implode(" {$query_obj['group']} ",$cond_arr);
281 }
282
283 ////    END UTILS
284 ///////////////////////////////////////////////////////////////////////////////
285
286
287 ///////////////////////////////////////////////////////////////////////////////
288 ////    JSON SERVER HANDLER LOGIC
289 //ignore notices
290 error_reporting(E_ALL & ~E_NOTICE);
291 ob_start();
292 insert_charset_header();
293 global $sugar_config;
294 if(!empty($sugar_config['session_dir'])) {
295         session_save_path($sugar_config['session_dir']);
296         $GLOBALS['log']->debug("JSON_SERVER:session_save_path:".$sugar_config['session_dir']);
297 }
298
299 session_start();
300 $GLOBALS['log']->debug("JSON_SERVER:session started");
301
302 $current_language = 'en_us'; // defaulting - will be set by user, then sys prefs
303
304 // create json parser
305 $json = getJSONobj();
306
307 // if the language is not set yet, then set it to the default language.
308 if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') {
309         $current_language = $_SESSION['authenticated_user_language'];
310 } else {
311         $current_language = $sugar_config['default_language'];
312 }
313
314 $locale = new Localization();
315
316 $GLOBALS['log']->debug("JSON_SERVER: current_language:".$current_language);
317
318 // if this is a get, than this is spitting out static javascript as if it was a file
319 // wp: DO NOT USE THIS. Include the javascript inline using include/json_config.php
320 // using <script src=json_server.php></script> does not cache properly on some browsers
321 // resulting in 2 or more server hits per page load. Very bad for SSL.
322 if(strtolower($_SERVER['REQUEST_METHOD'])== 'get') {
323         echo "alert('DEPRECATED API\nPlease report as a bug.');";
324 } else {
325         // else act as a JSON-RPC server for SugarCRM
326         // create result array
327         $response = array();
328         $response['result'] = null;
329         $response['id'] = "-1";
330
331         // authenticate user
332         $current_user = authenticate();
333
334         if(empty($current_user)) {
335                 $response['error'] = array("error_msg"=>"not logged in");
336                 print $json->encode($response, true);
337                 print "not logged in";
338         }
339
340         // extract request
341         if(isset($GLOBALS['HTTP_RAW_POST_DATA']))
342                 $request = $json->decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
343         else
344                 $request = $json->decode(file_get_contents("php://input"), true);
345
346
347         if(!is_array($request)) {
348                 $response['error'] = array("error_msg"=>"malformed request");
349                 print $json->encode($response, true);
350         }
351
352         // make sure required RPC fields are set
353         if(empty($request['method']) || empty($request['id'])) {
354                 $response['error'] = array("error_msg"=>"missing parameters");
355                 print $json->encode($response, true);
356         }
357
358         $response['id'] = $request['id'];
359
360         if(in_array($request['method'], $SUPPORTED_METHODS)) {
361                 call_user_func('json_'.$request['method'],$request['id'],$request['params']);
362         } else {
363                 $response['error'] = array("error_msg"=>"method:".$request["method"]." not supported");
364                 print $json->encode($response, true);
365         }
366 }
367
368 ob_end_flush();
369 sugar_cleanup();
370 exit();