]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/Home/QuickSearch.php
Release 6.5.12
[Github/sugarcrm.git] / modules / Home / QuickSearch.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2013 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('include/SugarObjects/templates/person/Person.php');
39 require_once('include/MVC/SugarModule.php');
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     /**
51      * Condition operators
52      * @var string
53      */
54     const CONDITION_CONTAINS    = 'contains';
55     const CONDITION_LIKE_CUSTOM = 'like_custom';
56     const CONDITION_EQUAL       = 'equal';
57
58     protected $extra_where;
59
60     /**
61      * Query a module for a list of items
62      *
63      * @param array $args
64      * example for querying Account module with 'a':
65      * array ('modules' => array('Accounts'), // module to use
66      *        'field_list' => array('name', 'id'), // fields to select
67      *        'group' => 'or', // how the conditions should be combined
68      *        'conditions' => array(array( // array of where conditions to use
69      *                              'name' => 'name', // field
70      *                              'op' => 'like_custom', // operation
71      *                              'end' => '%', // end of the query
72      *                              'value' => 'a',  // query value
73      *                              )
74      *                        ),
75      *        'order' => 'name', // order by
76      *        'limit' => '30', // limit, number of records to return
77      *       )
78      * @return array list of elements returned
79      */
80     public function query($args)
81     {
82         $args = $this->prepareArguments($args);
83         $args = $this->updateQueryArguments($args);
84         $data = $this->getRawResults($args);
85
86         return $this->getFormattedJsonResults($data, $args);
87     }
88
89     /**
90      * get_contact_array
91      *
92      */
93     public function get_contact_array($args)
94     {
95         $args    = $this->prepareArguments($args);
96         $args    = $this->updateContactArrayArguments($args);
97         $data    = $this->getRawResults($args);
98         $results = $this->prepareResults($data, $args);
99
100         return $this->getFilteredJsonResults($results);
101     }
102
103     /**
104      * Returns the list of users, faster than using query method for Users module
105      *
106      * @param array $args arguments used to construct query, see query() for example
107      * @return array list of users returned
108      */
109     public function get_user_array($args)
110     {
111         $condition = $args['conditions'][0]['value'];
112         $results   = $this->getUserResults($condition);
113
114         return $this->getJsonEncodedData($results);
115     }
116
117
118     /**
119      * Returns search results from external API
120      *
121      * @param array $args
122      * @return array
123      */
124     public function externalApi($args)
125     {
126         require_once('include/externalAPI/ExternalAPIFactory.php');
127         $data = array();
128         try {
129             $api = ExternalAPIFactory::loadAPI($args['api']);
130             $data['fields']     = $api->searchDoc($_REQUEST['query']);
131             $data['totalCount'] = count($data['fields']);
132         } catch(Exception $ex) {
133             $GLOBALS['log']->error($ex->getMessage());
134         }
135
136         return $this->getJsonEncodedData($data);
137     }
138
139
140     /**
141      * Internal function to construct where clauses
142      *
143      * @param Object $focus
144      * @param array $args
145      * @return string
146      */
147     protected function constructWhere($focus, $args)
148     {
149         global $db, $locale, $current_user;
150
151         $table = $focus->getTableName();
152         if (!empty($table)) {
153             $table_prefix = $db->getValidDBName($table).".";
154         } else {
155             $table_prefix = '';
156         }
157         $conditionArray = array();
158
159         if (!is_array($args['conditions'])) {
160             $args['conditions'] = array();
161         }
162
163         foreach($args['conditions'] as $condition)
164         {
165             switch ($condition['op'])
166             {
167                 case self::CONDITION_CONTAINS:
168                     array_push(
169                         $conditionArray,
170                         sprintf(
171                             "%s like '%%%s%%'",
172                             $table_prefix . $db->getValidDBName($condition['name']),
173                             $db->quote($condition['value']
174                     )));
175                     break;
176
177                 case self::CONDITION_LIKE_CUSTOM:
178                     $like = '';
179                     if (!empty($condition['begin'])) {
180                         $like .= $db->quote($condition['begin']);
181                     }
182                     $like .= $db->quote($condition['value']);
183
184                     if (!empty($condition['end'])) {
185                         $like .= $db->quote($condition['end']);
186                     }
187
188                     if ($focus instanceof Person){
189                         $nameFormat = $locale->getLocaleFormatMacro($current_user);
190
191                         if (strpos($nameFormat,'l') > strpos($nameFormat,'f')) {
192                             array_push(
193                                 $conditionArray,
194                                 $db->concat($table, array('first_name','last_name')) . " like '$like'"
195                             );
196                         } else {
197                             array_push(
198                                 $conditionArray,
199                                 $db->concat($table, array('last_name','first_name')) . " like '$like'"
200                             );
201                         }
202                     }
203                     else {
204                         array_push(
205                             $conditionArray,
206                             $table_prefix . $db->getValidDBName($condition['name']) . sprintf(" like '%s'", $like)
207                         );
208                     }
209                     break;
210
211                 case self::CONDITION_EQUAL:
212                     if ($condition['value']) {
213                         array_push(
214                             $conditionArray,
215                             sprintf("(%s = '%s')", $db->getValidDBName($condition['name']), $db->quote($condition['value']))
216                             );
217                     }
218                     break;
219
220                 default:
221                     array_push(
222                         $conditionArray,
223                         $table_prefix.$db->getValidDBName($condition['name']) . sprintf(" like '%s%%'", $db->quote($condition['value']))
224                     );
225             }
226         }
227
228         $whereClauseArray = array();
229         if (!empty($conditionArray)) {
230             $whereClauseArray[] = sprintf('(%s)', implode(" {$args['group']} ", $conditionArray));
231         }
232         if(!empty($this->extra_where)) {
233             $whereClauseArray[] = "({$this->extra_where})";
234         }
235
236         if ($table == 'users') {
237             $whereClauseArray[] = "users.status='Active'";
238         }
239
240         return implode(' AND ', $whereClauseArray);
241     }
242
243     /**
244      * Returns formatted data
245      *
246      * @param array $results
247      * @param array $args
248      * @return array
249      */
250     protected function formatResults($results, $args)
251     {
252         global $sugar_config;
253
254         $app_list_strings = null;
255         $data['totalCount'] = count($results);
256         $data['fields']     = array();
257
258         for ($i = 0; $i < count($results); $i++) {
259             $data['fields'][$i] = array();
260             $data['fields'][$i]['module'] = $results[$i]->object_name;
261
262             //C.L.: Bug 43395 - For Quicksearch, do not return values with salutation and title formatting
263             if($results[$i] instanceof Person)
264             {
265                 $results[$i]->createLocaleFormattedName = false;
266             }
267             $listData = $results[$i]->get_list_view_data();
268
269             foreach ($args['field_list'] as $field) {
270                 // handle enums
271                 if ((isset($results[$i]->field_name_map[$field]['type']) && $results[$i]->field_name_map[$field]['type'] == 'enum')
272                     || (isset($results[$i]->field_name_map[$field]['custom_type']) && $results[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
273
274                     // get fields to match enum vals
275                     if(empty($app_list_strings)) {
276                         if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
277                         else $current_language = $sugar_config['default_language'];
278                         $app_list_strings = return_app_list_strings_language($current_language);
279                     }
280
281                     // match enum vals to text vals in language pack for return
282                     if(!empty($app_list_strings[$results[$i]->field_name_map[$field]['options']])) {
283                         $results[$i]->$field = $app_list_strings[$results[$i]->field_name_map[$field]['options']][$results[$i]->$field];
284                     }
285                 }
286
287
288                 if (isset($listData[$field])) {
289                     $data['fields'][$i][$field] = $listData[$field];
290                 } else if (isset($results[$i]->$field)) {
291                     $data['fields'][$i][$field] = $results[$i]->$field;
292                 } else {
293                     $data['fields'][$i][$field] = '';
294                 }
295             }
296         }
297
298         if (is_array($data['fields'])) {
299             foreach ($data['fields'] as $i => $recordIn) {
300                 if (!is_array($recordIn)) {
301                     continue;
302                 }
303
304                 foreach ($recordIn as $col => $dataIn) {
305                     if (!is_scalar($dataIn)) {
306                         continue;
307                     }
308
309                     $data['fields'][$i][$col] = html_entity_decode($dataIn, ENT_QUOTES, 'UTF-8');
310                 }
311             }
312         }
313
314         return $data;
315     }
316
317     /**
318      * Filter duplicate results from the list
319      *
320      * @param array $list
321      * @return  array
322      */
323     protected function filterResults($list)
324     {
325         $fieldsFiltered = array();
326         foreach ($list['fields'] as $field) {
327             $found = false;
328             foreach ($fieldsFiltered as $item) {
329                 if ($item === $field) {
330                     $found = true;
331                     break;
332                 }
333             }
334
335             if (!$found) {
336                 $fieldsFiltered[] = $field;
337             }
338         }
339
340         $list['totalCount'] = count($fieldsFiltered);
341         $list['fields']     = $fieldsFiltered;
342
343         return $list;
344     }
345
346     /**
347      * Returns raw search results. Filters should be applied later.
348      *
349      * @param array $args
350      * @param boolean $singleSelect
351      * @return array
352      */
353     protected function getRawResults($args, $singleSelect = false)
354     {
355         $orderBy = !empty($args['order']) ? $args['order'] : '';
356         $limit   = !empty($args['limit']) ? intval($args['limit']) : '';
357         $data    = array();
358
359         foreach ($args['modules'] as $module) {
360             $focus = SugarModule::get($module)->loadBean();
361
362             $orderBy = $focus->db->getValidDBName(($args['order_by_name'] && $focus instanceof Person && $args['order'] == 'name') ? 'last_name' : $orderBy);
363
364             if ($focus->ACLAccess('ListView', true)) {
365                 $where = $this->constructWhere($focus, $args);
366                 $data  = $this->updateData($data, $focus, $orderBy, $where, $limit, $singleSelect);
367             }
368         }
369
370
371         return $data;
372     }
373
374     /**
375      * Returns search results with all fixes applied
376      *
377      * @param array $data
378      * @param array $args
379      * @return array
380      */
381     protected function prepareResults($data, $args)
382     {
383         $results['totalCount'] = $count = count($data);
384         $results['fields']     = array();
385
386         for ($i = 0; $i < $count; $i++) {
387             $field = array();
388             $field['module'] = $data[$i]->object_name;
389
390             $field = $this->overrideContactId($field, $data[$i], $args);
391             $field = $this->updateContactName($field, $args);
392
393             $results['fields'][$i] = $this->prepareField($field, $args);
394         }
395
396         return $results;
397     }
398
399     /**
400      * Returns user search results
401      *
402      * @param string $condition
403      * @return array
404      */
405     protected function getUserResults($condition)
406     {
407         $users = $this->getUserArray($condition);
408
409         $results = array();
410         $results['totalCount'] = count($users);
411         $results['fields']     = array();
412
413         foreach ($users as $id => $name) {
414             array_push(
415                 $results['fields'],
416                 array(
417                     'id' => (string) $id,
418                     'user_name' => $name,
419                     'module' => 'Users'
420             ));
421         }
422
423         return $results;
424     }
425
426     /**
427      * Merges current module search results to given list and returns it
428      *
429      * @param array $data
430      * @param SugarBean $focus
431      * @param string $orderBy
432      * @param string $where
433      * @param string $limit
434      * @param boolean $singleSelect
435      * @return array
436      */
437     protected function updateData($data, $focus, $orderBy, $where, $limit, $singleSelect = false)
438     {
439         $result = $focus->get_list($orderBy, $where, 0, $limit, -1, 0, $singleSelect);
440
441         return array_merge($data, $result['list']);
442     }
443
444     /**
445      * Updates search result with proper contact name
446      *
447      * @param array $result
448      * @param array $args
449      * @return string
450      */
451     protected function updateContactName($result, $args)
452     {
453         global $locale;
454
455         $result[$args['field_list'][0]] = $locale->getLocaleFormattedName(
456             $result['first_name'],
457             $result['last_name'],
458             $result['salutation']
459         );
460
461         return $result;
462     }
463
464     /**
465      * Overrides contact_id and reports_to_id params (to 'id')
466      *
467      * @param array $result
468      * @param object $data
469      * @param array $args
470      * @return array
471      */
472     protected function overrideContactId($result, $data, $args)
473     {
474         foreach ($args['field_list'] as $field) {
475             $result[$field] = (preg_match('/reports_to_id$/s',$field)
476                                || preg_match('/contact_id$/s',$field))
477                 ? $data->id // "reports_to_id" to "id"
478                 : $data->$field;
479         }
480
481         return $result;
482     }
483
484     /**
485      * Returns prepared arguments. Should be redefined in child classes.
486      *
487      * @param array $arguments
488      * @return array
489      */
490     protected function prepareArguments($args)
491     {
492         global $sugar_config;
493
494         // override query limits
495         if ($sugar_config['list_max_entries_per_page'] < ($args['limit'] + 1)) {
496             $sugar_config['list_max_entries_per_page'] = ($args['limit'] + 1);
497         }
498
499         $defaults = array(
500             'order_by_name' => false,
501         );
502         $this->extra_where = '';
503
504         // Sanitize group
505         /* BUG: 52684 properly check for 'and' jeff@neposystems.com */
506         if(!empty($args['group'])  && strcasecmp($args['group'], 'and') == 0) {
507             $args['group'] = 'AND';
508         } else {
509             $args['group'] = 'OR';
510         }
511
512         return array_merge($defaults, $args);
513     }
514
515     /**
516      * Returns prepared field array. Should be redefined in child classes.
517      *
518      * @param array $field
519      * @param array $args
520      * @return array
521      */
522     protected function prepareField($field, $args)
523     {
524         return $field;
525     }
526
527     /**
528      * Returns user array
529      *
530      * @param string $condition
531      * @return array
532      */
533     protected function getUserArray($condition)
534     {
535         return (showFullName())
536             // utils.php, if system is configured to show full name
537             ? getUserArrayFromFullName($condition, true)
538             : get_user_array(false, 'Active', '', false, $condition,' AND portal_only=0 ',false);
539     }
540
541     /**
542      * Returns additional where condition for non private teams
543      *
544      * @param array $args
545      * @return string
546      */
547     protected function getNonPrivateTeamsWhere($args)
548     {
549         global $db;
550
551         $where = sprintf(
552             "(teams.name like '%s%%' or teams.name_2 like '%s%%')",
553             $db->quote($args['conditions'][0]['value']),
554             $db->quote($args['conditions'][0]['value'])
555         );
556
557         $where .= (!empty($args['conditions'][1]) && $args['conditions'][1]['name'] == 'user_id')
558             ? sprintf(
559                 " AND teams.id in (select team_id from team_memberships where user_id = '%s')",
560                 $db->quote($args['conditions'][1]['value'])
561             )
562             : ' AND teams.private = 0';
563
564         return $where;
565     }
566
567     /**
568      * Returns JSON encoded data
569      *
570      * @param array $data
571      * @return string
572      */
573     protected function getJsonEncodedData($data)
574     {
575         $json = getJSONobj();
576
577         return $json->encodeReal($data);
578     }
579
580     /**
581      * Returns formatted JSON encoded search results
582      *
583      * @param array $args
584      * @param array $results
585      * @return string
586      */
587     protected function getFormattedJsonResults($results, $args)
588     {
589         $results = $this->formatResults($results, $args);
590
591         return $this->getJsonEncodedData($results);
592     }
593
594     /**
595      * Returns filtered JSON encoded search results
596      *
597      * @param array $results
598      * @return string
599      */
600     protected function getFilteredJsonResults($results)
601     {
602         $results = $this->filterResults($results);
603
604         return $this->getJsonEncodedData($results);
605     }
606
607     /**
608      * Returns updated arguments array
609      *
610      * @param array $args
611      * @return array
612      */
613     protected function updateQueryArguments($args)
614     {
615         $args['order_by_name'] = true;
616
617         return $args;
618     }
619
620     /**
621      * Returns updated arguments array for contact query
622      *
623      * @param array $args
624      * @return array
625      */
626     protected function updateContactArrayArguments($args)
627     {
628         return $args;
629     }
630
631     /**
632      * Returns updated arguments array for team query
633      *
634      * @param array $args
635      * @return array
636      */
637     protected function updateTeamArrayArguments($args)
638     {
639         $this->extra_where = $this->getNonPrivateTeamsWhere($args);
640         $args['modules'] = array('Teams');
641
642         return $args;
643     }
644 }