2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM 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 ********************************************************************************/
42 * Performs the search and returns the HTML widget containing the results
44 * @param $query string what we are searching for
45 * @param $modules array modules we are searching in
46 * @param $offset int search result offset
47 * @return string HTML widget
49 public function searchAndDisplay(
55 $query_encoded = urlencode($query);
56 $results = $this->_performSearch($query, $modules, $offset);
58 $str = '<div id="SpotResults">';
62 foreach($results as $m=>$data){
63 if(empty($data['data'])){
69 $countRemaining = $data['pageData']['offsets']['total'] - count($data['data']);
70 if($offset > 0) $countRemaining -= $offset;
72 $data['pageData']['offsets']['next']++;
73 if($countRemaining > 0){
75 <small class='more' onclick="DCMenu.spotZoom('$query', '$m','{$data['pageData']['offsets']['next']}' )">($countRemaining {$GLOBALS['app_strings']['LBL_SEARCH_MORE']})</small>
79 $modDisplayString = $m;
80 if(isset($GLOBALS['app_list_strings']['moduleList'][$m]))
81 $modDisplayString = $GLOBALS['app_list_strings']['moduleList'][$m];
83 $str.= "<div>{$modDisplayString} $more</div>";
85 foreach($data['data'] as $row){
88 if(!empty($row['NAME'])){
90 } else if(!empty($row['DOCUMENT_NAME'])) {
91 $name = $row['DOCUMENT_NAME'];
93 foreach($row as $k=>$v){
94 if(strpos($k, 'NAME') !== false && !empty($row[$k])){
102 foreach($row as $k=>$v){
103 if(strpos($k, 'NAME') !== false){
112 <li><a href="index.php?module={$data['pageData']['bean']['moduleDir']}&action=DetailView&record={$row['ID']}">$name</a></li>
121 <button onclick="document.location.href='index.php?module=Home&action=UnifiedSearch&search_form=false&advanced=false&query_string={$query_encoded}'">{$GLOBALS['app_strings']['LBL_EMAIL_SHOW_READ']}</button>
126 <button onclick="document.location.href='index.php?module=Home&action=UnifiedSearch&search_form=false&advanced=false&query_string={$query_encoded}'">{$GLOBALS['app_strings']['LBL_EMAIL_SHOW_READ']}</button>
129 $str .= $GLOBALS['app_strings']['LBL_EMAIL_SEARCH_NO_RESULTS'];
133 <button onclick="document.location.href='index.php?module=Home&action=UnifiedSearch&search_form=false&advanced=false&query_string={$query_encoded}'">{$GLOBALS['app_strings']['LBL_EMAIL_SHOW_READ']}</button>
142 * Returns the array containing the $searchFields for a module
144 * @param $moduleName string
147 protected static function getSearchFields(
151 if(file_exists("custom/modules/{$moduleName}/metadata/SearchFields.php")) {
152 $searchFields = array();
153 require "custom/modules/{$moduleName}/metadata/SearchFields.php" ;
154 return $searchFields;
155 } else if(file_exists("modules/{$moduleName}/metadata/SearchFields.php")) {
156 $searchFields = array();
157 require "modules/{$moduleName}/metadata/SearchFields.php" ;
158 return $searchFields;
165 * Get count from query
166 * @param SugarBean $seed
167 * @param string $main_query
169 protected function _getCount($seed, $main_query)
171 // $count_query = $seed->create_list_count_query($main_query);
172 $result = $seed->db->query("SELECT COUNT(*) as c FROM ($main_query) main");
173 $row = $seed->db->fetchByAssoc($result);
174 return isset($row['c'])?$row['c']:0;
178 * Performs the search
180 * @param $query string what we are searching for
181 * @param $modules array modules we are searching in
182 * @param $offset int search result offset
185 protected function _performSearch(
191 if(empty($query)) return array();
194 require_once 'include/SearchForm/SearchForm2.php' ;
196 $searchEmail = preg_match('/^([^%]|%)*@([^%]|%)*$/', $query);
198 $limit = ( !empty($GLOBALS['sugar_config']['max_spotresults_initial']) ? $GLOBALS['sugar_config']['max_spotresults_initial'] : 5 );
200 $limit = ( !empty($GLOBALS['sugar_config']['max_spotresults_more']) ? $GLOBALS['sugar_config']['max_spotresults_more'] : 20 );
202 $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
204 foreach($modules as $moduleName){
205 if (empty($primary_module)) $primary_module=$moduleName;
207 $searchFields = SugarSpot::getSearchFields($moduleName);
209 if (empty($searchFields[$moduleName])) continue;
211 $class = $GLOBALS['beanList'][$moduleName];
212 $return_fields = array();
213 $seed = new $class();
214 if(!$seed->ACLAccess('ListView')) continue;
216 if ($class == 'aCase') {
220 foreach($searchFields[$moduleName] as $k=>$v){
222 $searchFields[$moduleName][$k]['value'] = $query;
224 if(!empty($GLOBALS['dictionary'][$class]['unified_search'])){
225 if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
227 if(isset($searchFields[$moduleName][$k]['db_field'])){
228 foreach($searchFields[$moduleName][$k]['db_field'] as $field){
229 if(!empty($GLOBALS['dictionary'][$class]['fields'][$field]['unified_search'])){
235 if(strpos($k,'email') === false || !$searchEmail) {
236 unset($searchFields[$moduleName][$k]);
240 if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
241 unset($searchFields[$moduleName][$k]);
244 }else if(empty($GLOBALS['dictionary'][$class]['fields'][$k]) ){
245 unset($searchFields[$moduleName][$k]);
247 switch($GLOBALS['dictionary'][$class]['fields'][$k]['type']){
252 unset($searchFields[$moduleName][$k]);
255 if(!is_numeric($query)) {
256 unset($searchFields[$moduleName][$k]);
263 if (empty($searchFields[$moduleName])) continue;
265 if(isset($seed->field_defs['name'])) {
266 $return_fields['name'] = $seed->field_defs['name'];
269 foreach($seed->field_defs as $k => $v) {
270 if(isset($seed->field_defs[$k]['type']) && ($seed->field_defs[$k]['type'] == 'name') && !isset($return_fields[$k])) {
271 $return_fields[$k] = $seed->field_defs[$k];
275 if(!isset($return_fields['name'])) {
276 // if we couldn't find any name fields, try search fields that have name in it
277 foreach($searchFields[$moduleName] as $k => $v) {
278 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k])
279 && !isset($seed->field_defs[$k]['source'])) {
280 $return_fields[$k] = $seed->field_defs[$k];
286 if(!isset($return_fields['name'])) {
287 // last resort - any fields that have 'name' in their name
288 foreach($seed->field_defs as $k => $v) {
289 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k])
290 && !isset($seed->field_defs[$k]['source'])) {
291 $return_fields[$k] = $seed->field_defs[$k];
297 if(!isset($return_fields['name'])) {
298 // FAIL: couldn't find id & name for the module
299 $GLOBALS['log']->error("Unable to find name for module $moduleName");
303 if(isset($return_fields['name']['fields'])) {
304 // some names are composite
305 foreach($return_fields['name']['fields'] as $field) {
306 $return_fields[$field] = $seed->field_defs[$field];
311 $searchForm = new SearchForm ( $seed, $moduleName ) ;
312 $searchForm->setup (array ( $moduleName => array() ) , $searchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
313 $where_clauses = $searchForm->generateSearchWhere() ;
315 if(empty($where_clauses)) {
318 if(count($where_clauses) > 1) {
319 $query_parts = array();
321 $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
322 $search_keys = array_keys($searchFields[$moduleName]);
324 foreach($where_clauses as $n => $clause) {
325 $allfields = $return_fields;
326 $skey = $search_keys[$n];
327 if(isset($seed->field_defs[$skey])) {
328 // Joins for foreign fields aren't produced unless the field is in result, hence the merge
329 $allfields[$skey] = $seed->field_defs[$skey];
331 $ret_array = $seed->create_new_list_query('', $clause, $allfields, array(), 0, '', true, $seed, true);
332 $query_parts[] = $ret_array_start['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
334 $main_query = "(".join(") UNION (", $query_parts).")";
336 foreach($searchFields[$moduleName] as $k=>$v){
337 if(isset($seed->field_defs[$k])) {
338 $return_fields[$k] = $seed->field_defs[$k];
341 $ret_array = $seed->create_new_list_query('', $where_clauses[0], $return_fields, array(), 0, '', true, $seed, true);
342 $main_query = $ret_array['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
347 $result = $seed->db->query($main_query);
350 $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
353 if($offset == 'end') {
354 $totalCount = $this->_getCount($seed, $main_query);
356 $offset = (floor(($totalCount -1) / $limit)) * $limit;
361 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
366 while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
368 $temp->setupCustomFields($temp->module_dir);
369 $temp->loadFromRow($row);
370 $data[] = $temp->get_list_view_data($return_fields);
378 if($count >= $limit) {
379 $nextOffset = $offset + $limit;
383 $prevOffset = $offset - $limit;
384 if($prevOffset < 0) $prevOffset = 0;
387 if( $count >= $limit && $totalCounted){
388 if(!isset($totalCount)) {
389 $totalCount = $this->_getCount($seed, $main_query);
392 $totalCount = $count + $offset;
395 $pageData['offsets'] = array( 'current'=>$offset, 'next'=>$nextOffset, 'prev'=>$prevOffset, 'end'=>$endOffset, 'total'=>$totalCount, 'totalCounted'=>$totalCounted);
396 $pageData['bean'] = array('objectName' => $seed->object_name, 'moduleDir' => $seed->module_dir);
398 $results[$moduleName] = array("data" => $data, "pageData" => $pageData);
404 * Function used to walk the array and find keys that map the queried string.
405 * if both the pattern and module name is found the promote the string to thet top.
407 protected function _searchKeys(
413 //make the module name singular....
414 if ($patterns[1][strlen($patterns[1])-1] == 's') {
415 $patterns[1]=substr($patterns[1],0,(strlen($patterns[1])-1));
418 $module_exists = stripos($key,$patterns[1]); //primary module name.
419 $pattern_exists = stripos($key,$patterns[0]); //pattern provided by the user.
420 if ($module_exists !== false and $pattern_exists !== false) {
421 $GLOBALS['matching_keys']= array_merge(array(array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1)),$GLOBALS['matching_keys']);
424 if ($pattern_exists !== false) {
425 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);