2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2012 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('include/SugarObjects/templates/person/Person.php');
39 require_once('include/MVC/SugarModule.php');
42 * quicksearchQuery class, handles AJAX calls from quicksearch.js
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
48 class quicksearchQuery
54 const CONDITION_CONTAINS = 'contains';
55 const CONDITION_LIKE_CUSTOM = 'like_custom';
56 const CONDITION_EQUAL = 'equal';
58 protected $extra_where;
61 * Query a module for a list of items
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
75 * 'order' => 'name', // order by
76 * 'limit' => '30', // limit, number of records to return
78 * @return array list of elements returned
80 public function query($args)
82 $args = $this->prepareArguments($args);
83 $args = $this->updateQueryArguments($args);
84 $data = $this->getRawResults($args);
86 return $this->getFormattedJsonResults($data, $args);
93 public function get_contact_array($args)
95 $args = $this->prepareArguments($args);
96 $args = $this->updateContactArrayArguments($args);
97 $data = $this->getRawResults($args);
98 $results = $this->prepareResults($data, $args);
100 return $this->getFilteredJsonResults($results);
104 * Returns the list of users, faster than using query method for Users module
106 * @param array $args arguments used to construct query, see query() for example
107 * @return array list of users returned
109 public function get_user_array($args)
111 $condition = $args['conditions'][0]['value'];
112 $results = $this->getUserResults($condition);
114 return $this->getJsonEncodedData($results);
119 * Returns search results from external API
124 public function externalApi($args)
126 require_once('include/externalAPI/ExternalAPIFactory.php');
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());
136 return $this->getJsonEncodedData($data);
141 * Internal function to construct where clauses
143 * @param Object $focus
147 protected function constructWhere($focus, $args)
149 global $db, $locale, $current_user;
151 $table = $focus->getTableName();
152 if (!empty($table)) {
153 $table_prefix = $db->getValidDBName($table).".";
157 $conditionArray = array();
159 if (!is_array($args['conditions'])) {
160 $args['conditions'] = array();
163 foreach($args['conditions'] as $condition)
165 switch ($condition['op'])
167 case self::CONDITION_CONTAINS:
172 $table_prefix . $db->getValidDBName($condition['name']),
173 $db->quote($condition['value']
177 case self::CONDITION_LIKE_CUSTOM:
179 if (!empty($condition['begin'])) {
180 $like .= $db->quote($condition['begin']);
182 $like .= $db->quote($condition['value']);
184 if (!empty($condition['end'])) {
185 $like .= $db->quote($condition['end']);
188 if ($focus instanceof Person){
189 $nameFormat = $locale->getLocaleFormatMacro($current_user);
191 if (strpos($nameFormat,'l') > strpos($nameFormat,'f')) {
194 $db->concat($table, array('first_name','last_name')) . " like '$like'"
199 $db->concat($table, array('last_name','first_name')) . " like '$like'"
206 $table_prefix . $db->getValidDBName($condition['name']) . sprintf(" like '%s'", $like)
211 case self::CONDITION_EQUAL:
212 if ($condition['value']) {
215 sprintf("(%s = '%s')", $db->getValidDBName($condition['name']), $db->quote($condition['value']))
223 $table_prefix.$db->getValidDBName($condition['name']) . sprintf(" like '%s%%'", $db->quote($condition['value']))
228 $whereClause = sprintf('(%s)', implode(" {$args['group']} ", $conditionArray));
229 if(!empty($this->extra_where)) {
230 $whereClause .= " AND ({$this->extra_where})";
233 if ($table == 'users') {
234 $whereClause .= sprintf(" AND users.status='Active'");
241 * Returns formatted data
243 * @param array $results
247 protected function formatResults($results, $args)
249 global $sugar_config;
251 $app_list_strings = null;
252 $data['totalCount'] = count($results);
253 $data['fields'] = array();
255 for ($i = 0; $i < count($results); $i++) {
256 $data['fields'][$i] = array();
257 $data['fields'][$i]['module'] = $results[$i]->object_name;
259 //C.L.: Bug 43395 - For Quicksearch, do not return values with salutation and title formatting
260 if($results[$i] instanceof Person)
262 $results[$i]->createLocaleFormattedName = false;
264 $listData = $results[$i]->get_list_view_data();
266 foreach ($args['field_list'] as $field) {
268 if ((isset($results[$i]->field_name_map[$field]['type']) && $results[$i]->field_name_map[$field]['type'] == 'enum')
269 || (isset($results[$i]->field_name_map[$field]['custom_type']) && $results[$i]->field_name_map[$field]['custom_type'] == 'enum')) {
271 // get fields to match enum vals
272 if(empty($app_list_strings)) {
273 if(isset($_SESSION['authenticated_user_language']) && $_SESSION['authenticated_user_language'] != '') $current_language = $_SESSION['authenticated_user_language'];
274 else $current_language = $sugar_config['default_language'];
275 $app_list_strings = return_app_list_strings_language($current_language);
278 // match enum vals to text vals in language pack for return
279 if(!empty($app_list_strings[$results[$i]->field_name_map[$field]['options']])) {
280 $results[$i]->$field = $app_list_strings[$results[$i]->field_name_map[$field]['options']][$results[$i]->$field];
285 if (isset($listData[$field])) {
286 $data['fields'][$i][$field] = $listData[$field];
287 } else if (isset($results[$i]->$field)) {
288 $data['fields'][$i][$field] = $results[$i]->$field;
290 $data['fields'][$i][$field] = '';
295 if (is_array($data['fields'])) {
296 foreach ($data['fields'] as $i => $recordIn) {
297 if (!is_array($recordIn)) {
301 foreach ($recordIn as $col => $dataIn) {
302 if (!is_scalar($dataIn)) {
306 $data['fields'][$i][$col] = html_entity_decode($dataIn, ENT_QUOTES, 'UTF-8');
315 * Filter duplicate results from the list
320 protected function filterResults($list)
322 $fieldsFiltered = array();
323 foreach ($list['fields'] as $field) {
325 foreach ($fieldsFiltered as $item) {
326 if ($item === $field) {
333 $fieldsFiltered[] = $field;
337 $list['totalCount'] = count($fieldsFiltered);
338 $list['fields'] = $fieldsFiltered;
344 * Returns raw search results. Filters should be applied later.
347 * @param boolean $singleSelect
350 protected function getRawResults($args, $singleSelect = false)
352 $orderBy = !empty($args['order']) ? $args['order'] : '';
353 $limit = !empty($args['limit']) ? intval($args['limit']) : '';
356 foreach ($args['modules'] as $module) {
357 $focus = SugarModule::get($module)->loadBean();
359 $orderBy = $focus->db->getValidDBName(($args['order_by_name'] && $focus instanceof Person && $args['order'] == 'name') ? 'last_name' : $orderBy);
361 if ($focus->ACLAccess('ListView', true)) {
362 $where = $this->constructWhere($focus, $args);
363 $data = $this->updateData($data, $focus, $orderBy, $where, $limit, $singleSelect);
371 * Returns search results with all fixes applied
377 protected function prepareResults($data, $args)
379 $results['totalCount'] = $count = count($data);
380 $results['fields'] = array();
382 for ($i = 0; $i < $count; $i++) {
384 $field['module'] = $data[$i]->object_name;
386 $field = $this->overrideContactId($field, $data[$i], $args);
387 $field = $this->updateContactName($field, $args);
389 $results['fields'][$i] = $this->prepareField($field, $args);
396 * Returns user search results
398 * @param string $condition
401 protected function getUserResults($condition)
403 $users = $this->getUserArray($condition);
406 $results['totalCount'] = count($users);
407 $results['fields'] = array();
409 foreach ($users as $id => $name) {
413 'id' => (string) $id,
414 'user_name' => $name,
423 * Merges current module search results to given list and returns it
426 * @param SugarBean $focus
427 * @param string $orderBy
428 * @param string $where
429 * @param string $limit
430 * @param boolean $singleSelect
433 protected function updateData($data, $focus, $orderBy, $where, $limit, $singleSelect = false)
435 $result = $focus->get_list($orderBy, $where, 0, $limit, -1, 0, $singleSelect);
437 return array_merge($data, $result['list']);
441 * Updates search result with proper contact name
443 * @param array $result
447 protected function updateContactName($result, $args)
451 $result[$args['field_list'][0]] = $locale->getLocaleFormattedName(
452 $result['first_name'],
453 $result['last_name'],
454 $result['salutation']
461 * Overrides contact_id and reports_to_id params (to 'id')
463 * @param array $result
464 * @param object $data
468 protected function overrideContactId($result, $data, $args)
470 foreach ($args['field_list'] as $field) {
471 $result[$field] = (preg_match('/reports_to_id$/s',$field)
472 || preg_match('/contact_id$/s',$field))
473 ? $data->id // "reports_to_id" to "id"
481 * Returns prepared arguments. Should be redefined in child classes.
483 * @param array $arguments
486 protected function prepareArguments($args)
488 global $sugar_config;
490 // override query limits
491 if ($sugar_config['list_max_entries_per_page'] < ($args['limit'] + 1)) {
492 $sugar_config['list_max_entries_per_page'] = ($args['limit'] + 1);
496 'order_by_name' => false,
498 $this->extra_where = '';
501 /* BUG: 52684 properly check for 'and' jeff@neposystems.com */
502 if(!empty($args['group']) && strcasecmp($args['group'], 'and') == 0) {
503 $args['group'] = 'AND';
505 $args['group'] = 'OR';
508 return array_merge($defaults, $args);
512 * Returns prepared field array. Should be redefined in child classes.
514 * @param array $field
518 protected function prepareField($field, $args)
526 * @param string $condition
529 protected function getUserArray($condition)
531 return (showFullName())
532 // utils.php, if system is configured to show full name
533 ? getUserArrayFromFullName($condition, true)
534 : get_user_array(false, 'Active', '', false, $condition,' AND portal_only=0 ',false);
538 * Returns additional where condition for non private teams
543 protected function getNonPrivateTeamsWhere($args)
548 "(teams.name like '%s%%' or teams.name_2 like '%s%%')",
549 $db->quote($args['conditions'][0]['value']),
550 $db->quote($args['conditions'][0]['value'])
553 $where .= (!empty($args['conditions'][1]) && $args['conditions'][1]['name'] == 'user_id')
555 " AND teams.id in (select team_id from team_memberships where user_id = '%s')",
556 $db->quote($args['conditions'][1]['value'])
558 : ' AND teams.private = 0';
564 * Returns JSON encoded data
569 protected function getJsonEncodedData($data)
571 $json = getJSONobj();
573 return $json->encodeReal($data);
577 * Returns formatted JSON encoded search results
580 * @param array $results
583 protected function getFormattedJsonResults($results, $args)
585 $results = $this->formatResults($results, $args);
587 return $this->getJsonEncodedData($results);
591 * Returns filtered JSON encoded search results
593 * @param array $results
596 protected function getFilteredJsonResults($results)
598 $results = $this->filterResults($results);
600 return $this->getJsonEncodedData($results);
604 * Returns updated arguments array
609 protected function updateQueryArguments($args)
611 $args['order_by_name'] = true;
617 * Returns updated arguments array for contact query
622 protected function updateContactArrayArguments($args)
628 * Returns updated arguments array for team query
633 protected function updateTeamArrayArguments($args)
635 $this->extra_where = $this->getNonPrivateTeamsWhere($args);
636 $args['modules'] = array('Teams');