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-2012 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 // bug49650 - strip out asterisks from query in case
214 // user thinks asterisk is a wildcard value
215 $query = str_replace( '*' , '' , $query );
217 $limit = !empty($GLOBALS['sugar_config']['max_spotresults_initial']) ? $GLOBALS['sugar_config']['max_spotresults_initial'] : 5;
219 $limit = !empty($GLOBALS['sugar_config']['max_spotresults_more']) ? $GLOBALS['sugar_config']['max_spotresults_more'] : 20;
221 $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
224 global $current_user;
226 foreach($modules as $moduleName)
228 if (empty($primary_module))
230 $primary_module=$moduleName;
233 $searchFields = SugarSpot::getSearchFields($moduleName);
235 //Continue on to the next module if no search fields found for module
236 if (empty($searchFields[$moduleName]))
241 $return_fields = array();
242 $seed = SugarModule::get($moduleName)->loadBean();
244 //Continue on to next module if we don't have ListView ACLAccess for module
245 if(!$seed->ACLAccess('ListView')) {
249 $class = $seed->object_name;
251 foreach($searchFields[$moduleName] as $k=>$v)
254 $searchFields[$moduleName][$k]['value'] = $query;
256 //If force_unifiedsearch flag is true, we are essentially saying this field must be searched on (e.g. search_name in SearchFields.php file)
257 if(!empty($searchFields[$moduleName][$k]['force_unifiedsearch']))
262 if(!empty($GLOBALS['dictionary'][$class]['unified_search'])){
264 if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
266 if(isset($searchFields[$moduleName][$k]['db_field'])){
267 foreach($searchFields[$moduleName][$k]['db_field'] as $field)
269 if(!empty($GLOBALS['dictionary'][$class]['fields'][$field]['unified_search']))
271 if(isset($GLOBALS['dictionary'][$class]['fields'][$field]['type']))
273 if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$field]['type'], $query))
275 unset($searchFields[$moduleName][$k]);
284 # Bug 42961 Spot search for custom fields
285 if (!$keep && (isset($v['force_unifiedsearch']) == false || $v['force_unifiedsearch'] != true))
287 if(strpos($k,'email') === false || !$searchEmail) {
288 unset($searchFields[$moduleName][$k]);
292 if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
293 unset($searchFields[$moduleName][$k]);
296 }else if(empty($GLOBALS['dictionary'][$class]['fields'][$k]) ){
297 //If module did not have unified_search defined, then check the exception for an email search before we unset
298 if(strpos($k,'email') === false || !$searchEmail)
300 unset($searchFields[$moduleName][$k]);
302 }else if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$k]['type'], $query)){
303 unset($searchFields[$moduleName][$k]);
307 //If no search field criteria matched then continue to next module
308 if (empty($searchFields[$moduleName]))
313 //Variable used to store the "name" field displayed in results
316 if(isset($seed->field_defs['name']))
318 $return_fields['name'] = $seed->field_defs['name'];
319 $name_field = 'name';
323 foreach($seed->field_defs as $k => $v)
325 if(isset($seed->field_defs[$k]['type']) && ($seed->field_defs[$k]['type'] == 'name') && !isset($return_fields[$k]))
327 $return_fields[$k] = $seed->field_defs[$k];
332 if(!isset($return_fields['name']))
334 // if we couldn't find any name fields, try search fields that have name in it
335 foreach($searchFields[$moduleName] as $k => $v)
337 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
339 $return_fields[$k] = $seed->field_defs[$k];
347 if(!isset($return_fields['name']))
349 // last resort - any fields that have 'name' in their name
350 foreach($seed->field_defs as $k => $v)
352 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
354 $return_fields[$k] = $seed->field_defs[$k];
362 if(empty($name_field)) {
363 // FAIL: couldn't find a name field to display a result label
364 $GLOBALS['log']->error("Unable to find name field for module $moduleName");
368 if(isset($return_fields['name']['fields']))
370 // some names are composite name fields (e.g. last_name, first_name), add these to return list
371 foreach($return_fields['name']['fields'] as $field)
373 $return_fields[$field] = $seed->field_defs[$field];
377 $searchForm = new SearchForm ( $seed, $moduleName ) ;
378 $searchForm->setup (array ( $moduleName => array() ) , $searchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
379 $where_clauses = $searchForm->generateSearchWhere() ;
381 if(empty($where_clauses))
385 if(count($where_clauses) > 1) {
386 $query_parts = array();
388 $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
389 $search_keys = array_keys($searchFields[$moduleName]);
391 foreach($where_clauses as $n => $clause) {
392 $allfields = $return_fields;
393 $skey = $search_keys[$n];
394 if(isset($seed->field_defs[$skey])) {
395 // Joins for foreign fields aren't produced unless the field is in result, hence the merge
396 $allfields[$skey] = $seed->field_defs[$skey];
398 $ret_array = $seed->create_new_list_query('', $clause, $allfields, array(), 0, '', true, $seed, true);
399 $query_parts[] = $ret_array_start['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
401 $main_query = "(".join(") UNION (", $query_parts).")";
403 foreach($searchFields[$moduleName] as $k=>$v){
404 if(isset($seed->field_defs[$k])) {
405 $return_fields[$k] = $seed->field_defs[$k];
408 $ret_array = $seed->create_new_list_query('', $where_clauses[0], $return_fields, array(), 0, '', true, $seed, true);
409 $main_query = $ret_array['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
414 $result = $seed->db->query($main_query);
417 $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
420 if($offset == 'end') {
421 $totalCount = $this->_getCount($seed, $main_query);
423 $offset = (floor(($totalCount -1) / $limit)) * $limit;
428 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
433 while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
435 $temp->setupCustomFields($temp->module_dir);
436 $temp->loadFromRow($row);
437 $data[] = $temp->get_list_view_data($return_fields);
445 if($count >= $limit) {
446 $nextOffset = $offset + $limit;
450 $prevOffset = $offset - $limit;
451 if($prevOffset < 0) $prevOffset = 0;
454 if( $count >= $limit && $totalCounted){
455 if(!isset($totalCount)) {
456 $totalCount = $this->_getCount($seed, $main_query);
459 $totalCount = $count + $offset;
462 $pageData['offsets'] = array( 'current'=>$offset, 'next'=>$nextOffset, 'prev'=>$prevOffset, 'end'=>$endOffset, 'total'=>$totalCount, 'totalCounted'=>$totalCounted);
463 $pageData['bean'] = array('objectName' => $seed->object_name, 'moduleDir' => $seed->module_dir);
467 $results[$moduleName] = array("data"=>$data, "pageData"=>$pageData, "readAccess"=>$readAccess);
476 * Function used to walk the array and find keys that map the queried string.
477 * if both the pattern and module name is found the promote the string to thet top.
479 protected function _searchKeys(
485 //make the module name singular....
486 if ($patterns[1][strlen($patterns[1])-1] == 's') {
487 $patterns[1]=substr($patterns[1],0,(strlen($patterns[1])-1));
490 $module_exists = stripos($key,$patterns[1]); //primary module name.
491 $pattern_exists = stripos($key,$patterns[0]); //pattern provided by the user.
492 if ($module_exists !== false and $pattern_exists !== false) {
493 $GLOBALS['matching_keys']= array_merge(array(array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1)),$GLOBALS['matching_keys']);
496 if ($pattern_exists !== false) {
497 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);
506 * This is a private function to determine if the search type field should be filtered out based on the query string value
508 * @param String $type The string value of the field type (e.g. phone, date, datetime, int, etc.)
509 * @param String $query The search string value sent from the global search
510 * @return boolean True if the search type fits the query string value; false otherwise
512 protected function filterSearchType($type, $query)
523 if(!is_numeric($query)) {
528 //For a phone search we require at least three digits
529 if(!preg_match('/[0-9]{3,}/', $query))
535 if(!preg_match('/[0-9]/', $query))