]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SearchForm/SugarSpot.php
Release 6.4.1
[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-2012 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
260                                         if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
261
262                                                 if(isset($searchFields[$moduleName][$k]['db_field'])){
263                                                         foreach($searchFields[$moduleName][$k]['db_field'] as $field)
264                             {
265                                                                 if(!empty($GLOBALS['dictionary'][$class]['fields'][$field]['unified_search']))
266                                 {
267                                     if(isset($GLOBALS['dictionary'][$class]['fields'][$field]['type']))
268                                     {
269                                         if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$field]['type'], $query))
270                                         {
271                                             unset($searchFields[$moduleName][$k]);
272                                             continue;
273                                         }
274                                     }
275
276                                     $keep = true;
277                                                                 }
278                                                         } //foreach
279                                                 }
280                                                 if(!$keep){
281                                                         if(strpos($k,'email') === false || !$searchEmail) {
282                                                                 unset($searchFields[$moduleName][$k]);
283                                                         }
284                                                 }
285                                         }else{
286                                             if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
287                                                 unset($searchFields[$moduleName][$k]);
288                                             }
289                                         }
290                                 }else if(empty($GLOBALS['dictionary'][$class]['fields'][$k]) ){
291                                         //If module did not have unified_search defined, then check the exception for an email search before we unset
292                                         if(strpos($k,'email') === false || !$searchEmail)
293                                         {
294                                            unset($searchFields[$moduleName][$k]);
295                                         }
296                                 }else if(!$this->filterSearchType($GLOBALS['dictionary'][$class]['fields'][$k]['type'], $query)){
297                     unset($searchFields[$moduleName][$k]);
298                                 }
299                         } //foreach
300
301             //If no search field criteria matched then continue to next module
302                         if (empty($searchFields[$moduleName]))
303             {
304                 continue;
305             }
306
307             //Variable used to store the "name" field displayed in results
308             $name_field = null;
309
310                         if(isset($seed->field_defs['name']))
311             {
312                             $return_fields['name'] = $seed->field_defs['name'];
313                 $name_field = 'name';
314                         }
315
316
317                         foreach($seed->field_defs as $k => $v)
318             {
319                             if(isset($seed->field_defs[$k]['type']) && ($seed->field_defs[$k]['type'] == 'name') && !isset($return_fields[$k]))
320                 {
321                                     $return_fields[$k] = $seed->field_defs[$k];
322                                 }
323                         }
324
325
326                         if(!isset($return_fields['name']))
327             {
328                             // if we couldn't find any name fields, try search fields that have name in it
329                             foreach($searchFields[$moduleName] as $k => $v)
330                 {
331                                 if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
332                     {
333                                         $return_fields[$k] = $seed->field_defs[$k];
334                         $name_field = $k;
335                                         break;
336                                     }
337                             }
338                         }
339
340
341                         if(!isset($return_fields['name']))
342             {
343                             // last resort - any fields that have 'name' in their name
344                             foreach($seed->field_defs as $k => $v)
345                 {
346                     if(strpos($k, 'name') != -1 && isset($seed->field_defs[$k]) && !isset($seed->field_defs[$k]['source']))
347                     {
348                                         $return_fields[$k] = $seed->field_defs[$k];
349                                         $name_field = $k;
350                         break;
351                                     }
352                             }
353                         }
354
355
356                         if(empty($name_field)) {
357                             // FAIL: couldn't find a name field to display a result label
358                             $GLOBALS['log']->error("Unable to find name field for module $moduleName");
359                             continue;
360                         }
361
362                         if(isset($return_fields['name']['fields']))
363             {
364                             // some names are composite name fields (e.g. last_name, first_name), add these to return list
365                             foreach($return_fields['name']['fields'] as $field)
366                 {
367                                 $return_fields[$field] = $seed->field_defs[$field];
368                             }
369                         } 
370
371                         $searchForm = new SearchForm ( $seed, $moduleName ) ;
372                         $searchForm->setup (array ( $moduleName => array() ) , $searchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
373                         $where_clauses = $searchForm->generateSearchWhere() ;
374
375                         if(empty($where_clauses))
376             {
377                             continue;
378                         }
379                         if(count($where_clauses) > 1) {
380                             $query_parts =  array();
381
382                             $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
383                 $search_keys = array_keys($searchFields[$moduleName]);
384
385                 foreach($where_clauses as $n => $clause) {
386                                 $allfields = $return_fields;
387                                 $skey = $search_keys[$n];
388                                 if(isset($seed->field_defs[$skey])) {
389                         // Joins for foreign fields aren't produced unless the field is in result, hence the merge
390                                     $allfields[$skey] = $seed->field_defs[$skey];
391                                 }
392                     $ret_array = $seed->create_new_list_query('', $clause, $allfields, array(), 0, '', true, $seed, true);
393                     $query_parts[] = $ret_array_start['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
394                 }
395                 $main_query = "(".join(") UNION (", $query_parts).")";
396                         } else {
397                 foreach($searchFields[$moduleName] as $k=>$v){
398                     if(isset($seed->field_defs[$k])) {
399                                     $return_fields[$k] = $seed->field_defs[$k];
400                     }
401                             }
402                             $ret_array = $seed->create_new_list_query('', $where_clauses[0], $return_fields, array(), 0, '', true, $seed, true);
403                         $main_query = $ret_array['select'] . $ret_array['from'] . $ret_array['where'] . $ret_array['order_by'];
404                         }
405
406                         $totalCount = null;
407                     if($limit < -1) {
408                             $result = $seed->db->query($main_query);
409                     } else {
410                             if($limit == -1) {
411                                     $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
412                 }
413
414                 if($offset == 'end') {
415                             $totalCount = $this->_getCount($seed, $main_query);
416                             if($totalCount) {
417                             $offset = (floor(($totalCount -1) / $limit)) * $limit;
418                             } else {
419                                 $offset = 0;
420                             }
421                 }
422                 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
423                     }
424
425             $data = array();
426             $count = 0;
427             while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
428                         $temp = clone $seed;
429                             $temp->setupCustomFields($temp->module_dir);
430                                 $temp->loadFromRow($row);
431                                 $data[] = $temp->get_list_view_data($return_fields);
432                                 $count++;
433                     }
434
435                 $nextOffset = -1;
436                 $prevOffset = -1;
437                 $endOffset = -1;
438
439                 if($count >= $limit) {
440                         $nextOffset = $offset + $limit;
441                 }
442
443                 if($offset > 0) {
444                         $prevOffset = $offset - $limit;
445                         if($prevOffset < 0) $prevOffset = 0;
446                 }
447
448                 if( $count >= $limit && $totalCounted){
449                     if(!isset($totalCount)) {
450                             $totalCount  = $this->_getCount($seed, $main_query);
451                     }
452                 } else {
453                     $totalCount = $count + $offset;
454                 }
455
456             $pageData['offsets'] = array( 'current'=>$offset, 'next'=>$nextOffset, 'prev'=>$prevOffset, 'end'=>$endOffset, 'total'=>$totalCount, 'totalCounted'=>$totalCounted);
457                     $pageData['bean'] = array('objectName' => $seed->object_name, 'moduleDir' => $seed->module_dir);
458
459             $readAccess = true;
460
461                     $results[$moduleName] = array("data"=>$data, "pageData"=>$pageData, "readAccess"=>$readAccess);
462
463                 } //foreach
464
465         return $results;
466         }
467
468
469         /**
470      * Function used to walk the array and find keys that map the queried string.
471      * if both the pattern and module name is found the promote the string to thet top.
472      */
473     protected function _searchKeys(
474         $item1,
475         $key,
476         $patterns
477         )
478     {
479         //make the module name singular....
480         if ($patterns[1][strlen($patterns[1])-1] == 's') {
481             $patterns[1]=substr($patterns[1],0,(strlen($patterns[1])-1));
482         }
483
484         $module_exists = stripos($key,$patterns[1]); //primary module name.
485         $pattern_exists = stripos($key,$patterns[0]); //pattern provided by the user.
486         if ($module_exists !== false and $pattern_exists !== false)  {
487             $GLOBALS['matching_keys']= array_merge(array(array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1)),$GLOBALS['matching_keys']);
488         }
489         else {
490             if ($pattern_exists !== false) {
491                 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);
492             }
493         }
494     }
495
496
497     /**
498      * filterSearchType
499      *
500      * This is a private function to determine if the search type field should be filtered out based on the query string value
501      * 
502      * @param String $type The string value of the field type (e.g. phone, date, datetime, int, etc.)
503      * @param String $query The search string value sent from the global search
504      * @return boolean True if the search type fits the query string value; false otherwise
505      */
506     protected function filterSearchType($type, $query)
507     {
508         switch($type)
509         {
510             case 'id':
511             case 'date':
512             case 'datetime':
513             case 'bool':
514                 return false;
515                 break;
516             case 'int':
517                 if(!is_numeric($query)) {
518                    return false;
519                 }
520                 break;
521             case 'phone':
522                 //For a phone search we require at least three digits
523                 if(!preg_match('/[0-9]{3,}/', $query))
524                 {
525                     return false;
526                 }
527             case 'decimal':
528             case 'float':
529                 if(!preg_match('/[0-9]/', $query))
530                 {
531                    return false;
532                 }
533                 break;
534         }
535         return true;
536     }
537
538 }