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