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