1 <?php if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
2 /*********************************************************************************
3 * SugarCRM is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 require_once('soap/SoapHelperFunctions.php');
39 $GLOBALS['log']->debug("JSON_SERVER:");
40 $global_registry_var_name = 'GLOBAL_REGISTRY';
42 ///////////////////////////////////////////////////////////////////////////////
43 //// SUPPORTED METHODS
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
49 $SUPPORTED_METHODS = array(
54 'get_objects_from_module',
60 * Generic retrieve for getting data from a sugarbean
62 function json_retrieve($request_id, $params) {
64 global $beanFiles,$beanList;
67 $record = $params[0]['record'];
69 require_once($beanFiles[$beanList[$params[0]['module']]]);
70 $focus = new $beanList[$params[0]['module']];
71 $focus->retrieve($record);
73 // to get a simplified version of the sugarbean
74 $module_arr = populateBean($focus);
77 $response['id'] = $request_id;
78 $response['result'] = array("status"=>"success","record"=>$module_arr);
79 $json_response = $json->encode($response, true);
83 function json_query($request_id, $params) {
84 global $response, $sugar_config;
85 global $beanFiles, $beanList;
88 if($sugar_config['list_max_entries_per_page'] < 31) // override query limits
89 $sugar_config['list_max_entries_per_page'] = 31;
93 //decode condition parameter values..
94 if(is_array($args['conditions'])) {
95 foreach($args['conditions'] as $key=>$condition) {
96 if(!empty($condition['value'])) {
97 $where = $json->decode(utf8_encode($condition['value']));
98 // cn: bug 12693 - API change due to CSRF security changes.
99 $where = empty($where) ? $condition['value'] : $where;
100 $args['conditions'][$key]['value'] = $where;
105 $list_return = array();
107 if(! empty($args['module'])) {
108 $args['modules'] = array($args['module']);
111 foreach($args['modules'] as $module) {
112 require_once($beanFiles[$beanList[$module]]);
113 $focus = new $beanList[$module];
116 if(!empty($args['order'])) {
117 $query_orderby = $args['order'];
120 if(!empty($args['limit'])) {
121 $query_limit = $args['limit'];
123 $query_where = construct_where($args, $focus->table_name,$module);
125 if($focus->ACLAccess('ListView', true)) {
126 $focus->ungreedy_count=false;
127 $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
128 $list_return = array_merge($list_return,$curlist['list']);
132 $app_list_strings = null;
134 for($i = 0;$i < count($list_return);$i++) {
135 if(isset($list_return[$i]->emailAddress) && is_object($list_return[$i]->emailAddress)) {
136 $list_return[$i]->emailAddress->handleLegacyRetrieve($list_return[$i]);
139 $list_arr[$i]= array();
140 $list_arr[$i]['fields']= array();
141 $list_arr[$i]['module']= $list_return[$i]->object_name;
143 foreach($args['field_list'] as $field) {
145 if( (isset($list_return[$i]->field_name_map[$field]['type']) && $list_return[$i]->field_name_map[$field]['type'] == 'enum') ||
146 (isset($list_return[$i]->field_name_map[$field]['custom_type']) && $list_return[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
148 // get fields to match enum vals
149 if(empty($app_list_strings)) {
150 if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
151 else $current_language = $sugar_config['default_language'];
152 $app_list_strings = return_app_list_strings_language($current_language);
155 // match enum vals to text vals in language pack for return
156 if(!empty($app_list_strings[$list_return[$i]->field_name_map[$field]['options']])) {
157 $list_return[$i]->$field = $app_list_strings[$list_return[$i]->field_name_map[$field]['options']][$list_return[$i]->$field];
161 $list_arr[$i]['fields'][$field] = $list_return[$i]->$field;
166 $response['id'] = $request_id;
167 $response['result'] = array("list"=>$list_arr);
168 $json_response = $json->encode($response, true);
173 function json_set_accept_status($request_id, $params) {
174 global $current_user;
175 global $beanFiles,$beanList;
176 $json = getJSONobj();
177 require_once($beanFiles[$beanList[$params[0]['module']]]);
179 $focus = new $beanList[$params[0]['module']];
180 $focus->id = $params[0]['record'];
182 $test = $focus->set_accept_status($current_user,$params[0]['accept_status']);
185 $response['id'] = $request_id;
186 $response['result'] = array("status"=>"success","record"=>$params[0]['record'],'accept_status'=>$params[0]['accept_status']);
187 $json_response = $json->encode($response, true);
188 print $json_response;
193 * retrieves Users matching passed criteria
195 function json_get_user_array($request_id, $params) {
196 $json = getJSONobj();
199 //decode condition parameter values..
200 if(is_array($args['conditions'])) {
201 foreach($args['conditions'] as $key=>$condition) {
202 if(!empty($condition['value'])) {
203 $args['conditions'][$key]['value']=$json->decode($condition['value']);
209 $response['id'] = $request_id;
210 $response['result'] = array();
211 $response['result']['list'] = array();
214 $user_array = getUserArrayFromFullName($args['conditions'][0]['value']);
216 $user_array = get_user_array(false, "Active", $focus->assigned_user_id, false, $args['conditions'][0]['value']);
219 foreach($user_array as $id=>$name) {
220 array_push($response['result']['list'], array('fields' => array('id' => $id, 'user_name' => $name), 'module' => 'Users'));
223 print $json->encode($response, true);
226 function json_get_objects_from_module($request_id, $params) {
227 global $beanList, $beanFiles, $current_user;
228 $json = getJSONobj();
230 $module_name = $params[0]['module'];
231 $offset = intval($params[0]['offset']);
232 $where = $params[0]['where'];
233 $max = $params[0]['max'];
234 $order_by = $params[0]['order_by'];
237 if($module_name == 'CampaignProspects'){
238 $module_name = 'Prospects';
242 $class_name = $beanList[$module_name];
243 require_once($beanFiles[$class_name]);
244 $seed = new $class_name();
248 if($offset == '' || $offset == -1){
257 $fields = array('id', 'first_name', 'last_name');
258 $response = $seed->retrieveTargetList($where, $fields, $offset,-1,$max,$deleted);
260 $response = $seed->get_list($order_by, $where, $offset,-1,$max,$deleted);
263 $list = $response['list'];
264 $row_count = $response['row_count'];
266 $output_list = array();
267 foreach($list as $value)
269 $output_list[] = get_return_value($value, $module_name);
272 $response['id'] = $request_id;
274 $response['result'] = array('result_count'=>$row_count,'entry_list'=>$output_list);
275 $json_response = $json->encode($response, true);
276 print $json_response;
282 function json_email($request_id, $params) {
283 global $response, $sugar_config;
284 global $beanFiles,$beanList;
285 $json = getJSONobj();
289 if($sugar_config['list_max_entries_per_page'] < 50) // override query limits
290 $sugar_config['list_max_entries_per_page'] = 50;
292 $list_return = array();
294 if(! empty($args['module'])) {
295 $args['modules'] = array($args['module']);
298 foreach($args['modules'] as $module) {
299 require_once($beanFiles[$beanList[$module]]);
300 $focus = new $beanList[$module];
303 if(!empty($args['order'])) {
304 $query_orderby = $args['order'];
307 if(!empty($args['limit'])) {
308 $query_limit = $args['limit'];
310 $query_where = construct_where($args,$focus->table_name);
313 $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
314 $list_return = array_merge($list_return,$curlist['list']);
317 for($i = 0;$i < count($list_return);$i++) {
318 $list_arr[$i]= array();
319 $list_arr[$i]['fields']= array();
320 $list_arr[$i]['module']= $list_return[$i]->object_name;
322 foreach($args['field_list'] as $field) {
323 $list_arr[$i]['fields'][$field] = $list_return[$i]->$field;
327 $response['id'] = $request_id;
328 $response['result'] = array("list"=>$list_arr);
329 $json_response = $json->encode($response, true);
334 function json_get_full_list($request_id, $params) {
337 $json = getJSONobj();
338 require_once($beanFiles[$beanList[$params[0]['module']]]);
340 $where = str_replace('\\','', rawurldecode($params[0]['where']));
341 $order = str_replace('\\','', rawurldecode($params[0]['order']));
342 $focus = new $beanList[$params[0]['module']];
344 $fullList = $focus->get_full_list($order, $where, '');
345 $all_fields = array_merge($focus->column_fields,$focus->additional_column_fields);
347 $js_fields_arr = array();
349 if(isset($fullList) && !empty($fullList)) { // json error if this isn't defensive
351 foreach($fullList as $note) {
352 $js_fields_arr[$i] = array();
354 foreach($all_fields as $field) {
355 if(isset($note->$field)) {
356 $note->$field = from_html($note->$field);
357 $note->$field = preg_replace('/\r\n/','<BR>',$note->$field);
358 $note->$field = preg_replace('/\n/','<BR>',$note->$field);
359 $js_fields_arr[$i][$field] = addslashes($note->$field);
366 $fin['id'] = $request_id;
367 $fin['result'] = $js_fields_arr;
368 $out = $json->encode($fin, true);
372 //// END SUPPORTED METHODS
373 ///////////////////////////////////////////////////////////////////////////////
385 // ONLY USED FOR MEETINGS
386 function meeting_retrieve($module,$record) {
388 global $beanFiles,$beanList;
389 //header('Content-type: text/xml');
390 require_once($beanFiles[$beanList[$module]]);
391 $focus = new $beanList[$module];
392 $json = getJSONobj();
394 if(empty($module) || empty($record))
396 $response['error'] = array("error_msg"=>"method: retrieve: missing module or record as parameters");
397 print $json->encode($response, true);
401 $focus->retrieve($record);
403 $GLOBALS['log']->debug("JSON_SERVER:retrieved meeting:");
405 $module_arr = populateBean($focus);
407 if($module == 'Meetings')
409 $users = $focus->get_meeting_users();
410 } else if($module == 'Calls')
412 $users = $focus->get_call_users();
415 $module_arr['users_arr'] = array();
417 foreach($users as $user)
419 array_push($module_arr['users_arr'], populateBean($user));
421 $module_arr['orig_users_arr_hash'] = array();
422 foreach($users as $user)
424 $module_arr['orig_users_arr_hash'][$user->id] = '1';
427 $module_arr['contacts_arr'] = array();
429 $focus->load_relationships('contacts');
430 $contacts=$focus->get_linked_beans('contacts','Contact');
431 foreach($contacts as $contact)
433 array_push($module_arr['users_arr'], populateBean($contact));
439 // HAS MEETING SPECIFIC CODE:
440 function populateBean(&$focus) {
441 $all_fields = $focus->column_fields;
443 $all_fields = array_merge($all_fields,array('required','accept_status','name')); // need name field for contacts and users
444 //$all_fields = array_merge($focus->column_fields,$focus->additional_column_fields);
446 $module_arr = array();
448 $module_arr['module'] = $focus->object_name;
450 $module_arr['fields'] = array();
452 foreach($all_fields as $field)
454 if(isset($focus->$field))
456 $focus->$field = from_html($focus->$field);
457 $focus->$field = preg_replace("/\r\n/","<BR>",$focus->$field);
458 $focus->$field = preg_replace("/\n/","<BR>",$focus->$field);
459 $module_arr['fields'][$field] = $focus->$field;
462 $GLOBALS['log']->debug("JSON_SERVER:populate bean:");
477 function getUserJSON() {
481 function getUserConfigJSON() {
482 require_once('include/TimeDate.php');
483 $timedate = TimeDate::getInstance();
484 global $current_user,$global_registry_var_name,$json,$sugar_config;
486 if(isset($_SESSION['authenticated_user_theme']) && $_SESSION['authenticated_user_theme'] != '')
488 $theme = $_SESSION['authenticated_user_theme'];
492 $theme = $sugar_config['default_theme'];
495 $user_arr['theme'] = $theme;
496 $user_arr['fields'] = array();
497 $user_arr['module'] = 'User';
498 $user_arr['fields']['id'] = $current_user->id;
499 $user_arr['fields']['user_name'] = $current_user->user_name;
500 $user_arr['fields']['first_name'] = $current_user->first_name;
501 $user_arr['fields']['last_name'] = $current_user->last_name;
502 $user_arr['fields']['email'] = $current_user->email1;
503 $user_arr['fields']['gmt_offset'] = $timedate->getUserUTCOffset();
504 $str = "\n".$global_registry_var_name.".current_user = ".$json->encode($user_arr, true).";\n";
514 ///////////////////////////////////////////////////////////////////////////////
516 function authenticate() {
517 global $sugar_config;
519 $user_unique_key =(isset($_SESSION['unique_key'])) ? $_SESSION['unique_key'] : "";
520 $server_unique_key =(isset($sugar_config['unique_key'])) ? $sugar_config['unique_key'] : "";
522 if($user_unique_key != $server_unique_key) {
523 $GLOBALS['log']->debug("JSON_SERVER: user_unique_key:".$user_unique_key."!=".$server_unique_key);
528 if(!isset($_SESSION['authenticated_user_id'])) {
529 $GLOBALS['log']->debug("JSON_SERVER: authenticated_user_id NOT SET. DESTROY");
534 $current_user = new User();
536 $result = $current_user->retrieve($_SESSION['authenticated_user_id']);
537 $GLOBALS['log']->debug("JSON_SERVER: retrieved user from SESSION");
540 if($result == null) {
541 $GLOBALS['log']->debug("JSON_SERVER: could get a user from SESSION. DESTROY");
549 function construct_where(&$query_obj, $table='',$module=null) {
550 if(! empty($table)) {
555 if(! is_array($query_obj['conditions'])) {
556 $query_obj['conditions'] = array();
559 foreach($query_obj['conditions'] as $condition) {
561 if ($condition['name']=='email1' or $condition['name']=='email2') {
563 $email1_value=strtoupper($condition['value']);
564 $email1_condition = " {$table}id in ( SELECT er.bean_id AS id FROM email_addr_bean_rel er, " .
565 "email_addresses ea WHERE ea.id = er.email_address_id " .
566 "AND ea.deleted = 0 AND er.deleted = 0 AND er.bean_module = '{$module}' AND email_address_caps LIKE '%{$email1_value}%' )";
568 array_push($cond_arr,$email1_condition);
571 if($condition['op'] == 'contains') {
572 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '%".$GLOBALS['db']->quote($condition['value'])."%'";
574 if($condition['op'] == 'like_custom') {
576 if(!empty($condition['begin'])) $like .= $GLOBALS['db']->quote($condition['begin']);
577 $like .= $GLOBALS['db']->quote($condition['value']);
578 if(!empty($condition['end'])) $like .= $GLOBALS['db']->quote($condition['end']);
579 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '$like'";
580 } else { // starts_with
581 $cond_arr[] = $GLOBALS['db']->quote($table.$condition['name'])." like '".$GLOBALS['db']->quote($condition['value'])."%'";
586 if($table == 'users.') {
587 $cond_arr[] = $table."status='Active'";
590 return implode(" {$query_obj['group']} ",$cond_arr);
593 function getAppMetaJSON() {
594 global $global_registry_var_name, $sugar_config;
595 $json = getJSONobj();
597 $str = "\nvar ".$global_registry_var_name." = new Object();\n";
598 $str .= "\n".$global_registry_var_name.".config = {\"site_url\":\"".getJavascriptSiteURL()."\"};\n";
600 $str .= $global_registry_var_name.".meta = new Object();\n";
601 $str .= $global_registry_var_name.".meta.modules = new Object();\n";
602 $modules_arr = array('Meetings','Calls');
603 $meta_modules = array();
605 global $beanFiles,$beanList;
606 //header('Content-type: text/xml');
607 foreach($modules_arr as $module) {
608 require_once($beanFiles[$beanList[$module]]);
609 $focus = new $beanList[$module];
610 $meta_modules[$module] = array();
611 $meta_modules[$module]['field_defs'] = $focus->field_defs;
614 $str .= $global_registry_var_name.".meta.modules.Meetings = ". $json->encode($meta_modules['Meetings'], true)."\n";
615 $str .= $global_registry_var_name.".meta.modules.Calls = ". $json->encode($meta_modules['Calls'], true)."\n";
619 function getFocusData() {
620 global $global_registry_var_name;
621 $json = getJSONobj();
623 if(empty($_REQUEST['module']) )
625 elseif(empty($_REQUEST['record'] ) )
626 return "\n".$global_registry_var_name.'["focus"] = {"module":"'.$_REQUEST['module'].'",users_arr:[],fields:{"id":"-1"}}'."\n";
628 $module_arr = meeting_retrieve($_REQUEST['module'], $_REQUEST['record']);
629 return "\n".$global_registry_var_name."['focus'] = ". $json->encode($module_arr, true).";\n";
632 function getStringsJSON() {
633 //set module and application string arrays based upon selected language
634 global $current_language;
635 global $global_registry_var_name;
636 $json = getJSONobj();
638 $currentModule = 'Calendar';
639 $mod_list_strings = return_mod_list_strings_language($current_language,$currentModule);
640 $str = "\n".$global_registry_var_name."['calendar_strings'] = {\"dom_cal_month_long\":". $json->encode($mod_list_strings['dom_cal_month_long']).",\"dom_cal_weekdays_long\":". $json->encode($mod_list_strings['dom_cal_weekdays_long'])."}\n";
642 if(empty($_REQUEST['module']))
643 $_REQUEST['module'] = 'Home';
645 $currentModule = $_REQUEST['module'];
646 $mod_strings = return_module_language($current_language,$currentModule);
647 return $str . "\n".$global_registry_var_name."['meeting_strings'] = ". $json->encode($mod_strings, true)."\n";
650 ///////////////////////////////////////////////////////////////////////////////
654 ///////////////////////////////////////////////////////////////////////////////
655 //// JSON SERVER HANDLER LOGIC
657 error_reporting(E_ALL ^ E_NOTICE);
659 insert_charset_header();
661 if(!empty($sugar_config['session_dir'])) {
662 session_save_path($sugar_config['session_dir']);
663 $GLOBALS['log']->debug("JSON_SERVER:session_save_path:".$sugar_config['session_dir']);
667 $GLOBALS['log']->debug("JSON_SERVER:session started");
669 $current_language = 'en_us'; // defaulting - will be set by user, then sys prefs
671 // create json parser
672 $json = getJSONobj();
674 // if the language is not set yet, then set it to the default language.
675 if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') {
676 $current_language = $_SESSION['authenticated_user_language'];
678 $current_language = $sugar_config['default_language'];
681 $locale = new Localization();
683 $GLOBALS['log']->debug("JSON_SERVER: current_language:".$current_language);
685 // if this is a get, than this is spitting out static javascript as if it was a file
686 // wp: DO NOT USE THIS. Include the javascript inline using include/json_config.php
687 // using <script src=json_server.php></script> does not cache properly on some browsers
688 // resulting in 2 or more server hits per page load. Very bad for SSL.
689 if(strtolower($_SERVER['REQUEST_METHOD'])== 'get') {
690 echo "alert('DEPRECATED API\nPlease report as a bug.');";
692 * Deprecated for security reasons.
697 $current_user = authenticate();
698 if(empty($current_user)) {
699 $GLOBALS['log']->debug("JSON_SERVER: current_user isn't set");
704 $str .= getAppMetaJSON();
705 $GLOBALS['log']->debug("JSON_SERVER:getAppMetaJSON");
707 if($_GET['module'] != '_configonly') {
708 $str .= getFocusData();
709 $GLOBALS['log']->debug("JSON_SERVER: getFocusData");
710 $str .= getStringsJSON();
711 $GLOBALS['log']->debug("JSON_SERVER:getStringsJSON");
714 $str .= getUserConfigJSON();
715 $GLOBALS['log']->debug("JSON_SERVER:getUserConfigJSON");
719 // else act as a JSON-RPC server for SugarCRM
720 // create result array
722 $response['result'] = null;
723 $response['id'] = "-1";
726 $current_user = authenticate();
728 if(empty($current_user)) {
729 $response['error'] = array("error_msg"=>"not logged in");
730 print $json->encode($response, true);
731 print "not logged in";
735 if(isset($GLOBALS['HTTP_RAW_POST_DATA']))
736 $request = $json->decode($GLOBALS['HTTP_RAW_POST_DATA'], true);
738 $request = $json->decode(file_get_contents("php://input"), true);
741 if(!is_array($request)) {
742 $response['error'] = array("error_msg"=>"malformed request");
743 print $json->encode($response, true);
746 // make sure required RPC fields are set
747 if(empty($request['method']) || empty($request['id'])) {
748 $response['error'] = array("error_msg"=>"missing parameters");
749 print $json->encode($response, true);
752 $response['id'] = $request['id'];
754 if(in_array($request['method'], $SUPPORTED_METHODS)) {
755 call_user_func('json_'.$request['method'],$request['id'],$request['params']);
757 $response['error'] = array("error_msg"=>"method:".$request["method"]." not supported");
758 print $json->encode($response, true);