]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - include/SearchForm/SearchForm2.php
Release 6.5.0beta2
[Github/sugarcrm.git] / include / SearchForm / SearchForm2.php
1 <?php
2 /*********************************************************************************
3  * SugarCRM Community Edition is a customer relationship management program developed by
4  * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
5  * 
6  * This program is free software; you can redistribute it and/or modify it under
7  * the terms of the GNU Affero General Public License version 3 as published by the
8  * Free Software Foundation with the addition of the following permission added
9  * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
10  * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
11  * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
12  * 
13  * This program is distributed in the hope that it will be useful, but WITHOUT
14  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
15  * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
16  * details.
17  * 
18  * You should have received a copy of the GNU Affero General Public License along with
19  * this program; if not, see http://www.gnu.org/licenses or write to the Free
20  * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
21  * 02110-1301 USA.
22  * 
23  * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
24  * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
25  * 
26  * The interactive user interfaces in modified source and object code versions
27  * of this program must display Appropriate Legal Notices, as required under
28  * Section 5 of the GNU Affero General Public License version 3.
29  * 
30  * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
31  * these Appropriate Legal Notices must retain the display of the "Powered by
32  * SugarCRM" logo. If the display of the logo is not reasonably feasible for
33  * technical reasons, the Appropriate Legal Notices must display the words
34  * "Powered by SugarCRM".
35  ********************************************************************************/
36
37
38 require_once('include/tabs.php');
39 require_once('include/ListView/ListViewSmarty.php');
40
41 require_once('include/TemplateHandler/TemplateHandler.php');
42 require_once('include/EditView/EditView2.php');
43 require_once('include/FileLocator/FileLocator.php');
44
45
46  class SearchForm extends EditView{
47         var $seed = null;
48         var $module = '';
49         var $action = 'index';
50         var $searchdefs = array();
51         var $listViewDefs = array();
52         var $lv;
53         var $th;
54     var $tpl;
55     var $view = 'SearchForm';
56     var $displayView = 'basic_search';
57     var $formData;
58     var $fieldDefs;
59     var $customFieldDefs;
60     var $tabs;
61     var $parsedView = 'basic';
62     //may remove
63     var $searchFields;
64     var $displaySavedSearch = true;
65     //show the advanced tab
66     var $showAdvanced = true;
67     //show the basic tab
68     var $showBasic = true;
69     //array of custom tab to show declare in searchdefs (no custom tab if false)
70     var $showCustom = false;
71     // nb of tab to show
72     var $nbTabs = 0;
73     // hide saved searches drop and down near the search button
74     var $showSavedSearchesOptions = true;
75
76     var $displayType = 'searchView';
77
78     /**
79      * @var FileLocatorInterface
80      */
81     private $fileLocator;
82
83     /**
84      * @var array
85      */
86     private $options;
87
88         function SearchForm($seed, $module, $action = 'index', $options = array()){
89                 $this->th = new TemplateHandler();
90                 $this->th->loadSmarty();
91                 $this->seed = $seed;
92                 $this->module = $module;
93                 $this->action = $action;
94         $this->tabs = array(array('title'  => $GLOBALS['app_strings']['LNK_BASIC_SEARCH'],
95                             'link'   => $module . '|basic_search',
96                             'key'    => $module . '|basic_search',
97                             'name'   => 'basic',
98                             'displayDiv'   => ''),
99                       array('title'  => $GLOBALS['app_strings']['LNK_ADVANCED_SEARCH'],
100                             'link'   => $module . '|advanced_search',
101                             'key'    => $module . '|advanced_search',
102                             'name'   => 'advanced',
103                             'displayDiv'   => 'display:none'),
104                        );
105         $this->searchColumns = array () ;
106         $this->setOptions($options);
107     }
108
109     public function getFileLocator()
110     {
111         if (!$this->fileLocator) {
112             $ref = new ReflectionClass($this->options['locator_class']);
113             $this->fileLocator = $ref->newInstanceArgs($this->options['locator_class_params']);
114         }
115
116         return $this->fileLocator;
117     }
118
119     public function setOptions($options)
120     {
121         $defaults = array(
122             'locator_class' => 'FileLocator',
123             'locator_class_params' => array(
124                 array(
125                     'custom/modules/' . $this->module . '/tpls/SearchForm',
126                     'modules/' . $this->module . '/tpls/SearchForm',
127                     'custom/include/SearchForm/tpls',
128                     'include/SearchForm/tpls'
129                 )
130             )
131         );
132
133         $this->options = empty($options) ? $defaults : $options;
134     }
135
136         function setup($searchdefs, $searchFields = array(), $tpl, $displayView = 'basic_search', $listViewDefs = array()){
137                 $this->searchdefs =  $searchdefs[$this->module];
138                 $this->tpl = $tpl;
139                 //used by advanced search
140                 $this->listViewDefs = $listViewDefs;
141                 $this->displayView = $displayView;
142                 $this->view = $this->view.'_'.$displayView;
143                 $tokens = explode('_', $this->displayView);
144                 $this->parsedView = $tokens[0];
145                 if($this->displayView != 'saved_views'){
146                         $this->_build_field_defs();
147                 }
148
149         $this->searchFields = $searchFields[$this->module];
150
151         // Setup the tab array.
152         $this->tabs = array();
153         if($this->showBasic){
154             $this->nbTabs++;
155             $this->tabs[]=array('title'  => $GLOBALS['app_strings']['LNK_BASIC_SEARCH'],
156                                 'link'   => $this->module . '|basic_search',
157                                 'key'    => $this->module . '|basic_search',
158                                 'name'   => 'basic',
159                                 'displayDiv' => '');
160         }
161         if($this->showAdvanced){
162             $this->nbTabs++;
163             $this->tabs[]=array('title'  => $GLOBALS['app_strings']['LNK_ADVANCED_SEARCH'],
164                                 'link'   => $this->module . '|advanced_search',
165                                 'key'    => $this->module . '|advanced_search',
166                                 'name'   => 'advanced',
167                                 'displayDiv' => 'display:none');
168         }
169         if(isset($this->showCustom) && is_array($this->showCustom)){
170             foreach($this->showCustom as $v){
171                 $this->nbTabs++;
172                 $this->tabs[]=array('title'  => $GLOBALS['app_strings']["LNK_" . strtoupper($v)],
173                     'link'   => $this->module . '|' . $v,
174                     'key'    => $this->module . '|' . $v,
175                     'name'   => str_replace('_search','',$v),
176                     'displayDiv' => 'display:none',);
177             }
178         }
179         }
180
181         function display($header = true){
182         global $theme, $timedate, $current_user;
183                 $header_txt = '';
184                 $footer_txt = '';
185                 $return_txt = '';
186                 $this->th->ss->assign('module', $this->module);
187                 $this->th->ss->assign('action', $this->action);
188                 $this->th->ss->assign('displayView', $this->displayView);
189                 $this->th->ss->assign('APP', $GLOBALS['app_strings']);
190                 //Show the tabs only if there is more than one
191                 if($this->nbTabs>1){
192                     $this->th->ss->assign('TABS', $this->_displayTabs($this->module . '|' . $this->displayView));
193                 }
194                 $this->th->ss->assign('searchTableColumnCount',
195                     ((isset($this->searchdefs['templateMeta']['maxColumns']) ? $this->searchdefs['templateMeta']['maxColumns'] : 2) * 2 ) - 1);
196                 $this->th->ss->assign('fields', $this->fieldDefs);
197                 $this->th->ss->assign('customFields', $this->customFieldDefs);
198                 $this->th->ss->assign('formData', $this->formData);
199         $time_format = $timedate->get_user_time_format();
200         $this->th->ss->assign('TIME_FORMAT', $time_format);
201         $this->th->ss->assign('USER_DATEFORMAT', $timedate->get_user_date_format());
202         $this->th->ss->assign('CALENDAR_FDOW', $current_user->get_first_day_of_week());
203
204         $date_format = $timedate->get_cal_date_format();
205         $time_separator = ":";
206         if(preg_match('/\d+([^\d])\d+([^\d]*)/s', $time_format, $match)) {
207            $time_separator = $match[1];
208         }
209         // Create Smarty variables for the Calendar picker widget
210         $t23 = strpos($time_format, '23') !== false ? '%H' : '%I';
211         if(!isset($match[2]) || $match[2] == '') {
212           $this->th->ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M");
213         } else {
214           $pm = $match[2] == "pm" ? "%P" : "%p";
215           $this->th->ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M" . $pm);
216         }
217         $this->th->ss->assign('TIME_SEPARATOR', $time_separator);
218
219         //Show and hide the good tab form
220         foreach($this->tabs as $tabkey=>$viewtab){
221             $viewName=str_replace(array($this->module . '|','_search'),'',$viewtab['key']);
222             if(strpos($this->view,$viewName)!==false){
223                 $this->tabs[$tabkey]['displayDiv']='';
224                 //if this is advanced tab, use form with saved search sub form built in
225                 if($viewName=='advanced'){
226                     $this->tpl = 'SearchFormGenericAdvanced.tpl';
227                     if ($this->action =='ListView') {
228                         $this->th->ss->assign('DISPLAY_SEARCH_HELP', true);
229                     }
230                     $this->th->ss->assign('DISPLAY_SAVED_SEARCH', $this->displaySavedSearch);
231                     $this->th->ss->assign('SAVED_SEARCH', $this->displaySavedSearch());
232                     //this determines whether the saved search subform should be rendered open or not
233                     if(isset($_REQUEST['showSSDIV']) && $_REQUEST['showSSDIV']=='yes'){
234                         $this->th->ss->assign('SHOWSSDIV', 'yes');
235                         $this->th->ss->assign('DISPLAYSS', '');
236                     }else{
237                         $this->th->ss->assign('SHOWSSDIV', 'no');
238                         $this->th->ss->assign('DISPLAYSS', 'display:none');
239                     }
240                 }
241             }else{
242                 $this->tabs[$tabkey]['displayDiv']='display:none';
243             }
244
245         }
246
247         $this->th->ss->assign('TAB_ARRAY', $this->tabs);
248
249         $totalWidth = 0;
250         if ( isset($this->searchdefs['templateMeta']['widths'])
251                 && isset($this->searchdefs['templateMeta']['maxColumns'])) {
252             $totalWidth = ( $this->searchdefs['templateMeta']['widths']['label'] +
253                                 $this->searchdefs['templateMeta']['widths']['field'] ) *
254                                 $this->searchdefs['templateMeta']['maxColumns'];
255             // redo the widths in case they are too big
256             if ( $totalWidth > 100 ) {
257                 $resize = 100 / $totalWidth;
258                 $this->searchdefs['templateMeta']['widths']['label'] =
259                     $this->searchdefs['templateMeta']['widths']['label'] * $resize;
260                 $this->searchdefs['templateMeta']['widths']['field'] =
261                     $this->searchdefs['templateMeta']['widths']['field'] * $resize;
262             }
263         }
264         $this->th->ss->assign('templateMeta', $this->searchdefs['templateMeta']);
265         $this->th->ss->assign('HAS_ADVANCED_SEARCH', !empty($this->searchdefs['layout']['advanced_search']));
266         $this->th->ss->assign('displayType', $this->displayType);
267         // return the form of the shown tab only
268         if($this->showSavedSearchesOptions){
269             $this->th->ss->assign('SAVED_SEARCHES_OPTIONS', $this->displaySavedSearchSelect());
270         }
271         if ($this->module == 'Documents'){
272             $this->th->ss->assign('DOCUMENTS_MODULE', true);
273         }
274         $return_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchForm_'.$this->parsedView, $this->getFileLocator()->locate($this->tpl));
275         if($header){
276                         $this->th->ss->assign('return_txt', $return_txt);
277                         $header_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormHeader', $this->getFileLocator()->locate('header.tpl'));
278             //pass in info to render the select dropdown below the form
279             $footer_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormFooter', $this->getFileLocator()->locate('footer.tpl'));
280                         $return_txt = $header_txt.$footer_txt;
281                 }
282                 return $return_txt;
283         }
284
285   function displaySavedSearch(){
286         $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
287         return $savedSearch->getForm($this->module, false);
288     }
289
290
291   function displaySavedSearchSelect(){
292         $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
293         return $savedSearch->getSelect($this->module);
294     }
295
296
297
298         /**
299      * displays the tabs (top of the search form)
300      *
301      * @param string $currentKey key in $this->tabs to show as the current tab
302      *
303      * @return string html
304      */
305     function _displayTabs($currentKey)
306     {
307         if(isset($_REQUEST['saved_search_select']) && $_REQUEST['saved_search_select']!='_none') {
308             $saved_search=loadBean('SavedSearch');
309             $saved_search->retrieveSavedSearch($_REQUEST['saved_search_select']);
310         }
311
312         $str = '<script>';
313         if(!empty($_REQUEST['displayColumns']))
314             $str .= 'SUGAR.savedViews.displayColumns = "' . $_REQUEST['displayColumns'] . '";';
315         elseif(isset($saved_search->contents['displayColumns']) && !empty($saved_search->contents['displayColumns']))
316             $str .= 'SUGAR.savedViews.displayColumns = "' . $saved_search->contents['displayColumns'] . '";';
317         if(!empty($_REQUEST['hideTabs']))
318             $str .= 'SUGAR.savedViews.hideTabs = "' . $_REQUEST['hideTabs'] . '";';
319         elseif(isset($saved_search->contents['hideTabs']) && !empty($saved_search->contents['hideTabs']))
320             $str .= 'SUGAR.savedViews.hideTabs = "' . $saved_search->contents['hideTabs'] . '";';
321         if(!empty($_REQUEST['orderBy']))
322             $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $_REQUEST['orderBy'] . '";';
323         elseif(isset($saved_search->contents['orderBy']) && !empty($saved_search->contents['orderBy']))
324             $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $saved_search->contents['orderBy'] . '";';
325         if(!empty($_REQUEST['sortOrder']))
326             $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $_REQUEST['sortOrder'] . '";';
327         elseif(isset($saved_search->contents['sortOrder']) && !empty($saved_search->contents['sortOrder']))
328             $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $saved_search->contents['sortOrder'] . '";';
329
330         $str .= '</script>';
331
332         return $str;
333     }
334
335         /*
336          * Generate the data
337          */
338         function _build_field_defs(){
339                 $this->formData = array();
340                 $this->fieldDefs = array();
341                 foreach($this->searchdefs['layout'][$this->displayView] as $data){
342                         if(is_array($data)){
343                                 //Fields may be listed but disabled so that when they are enabled, they have the correct custom display data.
344                                 if (isset($data['enabled']) && $data['enabled'] == false)
345                                         continue;
346                                 $data['name'] = $data['name'].'_'.$this->parsedView;
347                                 $this->formData[] = array('field' => $data);
348                                 $this->fieldDefs[$data['name']]= $data;
349                         } else {
350                                 $this->formData[] = array('field' => array('name'=>$data.'_'.$this->parsedView));
351                         }
352                 }
353
354                 if($this->seed){
355                         $this->seed->fill_in_additional_detail_fields();
356                         // hack to make the employee status field for the Users/Employees module display correctly
357                         if($this->seed->object_name == 'Employee' || $this->seed->object_name == 'User'){
358                 $this->seed->field_defs['employee_status']['type'] = 'enum';
359                 $this->seed->field_defs['employee_status']['massupdate'] = true;
360                 $this->seed->field_defs['employee_status']['options'] = 'employee_status_dom';
361                 unset($this->seed->field_defs['employee_status']['function']);
362             }
363
364                 foreach($this->seed->toArray() as $name => $value) {
365                     $fvName = $name.'_'.$this->parsedView;
366                 if(!empty($this->fieldDefs[$fvName]))
367                         $this->fieldDefs[$fvName] = array_merge($this->seed->field_defs[$name], $this->fieldDefs[$fvName]);
368                     else{
369                         $this->fieldDefs[$fvName] = $this->seed->field_defs[$name];
370                         $this->fieldDefs[$fvName]['name'] = $this->fieldDefs[$fvName]['name'].'_'.$this->parsedView;
371                     }
372
373                     if(isset($this->fieldDefs[$fvName]['type']) && $this->fieldDefs[$fvName]['type'] == 'relate') {
374                         if(isset($this->fieldDefs[$fvName]['id_name'])) {
375                            $this->fieldDefs[$fvName]['id_name'] .= '_'.$this->parsedView;
376                         }
377                     }
378
379                     if(isset($this->fieldDefs[$fvName]['options']) && isset($GLOBALS['app_list_strings'][$this->fieldDefs[$fvName]['options']]))
380                 {
381                         // fill in enums
382                     $this->fieldDefs[$fvName]['options'] = $GLOBALS['app_list_strings'][$this->fieldDefs[$fvName]['options']];
383                     //Hack to add blanks for parent types on search views
384                     if ($this->fieldDefs[$fvName]['type'] == "parent_type" || $this->fieldDefs[$fvName]['type'] == "parent")
385                     {
386                         $this->fieldDefs[$fvName]['options'] = array_merge(array(""=>""), $this->fieldDefs[$fvName]['options']);
387                     }
388                     }
389
390                     if(isset($this->fieldDefs[$fvName]['function'])) {
391
392                         $this->fieldDefs[$fvName]['type']='multienum';
393
394                                 if(is_array($this->fieldDefs[$fvName]['function'])) {
395                                    $this->fieldDefs[$fvName]['function']['preserveFunctionValue']=true;
396                                 }
397
398                                 $function = $this->fieldDefs[$fvName]['function'];
399
400                                 if(is_array($function) && isset($function['name'])){
401                                         $function_name = $this->fieldDefs[$fvName]['function']['name'];
402                                 }else{
403                                         $function_name = $this->fieldDefs[$fvName]['function'];
404                                 }
405
406                                         if(!empty($this->fieldDefs[$fvName]['function']['returns']) && $this->fieldDefs[$fvName]['function']['returns'] == 'html'){
407                                                 if(!empty($this->fieldDefs[$fvName]['function']['include'])){
408                                                                 require_once($this->fieldDefs[$fvName]['function']['include']);
409                                                 }
410                                                 $value = call_user_func($function_name, $this->seed, $name, $value, $this->view);
411                                                 $this->fieldDefs[$fvName]['value'] = $value;
412                                         }else{
413                                                 if(!isset($function['params']) || !is_array($function['params'])) {
414                                                         $this->fieldDefs[$fvName]['options'] = call_user_func($function_name, $this->seed, $name, $value, $this->view);
415                                                 } else {
416                                                         $this->fieldDefs[$fvName]['options'] = call_user_func_array($function_name, $function['params']);
417                                                 }
418                                         }
419                         }
420                         if(isset($this->fieldDefs[$name]['type']) && $this->fieldDefs[$fvName]['type'] == 'function'
421                        && isset($this->fieldDefs[$fvName]['function_name']))
422                 {
423                                 $value = $this->callFunction($this->fieldDefs[$fvName]);
424                                 $this->fieldDefs[$fvName]['value'] = $value;
425                         }
426
427                     $this->fieldDefs[$name]['value'] = $value;
428
429
430                     if((!empty($_REQUEST[$fvName]) || (isset($_REQUEST[$fvName]) && $_REQUEST[$fvName] == '0'))
431                 && empty($this->fieldDefs[$fvName]['function']['preserveFunctionValue'])) {
432                         $value = $_REQUEST[$fvName];
433                         $this->fieldDefs[$fvName]['value'] = $value;
434                     }
435
436                 } //foreach
437
438
439                 }
440
441         }
442
443             /**
444      * Populate the searchFields from an array
445      *
446      * @param array $array array to search through
447      * @param string $switchVar variable to use in switch statement
448      * @param bool $addAllBeanFields true to process at all bean fields
449      */
450     function populateFromArray(&$array, $switchVar = null, $addAllBeanFields = true) {
451
452        if((!empty($array['searchFormTab']) || !empty($switchVar)) && !empty($this->searchFields)) {
453                         $arrayKeys = array_keys($array);
454             $searchFieldsKeys = array_keys($this->searchFields);
455             if(empty($switchVar)) $switchVar = $array['searchFormTab'];
456             //name of  the search tab
457             $SearchName=str_replace('_search', '', $switchVar);
458             if($switchVar=='saved_views'){
459                 foreach($this->searchFields as $name => $params) {
460                     foreach($this->tabs as $tabName){
461                         if(!empty($array[$name . '_' . $tabName['name']])) {
462                              $this->searchFields[$name]['value'] = $array[$name . '_' . $tabName['name']];
463                              if(empty($this->fieldDefs[$name . '_' . $tabName['name']]['value'])) $this->fieldDefs[$name . '_' . $tabName['name']]['value'] = $array[$name . '_' . $tabName['name']];
464                         }
465                     }
466                 }
467                 if($addAllBeanFields) {
468                     foreach($this->seed->field_name_map as $key => $params) {
469                         if(!in_array($key, $searchFieldsKeys)) {
470                             foreach($this->tabs->name as $tabName){
471                                 if(in_array($key . '_' . $tabName['name'], $arrayKeys) ) {
472                                                                         $this->searchFields[$key] = array('query_type' => 'default',
473                                                                       'value'      => $array[$key . '_' . $tabName['name']]);
474                                 }
475                             }
476                         }
477                     }
478                 }
479             }else{
480
481                 $fromMergeRecords = isset($array['merge_module']);
482
483                 foreach($this->searchFields as $name => $params) {
484                                         $long_name = $name.'_'.$SearchName;
485                                         /*nsingh 21648: Add additional check for bool values=0. empty() considers 0 to be empty Only repopulates if value is 0 or 1:( */
486                     if (isset($array[$long_name]) && ( $array[$long_name] !== '' || (isset($this->fieldDefs[$long_name]['type']) && $this->fieldDefs[$long_name]['type'] == 'bool'&& ($array[$long_name]=='0' || $array[$long_name]=='1'))))
487                                         {
488                         $this->searchFields[$name]['value'] = $array[$long_name];
489                         if(empty($this->fieldDefs[$long_name]['value'])) {
490                                 $this->fieldDefs[$long_name]['value'] = $array[$long_name];
491                         }
492                     }
493                     else if(!empty($array[$name]) && !$fromMergeRecords) // basic
494                     {
495                         $this->searchFields[$name]['value'] = $array[$name];
496                         if(empty($this->fieldDefs[$long_name]['value'])) {
497                                 $this->fieldDefs[$long_name]['value'] = $array[$name];
498                         }
499                     }
500
501                     if(!empty($params['enable_range_search']) && isset($this->searchFields[$name]['value']))
502                                         {
503                                                 if(preg_match('/^range_(.*?)$/', $long_name, $match) && isset($array[$match[1].'_range_choice']))
504                                                 {
505                                                         $this->searchFields[$name]['operator'] = $array[$match[1].'_range_choice'];
506                                                 }
507                                         }
508
509                                         if(!empty($params['is_date_field']) && isset($this->searchFields[$name]['value']))
510                                         {
511                                                 global $timedate;
512                         // FG - bug 45287 - to db conversion is ok, but don't adjust timezone (not now), otherwise you'll jump to the day before (if at GMT-xx)
513                                                 $date_value = $timedate->to_db_date($this->searchFields[$name]['value'], false);
514                                                 $this->searchFields[$name]['value'] = $date_value == '' ? $this->searchFields[$name]['value'] : $date_value;
515                                         }
516                 }
517
518                 if((empty($array['massupdate']) || $array['massupdate'] == 'false') && $addAllBeanFields) {
519                     foreach($this->seed->field_name_map as $key => $params) {
520                         if($key != 'assigned_user_name' && $key != 'modified_by_name')
521                         {
522                                 $long_name = $key.'_'.$SearchName;
523                                 
524                                 if(in_array($key.'_'.$SearchName, $arrayKeys) && !in_array($key, $searchFieldsKeys))
525                                 {
526                                         $this->searchFields[$key] = array('query_type' => 'default', 'value' => $array[$long_name]);
527
528                                 if (!empty($params['type']) && $params['type'] == 'parent'
529                                     && !empty($params['type_name']) && !empty($this->searchFields[$key]['value']))
530                                 {
531                                             require_once('include/SugarFields/SugarFieldHandler.php');
532                                                                                 $sfh = new SugarFieldHandler();
533                                                                 $sf = $sfh->getSugarField('Parent');
534
535                                         $this->searchFields[$params['type_name']] = array('query_type' => 'default',
536                                                                                           'value'      => $sf->getSearchInput($params['type_name'], $array));
537                                 }
538
539                                 if(empty($this->fieldDefs[$long_name]['value'])) {
540                                     $this->fieldDefs[$long_name]['value'] =  $array[$long_name];
541                                 }
542                             }
543                         }
544                     }
545                 }
546             }
547         }
548
549
550        if ( is_array($this->searchFields) ) {
551            foreach ( $this->searchFields as $fieldName => $field ) {
552                if ( !empty($field['value']) && is_string($field['value']) ) {
553                    $this->searchFields[$fieldName]['value'] = trim($field['value']);
554                }
555            }
556        }
557
558     }
559
560     /**
561      * Populate the searchFields from $_REQUEST
562      *
563      * @param string $switchVar variable to use in switch statement
564      * @param bool $addAllBeanFields true to process at all bean fields
565      */
566     function populateFromRequest($switchVar = null, $addAllBeanFields = true) {
567         $this->populateFromArray($_REQUEST, $switchVar, $addAllBeanFields);
568     }
569
570
571         /**
572      * Parse date expression and return WHERE clause
573      * @param string $operator Date expression operator
574      * @param string DB field name
575       * @param string DB field type
576      */
577     protected function parseDateExpression($operator, $db_field, $field_type = '')
578     {
579         if ($field_type == "date") {
580             $type = "date";
581             $adjForTZ = false;
582         } else {
583             $type = "datetime";
584             $adjForTZ = true;
585         }
586         $dates = TimeDate::getInstance()->parseDateRange($operator, null, $adjForTZ);
587         if(empty($dates)) return '';
588         $start = $this->seed->db->convert($this->seed->db->quoted($dates[0]->asDb()), $type);
589         $end = $this->seed->db->convert($this->seed->db->quoted($dates[1]->asDb()), $type);
590         return "($db_field >= $start AND $db_field <= $end)";
591     }
592
593      /**
594       * generateSearchWhere
595       *
596       * This function serves as the central piece of SearchForm2.php
597       * It is responsible for creating the WHERE clause for a given search operation
598       *
599       * @param bool $add_custom_fields boolean indicating whether or not custom fields should be added
600       * @param string $module Module to search against
601       *
602       * @return string the SQL WHERE clause based on the arguments supplied in SearchForm2 instance
603       */
604      public function generateSearchWhere($add_custom_fields = false, $module='') {
605          global $timedate;
606
607          $db = $this->seed->db;
608          $this->searchColumns = array () ;
609          $values = $this->searchFields;
610
611          $where_clauses = array();
612          $like_char = '%';
613          $table_name = $this->seed->object_name;
614          $this->seed->fill_in_additional_detail_fields();
615
616          //rrs check for team_id
617
618          foreach($this->searchFields as $field=>$parms) {
619              $customField = false;
620              // Jenny - Bug 7462: We need a type check here to avoid database errors
621              // when searching for numeric fields. This is a temporary fix until we have
622              // a generic search form validation mechanism.
623              $type = (!empty($this->seed->field_name_map[$field]['type']))?$this->seed->field_name_map[$field]['type']:'';
624
625              //If range search is enabled for the field, we first check if this is the starting range
626              if(!empty($parms['enable_range_search']) && empty($type))
627              {
628                  if(preg_match('/^start_range_(.*?)$/', $field, $match))
629                  {
630                      $real_field = $match[1];
631                      $start_field = 'start_range_' . $real_field;
632                      $end_field = 'end_range_' . $real_field;
633
634                      if(isset($this->searchFields[$start_field]['value']) && isset($this->searchFields[$end_field]['value']))
635                      {
636                          $this->searchFields[$real_field]['value'] = $this->searchFields[$start_field]['value'] . '<>' . $this->searchFields[$end_field]['value'];
637                          $this->searchFields[$real_field]['operator'] = 'between';
638                          $parms['value'] = $this->searchFields[$real_field]['value'];
639                          $parms['operator'] = 'between';
640
641                          $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
642                          if($field_type == 'datetimecombo' || $field_type == 'datetime')
643                          {
644                                 $type = $field_type;
645                          }
646
647                          $field = $real_field;
648                          unset($this->searchFields[$end_field]['value']);
649                      }
650                  } else if (preg_match('/^range_(.*?)$/', $field, $match) && isset($this->searchFields[$field]['value'])) {
651                      $real_field = $match[1];
652
653                      //Special case for datetime and datetimecombo fields.  By setting the type here we allow an actual between search
654                      if(in_array($parms['operator'], array('=', 'between', "not_equal", 'less_than', 'greater_than', 'less_than_equals', 'greater_than_equals')))
655                      {
656                         $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
657                         if(strtolower($field_type) == 'readonly' && isset($this->seed->field_name_map[$real_field]['dbType'])) {
658                            $field_type = $this->seed->field_name_map[$real_field]['dbType'];
659                         }
660                         if($field_type == 'datetimecombo' || $field_type == 'datetime' || $field_type == 'int')
661                         {
662                            $type = $field_type;
663                         }
664                      }
665
666                      $this->searchFields[$real_field]['value'] = $this->searchFields[$field]['value'];
667                      $this->searchFields[$real_field]['operator'] = $this->searchFields[$field]['operator'];
668                      $params['value'] = $this->searchFields[$field]['value'];
669                      $params['operator'] = $this->searchFields[$field]['operator'];
670                      unset($this->searchFields[$field]['value']);
671                      $field = $real_field;
672                  } else {
673                      //Skip this range search field, it is the end field THIS IS NEEDED or the end range date will break the query
674                      continue;
675                  }
676              }
677
678              //Test to mark whether or not the field is a custom field
679              if(!empty($this->seed->field_name_map[$field]['source'])
680                  && ($this->seed->field_name_map[$field]['source'] == 'custom_fields' ||
681                      //Non-db custom fields, such as custom relates
682                      ($this->seed->field_name_map[$field]['source'] == 'non-db'
683                      && (!empty($this->seed->field_name_map[$field]['custom_module']) ||
684                           isset($this->seed->field_name_map[$field]['ext2']))))){
685                  $customField = true;
686              }
687
688              if ($type == 'int' && isset($parms['value']) && !empty($parms['value'])) {
689                  require_once ('include/SugarFields/SugarFieldHandler.php');
690                  $intField = SugarFieldHandler::getSugarField('int');
691                  $newVal = $intField->getSearchWhereValue($parms['value']);
692                  $parms['value'] = $newVal;
693              } elseif($type == 'html' && $customField) {
694                  continue;
695              }
696
697
698              if(isset($parms['value']) && $parms['value'] != "") {
699
700                  $operator = $db->isNumericType($type)?'=':'like';
701                  if(!empty($parms['operator'])) {
702                      $operator = strtolower($parms['operator']);
703                  }
704
705                  if(is_array($parms['value'])) {
706                      $field_value = '';
707
708                      // always construct the where clause for multiselects using the 'like' form to handle combinations of multiple $vals and multiple $parms
709                       if(!empty($this->seed->field_name_map[$field]['isMultiSelect']) && $this->seed->field_name_map[$field]['isMultiSelect']) {
710                          // construct the query for multenums
711                          // use the 'like' query as both custom and OOB multienums are implemented with types that cannot be used with an 'in'
712                          $operator = 'custom_enum';
713                          $table_name = $this->seed->table_name ;
714                          if ($customField)
715                              $table_name .= "_cstm" ;
716                          $db_field = $table_name . "." . $field;
717
718                          foreach($parms['value'] as $val) {
719                              if($val != ' ' and $val != '') {
720                                     $qVal = $db->quote($val);
721                                     if (!empty($field_value)) {
722                                         $field_value .= ' or ';
723                                     }
724                                     $field_value .= "$db_field like '%^$qVal^%'";
725                              } else {
726                                  $field_value .= '('.$db_field . ' IS NULL or '.$db_field."='^^' or ".$db_field."='')";
727                              }
728                          }
729
730                      } else {
731                          $operator = $operator != 'subquery' ? 'in' : $operator;
732                          foreach($parms['value'] as $val) {
733                              if($val != ' ' and $val != '') {
734                                  if (!empty($field_value)) {
735                                      $field_value .= ',';
736                                  }
737                                  $field_value .= $db->quoteType($type, $val);
738                              }
739                                  // Bug 41209: adding a new operator "isnull" here
740                                  // to handle the case when blank is selected from dropdown.
741                                  // In that case, $val is empty.
742                                  // When $val is empty, we need to use "IS NULL",
743                                  // as "in (null)" won't work
744                                  else if ($operator=='in') {
745                                      $operator = 'isnull';
746                                  }
747                          }
748                      }
749
750                  } else {
751                      $field_value = $parms['value'];
752                  }
753
754                  //set db_fields array.
755                  if(!isset($parms['db_field'])) {
756                      $parms['db_field'] = array($field);
757                  }
758
759                  //This if-else block handles the shortcut checkbox selections for "My Items" and "Closed Only"
760                  if(!empty($parms['my_items'])) {
761                      if( $parms['value'] == false ) {
762                          continue;
763                      } else {
764                          //my items is checked.
765                          global $current_user;
766                          $field_value = $db->quote($current_user->id);
767                          $operator = '=' ;
768                      }
769                  } else if(!empty($parms['closed_values']) && is_array($parms['closed_values'])) {
770                      if( $parms['value'] == false ) {
771                          continue;
772                      } else {
773                          $field_value = '';
774                          foreach($parms['closed_values'] as $closed_value)
775                          {
776                              $field_value .= "," . $db->quoted($closed_value);
777                          }
778                          $field_value = substr($field_value, 1);
779                      }
780                  }
781
782                  $where = '';
783                  $itr = 0;
784
785                  if($field_value != '' || $operator=='isnull') {
786
787                      $this->searchColumns [ strtoupper($field) ] = $field ;
788
789                      foreach ($parms['db_field'] as $db_field) {
790                          if (strstr($db_field, '.') === false) {
791                              //Try to get the table for relate fields from link defs
792                              if ($type == 'relate' && !empty($this->seed->field_name_map[$field]['link'])
793                                  && !empty($this->seed->field_name_map[$field]['rname'])) {
794                                      $link = $this->seed->field_name_map[$field]['link'];
795                                      $relname = $link['relationship'];
796                                      if (($this->seed->load_relationship($link))){
797                                          //Martin fix #27494
798                                          $db_field = $this->seed->field_name_map[$field]['name'];
799                                      } else {
800                                          //Best Guess for table name
801                                          $db_field = strtolower($link['module']) . '.' . $db_field;
802                                      }
803
804
805                              }
806                              else if ($type == 'parent') {
807                                  if (!empty($this->searchFields['parent_type'])) {
808                                      $parentType = $this->searchFields['parent_type'];
809                                      $rel_module = $parentType['value'];
810                                      global $beanFiles, $beanList;
811                                      if(!empty($beanFiles[$beanList[$rel_module]])) {
812                                          require_once($beanFiles[$beanList[$rel_module]]);
813                                          $rel_seed = new $beanList[$rel_module]();
814                                          $db_field = 'parent_' . $rel_module . '_' . $rel_seed->table_name . '.name';
815                                      }
816                                  }
817                              }
818                              // Relate fields in custom modules and custom relate fields
819                              else if ($type == 'relate' && $customField && !empty($this->seed->field_name_map[$field]['module'])) {
820                                  $db_field = !empty($this->seed->field_name_map[$field]['name'])?$this->seed->field_name_map[$field]['name']:'name';
821                              }
822                             else if(!$customField){
823                                 if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
824                                     $db_field = $db->concat($this->seed->table_name, $this->seed->field_name_map[$db_field]['db_concat_fields']);
825                                 else
826                                     $db_field = $this->seed->table_name .  "." . $db_field;
827                              }else{
828                                  if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
829                                     $db_field = $db->concat($this->seed->table_name .  "_cstm.", $this->seed->field_name_map[$db_field]['db_concat_fields']);
830                                 else
831                                     $db_field = $this->seed->table_name .  "_cstm." . $db_field;
832                              }
833
834                          }
835
836                          if($type == 'date') {
837                             // The regular expression check is to circumvent special case YYYY-MM
838                              $operator = '=';
839                              if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) != 0) { // preg_match returns number of matches
840                                 $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m"));
841                             } else {
842                                 $field_value = $timedate->to_db_date($field_value, false);
843                                 $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m-%d"));
844                             }
845                          }
846
847                          if($type == 'datetime' || $type == 'datetimecombo') {
848                              try {
849                                  if($operator == '=' || $operator == 'between') {
850                                      // FG - bug45287 - If User asked for a range, takes edges from it.
851                                      $placeholderPos = strpos($field_value, "<>");
852                                      if ($placeholderPos !== FALSE && $placeholderPos > 0)
853                                      {
854                                          $datesLimit = explode("<>", $field_value);
855                                          $dateStart = $timedate->getDayStartEndGMT($datesLimit[0]);
856                                          $dateEnd = $timedate->getDayStartEndGMT($datesLimit[1]);
857                                          $dates = $dateStart;
858                                          $dates['end'] = $dateEnd['end'];
859                                          $dates['enddate'] = $dateEnd['enddate'];
860                                          $dates['endtime'] = $dateEnd['endtime'];
861                                      }
862                                      else
863                                      {
864                                          $dates = $timedate->getDayStartEndGMT($field_value);
865                                      }
866                                      // FG - bug45287 - Note "start" and "end" are the correct interval at GMT timezone
867                                      $field_value = array($dates["start"], $dates["end"]);
868                                      $operator = 'between';
869                                  } else if($operator == 'not_equal') {
870                                     $dates = $timedate->getDayStartEndGMT($field_value);
871                                     $field_value = array($dates["start"], $dates["end"]);
872                                     $operator = 'date_not_equal';
873                                  } else if($operator == 'greater_than') {
874                                     $dates = $timedate->getDayStartEndGMT($field_value);
875                                     $field_value = $dates["end"];
876                                  } else if($operator == 'less_than') {
877                                     $dates = $timedate->getDayStartEndGMT($field_value);
878                                     $field_value = $dates["start"];
879                                  } else if($operator == 'greater_than_equals') {
880                                     $dates = $timedate->getDayStartEndGMT($field_value);
881                                     $field_value = $dates["start"];
882                                  } else if($operator == 'less_than_equals') {
883                                     $dates = $timedate->getDayStartEndGMT($field_value);
884                                     $field_value = $dates["end"];
885                                  }
886                              } catch(Exception $timeException) {
887                                  //In the event that a date value is given that cannot be correctly processed by getDayStartEndGMT method,
888                                  //just skip searching on this field and continue.  This may occur if user switches locale date formats
889                                  //in another browser screen, but re-runs a search with the previous format on another screen
890                                  $GLOBALS['log']->error($timeException->getMessage());
891                                  continue;
892                              }
893                          }
894
895                          if($type == 'decimal' || $type == 'float' || $type == 'currency' || (!empty($parms['enable_range_search']) && empty($parms['is_date_field']))) {
896                              require_once('modules/Currencies/Currency.php');
897
898                              //we need to handle formatting either a single value or 2 values in case the 'between' search option is set
899                              //start by splitting the string if the between operator exists
900                              $fieldARR = explode('<>', $field_value);
901                              //set the first pass through boolean
902                              $values = array();
903                              foreach($fieldARR as $fv){
904                                  //reset the field value, it will be rebuild in the foreach loop below
905                                  $tmpfield_value = unformat_number($fv);
906
907                                  if ( $type == 'currency' && stripos($field,'_usdollar')!==FALSE ) {
908                                      // It's a US Dollar field, we need to do some conversions from the user's local currency
909                                      $currency_id = $GLOBALS['current_user']->getPreference('currency');
910                                      if ( empty($currency_id) ) {
911                                          $currency_id = -99;
912                                      }
913                                      if ( $currency_id != -99 ) {
914                                          $currency = new Currency();
915                                          $currency->retrieve($currency_id);
916                                          $tmpfield_value = $currency->convertToDollar($tmpfield_value);
917                                      }
918                                  }
919                                  $values[] = $tmpfield_value;
920                              }
921
922                              $field_value = join('<>',$values);
923
924                              if(!empty($parms['enable_range_search']) && $parms['operator'] == '=' && $type != 'int')
925                              {
926                                  // Databases can't really search for floating point numbers, because they can't be accurately described in binary,
927                                  // So we have to fuzz out the math a little bit
928                                  $field_value = array(($field_value - 0.01) , ($field_value + 0.01));
929                                  $operator = 'between';
930                              }
931                          }
932
933
934                          if($db->supports("case_sensitive") && isset($parms['query_type']) && $parms['query_type'] == 'case_insensitive') {
935                                $db_field = 'upper(' . $db_field . ")";
936                                $field_value = strtoupper($field_value);
937                          }
938
939                          $itr++;
940                          if(!empty($where)) {
941                              $where .= " OR ";
942                          }
943
944                          //Here we make a last attempt to determine the field type if possible
945                          if(empty($type) && isset($parms['db_field']) && isset($parms['db_field'][0]) && isset($this->seed->field_defs[$parms['db_field'][0]]['type']))
946                          {
947                              $type = $this->seed->field_defs[$parms['db_field'][0]]['type'];
948                          }
949
950                          switch(strtolower($operator)) {
951                              case 'subquery':
952                                  $in = 'IN';
953                                  if ( isset($parms['subquery_in_clause']) ) {
954                                      if ( !is_array($parms['subquery_in_clause']) ) {
955                                          $in = $parms['subquery_in_clause'];
956                                      }
957                                      elseif ( isset($parms['subquery_in_clause'][$field_value]) ) {
958                                          $in = $parms['subquery_in_clause'][$field_value];
959                                      }
960                                  }
961                                  $sq = $parms['subquery'];
962                                  if(is_array($sq)){
963                                      $and_or = ' AND ';
964                                      if (isset($sq['OR'])){
965                                          $and_or = ' OR ';
966                                      }
967                                      $first = true;
968                                      foreach($sq as $q){
969                                          if(empty($q) || strlen($q)<2) continue;
970                                          if(!$first){
971                                              $where .= $and_or;
972                                          }
973                                          $where .= " {$db_field} $in ({$q} ".$this->seed->db->quoted($field_value.'%').") ";
974                                          $first = false;
975                                      }
976                                  }elseif(!empty($parms['query_type']) && $parms['query_type'] == 'format'){
977                                      $stringFormatParams = array(0 => $field_value, 1 => $GLOBALS['current_user']->id);
978                                      $where .= "{$db_field} $in (".string_format($parms['subquery'], $stringFormatParams).")";
979                                  }else{
980                                      //Bug#37087: Re-write our sub-query to it is executed first and contents stored in a derived table to avoid mysql executing the query
981                                      //outside in. Additional details: http://bugs.mysql.com/bug.php?id=9021
982                                     $where .= "{$db_field} $in (select * from ({$parms['subquery']} ".$this->seed->db->quoted($field_value.'%').") as {$field}_derived)";
983                                  }
984
985                                  break;
986
987                              case 'like':
988                                  if($type == 'bool' && $field_value == 0) {
989                                      // Bug 43452 - FG - Added parenthesis surrounding the OR (without them the WHERE clause would be broken)
990                                      $where .=  "( " . $db_field . " = '0' OR " . $db_field . " IS NULL )";
991                                  }
992                                  else {
993                                      //check to see if this is coming from unified search or not
994                                      $UnifiedSearch = !empty($parms['force_unifiedsearch']);
995                                      if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'UnifiedSearch'){
996                                          $UnifiedSearch = true;
997                                      }
998
999                                      //check to see if this is a universal search OR the field has db_concat_fields set in vardefs, AND the field name is "last_name"
1000                                      //BUG 45709: Tasks Advanced Search: Contact Name field does not return matches on full names
1001                                      //Frank: Adding Surabhi's fix back which seem to have gone missing in CottonCandy merge
1002                                      if(($UnifiedSearch || !empty($this->seed->field_name_map[$field]['db_concat_fields'])) && strpos($db_field, 'last_name') !== false){
1003                                          //split the string value, and the db field name
1004                                          $string = explode(' ', $field_value);
1005                                          $column_name =  explode('.', $db_field);
1006                                          //when a search is done with a space, we concatenate and search against the full name.
1007                                          if(count($string)>1){
1008                                              //add where clause against concatenated fields
1009                                              $where .= $this->seed->db->concat($column_name[0],array('first_name','last_name')) . " LIKE ".$this->seed->db->quoted($field_value.'%');
1010                                              $where .= ' OR ' . $this->seed->db->concat($column_name[0],array('last_name','first_name')) . " LIKE ".$this->seed->db->quoted($field_value.'%');
1011                                          }else{
1012                                              //no space was found, add normal where clause
1013                                              $where .=  $db_field . " like ".$this->seed->db->quoted(sql_like_string($field_value, $like_char));
1014                                          }
1015
1016                                      }else {
1017
1018                                          //Check if this is a first_name, last_name search
1019                                          if(isset($this->seed->field_name_map) && isset($this->seed->field_name_map[$db_field]))
1020                                          {
1021                                              $vardefEntry = $this->seed->field_name_map[$db_field];
1022                                              if(!empty($vardefEntry['db_concat_fields']) && in_array('first_name', $vardefEntry['db_concat_fields']) && in_array('last_name', $vardefEntry['db_concat_fields']))
1023                                              {
1024                                                    if(!empty($GLOBALS['app_list_strings']['salutation_dom']) && is_array($GLOBALS['app_list_strings']['salutation_dom']))
1025                                                    {
1026                                                       foreach($GLOBALS['app_list_strings']['salutation_dom'] as $salutation)
1027                                                       {
1028                                                          if(!empty($salutation) && strpos($field_value, $salutation) === 0)
1029                                                          {
1030                                                             $field_value = trim(substr($field_value, strlen($salutation)));
1031                                                             break;
1032                                                          }
1033                                                       }
1034                                                    }
1035                                              }
1036                                          }
1037
1038                                          //field is not last name or this is not from global unified search, so do normal where clause
1039                                          $where .=  $db_field . " like ".$this->seed->db->quoted(sql_like_string($field_value, $like_char));
1040                                      }
1041                                  }
1042                                  break;
1043                              case 'not in':
1044                                  $where .= $db_field . ' not in ('.$field_value.')';
1045                                  break;
1046                              case 'in':
1047                                  $where .=  $db_field . ' in ('.$field_value.')';
1048                                  break;
1049                              case '=':
1050                                  if($type == 'bool' && $field_value == 0) {
1051                                      $where .=  "($db_field = 0 OR $db_field IS NULL)";
1052                                  }
1053                                  else {
1054                                      $where .=  $db_field . " = ".$db->quoteType($type, $field_value);
1055                                  }
1056                                  break;
1057                              // tyoung bug 15971 - need to add these special cases into the $where query
1058                              case 'custom_enum':
1059                                  $where .= $field_value;
1060                                  break;
1061                              case 'between':
1062                                  if(!is_array($field_value)) {
1063                                      $field_value = explode('<>', $field_value);
1064                                  }
1065                                  $field_value[0] = $db->quoteType($type, $field_value[0]);
1066                                  $field_value[1] = $db->quoteType($type, $field_value[1]);
1067                                  $where .= "($db_field >= {$field_value[0]} AND $db_field <= {$field_value[1]})";
1068                                  break;
1069                              case 'date_not_equal':
1070                                  if(!is_array($field_value)) {
1071                                      $field_value = explode('<>', $field_value);
1072                                  }
1073                                  $field_value[0] = $db->quoteType($type, $field_value[0]);
1074                                  $field_value[1] = $db->quoteType($type, $field_value[1]);
1075                                  $where .= "($db_field IS NULL OR $db_field < {$field_value[0]} OR $db_field > {$field_value[1]})";
1076                                  break;
1077                              case 'innerjoin':
1078                                  $this->seed->listview_inner_join[] = $parms['innerjoin'] . " '" . $parms['value'] . "%')";
1079                                  break;
1080                              case 'not_equal':
1081                                  $field_value = $db->quoteType($type, $field_value);
1082                                  $where .= "($db_field IS NULL OR $db_field != $field_value)";
1083                                  break;
1084                              case 'greater_than':
1085                                  $field_value = $db->quoteType($type, $field_value);
1086                                  $where .= "$db_field > $field_value";
1087                                  break;
1088                              case 'greater_than_equals':
1089                                  $field_value = $db->quoteType($type, $field_value);
1090                                  $where .= "$db_field >= $field_value";
1091                                  break;
1092                              case 'less_than':
1093                                  $field_value = $db->quoteType($type, $field_value);
1094                                  $where .= "$db_field < $field_value";
1095                                  break;
1096                              case 'less_than_equals':
1097                                  $field_value = $db->quoteType($type, $field_value);
1098                                  $where .= "$db_field <= $field_value";
1099                                  break;
1100                              case 'next_7_days':
1101                              case 'last_7_days':
1102                              case 'last_month':
1103                              case 'this_month':
1104                              case 'next_month':
1105                              case 'last_30_days':
1106                              case 'next_30_days':
1107                              case 'this_year':
1108                              case 'last_year':
1109                              case 'next_year':
1110                                  if (!empty($field) && !empty($this->seed->field_name_map[$field]['type'])) {
1111                                      $where .= $this->parseDateExpression(strtolower($operator), $db_field, $this->seed->field_name_map[$field]['type']);
1112                                  } else {
1113                                      $where .= $this->parseDateExpression(strtolower($operator), $db_field);
1114                                  }
1115                                  break;
1116                              case 'isnull':
1117                                  $where .=  "($db_field IS NULL OR $db_field = '')";
1118                                  if ($field_value != '')
1119                                      $where .=  ' OR ' . $db_field . " in (".$field_value.')';
1120                                  break;
1121                          }
1122                      }
1123                  }
1124
1125                  if(!empty($where)) {
1126                      if($itr > 1) {
1127                          array_push($where_clauses, '( '.$where.' )');
1128                      }
1129                      else {
1130                          array_push($where_clauses, $where);
1131                      }
1132                  }
1133              }
1134          }
1135
1136          return $where_clauses;
1137      }
1138
1139
1140
1141     /**
1142      * isEmptyDropdownField
1143      *
1144      * This function checks to see if a blank dropdown field was supplied.  This scenario will occur where
1145      * a dropdown select is in single selection mode
1146      *
1147      * @param $value Mixed dropdown value
1148      */
1149     private function isEmptyDropdownField($name='', $value=array())
1150     {
1151         $result = is_array($value) && isset($value[0]) && $value[0] == '';
1152         $GLOBALS['log']->debug("Found empty value for {$name} dropdown search key");
1153         return $result;
1154     }
1155
1156     /**
1157     * Return the search defs for a particular module.
1158     *
1159     * @static
1160     * @param $module
1161     */
1162     public static function retrieveSearchDefs($module)
1163     {
1164         $searchdefs = array();
1165         $searchFields = array();
1166
1167         if(file_exists('custom/modules/'.$module.'/metadata/metafiles.php'))
1168         {
1169             require('custom/modules/'.$module.'/metadata/metafiles.php');
1170         }
1171         elseif(file_exists('modules/'.$module.'/metadata/metafiles.php'))
1172         {
1173             require('modules/'.$module.'/metadata/metafiles.php');
1174         }
1175
1176         if (file_exists('custom/modules/'.$module.'/metadata/searchdefs.php'))
1177         {
1178             require('custom/modules/'.$module.'/metadata/searchdefs.php');
1179         }
1180         elseif (!empty($metafiles[$module]['searchdefs']))
1181         {
1182             require($metafiles[$module]['searchdefs']);
1183         }
1184         elseif (file_exists('modules/'.$module.'/metadata/searchdefs.php'))
1185         {
1186             require('modules/'.$module.'/metadata/searchdefs.php');
1187         }
1188
1189
1190         if(!empty($metafiles[$module]['searchfields']))
1191         {
1192             require($metafiles[$module]['searchfields']);
1193         }
1194         elseif(file_exists('modules/'.$module.'/metadata/SearchFields.php'))
1195         {
1196             require('modules/'.$module.'/metadata/SearchFields.php');
1197         }
1198         if(file_exists('custom/modules/'.$module.'/metadata/SearchFields.php'))
1199         {
1200             require('custom/modules/'.$module.'/metadata/SearchFields.php');
1201         }
1202
1203         return array('searchdefs' => $searchdefs, 'searchFields' => $searchFields );
1204     }
1205 }
1206