]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SearchForm/SugarSpot.php
Release 6.2.0beta4
[Github/sugarcrm.git] / include / SearchForm / SugarSpot.php
1 <?php
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.
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 class SugarSpot
40 {
41         /**
42          * Performs the search and returns the HTML widget containing the results
43          *
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
48          */
49         public function searchAndDisplay(
50             $query,
51             $modules,
52             $offset = -1
53             )
54         {
55                 $query_encoded = urlencode($query);
56             $results = $this->_performSearch($query, $modules, $offset);
57
58                 $str = '<div id="SpotResults">';
59
60                 $actions=0;
61                 $foundData = false;
62                 foreach($results as $m=>$data){
63                         if(empty($data['data'])){
64                                 continue;
65                         }
66
67                         $foundData = true;
68
69                         $countRemaining = $data['pageData']['offsets']['total'] - count($data['data']);
70                         if($offset > 0) $countRemaining -= $offset;
71                         $more = '';
72                         $data['pageData']['offsets']['next']++;
73                         if($countRemaining > 0){
74                                 $more = <<<EOHTML
75 <small class='more' onclick="DCMenu.spotZoom('$query', '$m','{$data['pageData']['offsets']['next']}' )">($countRemaining {$GLOBALS['app_strings']['LBL_SEARCH_MORE']})</small>
76 EOHTML;
77                         }
78
79                         $modDisplayString = $m;
80                         if(isset($GLOBALS['app_list_strings']['moduleList'][$m]))
81                             $modDisplayString = $GLOBALS['app_list_strings']['moduleList'][$m];
82
83                         $str.= "<div>{$modDisplayString} $more</div>";
84                         $str.= '<ul>';
85                         foreach($data['data'] as $row){
86                                 $name = '';
87                                 
88                                 if(!empty($row['NAME'])){
89                                         $name = $row['NAME'];
90                                 } else if(!empty($row['DOCUMENT_NAME'])) {
91                                     $name = $row['DOCUMENT_NAME'];
92                                 } else {
93                                         foreach($row as $k=>$v){
94                                                 if(strpos($k, 'NAME') !== false && !empty($row[$k])){
95                                                         $name = $v;
96                                                         break;
97                                                 }
98                                         }
99
100                                         if(empty($name))
101                                         {
102                                                 foreach($row as $k=>$v){
103                                                         if(strpos($k, 'NAME') !== false){
104                                                                 $name = $v;
105                                                                 break;
106                                                         }
107                                                 }
108                                         }
109                                 }
110
111                                     $str .= <<<EOHTML
112 <li><a href="index.php?module={$data['pageData']['bean']['moduleDir']}&action=DetailView&record={$row['ID']}">$name</a></li>
113 EOHTML;
114                         }
115                         $str.= '</ul>';
116                 }
117
118                 if($foundData)
119                 {
120                         $str = <<<EOHTML
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>
122                         <br><br>
123                         {$str}
124                         </div>
125                         <p>
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>
127 EOHTML;
128                 } else {
129                         $str .= $GLOBALS['app_strings']['LBL_EMAIL_SEARCH_NO_RESULTS'];
130                         $str .= <<<EOHTML
131                         </div>
132                         <p>
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>
134 EOHTML;
135
136                 }
137
138                 return $str;
139         }
140
141         /**
142          * Returns the array containing the $searchFields for a module
143          *
144          * @param  $moduleName string
145          * @return array
146          */
147         protected static function getSearchFields(
148             $moduleName
149             )
150         {
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;
159                 } else {
160                         return array();
161                 }
162         }
163
164         /**
165          * Get count from query
166          * @param SugarBean $seed
167          * @param string $main_query
168          */
169         protected function _getCount($seed, $main_query)
170         {
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;
175         }
176
177         /**
178          * Performs the search
179          *
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
183          * @return array
184          */
185         protected function _performSearch(
186             $query,
187             $modules,
188             $offset = -1
189             )
190         {
191             if(empty($query)) return array();
192                 $primary_module='';
193                 $results = array();
194                 require_once 'include/SearchForm/SearchForm2.php' ;
195                 $where = '';
196         $searchEmail = preg_match('/^([^%]|%)*@([^%]|%)*$/', $query);
197
198         $limit = ( !empty($GLOBALS['sugar_config']['max_spotresults_initial']) ? $GLOBALS['sugar_config']['max_spotresults_initial'] : 5 );
199                 if($offset !== -1){
200                         $limit = ( !empty($GLOBALS['sugar_config']['max_spotresults_more']) ? $GLOBALS['sugar_config']['max_spotresults_more'] : 20 );
201                 }
202         $totalCounted = empty($GLOBALS['sugar_config']['disable_count_query']);
203
204             foreach($modules as $moduleName){
205                     if (empty($primary_module)) $primary_module=$moduleName;
206
207                         $searchFields = SugarSpot::getSearchFields($moduleName);
208
209                         if (empty($searchFields[$moduleName])) continue;
210
211                         $class = $GLOBALS['beanList'][$moduleName];
212                         $return_fields = array();
213                         $seed = new $class();
214             if(!$seed->ACLAccess('ListView')) continue;
215
216                         if ($class == 'aCase') {
217                             $class = 'Case';
218                         }
219                         
220                         foreach($searchFields[$moduleName] as $k=>$v){
221                                 $keep = false;
222                                 $searchFields[$moduleName][$k]['value'] = $query;
223
224                                 if(!empty($GLOBALS['dictionary'][$class]['unified_search'])){
225                                         if(empty($GLOBALS['dictionary'][$class]['fields'][$k]['unified_search'])){
226
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'])){
230                                                                         $keep = true;
231                                                                 }
232                                                         }
233                                                 }
234                                                 if(!$keep){
235                                                         if(strpos($k,'email') === false || !$searchEmail) {
236                                                                 unset($searchFields[$moduleName][$k]);
237                                                         }
238                                                 }
239                                         }else{
240                                             if($GLOBALS['dictionary'][$class]['fields'][$k]['type'] == 'int' && !is_numeric($query)) {
241                                                 unset($searchFields[$moduleName][$k]);
242                                             }
243                                         }
244                                 }else if(empty($GLOBALS['dictionary'][$class]['fields'][$k]) ){
245                                         unset($searchFields[$moduleName][$k]);
246                                 }else{
247                                         switch($GLOBALS['dictionary'][$class]['fields'][$k]['type']){
248                                                 case 'id':
249                                                 case 'date':
250                                                 case 'datetime':
251                                                 case 'bool':
252                                                         unset($searchFields[$moduleName][$k]);
253                                                         break;
254                                                 case 'int':
255                                                     if(!is_numeric($query)) {
256                                                         unset($searchFields[$moduleName][$k]);
257                                                         break;
258                                                     }
259                                         }
260                                 }
261                         }
262
263                         if (empty($searchFields[$moduleName])) continue;
264
265                         if(isset($seed->field_defs['name'])) {
266                             $return_fields['name'] = $seed->field_defs['name'];
267                         }
268
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];
272                                 }
273                         }
274
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];
281                                         break;
282                                     }
283                             }
284                         }
285
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];
292                                         break;
293                                     }
294                             }
295                         }
296
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");
300                             continue;
301                         }
302
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];
307                             }
308                         }
309
310
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() ;
314                         
315                         if(empty($where_clauses)) {
316                             continue;
317                         }
318                         if(count($where_clauses) > 1) {
319                             $query_parts =  array();
320
321                             $ret_array_start = $seed->create_new_list_query('', '', $return_fields, array(), 0, '', true, $seed, true);
322                 $search_keys = array_keys($searchFields[$moduleName]);
323
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];
330                                 }
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'];
333                 }
334                 $main_query = "(".join(") UNION (", $query_parts).")";
335                         } else {
336                 foreach($searchFields[$moduleName] as $k=>$v){
337                     if(isset($seed->field_defs[$k])) {
338                                     $return_fields[$k] = $seed->field_defs[$k];
339                     }
340                             }
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'];
343                         }
344
345                         $totalCount = null;
346                     if($limit < -1) {
347                             $result = $seed->db->query($main_query);
348                     } else {
349                             if($limit == -1) {
350                                     $limit = $GLOBALS['sugar_config']['list_max_entries_per_page'];
351                 }
352
353                 if($offset == 'end') {
354                             $totalCount = $this->_getCount($seed, $main_query);
355                             if($totalCount) {
356                             $offset = (floor(($totalCount -1) / $limit)) * $limit;
357                             } else {
358                                 $offset = 0;
359                             }
360                 }
361                 $result = $seed->db->limitQuery($main_query, $offset, $limit + 1);
362                     }
363
364             $data = array();
365             $count = 0;
366             while($count < $limit && ($row = $seed->db->fetchByAssoc($result))) {
367                         $temp = clone $seed;
368                             $temp->setupCustomFields($temp->module_dir);
369                                 $temp->loadFromRow($row);
370                                 $data[] = $temp->get_list_view_data($return_fields);
371                                 $count++;
372                     }
373
374                 $nextOffset = -1;
375                 $prevOffset = -1;
376                 $endOffset = -1;
377
378                 if($count >= $limit) {
379                         $nextOffset = $offset + $limit;
380                 }
381
382                 if($offset > 0) {
383                         $prevOffset = $offset - $limit;
384                         if($prevOffset < 0) $prevOffset = 0;
385                 }
386
387                 if( $count >= $limit && $totalCounted){
388                     if(!isset($totalCount)) {
389                             $totalCount  = $this->_getCount($seed, $main_query);
390                     }
391                 } else {
392                     $totalCount = $count + $offset;
393                 }
394
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);
397
398                     $results[$moduleName] = array("data" => $data, "pageData" => $pageData);
399                 }
400         return $results;
401         }
402
403         /**
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.
406      */
407     protected function _searchKeys(
408         $item1,
409         $key,
410         $patterns
411         )
412     {
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));
416         }
417
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']);
422         }
423         else {
424             if ($pattern_exists !== false) {
425                 $GLOBALS['matching_keys'][]=array('NAME'=>$key, 'ID'=>$key, 'VALUE'=>$item1);
426             }
427         }
428     }
429 }