]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Home/quicksearchQuery.php
Release 6.2.2
[Github/sugarcrm.git] / modules / Home / quicksearchQuery.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  require_once('include/SugarObjects/templates/person/Person.php');
39   
40
41 /**
42  * quicksearchQuery class, handles AJAX calls from quicksearch.js
43  *
44  * @copyright  2004-2007 SugarCRM Inc.
45  * @license    http://www.sugarcrm.com/crm/products/sugar-professional-eula.html  SugarCRM Professional End User License
46  * @since      Class available since Release 4.5.1
47  */
48 class quicksearchQuery {
49     /**
50      * Internal function to construct where clauses
51      */
52     function constructWhere(&$query_obj, $focus) {
53         $table = $focus->getTableName();
54         if (! empty($table)) {
55             $table .= ".";
56         }
57         $cond_arr = array();
58     
59         if (!is_array($query_obj['conditions'])) {
60             $query_obj['conditions'] = array();
61         }
62   
63         foreach($query_obj['conditions'] as $condition) {
64                         if($condition['op'] == 'contains') {
65                         array_push($cond_arr,$GLOBALS['db']->quote($table.$condition['name'])." like '%".$GLOBALS['db']->quote($condition['value'])."%'");
66                 } else if($condition['op'] == 'like_custom') {
67                         $like = '';
68                    if(!empty($condition['begin'])) $like .= $GLOBALS['db']->quote($condition['begin']);
69                    $like .= $GLOBALS['db']->quote($condition['value']);
70                    if(!empty($condition['end'])) $like .= $GLOBALS['db']->quote($condition['end']);
71                        
72                    if ($focus instanceof Person){
73                                 $nameFormat = $GLOBALS['locale']->getLocaleFormatMacro($GLOBALS['current_user']);
74                     if ( strpos($nameFormat,'l') > strpos($nameFormat,'f') ) {
75                         array_push($cond_arr,db_concat(rtrim($table,'.'),array('first_name','last_name')) . " like '$like'");
76                     }
77                     else {
78                         array_push($cond_arr,db_concat(rtrim($table,'.'),array('last_name','first_name')) . " like '$like'");
79                     }
80                    }
81                    else {
82                         array_push($cond_arr,$GLOBALS['db']->quote($table.$condition['name'])." like '$like'");
83                    }
84                 } else { // starts_with
85                          array_push($cond_arr,$GLOBALS['db']->quote($table.$condition['name'])." like '".$GLOBALS['db']->quote($condition['value'])."%'");
86                 }
87             }
88             
89         $whereClause = '('.implode(" {$query_obj['group']} ",$cond_arr).')';
90         
91         if($table == 'users.') 
92             $whereClause .= " AND {$table}status='Active'";
93         
94         // Need to include the default whereStatement
95                 if(!empty($query_obj['whereExtra'])){
96             if(!empty($whereClause))$whereClause .= ' AND ';
97             $whereClause .= html_entity_decode($query_obj['whereExtra'],ENT_QUOTES);
98                 }
99                 
100         return $whereClause;
101     }
102     
103     /**
104      * Query a module for a list of items
105      * 
106      * @param array $args
107      * example for querying Account module with 'a':
108      * array ('modules' => array('Accounts'), // module to use
109      *        'field_list' => array('name', 'id'), // fields to select
110      *        'group' => 'or', // how the conditions should be combined
111      *        'conditions' => array(array( // array of where conditions to use
112      *                              'name' => 'name', // field 
113      *                              'op' => 'like_custom', // operation
114      *                              'end' => '%', // end of the query
115      *                              'value' => 'a',  // query value
116      *                              )
117      *                        ),
118      *        'order' => 'name', // order by
119      *        'limit' => '30', // limit, number of records to return 
120      *       )
121      * @return array list of elements returned
122      */
123     function query($args) {
124         $json = getJSONobj();
125         global $sugar_config;
126         global $beanFiles, $beanList;
127         
128         if($sugar_config['list_max_entries_per_page'] < ($args['limit'] + 1)) // override query limits
129             $sugar_config['list_max_entries_per_page'] = ($args['limit'] + 1);
130         
131         $list_return = array();
132         
133         foreach($args['modules'] as $module) {
134             require_once($beanFiles[$beanList[$module]]);
135                         
136                         $focus = new $beanList[$module];        
137             
138                         $query_orderby = '';
139             if (!empty($args['order'])) {
140                 $query_orderby = $args['order'];
141                 if ($focus instanceof Person && $args['order'] == 'name') {
142                         $query_orderby = 'last_name';
143                 }
144             }
145             $query_limit = '';
146             if (!empty($args['limit'])) {
147                 $query_limit = $args['limit'];
148             }
149
150             $query_where = $this->constructWhere($args, $focus);
151            
152             $list_arr = array();
153             if($focus->ACLAccess('ListView', true)) 
154             {
155                 $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
156                 $list_return = array_merge($list_return,$curlist['list']);
157             }
158         }
159         $list_arr = $this->formatResults($args, $list_return);
160         return $json->encodeReal($list_arr);
161     }
162     
163     protected function formatResults($args, $list_return){
164         global $sugar_config;
165         $app_list_strings = null;
166         $list_arr['totalCount']=count($list_return);
167         $list_arr['fields']= array();
168         for($i = 0; $i < count($list_return); $i++) {
169             $list_arr['fields'][$i]= array();
170             $list_arr['fields'][$i]['module']= $list_return[$i]->object_name;
171             
172             //C.L.: Bug 43395 - For Quicksearch, do not return values with salutation and title formatting
173             if($list_return[$i] instanceof Person)
174             {
175                $list_return[$i]->createLocaleFormattedName = false;
176             }
177             
178             $listData = $list_return[$i]->get_list_view_data();
179                 
180             foreach($args['field_list'] as $field) {
181                 // handle enums
182                 if( (isset($list_return[$i]->field_name_map[$field]['type']) && $list_return[$i]->field_name_map[$field]['type'] == 'enum') || 
183                     (isset($list_return[$i]->field_name_map[$field]['custom_type']) && $list_return[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
184                     
185                     // get fields to match enum vals
186                     if(empty($app_list_strings)) {
187                         if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
188                         else $current_language = $sugar_config['default_language'];
189                         $app_list_strings = return_app_list_strings_language($current_language);
190                     }
191                     
192                     // match enum vals to text vals in language pack for return
193                     if(!empty($app_list_strings[$list_return[$i]->field_name_map[$field]['options']])) {
194                         $list_return[$i]->$field = $app_list_strings[$list_return[$i]->field_name_map[$field]['options']][$list_return[$i]->$field];
195                     }
196                 }
197
198                         
199                 if (isset($listData[$field]))
200                         {
201                     $list_arr['fields'][$i][$field] = $listData[$field];
202                         }
203                         else if (isset($list_return[$i]->$field))
204                 {
205                     $list_arr['fields'][$i][$field] = $list_return[$i]->$field;
206                 }
207                 else {
208                         $list_arr['fields'][$i][$field] = "";
209                 }
210             }
211         }
212         if(is_array($list_arr['fields'])) {
213             foreach ( $list_arr['fields'] as $i => $recordIn ) {
214                 if(!is_array($recordIn)){
215                     continue;
216                 }
217                 foreach( $recordIn as $col => $dataIn ) {
218                     if ( !is_scalar($dataIn) ) {
219                         continue;
220                     }
221                     $list_arr['fields'][$i][$col] = html_entity_decode($dataIn,ENT_QUOTES,'UTF-8');
222                 }
223             }
224         }
225         return $list_arr;
226     }
227     
228     /**
229      * get_contact_array
230      * 
231      */
232     function get_contact_array($args) {
233         $json = getJSONobj();
234         global $sugar_config, $beanFiles, $beanList, $locale;
235         
236         if($sugar_config['list_max_entries_per_page'] < ($args['limit'] + 1)) // override query limits
237             $sugar_config['list_max_entries_per_page'] = ($args['limit'] + 1);
238         
239         $list_return = array();
240         
241         foreach($args['modules'] as $module) {
242             require_once($beanFiles[$beanList[$module]]);
243             $focus = new $beanList[$module];
244             
245             $query_orderby = '';
246             if (!empty($args['order'])) {
247                 $query_orderby = $args['order'];
248             }
249             $query_limit = '';
250             if (!empty($args['limit'])) {
251                 $query_limit = $args['limit'];
252             }
253             $query_where = $this->constructWhere($args, $focus);
254             $list_arr = array();
255             if($focus->ACLAccess('ListView', true)) {
256                 $curlist = $focus->get_list($query_orderby, $query_where, 0, $query_limit, -1, 0);
257                 $list_return = array_merge($list_return,$curlist['list']);
258             }
259         }
260         $list_arr['totalCount']=count($list_return);
261         $list_arr['fields']= array();
262         for($i = 0; $i < count($list_return); $i++) {
263             $list_arr['fields'][$i]= array();
264             $list_arr['fields'][$i]['module']= $list_return[$i]->object_name;
265             $contactName = "";
266             foreach($args['field_list'] as $field) {
267                 // We are overriding the contact_id param and the reports_to_id param to change to 'id'
268                 if(preg_match('/reports_to_id$/s',$field) || preg_match('/contact_id$/s',$field)) {  // We are overriding the reports_to_id param to change to 'id'
269                     $list_arr['fields'][$i][$field] = $list_return[$i]->id;
270                 }
271                 else {
272                     $list_arr['fields'][$i][$field] = $list_return[$i]->$field;
273                 }
274             } //foreach
275             
276             $contactName = $locale->getLocaleFormattedName($list_arr['fields'][$i]['first_name'], 
277                                                            $list_arr['fields'][$i]['last_name'],
278                                                            $list_arr['fields'][$i]['salutation']);
279                                                          
280             $list_arr['fields'][$i][$args['field_list'][0]] = $contactName;
281         } //for
282         
283         $str = $json->encodeReal($list_arr); 
284         return $str;    
285     }
286
287     
288     /**
289      * Returns the list of users, faster than using query method for Users module
290      * 
291      * @param array $args arguments used to construct query, see query() for example
292      * 
293      * @return array list of users returned
294      */
295     function get_user_array($args) {
296         global $json;
297         $json = getJSONobj();
298
299         $response = array();
300         
301         if(showFullName()) { // utils.php, if system is configured to show full name
302                 $user_array = getUserArrayFromFullName($args['conditions'][0]['value'], true);
303         } else {
304             $user_array = get_user_array(false, "Active", '', false, $args['conditions'][0]['value'],' AND portal_only=0 ',false);
305         }
306         $response['totalCount']=count($user_array);
307         $response['fields']=array();
308         $i=0;
309         foreach($user_array as $id=>$name) {
310             array_push($response['fields'], array('id' => (string) $id, 'user_name' => $name, 'module' => 'Users'));
311             $i++;
312         }
313     
314         return $json->encodeReal($response);
315     }
316     
317
318     function externalApi($data) {
319         require_once('include/externalAPI/ExternalAPIFactory.php');
320         
321         $api = ExternalAPIFactory::loadAPI($data['api']);
322
323         $json = getJSONobj();
324
325         $listArray['fields'] = $api->searchDoc($_REQUEST['query']);
326         $listArray['totalCount'] = count($listArray['fields']);
327         
328         $listJson = $json->encodeReal($listArray);
329         
330         return $listJson;
331     }
332 }
333
334 $json = getJSONobj();
335 $data = $json->decode(html_entity_decode($_REQUEST['data']));
336 if(isset($_REQUEST['query']) && !empty($_REQUEST['query'])){
337     foreach($data['conditions'] as $k=>$v){
338         if(empty($data['conditions'][$k]['value'])){
339                 $data['conditions'][$k]['value']=$_REQUEST['query'];
340         }
341     }
342 }
343  
344 $quicksearchQuery = new quicksearchQuery();
345
346 $method = !empty($data['method']) ? $data['method'] : 'query';
347 if(method_exists($quicksearchQuery, $method)) {
348    echo $quicksearchQuery->$method($data);
349 }
350
351 ?>