]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SearchForm/SugarSpot.php
Release 6.4.0
[Github/sugarcrm.git] / include / SearchForm / SugarSpot.php
1 <?php
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.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38
39 /**
40  * Global search
41  * @api
42  */
43 class SugarSpot
44 {
45         /**
46      * searchAndDisplay
47      *
48          * Performs the search and returns the HTML widget containing the results
49          *
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
54          */
55         public function searchAndDisplay($query, $modules, $offset=-1)
56         {
57         global $current_user;
58                 $query_encoded = urlencode($query);
59             $results = $this->_performSearch($query, $modules, $offset);
60         $displayResults = array();
61         $displayMoreForModule = array();
62
63                 foreach($results as $m=>$data)
64         {
65                         if(empty($data['data']))
66             {
67                                 continue;
68                         }
69
70             $total = count($data['data']);
71                         $countRemaining = $data['pageData']['offsets']['total'] - $total;
72
73             if(isset($results[$m]['readAccess']) && !$results[$m]['readAccess'])
74             {
75                $displayTotal = $countRemaining > 0 ? ($total + $countRemaining) : $total;
76                $displayResults[$m]['link'] = array('total'=>$displayTotal, 'count_remaining'=>$countRemaining, 'query_encoded'=>$query_encoded);
77                continue;
78             }
79
80                         if($offset > 0)
81             {
82                 $countRemaining -= $offset;
83             }
84
85                         if($countRemaining > 0)
86             {
87                 $displayMoreForModule[$m] = array('query'=>$query,
88                                                   'offset'=>$data['pageData']['offsets']['next']++,
89                                                   'countRemaining'=>$countRemaining);
90                         }
91
92             foreach($data['data'] as $row)
93             {
94                                 $name = '';
95
96                 //Determine a name to use
97                                 if(!empty($row['NAME']))
98                 {
99                                         $name = $row['NAME'];
100                                 } else if(!empty($row['DOCUMENT_NAME'])) {
101                                     $name = $row['DOCUMENT_NAME'];
102                                 } else {
103                     $foundName = '';
104                                         foreach($row as $k=>$v){
105                                                 if(strpos($k, 'NAME') !== false)
106                         {
107                             if(!empty($row[$k]))
108                             {
109                                                             $name = $v;
110                                                             break;
111                             } else if(empty($foundName)) {
112                                 $foundName = $v;
113                             }
114                                                 }
115                                         }
116
117                                         if(empty($name))
118                                         {
119                                            $name = $foundName;
120                                         }
121                                 }
122
123                                 $displayResults[$m][$row['ID']] = $name;
124
125                     }
126
127
128
129         }
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'))
138         {
139             $template = 'custom/include/SearchForm/tpls/SugarSpot.tpl';
140         }
141         return $ss->fetch($template);
142         }
143
144         /**
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)
148          *
149          * @param  $moduleName String name of module to retrieve SearchFields entries for
150          * @return array of SearchFields
151          */
152         protected static function getSearchFields(
153             $moduleName
154             )
155         {
156                 $searchFields = array();
157
158                 if(file_exists("modules/{$moduleName}/metadata/SearchFields.php"))
159                 {
160                     require("modules/{$moduleName}/metadata/SearchFields.php");
161                 }
162
163                 if(file_exists("custom/modules/{$moduleName}/metadata/SearchFields.php"))
164                 {
165                     require("custom/modules/{$moduleName}/metadata/SearchFields.php");
166                 }
167
168                 return $searchFields;
169         }
170
171
172         /**
173          * Get count from query
174          * @param SugarBean $seed
175          * @param string $main_query
176          */
177         protected function _getCount($seed, $main_query)
178         {
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;
183         }
184
185         /**
186      * _performSearch
187      *
188          * Performs the search from the global search field.
189          *
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
193          * @return array
194          */
195         protected function _performSearch(
196             $query,
197             $modules,
198             $offset = -1
199             )
200         {
201         //Return an empty array if no query string is given
202             if(empty($query))
203         {
204             return array();
205         }
206
207                 $primary_module='';
208                 $results = array();
209                 require_once 'include/SearchForm/SearchForm2.php' ;
210                 $where = '';
211         $searchEmail = preg_match('/^([^%]|%)*@([^%]|%)*$/', $query);
212
213         $limit = !empty($GLOBALS['sugar_config']['max_spotresults_initial']) ? $GLOBALS['sugar_config']['max_spotresults_initial'] : 5;
214                 if($offset !== -1){
215                         $limit = !empty($GLOBALS['sugar_config']['max_spotresults_more']) ? $GLOBALS['sugar_config']['max_spotresults_more'] : 20;
216                 }
217         $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
218
219
220         global $current_user;
221
222             foreach($modules as $moduleName)
223         {
224                     if (empty($primary_module))
225                     {
226                         $primary_module=$moduleName;
227                     }
228
229                         $searchFields = SugarSpot::getSearchFields($moduleName);
230
231             //Continue on to the next module if no search fields found for module
232                         if (empty($searchFields[$moduleName]))
233                         {
234                                 continue;
235                         }
236
237                         $return_fields = array();
238                         $seed = SugarModule::get($moduleName)->loadBean();
239
240             //Continue on to next module if we don't have ListView ACLAccess for module
241             if(!$seed->ACLAccess('ListView')) {
242                continue;
243             }
244
245             $class = $seed->object_name;
246
247                         foreach($searchFields[$moduleName] as $k=>$v)
248             {
249                                 $keep = false;
250                                 $searchFields[$moduleName][$k]['value'] = $query;
251
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']))
254                 {
255                     continue;
256                 }
257
258                                 if(!empty($GLOBALS['dictionary'][$class]['unified_search'])){
259                                         if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
260
261                                                 if(isset($searchFields[$moduleName][$k]['db_field'])){
262                                                         foreach($searchFields[$moduleName][$k]['db_field'] as $field)
263                             {
264                                                                 if(!empty($GLOBALS['dictionary'][$class]['fields'][$field]['unified_search']))
265                                 {
266                                     if(isset($GLOBALS['dictionary'][$class]['fields'][$field]['type']))
267                                     {
268                                         if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$field]['type'], $query))
269                                         {
270                                             unset($searchFields[$moduleName][$k]);
271                                             continue;
272                                         }
273                                     } else {
274                                                                             $keep = true;
275                                     }
276                                                                 }
277                                                         } //foreach
278                                                 }
279                                                 if(!$keep){
280                                                         if(strpos($k,'email') === false || !$searchEmail) {
281                                                                 unset($searchFields[$moduleName][$k]);
282                                                         }
283                                                 }
284                                         }else{
285                                             if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
286                                                 unset($searchFields[$moduleName][$k]);
287                                             }
288                                         }
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)
292                                         {
293                                            unset($searchFields[$moduleName][$k]);
294                                         }
295                                 }else if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$k]['type'], $query)){
296                     unset($searchFields[$moduleName][$k]);
297                                 }
298                         } //foreach
299
300             //If no search field criteria matched then continue to next module
301                         if (empty($searchFields[$moduleName]))
302             {
303                 continue;
304             }
305
306             //Variable used to store the "name" field displayed in results
307             $name_field = null;
308
309                         if(isset($seed->field_defs['name']))
310             {
311                             $return_fields['name'] = $seed->field_defs['name'];
312                 $name_field = 'name';
313                         }
314
315
316                         foreach($seed->field_defs as $k => $v)
317             {
318                             if(isset($seed->field_defs[$k]['type']) && ($seed->field_defs[$k]['type'] == 'name') && !isset($return_fields[$k]))
319                 {
320                                     $return_fields[$k] = $seed->field_defs[$k];
321                                 }
322                         }
323
324
325                         if(!isset($return_fields['name']))
326             {
327                             // if we couldn't find any name fields, try search fields that have name in it
328                             foreach($searchFields[$moduleName] as $k => $v)
329                 {
330                                 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
331                     {
332                                         $return_fields[$k] = $seed->field_defs[$k];
333                         $name_field = $k;
334                                         break;
335                                     }
336                             }
337                         }
338
339
340                         if(!isset($return_fields['name']))
341             {
342                             // last resort - any fields that have 'name' in their name
343                             foreach($seed->field_defs as $k => $v)
344                 {
345                     if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
346                     {
347                                         $return_fields[$k] = $seed->field_defs[$k];
348                                         $name_field = $k;
349                         break;
350                                     }
351                             }
352                         }
353
354
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");
358                             continue;
359                         }
360
361                         if(isset($return_fields['name']['fields']))
362             {
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)
365                 {
366                                 $return_fields[$field] = $seed->field_defs[$field];
367                             }
368                         } 
369
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() ;
373
374                         if(empty($where_clauses))
375             {
376                             continue;
377                         }
378                         if(count($where_clauses) > 1) {
379                             $query_parts =  array();
380
381                             $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
382                 $search_keys = array_keys($searchFields[$moduleName]);
383
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];
390                                 }
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'];
393                 }
394                 $main_query = "(".join(") UNION (", $query_parts).")";
395                         } else {
396                 foreach($searchFields[$moduleName] as $k=>$v){
397                     if(isset($seed->field_defs[$k])) {
398                                     $return_fields[$k] = $seed->field_defs[$k];
399                     }
400                             }
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'];
403                         }
404
405                         $totalCount = null;
406                     if($limit < -1) {
407                             $result = $seed->db->query($main_query);
408                     } else {
409                             if($limit == -1) {
410                                     $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
411                 }
412
413                 if($offset == 'end') {
414                             $totalCount = $this->_getCount($seed, $main_query);
415                             if($totalCount) {
416                             $offset = (floor(($totalCount -1) / $limit)) * $limit;
417                             } else {
418                                 $offset = 0;
419                             }
420                 }
421                 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
422                     }
423
424             $data = array();
425             $count = 0;
426             while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
427                         $temp = clone $seed;
428                             $temp->setupCustomFields($temp->module_dir);
429                                 $temp->loadFromRow($row);
430                                 $data[] = $temp->get_list_view_data($return_fields);
431                                 $count++;
432                     }
433
434                 $nextOffset = -1;
435                 $prevOffset = -1;
436                 $endOffset = -1;
437
438                 if($count >= $limit) {
439                         $nextOffset = $offset + $limit;
440                 }
441
442                 if($offset > 0) {
443                         $prevOffset = $offset - $limit;
444                         if($prevOffset < 0) $prevOffset = 0;
445                 }
446
447                 if( $count >= $limit && $totalCounted){
448                     if(!isset($totalCount)) {
449                             $totalCount  = $this->_getCount($seed, $main_query);
450                     }
451                 } else {
452                     $totalCount = $count + $offset;
453                 }
454
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);
457
458             $readAccess = true;
459
460                     $results[$moduleName] = array("data"=>$data, "pageData"=>$pageData, "readAccess"=>$readAccess);
461
462                 } //foreach
463
464         return $results;
465         }
466
467
468         /**
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.
471      */
472     protected function _searchKeys(
473         $item1,
474         $key,
475         $patterns
476         )
477     {
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));
481         }
482
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']);
487         }
488         else {
489             if ($pattern_exists !== false) {
490                 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);
491             }
492         }
493     }
494
495
496     /**
497      * filterSearchType
498      *
499      * This is a private function to determine if the search type field should be filtered out based on the query string value
500      * 
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
504      */
505     protected function filterSearchType($type, $query)
506     {
507         switch($type)
508         {
509             case 'id':
510             case 'date':
511             case 'datetime':
512             case 'bool':
513                 return false;
514                 break;
515             case 'int':
516                 if(!is_numeric($query)) {
517                    return false;
518                 }
519                 break;
520             case 'phone':
521             case 'decimal':
522             case 'float':
523                 if(!preg_match('/[0-9]/', $query))
524                 {
525                    return false;
526                 }
527                 break;
528         }
529         return true;
530     }
531
532 }