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.
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.
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
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
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.
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.
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 ********************************************************************************/
48 * Performs the search and returns the HTML widget containing the results
50 * @param $query string what we are searching for
51 * @param $modules array modules we are searching in
52 * @param $offset int search result offset
53 * @return string HTML code containing results
55 public function searchAndDisplay($query, $modules, $offset=-1)
58 $query_encoded = urlencode($query);
59 $results = $this->_performSearch($query, $modules, $offset);
60 $displayResults = array();
61 $displayMoreForModule = array();
63 foreach($results as $m=>$data)
65 if(empty($data['data']))
70 $total = count($data['data']);
71 $countRemaining = $data['pageData']['offsets']['total'] - $total;
73 if(isset($results[$m]['readAccess']) && !$results[$m]['readAccess'])
75 $displayTotal = $countRemaining > 0 ? ($total + $countRemaining) : $total;
76 $displayResults[$m]['link'] = array('total'=>$displayTotal, 'count_remaining'=>$countRemaining, 'query_encoded'=>$query_encoded);
82 $countRemaining -= $offset;
85 if($countRemaining > 0)
87 $displayMoreForModule[$m] = array('query'=>$query,
88 'offset'=>$data['pageData']['offsets']['next']++,
89 'countRemaining'=>$countRemaining);
92 foreach($data['data'] as $row)
96 //Determine a name to use
97 if(!empty($row['NAME']))
100 } else if(!empty($row['DOCUMENT_NAME'])) {
101 $name = $row['DOCUMENT_NAME'];
104 foreach($row as $k=>$v){
105 if(strpos($k, 'NAME') !== false)
111 } else if(empty($foundName)) {
123 $displayResults[$m][$row['ID']] = $name;
130 $ss = new Sugar_Smarty();
131 $ss->assign('displayResults', $displayResults);
132 $ss->assign('displayMoreForModule', $displayMoreForModule);
133 $ss->assign('appStrings', $GLOBALS['app_strings']);
134 $ss->assign('appListStrings', $GLOBALS['app_list_strings']);
135 $ss->assign('queryEncoded', $query_encoded);
136 $template = 'include/SearchForm/tpls/SugarSpot.tpl';
137 if(file_exists('custom/include/SearchForm/tpls/SugarSpot.tpl'))
139 $template = 'custom/include/SearchForm/tpls/SugarSpot.tpl';
141 return $ss->fetch($template);
145 * Returns the array containing the $searchFields for a module. This function
146 * first checks the default installation directories for the SearchFields.php file and then
147 * loads any custom definition (if found)
149 * @param $moduleName String name of module to retrieve SearchFields entries for
150 * @return array of SearchFields
152 protected static function getSearchFields(
156 $searchFields = array();
158 if(file_exists("modules/{$moduleName}/metadata/SearchFields.php"))
160 require("modules/{$moduleName}/metadata/SearchFields.php");
163 if(file_exists("custom/modules/{$moduleName}/metadata/SearchFields.php"))
165 require("custom/modules/{$moduleName}/metadata/SearchFields.php");
168 return $searchFields;
173 * Get count from query
174 * @param SugarBean $seed
175 * @param string $main_query
177 protected function _getCount($seed, $main_query)
179 // $count_query = $seed->create_list_count_query($main_query);
180 $result = $seed->db->query("SELECT COUNT(*) as c FROM ($main_query) main");
181 $row = $seed->db->fetchByAssoc($result);
182 return isset($row['c'])?$row['c']:0;
188 * Performs the search from the global search field.
190 * @param $query string what we are searching for
191 * @param $modules array modules we are searching in
192 * @param $offset int search result offset
195 protected function _performSearch(
201 //Return an empty array if no query string is given
209 require_once 'include/SearchForm/SearchForm2.php' ;
211 $searchEmail = preg_match('/^([^%]|%)*@([^%]|%)*$/', $query);
213 $limit = !empty($GLOBALS['sugar_config']['max_spotresults_initial']) ? $GLOBALS['sugar_config']['max_spotresults_initial'] : 5;
215 $limit = !empty($GLOBALS['sugar_config']['max_spotresults_more']) ? $GLOBALS['sugar_config']['max_spotresults_more'] : 20;
217 $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
220 global $current_user;
222 foreach($modules as $moduleName)
224 if (empty($primary_module))
226 $primary_module=$moduleName;
229 $searchFields = SugarSpot::getSearchFields($moduleName);
231 //Continue on to the next module if no search fields found for module
232 if (empty($searchFields[$moduleName]))
237 $return_fields = array();
238 $seed = SugarModule::get($moduleName)->loadBean();
240 //Continue on to next module if we don't have ListView ACLAccess for module
241 if(!$seed->ACLAccess('ListView')) {
245 $class = $seed->object_name;
247 foreach($searchFields[$moduleName] as $k=>$v)
250 $searchFields[$moduleName][$k]['value'] = $query;
252 //If force_unifiedsearch flag is true, we are essentially saying this field must be searched on (e.g. search_name in SearchFields.php file)
253 if(!empty($searchFields[$moduleName][$k]['force_unifiedsearch']))
258 if(!empty($GLOBALS['dictionary'][$class]['unified_search'])){
259 if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
261 if(isset($searchFields[$moduleName][$k]['db_field'])){
262 foreach($searchFields[$moduleName][$k]['db_field'] as $field)
264 if(!empty($GLOBALS['dictionary'][$class]['fields'][$field]['unified_search']))
266 if(isset($GLOBALS['dictionary'][$class]['fields'][$field]['type']))
268 if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$field]['type'], $query))
270 unset($searchFields[$moduleName][$k]);
280 if(strpos($k,'email') === false || !$searchEmail) {
281 unset($searchFields[$moduleName][$k]);
285 if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
286 unset($searchFields[$moduleName][$k]);
289 }else if(empty($GLOBALS['dictionary'][$class]['fields'][$k]) ){
290 //If module did not have unified_search defined, then check the exception for an email search before we unset
291 if(strpos($k,'email') === false || !$searchEmail)
293 unset($searchFields[$moduleName][$k]);
295 }else if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$k]['type'], $query)){
296 unset($searchFields[$moduleName][$k]);
300 //If no search field criteria matched then continue to next module
301 if (empty($searchFields[$moduleName]))
306 //Variable used to store the "name" field displayed in results
309 if(isset($seed->field_defs['name']))
311 $return_fields['name'] = $seed->field_defs['name'];
312 $name_field = 'name';
316 foreach($seed->field_defs as $k => $v)
318 if(isset($seed->field_defs[$k]['type']) && ($seed->field_defs[$k]['type'] == 'name') && !isset($return_fields[$k]))
320 $return_fields[$k] = $seed->field_defs[$k];
325 if(!isset($return_fields['name']))
327 // if we couldn't find any name fields, try search fields that have name in it
328 foreach($searchFields[$moduleName] as $k => $v)
330 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
332 $return_fields[$k] = $seed->field_defs[$k];
340 if(!isset($return_fields['name']))
342 // last resort - any fields that have 'name' in their name
343 foreach($seed->field_defs as $k => $v)
345 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
347 $return_fields[$k] = $seed->field_defs[$k];
355 if(empty($name_field)) {
356 // FAIL: couldn't find a name field to display a result label
357 $GLOBALS['log']->error("Unable to find name field for module $moduleName");
361 if(isset($return_fields['name']['fields']))
363 // some names are composite name fields (e.g. last_name, first_name), add these to return list
364 foreach($return_fields['name']['fields'] as $field)
366 $return_fields[$field] = $seed->field_defs[$field];
370 $searchForm = new SearchForm ( $seed, $moduleName ) ;
371 $searchForm->setup (array ( $moduleName => array() ) , $searchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
372 $where_clauses = $searchForm->generateSearchWhere() ;
374 if(empty($where_clauses))
378 if(count($where_clauses) > 1) {
379 $query_parts = array();
381 $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
382 $search_keys = array_keys($searchFields[$moduleName]);
384 foreach($where_clauses as $n => $clause) {
385 $allfields = $return_fields;
386 $skey = $search_keys[$n];
387 if(isset($seed->field_defs[$skey])) {
388 // Joins for foreign fields aren't produced unless the field is in result, hence the merge
389 $allfields[$skey] = $seed->field_defs[$skey];
391 $ret_array = $seed->create_new_list_query('', $clause, $allfields, array(), 0, '', true, $seed, true);
392 $query_parts[] = $ret_array_start['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
394 $main_query = "(".join(") UNION (", $query_parts).")";
396 foreach($searchFields[$moduleName] as $k=>$v){
397 if(isset($seed->field_defs[$k])) {
398 $return_fields[$k] = $seed->field_defs[$k];
401 $ret_array = $seed->create_new_list_query('', $where_clauses[0], $return_fields, array(), 0, '', true, $seed, true);
402 $main_query = $ret_array['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
407 $result = $seed->db->query($main_query);
410 $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
413 if($offset == 'end') {
414 $totalCount = $this->_getCount($seed, $main_query);
416 $offset = (floor(($totalCount -1) / $limit)) * $limit;
421 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
426 while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
428 $temp->setupCustomFields($temp->module_dir);
429 $temp->loadFromRow($row);
430 $data[] = $temp->get_list_view_data($return_fields);
438 if($count >= $limit) {
439 $nextOffset = $offset + $limit;
443 $prevOffset = $offset - $limit;
444 if($prevOffset < 0) $prevOffset = 0;
447 if( $count >= $limit && $totalCounted){
448 if(!isset($totalCount)) {
449 $totalCount = $this->_getCount($seed, $main_query);
452 $totalCount = $count + $offset;
455 $pageData['offsets'] = array( 'current'=>$offset, 'next'=>$nextOffset, 'prev'=>$prevOffset, 'end'=>$endOffset, 'total'=>$totalCount, 'totalCounted'=>$totalCounted);
456 $pageData['bean'] = array('objectName' => $seed->object_name, 'moduleDir' => $seed->module_dir);
460 $results[$moduleName] = array("data"=>$data, "pageData"=>$pageData, "readAccess"=>$readAccess);
469 * Function used to walk the array and find keys that map the queried string.
470 * if both the pattern and module name is found the promote the string to thet top.
472 protected function _searchKeys(
478 //make the module name singular....
479 if ($patterns[1][strlen($patterns[1])-1] == 's') {
480 $patterns[1]=substr($patterns[1],0,(strlen($patterns[1])-1));
483 $module_exists = stripos($key,$patterns[1]); //primary module name.
484 $pattern_exists = stripos($key,$patterns[0]); //pattern provided by the user.
485 if ($module_exists !== false and $pattern_exists !== false) {
486 $GLOBALS['matching_keys']= array_merge(array(array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1)),$GLOBALS['matching_keys']);
489 if ($pattern_exists !== false) {
490 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);
499 * This is a private function to determine if the search type field should be filtered out based on the query string value
501 * @param String $type The string value of the field type (e.g. phone, date, datetime, int, etc.)
502 * @param String $query The search string value sent from the global search
503 * @return boolean True if the search type fits the query string value; false otherwise
505 protected function filterSearchType($type, $query)
516 if(!is_numeric($query)) {
523 if(!preg_match('/[0-9]/', $query))