2 /*********************************************************************************
3 * SugarCRM is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2011 SugarCRM Inc.
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.
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
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
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.
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.
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 ********************************************************************************/
38 * Created on May 30, 2007
40 * To change the template for this generated file go to
41 * Window - Preferences - PHPeclipse - PHP - Code Templates
43 require_once('include/tabs.php');
44 require_once('include/ListView/ListViewSmarty.php');
46 require_once('include/TemplateHandler/TemplateHandler.php');
47 require_once('include/EditView/EditView2.php');
50 class SearchForm extends EditView{
53 var $action = 'index';
54 var $searchdefs = array();
55 var $listViewDefs = array();
59 var $view = 'SearchForm';
60 var $displayView = 'basic_search';
65 var $parsedView = 'basic';
68 var $displaySavedSearch = true;
69 //show the advanced tab
70 var $showAdvanced = true;
72 var $showBasic = true;
73 //array of custom tab to show declare in searchdefs (no custom tab if false)
74 var $showCustom = false;
77 // hide saved searches drop and down near the search button
78 var $showSavedSearchesOptions = true;
80 var $displayType = 'searchView';
82 function SearchForm($seed, $module, $action = 'index'){
83 $this->th = new TemplateHandler();
84 $this->th->loadSmarty();
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',
93 array('title' => $GLOBALS['app_strings']['LNK_ADVANCED_SEARCH'],
94 'link' => $module . '|advanced_search',
95 'key' => $module . '|advanced_search',
97 'displayDiv' => 'display:none'),
99 $this->searchColumns = array () ;
102 function setup($searchdefs, $searchFields = array(), $tpl, $displayView = 'basic_search', $listViewDefs = array()){
103 $this->searchdefs = $searchdefs[$this->module];
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();
115 $this->searchFields = $searchFields[$this->module];
117 // Setub the tab array
118 $this->tabs = array();
119 if($this->showBasic){
121 $this->tabs[]=array('title' => $GLOBALS['app_strings']['LNK_BASIC_SEARCH'],
122 'link' => $this->module . '|basic_search',
123 'key' => $this->module . '|basic_search',
127 if($this->showAdvanced){
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');
135 if($this->showCustom){
136 foreach($this->showCustom as $v){
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',);
147 function display($header = true){
148 global $theme, $timedate;
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
158 $this->th->ss->assign('TABS', $this->_displayTabs($this->module . '|' . $this->displayView));
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());
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];
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");
179 $pm = $match[2] == "pm" ? "%P" : "%p";
180 $this->th->ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M" . $pm);
182 $this->th->ss->assign('TIME_SEPARATOR', $time_separator);
184 //Show and hide the good tab form
185 foreach($this->tabs as $tabkey=>$viewtab){
186 $viewName=str_replace(array($this->module . '|','_search'),'',$viewtab['key']);
187 if(strpos($this->view,$viewName)!==false){
188 $this->tabs[$tabkey]['displayDiv']='';
189 //if this is advanced tab, use form with saved search sub form built in
190 if($viewName=='advanced'){
191 $this->tpl = 'include/SearchForm/tpls/SearchFormGenericAdvanced.tpl';
192 if ($this->action =='ListView') {
193 $this->th->ss->assign('DISPLAY_SEARCH_HELP', true);
195 $this->th->ss->assign('DISPLAY_SAVED_SEARCH', $this->displaySavedSearch);
196 $this->th->ss->assign('SAVED_SEARCH', $this->displaySavedSearch());
197 //this determines whether the saved search subform should be rendered open or not
198 if(isset($_REQUEST['showSSDIV']) && $_REQUEST['showSSDIV']=='yes'){
199 $this->th->ss->assign('SHOWSSDIV', 'yes');
200 $this->th->ss->assign('DISPLAYSS', '');
202 $this->th->ss->assign('SHOWSSDIV', 'no');
203 $this->th->ss->assign('DISPLAYSS', 'display:none');
207 $this->tabs[$tabkey]['displayDiv']='display:none';
212 $this->th->ss->assign('TAB_ARRAY', $this->tabs);
215 if ( isset($this->searchdefs['templateMeta']['widths'])
216 && isset($this->searchdefs['templateMeta']['maxColumns'])) {
217 $totalWidth = ( $this->searchdefs['templateMeta']['widths']['label'] +
218 $this->searchdefs['templateMeta']['widths']['field'] ) *
219 $this->searchdefs['templateMeta']['maxColumns'];
220 // redo the widths in case they are too big
221 if ( $totalWidth > 100 ) {
222 $resize = 100 / $totalWidth;
223 $this->searchdefs['templateMeta']['widths']['label'] =
224 $this->searchdefs['templateMeta']['widths']['label'] * $resize;
225 $this->searchdefs['templateMeta']['widths']['field'] =
226 $this->searchdefs['templateMeta']['widths']['field'] * $resize;
229 $this->th->ss->assign('templateMeta', $this->searchdefs['templateMeta']);
230 $this->th->ss->assign('HAS_ADVANCED_SEARCH', !empty($this->searchdefs['layout']['advanced_search']));
231 $this->th->ss->assign('displayType', $this->displayType);
232 // return the form of the shown tab only
233 if($this->showSavedSearchesOptions){
234 $this->th->ss->assign('SAVED_SEARCHES_OPTIONS', $this->displaySavedSearchSelect());
236 if ($this->module == 'Documents'){
237 $this->th->ss->assign('DOCUMENTS_MODULE', true);
239 $return_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchForm_'.$this->parsedView, $this->tpl);
241 $this->th->ss->assign('return_txt', $return_txt);
242 $header_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormHeader', 'include/SearchForm/tpls/header.tpl');
243 //pass in info to render the select dropdown below the form
244 $footer_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormFooter', 'include/SearchForm/tpls/footer.tpl');
245 $return_txt = $header_txt.$footer_txt;
250 function displaySavedSearch(){
251 $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
252 return $savedSearch->getForm($this->module, false);
256 function displaySavedSearchSelect(){
257 $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
258 return $savedSearch->getSelect($this->module);
264 * displays the tabs (top of the search form)
266 * @param string $currentKey key in $this->tabs to show as the current tab
268 * @return string html
270 function _displayTabs($currentKey)
272 if(isset($_REQUEST['saved_search_select']) && $_REQUEST['saved_search_select']!='_none') {
273 $saved_search=loadBean('SavedSearch');
274 $saved_search->retrieveSavedSearch($_REQUEST['saved_search_select']);
278 if(!empty($_REQUEST['displayColumns']))
279 $str .= 'SUGAR.savedViews.displayColumns = "' . $_REQUEST['displayColumns'] . '";';
280 elseif(isset($saved_search->contents['displayColumns']) && !empty($saved_search->contents['displayColumns']))
281 $str .= 'SUGAR.savedViews.displayColumns = "' . $saved_search->contents['displayColumns'] . '";';
282 if(!empty($_REQUEST['hideTabs']))
283 $str .= 'SUGAR.savedViews.hideTabs = "' . $_REQUEST['hideTabs'] . '";';
284 elseif(isset($saved_search->contents['hideTabs']) && !empty($saved_search->contents['hideTabs']))
285 $str .= 'SUGAR.savedViews.hideTabs = "' . $saved_search->contents['hideTabs'] . '";';
286 if(!empty($_REQUEST['orderBy']))
287 $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $_REQUEST['orderBy'] . '";';
288 elseif(isset($saved_search->contents['orderBy']) && !empty($saved_search->contents['orderBy']))
289 $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $saved_search->contents['orderBy'] . '";';
290 if(!empty($_REQUEST['sortOrder']))
291 $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $_REQUEST['sortOrder'] . '";';
292 elseif(isset($saved_search->contents['sortOrder']) && !empty($saved_search->contents['sortOrder']))
293 $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $saved_search->contents['sortOrder'] . '";';
303 function _build_field_defs(){
304 $this->formData = array();
305 $this->fieldDefs = array();
306 foreach($this->searchdefs['layout'][$this->displayView] as $data){
308 //Fields may be listed but disabled so that when they are enabled, they have the correct custom display data.
309 if (isset($data['enabled']) && $data['enabled'] == false)
311 $data['name'] = $data['name'].'_'.$this->parsedView;
312 $this->formData[] = array('field' => $data);
313 $this->fieldDefs[$data['name']]= $data;
315 $this->formData[] = array('field' => array('name'=>$data.'_'.$this->parsedView));
320 $this->seed->fill_in_additional_detail_fields();
321 // hack to make the employee status field for the Users/Employees module display correctly
322 if($this->seed->object_name == 'Employee' || $this->seed->object_name == 'User'){
323 $this->seed->field_defs['employee_status']['type'] = 'enum';
324 $this->seed->field_defs['employee_status']['massupdate'] = true;
325 $this->seed->field_defs['employee_status']['options'] = 'employee_status_dom';
326 unset($this->seed->field_defs['employee_status']['function']);
329 foreach($this->seed->toArray() as $name => $value) {
330 if(!empty($this->fieldDefs[$name.'_'.$this->parsedView]))
331 $this->fieldDefs[$name.'_'.$this->parsedView] = array_merge($this->seed->field_defs[$name], $this->fieldDefs[$name.'_'.$this->parsedView]);
333 $this->fieldDefs[$name.'_'.$this->parsedView] = $this->seed->field_defs[$name];
334 $this->fieldDefs[$name.'_'.$this->parsedView]['name'] = $this->fieldDefs[$name.'_'.$this->parsedView]['name'].'_'.$this->parsedView;
337 if(isset($this->fieldDefs[$name.'_'.$this->parsedView]['type']) && $this->fieldDefs[$name.'_'.$this->parsedView]['type'] == 'relate') {
338 if(isset($this->fieldDefs[$name.'_'.$this->parsedView]['id_name'])) {
339 $this->fieldDefs[$name.'_'.$this->parsedView]['id_name'] .= '_'.$this->parsedView;
343 if(isset($this->fieldDefs[$name.'_'.$this->parsedView]['options']) && isset($GLOBALS['app_list_strings'][$this->fieldDefs[$name.'_'.$this->parsedView]['options']])) {
344 $this->fieldDefs[$name.'_'.$this->parsedView]['options'] = $GLOBALS['app_list_strings'][$this->fieldDefs[$name.'_'.$this->parsedView]['options']]; // fill in enums
347 if(isset($this->fieldDefs[$name.'_'.$this->parsedView]['function'])) {
349 $this->fieldDefs[$name.'_'.$this->parsedView]['type']='multienum';
351 if(is_array($this->fieldDefs[$name.'_'.$this->parsedView]['function'])) {
352 $this->fieldDefs[$name.'_'.$this->parsedView]['function']['preserveFunctionValue']=true;
355 $function = $this->fieldDefs[$name.'_'.$this->parsedView]['function'];
357 if(is_array($function) && isset($function['name'])){
358 $function_name = $this->fieldDefs[$name.'_'.$this->parsedView]['function']['name'];
360 $function_name = $this->fieldDefs[$name.'_'.$this->parsedView]['function'];
363 if(!empty($this->fieldDefs[$name.'_'.$this->parsedView]['function']['returns']) && $this->fieldDefs[$name.'_'.$this->parsedView]['function']['returns'] == 'html'){
364 if(!empty($this->fieldDefs[$name.'_'.$this->parsedView]['function']['include'])){
365 require_once($this->fieldDefs[$name.'_'.$this->parsedView]['function']['include']);
367 $value = $function_name($this->seed, $name, $value, $this->view);
368 $this->fieldDefs[$name.'_'.$this->parsedView]['value'] = $value;
370 if(!isset($function['params']) || !is_array($function['params'])) {
371 $this->fieldDefs[$name.'_'.$this->parsedView]['options'] = $function_name($this->seed, $name, $value, $this->view);
373 $this->fieldDefs[$name.'_'.$this->parsedView]['options'] = call_user_func_array($function_name, $function['params']);
377 if(isset($this->fieldDefs[$name]['type']) && $this->fieldDefs[$name.'_'.$this->parsedView]['type'] == 'function' && isset($this->fieldDefs[$name.'_'.$this->parsedView]['function_name'])){
378 $value = $this->callFunction($this->fieldDefs[$name.'_'.$this->parsedView]);
379 $this->fieldDefs[$name.'_'.$this->parsedView]['value'] = $value;
382 $this->fieldDefs[$name]['value'] = $value;
385 if((!empty($_REQUEST[$name.'_'.$this->parsedView]) || (isset($_REQUEST[$name.'_'.$this->parsedView]) && $_REQUEST[$name.'_'.$this->parsedView] == '0'))
386 && empty($this->fieldDefs[$name.'_'.$this->parsedView]['function']['preserveFunctionValue'])) {
387 $value = $_REQUEST[$name.'_'.$this->parsedView];
388 $this->fieldDefs[$name.'_'.$this->parsedView]['value'] = $value;
399 * Populate the searchFields from an array
401 * @param array $array array to search through
402 * @param string $switchVar variable to use in switch statement
403 * @param bool $addAllBeanFields true to process at all bean fields
405 function populateFromArray(&$array, $switchVar = null, $addAllBeanFields = true) {
407 if((!empty($array['searchFormTab']) || !empty($switchVar)) && !empty($this->searchFields)) {
408 $arrayKeys = array_keys($array);
409 $searchFieldsKeys = array_keys($this->searchFields);
410 if(empty($switchVar)) $switchVar = $array['searchFormTab'];
411 //name of the search tab
412 $SearchName=str_replace('_search', '', $switchVar);
413 if($switchVar=='saved_views'){
414 foreach($this->searchFields as $name => $params) {
415 foreach($this->tabs as $tabName){
416 if(!empty($array[$name . '_' . $tabName['name']])) {
417 $this->searchFields[$name]['value'] = $array[$name . '_' . $tabName['name']];
418 if(empty($this->fieldDefs[$name . '_' . $tabName['name']]['value'])) $this->fieldDefs[$name . '_' . $tabName['name']]['value'] = $array[$name . '_' . $tabName['name']];
422 if($addAllBeanFields) {
423 foreach($this->seed->field_name_map as $key => $params) {
424 if(!in_array($key, $searchFieldsKeys)) {
425 foreach($this->tabs->name as $tabName){
426 if(in_array($key . '_' . $tabName['name'], $arrayKeys) ) {
427 $this->searchFields[$key] = array('query_type' => 'default',
428 'value' => $array[$key . '_' . $tabName['name']]);
437 $fromMergeRecords = isset($array['merge_module']);
439 foreach($this->searchFields as $name => $params) {
440 $long_name = $name.'_'.$SearchName; /*nsingh 21648: Add additional check for bool values=0. empty() considers 0 to be empty Only repopulates if value is 0 or 1:( */
441 if(isset($array[$long_name]) && ( $array[$long_name] !== ''
442 || (isset($this->fieldDefs[$long_name]) && $this->fieldDefs[$long_name]['type'] == 'bool'
443 && ($array[$long_name]=='0' || $array[$long_name]=='1'))) )
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];
449 }else if(!empty($array[$name]) && !$fromMergeRecords) { //basic
450 $this->searchFields[$name]['value'] = $array[$name];
451 if(empty($this->fieldDefs[$long_name]['value'])) $this->fieldDefs[$long_name]['value'] = $array[$name];
455 if((empty($array['massupdate']) || $array['massupdate'] == 'false') && $addAllBeanFields) {
456 foreach($this->seed->field_name_map as $key => $params) {
457 if($key != 'assigned_user_name' && $key != 'modified_by_name')
459 if(in_array($key.'_'.$SearchName, $arrayKeys) && !in_array($key, $searchFieldsKeys)) {
460 $this->searchFields[$key] = array('query_type' => 'default',
461 'value' => $array[$key.'_'.$SearchName]);
462 if (!empty($params['type']) && $params['type'] == 'parent'
463 && !empty($params['type_name']) && !empty($this->searchFields[$key]['value']))
465 $this->searchFields[$params['type_name']] = array('query_type' => 'default',
466 'value' => $array[$params['type_name']]);
468 if(empty($this->fieldDefs[$long_name]['value'])) {
469 $this->fieldDefs[$key.'_'.$SearchName]['value'] = $array[$key.'_'.$SearchName];
480 if ( is_array($this->searchFields) ) {
481 foreach ( $this->searchFields as $fieldName => $field ) {
482 if ( !empty($field['value']) && is_string($field['value']) ) {
483 $this->searchFields[$fieldName]['value'] = trim($field['value']);
490 * Populate the searchFields from $_REQUEST
492 * @param string $switchVar variable to use in switch statement
493 * @param bool $addAllBeanFields true to process at all bean fields
495 function populateFromRequest($switchVar = null, $addAllBeanFields = true) {
496 $this->populateFromArray($_REQUEST, $switchVar, $addAllBeanFields);
499 function generateSearchWhere($add_custom_fields = false, $module='') {
502 $this->searchColumns = array () ;
504 $values = $this->searchFields;
506 $where_clauses = array();
508 $table_name = $this->seed->object_name;
509 $this->seed->fill_in_additional_detail_fields();
511 //rrs check for team_id
512 foreach($this->searchFields as $field=>$parms) {
513 $customField = false;
514 // Jenny - Bug 7462: We need a type check here to avoid database errors
515 // when searching for numeric fields. This is a temporary fix until we have
516 // a generic search form validation mechanism.
517 $type = (!empty($this->seed->field_name_map[$field]['type']))?$this->seed->field_name_map[$field]['type']:'';
519 if(!empty($this->seed->field_name_map[$field]['source'])
520 && ($this->seed->field_name_map[$field]['source'] == 'custom_fields' ||
521 //Non-db custom fields, such as custom relates
522 ($this->seed->field_name_map[$field]['source'] == 'non-db'
523 && (!empty($this->seed->field_name_map[$field]['custom_module']) ||
524 isset($this->seed->field_name_map[$field]['ext2']))))){
528 if ($type == 'int') {
529 if (!empty($parms['value'])) {
530 $tempVal = explode(',', $parms['value']);
532 foreach($tempVal as $key => $val) {
535 if(!empty($val) && !(is_numeric($val)))
540 $parms['value'] = $newVal;
544 //Navjeet- 6/24/08 checkboxes have been changed to dropdowns, so we can query unchecked checkboxes! Bug: 21648.
546 // elseif($type == 'bool' && empty($parms['value']) && preg_match("/current_user_only/", string subject, array subpatterns, int flags, [int offset])) {
550 elseif($type == 'html' && $customField) {
554 if(isset($parms['value']) && $parms['value'] != "") {
557 if(!empty($parms['operator'])) {
558 $operator = $parms['operator'];
561 if(is_array($parms['value'])) {
564 // always construct the where clause for multiselects using the 'like' form to handle combinations of multiple $vals and multiple $parms
565 if(/*$GLOBALS['db']->dbType != 'mysql' &&*/ !empty($this->seed->field_name_map[$field]['isMultiSelect']) && $this->seed->field_name_map[$field]['isMultiSelect']) {
566 // construct the query for multenums
567 // use the 'like' query for all mssql and oracle examples as both custom and OOB multienums are implemented with types that cannot be used with an 'in'
568 $operator = 'custom_enum';
569 $table_name = $this->seed->table_name ;
571 $table_name .= "_cstm" ;
572 $db_field = $table_name . "." . $field;
574 foreach($parms['value'] as $key => $val) {
575 if($val != ' ' and $val != '') {
576 $qVal = $GLOBALS['db']->quote($val);
577 if (!empty($field_value)) {
578 $field_value .= ' or ';
580 $field_value .= "$db_field like '%^$qVal^%'";
582 $field_value .= '('.$db_field . ' IS NULL or '.$db_field."='^^' or ".$db_field."='')";
587 $operator = $operator != 'subquery' ? 'in' : $operator;
588 foreach($parms['value'] as $key => $val) {
589 if($val != ' ' and $val != '') {
590 if (!empty($field_value)) {
593 $field_value .= "'" . $GLOBALS['db']->quote($val) . "'";
595 // Bug 41209: adding a new operator "isnull" here
596 // to handle the case when blank is selected from dropdown.
597 // In that case, $val is empty.
598 // When $val is empty, we need to use "IS NULL",
599 // as "in (null)" won't work
600 else if ($operator=='in') {
601 $operator = 'isnull';
608 $field_value = $GLOBALS['db']->quote($parms['value']);
611 //set db_fields array.
612 if(!isset($parms['db_field'])) {
613 $parms['db_field'] = array($field);
616 if(isset($parms['my_items']) and $parms['my_items'] == true) {
617 if( $parms['value'] == false ) { //do not include where clause for custom fields with checkboxes that are unchecked
621 else{ //my items is checked.
622 global $current_user;
623 $field_value = $GLOBALS['db']->quote($current_user->id);
626 // $operator = ($parms['value'] == '1') ? '=' : '!=';
632 if($field_value != '' || $operator=='isnull') {
634 $this->searchColumns [ strtoupper($field) ] = $field ;
636 foreach ($parms['db_field'] as $db_field) {
637 if (strstr($db_field, '.') === false) {
638 //Try to get the table for relate fields from link defs
639 if ($type == 'relate' && !empty($this->seed->field_name_map[$field]['link'])
640 && !empty($this->seed->field_name_map[$field]['rname'])) {
641 $link = $this->seed->field_name_map[$field]['link'];
642 $relname = $link['relationship'];
643 if (($this->seed->load_relationship($link))){
645 $db_field = $this->seed->field_name_map[$field]['name'];
647 //Best Guess for table name
648 $db_field = strtolower($link['module']) . '.' . $db_field;
651 else if ($type == 'parent') {
652 if (!empty($this->searchFields['parent_type'])) {
653 $parentType = $this->searchFields['parent_type'];
654 $rel_module = $parentType['value'];
655 global $beanFiles, $beanList;
656 if(!empty($beanFiles[$beanList[$rel_module]])) {
657 require_once($beanFiles[$beanList[$rel_module]]);
658 $rel_seed = new $beanList[$rel_module]();
659 $db_field = 'parent_' . $rel_module . '_' . $rel_seed->table_name . '.name';
663 // Relate fields in custom modules and custom relate fields
664 else if ($type == 'relate' && $customField && !empty($this->seed->field_name_map[$field]['module'])) {
665 $db_field = !empty($this->seed->field_name_map[$field]['name'])?$this->seed->field_name_map[$field]['name']:'name';
667 else if(!$customField){
668 if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
669 $db_field = db_concat($this->seed->table_name, $this->seed->field_name_map[$db_field]['db_concat_fields']);
671 $db_field = $this->seed->table_name . "." . $db_field;
673 if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
674 $db_field = db_concat($this->seed->table_name . "_cstm.", $this->seed->field_name_map[$db_field]['db_concat_fields']);
676 $db_field = $this->seed->table_name . "_cstm." . $db_field;
681 if($type == 'date') {
682 // Collin - Have mysql as first because it's usually the case
683 // The regular expression check is to circumvent special case YYYY-MM
684 if($GLOBALS['db']->dbType == 'mysql') {
685 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
686 $field_value = $timedate->to_db_date($field_value, false);
689 $operator = 'db_date';
691 } else if($GLOBALS['db']->dbType == 'mssql') {
692 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
693 $field_value = "Convert(DateTime, '".$timedate->to_db_date($field_value, false)."')";
695 $operator = 'db_date';
697 $field_value = $timedate->to_db_date($field_value, false);
702 if($type == 'datetime' || $type == 'datetimecombo') {
703 $dates = $timedate->getDayStartEndGMT($field_value);
704 $field_value = $dates["start"] . "<>" . $dates["end"];
705 $operator = 'between';
707 if($type == 'decimal' || $type == 'float' || $type == 'currency') {
708 require_once('modules/Currencies/Currency.php');
710 $field_value = unformat_number($field_value);
711 if ( $type == 'currency' && stripos($field,'_usdollar')!==FALSE ) {
712 // It's a US Dollar field, we need to do some conversions from the user's local currency
713 $currency_id = $GLOBALS['current_user']->getPreference('currency');
714 if ( empty($currency_id) ) {
717 if ( $currency_id != -99 ) {
718 $currency = new Currency();
719 $currency->retrieve($currency_id);
720 $field_value = $currency->convertToDollar($field_value);
724 // Databases can't really search for floating point numbers, because they can't be accurately described in binary,
725 // So we have to fuzz out the match a little bit
726 $top = $field_value + 0.01;
727 $bottom = $field_value - 0.01;
728 $field_value = $bottom . "<>" . $top;
729 $operator = 'between';
739 switch(strtolower($operator)) {
742 if ( isset($parms['subquery_in_clause']) ) {
743 if ( !is_array($parms['subquery_in_clause']) ) {
744 $in = $parms['subquery_in_clause'];
746 elseif ( isset($parms['subquery_in_clause'][$field_value]) ) {
747 $in = $parms['subquery_in_clause'][$field_value];
750 $sq = $parms['subquery'];
753 if (isset($sq['OR'])){
758 if(empty($q) || strlen($q)<2) continue;
762 $where .= " {$db_field} $in ({$q} '{$field_value}%') ";
765 }elseif(!empty($parms['query_type']) && $parms['query_type'] == 'format'){
766 $stringFormatParams = array(0 => $field_value, 1 => $GLOBALS['current_user']->id);
767 $where .= "{$db_field} $in (".string_format($parms['subquery'], $stringFormatParams).")";
769 $where .= "{$db_field} $in ({$parms['subquery']} '{$field_value}%')";
775 if($type == 'bool' && $field_value == 0) {
776 $where .= $db_field . " = '0' OR " . $db_field . " IS NULL";
779 //check to see if this is coming from unified search or not
780 $UnifiedSearch = !empty($parms['force_unifiedsearch']);
781 if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'UnifiedSearch'){
782 $UnifiedSearch = true;
784 //check to see if this is a universal search, AND the field name is "last_name"
785 if($UnifiedSearch && strpos($db_field, 'last_name') !== false){
786 //split the string value, and the db field name
787 $string = explode(' ', $field_value);
788 $column_name = explode('.', $db_field);
790 //when a search is done with a space, we concatenate and search against the full name.
791 if(count($string)>1){
792 //add where clause agains concatenated fields
793 $where .= $GLOBALS['db']->concat($column_name[0],array('first_name','last_name')) . " LIKE '{$field_value}%'";
794 $where .= ' OR ' . $GLOBALS['db']->concat($column_name[0],array('last_name','first_name')) . " LIKE '{$field_value}%'";
796 //no space was found, add normal where clause
797 $where .= $db_field . " like '".$field_value.$like_char."'";
801 //field is not last name or this is not from global unified search, so do normal where clause
802 $where .= $db_field . " like '".$field_value.$like_char."'";
807 $where .= $db_field . " in (".$field_value.')';
810 if($type == 'bool' && $field_value == 0) {
811 $where .= $db_field . " = '0' OR " . $db_field . " IS NULL";
814 $where .= $db_field . " = '".$field_value ."'";
818 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) == 0) {
819 $where .= $db_field . " = ". $field_value;
821 // Create correct date_format conversion String
822 if($GLOBALS['db']->dbType == 'oci8') {
823 $where .= db_convert($db_field,'date_format',array("'YYYY-MM'")) . " = '" . $field_value . "'";
825 $where .= db_convert($db_field,'date_format',array("'%Y-%m'")) . " = '" . $field_value . "'";
829 // tyoung bug 15971 - need to add these special cases into the $where query
831 $where .= $field_value;
834 $field_value = explode('<>', $field_value);
835 $where .= $db_field . " >= '".$field_value[0] . "' AND " .$db_field . " <= '".$field_value[1]."'";
838 $this->seed->listview_inner_join[] = $parms['innerjoin'] . " '" . $parms['value'] . "%')";
841 // OOTB fields are NULL, custom fields are blank
842 $where .= '('.$db_field . ' IS NULL or ' . $db_field . "='')";
843 if ($field_value != '')
844 $where .= ' OR ' . $db_field . " in (".$field_value.')';
852 array_push($where_clauses, '( '.$where.' )');
855 array_push($where_clauses, $where);
861 return $where_clauses;