2 /*********************************************************************************
3 * SugarCRM Community Edition is a customer relationship management program developed by
4 * SugarCRM, Inc. Copyright (C) 2004-2012 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 require_once('include/tabs.php');
39 require_once('include/ListView/ListViewSmarty.php');
40 require_once('include/TemplateHandler/TemplateHandler.php');
41 require_once('include/EditView/EditView2.php');
44 class SearchForm extends EditView{
47 var $action = 'index';
48 var $searchdefs = array();
49 var $listViewDefs = array();
53 var $view = 'SearchForm';
54 var $displayView = 'basic_search';
59 var $parsedView = 'basic';
62 var $displaySavedSearch = true;
63 //show the advanced tab
64 var $showAdvanced = true;
66 var $showBasic = true;
67 //array of custom tab to show declare in searchdefs (no custom tab if false)
68 var $showCustom = false;
71 // hide saved searches drop and down near the search button
72 var $showSavedSearchesOptions = true;
74 var $displayType = 'searchView';
81 public function SearchForm($seed, $module, $action = 'index', $options = array())
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 () ;
100 $this->setOptions($options);
103 function setup($searchdefs, $searchFields = array(), $tpl, $displayView = 'basic_search', $listViewDefs = array()){
104 $this->searchdefs = $searchdefs[$this->module];
106 //used by advanced search
107 $this->listViewDefs = $listViewDefs;
108 $this->displayView = $displayView;
109 $this->view = $this->view.'_'.$displayView;
110 $tokens = explode('_', $this->displayView);
111 $this->parsedView = $tokens[0];
112 $this->searchFields = $searchFields[$this->module];
113 if($this->displayView != 'saved_views'){
114 $this->_build_field_defs();
118 // Setup the tab array.
119 $this->tabs = array();
120 if($this->showBasic){
122 $this->tabs[]=array('title' => $GLOBALS['app_strings']['LNK_BASIC_SEARCH'],
123 'link' => $this->module . '|basic_search',
124 'key' => $this->module . '|basic_search',
128 if($this->showAdvanced){
130 $this->tabs[]=array('title' => $GLOBALS['app_strings']['LNK_ADVANCED_SEARCH'],
131 'link' => $this->module . '|advanced_search',
132 'key' => $this->module . '|advanced_search',
133 'name' => 'advanced',
134 'displayDiv' => 'display:none');
136 if(isset($this->showCustom) && is_array($this->showCustom)){
137 foreach($this->showCustom as $v){
139 $this->tabs[]=array('title' => $GLOBALS['app_strings']["LNK_" . strtoupper($v)],
140 'link' => $this->module . '|' . $v,
141 'key' => $this->module . '|' . $v,
142 'name' => str_replace('_search','',$v),
143 'displayDiv' => 'display:none',);
148 function display($header = true){
149 global $theme, $timedate, $current_user;
153 $this->th->ss->assign('module', $this->module);
154 $this->th->ss->assign('action', $this->action);
155 $this->th->ss->assign('displayView', $this->displayView);
156 $this->th->ss->assign('APP', $GLOBALS['app_strings']);
157 //Show the tabs only if there is more than one
159 $this->th->ss->assign('TABS', $this->_displayTabs($this->module . '|' . $this->displayView));
161 $this->th->ss->assign('searchTableColumnCount',
162 ((isset($this->searchdefs['templateMeta']['maxColumns']) ? $this->searchdefs['templateMeta']['maxColumns'] : 2) * 2 ) - 1);
163 $this->th->ss->assign('fields', $this->fieldDefs);
164 $this->th->ss->assign('customFields', $this->customFieldDefs);
165 $this->th->ss->assign('formData', $this->formData);
166 $time_format = $timedate->get_user_time_format();
167 $this->th->ss->assign('TIME_FORMAT', $time_format);
168 $this->th->ss->assign('USER_DATEFORMAT', $timedate->get_user_date_format());
169 $this->th->ss->assign('CALENDAR_FDOW', $current_user->get_first_day_of_week());
171 $date_format = $timedate->get_cal_date_format();
172 $time_separator = ":";
173 if(preg_match('/\d+([^\d])\d+([^\d]*)/s', $time_format, $match)) {
174 $time_separator = $match[1];
176 // Create Smarty variables for the Calendar picker widget
177 $t23 = strpos($time_format, '23') !== false ? '%H' : '%I';
178 if(!isset($match[2]) || $match[2] == '') {
179 $this->th->ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M");
181 $pm = $match[2] == "pm" ? "%P" : "%p";
182 $this->th->ss->assign('CALENDAR_FORMAT', $date_format . ' ' . $t23 . $time_separator . "%M" . $pm);
184 $this->th->ss->assign('TIME_SEPARATOR', $time_separator);
186 //Show and hide the good tab form
187 foreach($this->tabs as $tabkey=>$viewtab){
188 $viewName=str_replace(array($this->module . '|','_search'),'',$viewtab['key']);
189 if(strpos($this->view,$viewName)!==false){
190 $this->tabs[$tabkey]['displayDiv']='';
191 //if this is advanced tab, use form with saved search sub form built in
192 if($viewName=='advanced'){
193 $this->tpl = 'SearchFormGenericAdvanced.tpl';
194 if ($this->action =='ListView') {
195 $this->th->ss->assign('DISPLAY_SEARCH_HELP', true);
197 $this->th->ss->assign('DISPLAY_SAVED_SEARCH', $this->displaySavedSearch);
198 $this->th->ss->assign('SAVED_SEARCH', $this->displaySavedSearch());
199 //this determines whether the saved search subform should be rendered open or not
200 if(isset($_REQUEST['showSSDIV']) && $_REQUEST['showSSDIV']=='yes'){
201 $this->th->ss->assign('SHOWSSDIV', 'yes');
202 $this->th->ss->assign('DISPLAYSS', '');
204 $this->th->ss->assign('SHOWSSDIV', 'no');
205 $this->th->ss->assign('DISPLAYSS', 'display:none');
209 $this->tabs[$tabkey]['displayDiv']='display:none';
214 $this->th->ss->assign('TAB_ARRAY', $this->tabs);
217 if ( isset($this->searchdefs['templateMeta']['widths'])
218 && isset($this->searchdefs['templateMeta']['maxColumns'])) {
219 $totalWidth = ( $this->searchdefs['templateMeta']['widths']['label'] +
220 $this->searchdefs['templateMeta']['widths']['field'] ) *
221 $this->searchdefs['templateMeta']['maxColumns'];
222 // redo the widths in case they are too big
223 if ( $totalWidth > 100 ) {
224 $resize = 100 / $totalWidth;
225 $this->searchdefs['templateMeta']['widths']['label'] =
226 $this->searchdefs['templateMeta']['widths']['label'] * $resize;
227 $this->searchdefs['templateMeta']['widths']['field'] =
228 $this->searchdefs['templateMeta']['widths']['field'] * $resize;
231 $this->th->ss->assign('templateMeta', $this->searchdefs['templateMeta']);
232 $this->th->ss->assign('HAS_ADVANCED_SEARCH', !empty($this->searchdefs['layout']['advanced_search']));
233 $this->th->ss->assign('displayType', $this->displayType);
234 // return the form of the shown tab only
235 if($this->showSavedSearchesOptions){
236 $this->th->ss->assign('SAVED_SEARCHES_OPTIONS', $this->displaySavedSearchSelect());
238 if ($this->module == 'Documents'){
239 $this->th->ss->assign('DOCUMENTS_MODULE', true);
242 $return_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchForm_'.$this->parsedView, $this->locateFile($this->tpl));
245 $this->th->ss->assign('return_txt', $return_txt);
246 $header_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormHeader', $this->locateFile('header.tpl'));
247 //pass in info to render the select dropdown below the form
248 $footer_txt = $this->th->displayTemplate($this->seed->module_dir, 'SearchFormFooter', $this->locateFile('footer.tpl'));
249 $return_txt = $header_txt.$footer_txt;
256 * @param array $options
257 * @return SearchForm2
259 public function setOptions($options = null)
262 'locator_class' => 'FileLocator',
263 'locator_class_params' => array(
265 'custom/modules/' . $this->module . '/tpls/SearchForm',
266 'modules/' . $this->module . '/tpls/SearchForm',
267 'custom/include/SearchForm/tpls',
268 'include/SearchForm/tpls'
273 $this->options = empty($options) ? $defaults : $options;
281 public function getOptions()
283 return $this->options;
288 * Locate a file in the custom or stock folders. Look in the custom folders first.
290 * @param string $file The file we are looking for
291 * @return bool|string If the file is found return the path, False if not
293 protected function locateFile($file)
295 $paths = isset($this->options['locator_class_params'])?$this->options['locator_class_params'][0]:array();
296 foreach ($paths as $path) {
297 if (is_file($path . '/' . $file)) {
298 return $path . '/' . $file;
305 function displaySavedSearch()
307 $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
308 return $savedSearch->getForm($this->module, false);
312 function displaySavedSearchSelect(){
313 $savedSearch = new SavedSearch($this->listViewDefs[$this->module], $this->lv->data['pageData']['ordering']['orderBy'], $this->lv->data['pageData']['ordering']['sortOrder']);
314 return $savedSearch->getSelect($this->module);
320 * displays the tabs (top of the search form)
322 * @param string $currentKey key in $this->tabs to show as the current tab
324 * @return string html
326 function _displayTabs($currentKey)
328 if(isset($_REQUEST['saved_search_select']) && $_REQUEST['saved_search_select']!='_none') {
329 $saved_search=loadBean('SavedSearch');
330 $saved_search->retrieveSavedSearch($_REQUEST['saved_search_select']);
334 if(!empty($_REQUEST['displayColumns']))
335 $str .= 'SUGAR.savedViews.displayColumns = "' . $_REQUEST['displayColumns'] . '";';
336 elseif(isset($saved_search->contents['displayColumns']) && !empty($saved_search->contents['displayColumns']))
337 $str .= 'SUGAR.savedViews.displayColumns = "' . $saved_search->contents['displayColumns'] . '";';
338 if(!empty($_REQUEST['hideTabs']))
339 $str .= 'SUGAR.savedViews.hideTabs = "' . $_REQUEST['hideTabs'] . '";';
340 elseif(isset($saved_search->contents['hideTabs']) && !empty($saved_search->contents['hideTabs']))
341 $str .= 'SUGAR.savedViews.hideTabs = "' . $saved_search->contents['hideTabs'] . '";';
342 if(!empty($_REQUEST['orderBy']))
343 $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $_REQUEST['orderBy'] . '";';
344 elseif(isset($saved_search->contents['orderBy']) && !empty($saved_search->contents['orderBy']))
345 $str .= 'SUGAR.savedViews.selectedOrderBy = "' . $saved_search->contents['orderBy'] . '";';
346 if(!empty($_REQUEST['sortOrder']))
347 $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $_REQUEST['sortOrder'] . '";';
348 elseif(isset($saved_search->contents['sortOrder']) && !empty($saved_search->contents['sortOrder']))
349 $str .= 'SUGAR.savedViews.selectedSortOrder = "' . $saved_search->contents['sortOrder'] . '";';
359 function _build_field_defs(){
360 $this->formData = array();
361 $this->fieldDefs = array();
362 foreach($this->searchdefs['layout'][$this->displayView] as $data){
364 //Fields may be listed but disabled so that when they are enabled, they have the correct custom display data.
365 if (isset($data['enabled']) && $data['enabled'] == false)
367 $data['name'] = $data['name'].'_'.$this->parsedView;
368 $this->formData[] = array('field' => $data);
369 $this->fieldDefs[$data['name']]= $data;
371 $this->formData[] = array('field' => array('name'=>$data.'_'.$this->parsedView));
376 $this->seed->fill_in_additional_detail_fields();
377 // hack to make the employee status field for the Users/Employees module display correctly
378 if($this->seed->object_name == 'Employee' || $this->seed->object_name == 'User'){
379 $this->seed->field_defs['employee_status']['type'] = 'enum';
380 $this->seed->field_defs['employee_status']['massupdate'] = true;
381 $this->seed->field_defs['employee_status']['options'] = 'employee_status_dom';
382 unset($this->seed->field_defs['employee_status']['function']);
385 foreach($this->seed->toArray() as $name => $value) {
386 $fvName = $name.'_'.$this->parsedView;
387 if(!empty($this->fieldDefs[$fvName]))
388 $this->fieldDefs[$fvName] = array_merge($this->seed->field_defs[$name], $this->fieldDefs[$fvName]);
390 $this->fieldDefs[$fvName] = $this->seed->field_defs[$name];
391 $this->fieldDefs[$fvName]['name'] = $this->fieldDefs[$fvName]['name'].'_'.$this->parsedView;
394 if(isset($this->fieldDefs[$fvName]['type']) && $this->fieldDefs[$fvName]['type'] == 'relate') {
395 if(isset($this->fieldDefs[$fvName]['id_name'])) {
396 $this->fieldDefs[$fvName]['id_name'] .= '_'.$this->parsedView;
400 if(isset($this->fieldDefs[$fvName]['options']) && isset($GLOBALS['app_list_strings'][$this->fieldDefs[$fvName]['options']]))
403 $this->fieldDefs[$fvName]['options'] = $GLOBALS['app_list_strings'][$this->fieldDefs[$fvName]['options']];
404 //Hack to add blanks for parent types on search views
405 //53131 - add blank option for SearchField options with def 'options_add_blank' set to true
406 if ($this->fieldDefs[$fvName]['type'] == "parent_type" || $this->fieldDefs[$fvName]['type'] == "parent" || (isset($this->searchFields[$name]['options_add_blank']) && $this->searchFields[$name]['options_add_blank']) )
408 $this->fieldDefs[$fvName]['options'] = array_merge(array(""=>""), $this->fieldDefs[$fvName]['options']);
412 if(isset($this->fieldDefs[$fvName]['function'])) {
414 $this->fieldDefs[$fvName]['type']='multienum';
416 if(is_array($this->fieldDefs[$fvName]['function'])) {
417 $this->fieldDefs[$fvName]['function']['preserveFunctionValue']=true;
420 $function = $this->fieldDefs[$fvName]['function'];
422 if(is_array($function) && isset($function['name'])){
423 $function_name = $this->fieldDefs[$fvName]['function']['name'];
425 $function_name = $this->fieldDefs[$fvName]['function'];
428 if(!empty($this->fieldDefs[$fvName]['function']['returns']) && $this->fieldDefs[$fvName]['function']['returns'] == 'html'){
429 if(!empty($this->fieldDefs[$fvName]['function']['include'])){
430 require_once($this->fieldDefs[$fvName]['function']['include']);
432 $value = call_user_func($function_name, $this->seed, $name, $value, $this->view);
433 $this->fieldDefs[$fvName]['value'] = $value;
435 if(!isset($function['params']) || !is_array($function['params'])) {
436 $this->fieldDefs[$fvName]['options'] = call_user_func($function_name, $this->seed, $name, $value, $this->view);
438 $this->fieldDefs[$fvName]['options'] = call_user_func_array($function_name, $function['params']);
442 if(isset($this->fieldDefs[$name]['type']) && $this->fieldDefs[$fvName]['type'] == 'function'
443 && isset($this->fieldDefs[$fvName]['function_name']))
445 $value = $this->callFunction($this->fieldDefs[$fvName]);
446 $this->fieldDefs[$fvName]['value'] = $value;
449 $this->fieldDefs[$name]['value'] = $value;
452 if((!empty($_REQUEST[$fvName]) || (isset($_REQUEST[$fvName]) && $_REQUEST[$fvName] == '0'))
453 && empty($this->fieldDefs[$fvName]['function']['preserveFunctionValue'])) {
454 $value = $_REQUEST[$fvName];
455 $this->fieldDefs[$fvName]['value'] = $value;
466 * Populate the searchFields from an array
468 * @param array $array array to search through
469 * @param string $switchVar variable to use in switch statement
470 * @param bool $addAllBeanFields true to process at all bean fields
472 function populateFromArray(&$array, $switchVar = null, $addAllBeanFields = true) {
474 if((!empty($array['searchFormTab']) || !empty($switchVar)) && !empty($this->searchFields)) {
475 $arrayKeys = array_keys($array);
476 $searchFieldsKeys = array_keys($this->searchFields);
477 if(empty($switchVar)) $switchVar = $array['searchFormTab'];
478 //name of the search tab
479 $SearchName=str_replace('_search', '', $switchVar);
480 if($switchVar=='saved_views'){
481 foreach($this->searchFields as $name => $params) {
482 foreach($this->tabs as $tabName){
483 if(!empty($array[$name . '_' . $tabName['name']])) {
484 $this->searchFields[$name]['value'] = $array[$name . '_' . $tabName['name']];
485 if(empty($this->fieldDefs[$name . '_' . $tabName['name']]['value'])) $this->fieldDefs[$name . '_' . $tabName['name']]['value'] = $array[$name . '_' . $tabName['name']];
489 if($addAllBeanFields) {
490 foreach($this->seed->field_name_map as $key => $params) {
491 if(!in_array($key, $searchFieldsKeys)) {
492 foreach($this->tabs->name as $tabName){
493 if(in_array($key . '_' . $tabName['name'], $arrayKeys) ) {
494 $this->searchFields[$key] = array('query_type' => 'default',
495 'value' => $array[$key . '_' . $tabName['name']]);
503 $fromMergeRecords = isset($array['merge_module']);
505 foreach($this->searchFields as $name => $params) {
506 $long_name = $name.'_'.$SearchName;
507 /*nsingh 21648: Add additional check for bool values=0. empty() considers 0 to be empty Only repopulates if value is 0 or 1:( */
508 if (isset($array[$long_name]) && ( $array[$long_name] !== '' || (isset($this->fieldDefs[$long_name]['type']) && $this->fieldDefs[$long_name]['type'] == 'bool'&& ($array[$long_name]=='0' || $array[$long_name]=='1'))))
510 $this->searchFields[$name]['value'] = $array[$long_name];
511 if(empty($this->fieldDefs[$long_name]['value'])) {
512 $this->fieldDefs[$long_name]['value'] = $array[$long_name];
515 else if(!empty($array[$name]) && !$fromMergeRecords) // basic
517 $this->searchFields[$name]['value'] = $array[$name];
518 if(empty($this->fieldDefs[$long_name]['value'])) {
519 $this->fieldDefs[$long_name]['value'] = $array[$name];
523 if(!empty($params['enable_range_search']) && isset($this->searchFields[$name]['value']))
525 if(preg_match('/^range_(.*?)$/', $long_name, $match) && isset($array[$match[1].'_range_choice']))
527 $this->searchFields[$name]['operator'] = $array[$match[1].'_range_choice'];
531 if(!empty($params['is_date_field']) && isset($this->searchFields[$name]['value']))
534 // 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)
535 $date_value = $timedate->to_db_date($this->searchFields[$name]['value'], false);
536 $this->searchFields[$name]['value'] = $date_value == '' ? $this->searchFields[$name]['value'] : $date_value;
540 if((empty($array['massupdate']) || $array['massupdate'] == 'false') && $addAllBeanFields) {
541 foreach($this->seed->field_name_map as $key => $params) {
542 if($key != 'assigned_user_name' && $key != 'modified_by_name')
544 $long_name = $key.'_'.$SearchName;
546 if(in_array($key.'_'.$SearchName, $arrayKeys) && !in_array($key, $searchFieldsKeys))
548 $this->searchFields[$key] = array('query_type' => 'default', 'value' => $array[$long_name]);
550 if (!empty($params['type']) && $params['type'] == 'parent'
551 && !empty($params['type_name']) && !empty($this->searchFields[$key]['value']))
553 require_once('include/SugarFields/SugarFieldHandler.php');
554 $sfh = new SugarFieldHandler();
555 $sf = $sfh->getSugarField('Parent');
557 $this->searchFields[$params['type_name']] = array('query_type' => 'default',
558 'value' => $sf->getSearchInput($params['type_name'], $array));
561 if(empty($this->fieldDefs[$long_name]['value'])) {
562 $this->fieldDefs[$long_name]['value'] = $array[$long_name];
572 if ( is_array($this->searchFields) ) {
573 foreach ( $this->searchFields as $fieldName => $field ) {
574 if ( !empty($field['value']) && is_string($field['value']) ) {
575 $this->searchFields[$fieldName]['value'] = trim($field['value']);
583 * Populate the searchFields from $_REQUEST
585 * @param string $switchVar variable to use in switch statement
586 * @param bool $addAllBeanFields true to process at all bean fields
588 function populateFromRequest($switchVar = null, $addAllBeanFields = true) {
589 $this->populateFromArray($_REQUEST, $switchVar, $addAllBeanFields);
594 * Parse date expression and return WHERE clause
595 * @param string $operator Date expression operator
596 * @param string DB field name
597 * @param string DB field type
599 protected function parseDateExpression($operator, $db_field, $field_type = '')
601 if ($field_type == "date") {
608 $dates = TimeDate::getInstance()->parseDateRange($operator, null, $adjForTZ);
609 if(empty($dates)) return '';
610 $start = $this->seed->db->convert($this->seed->db->quoted($dates[0]->asDb()), $type);
611 $end = $this->seed->db->convert($this->seed->db->quoted($dates[1]->asDb()), $type);
612 return "($db_field >= $start AND $db_field <= $end)";
616 * generateSearchWhere
618 * This function serves as the central piece of SearchForm2.php
619 * It is responsible for creating the WHERE clause for a given search operation
621 * @param bool $add_custom_fields boolean indicating whether or not custom fields should be added
622 * @param string $module Module to search against
624 * @return string the SQL WHERE clause based on the arguments supplied in SearchForm2 instance
626 public function generateSearchWhere($add_custom_fields = false, $module='') {
629 $db = $this->seed->db;
630 $this->searchColumns = array () ;
631 $values = $this->searchFields;
633 $where_clauses = array();
635 $table_name = $this->seed->object_name;
636 $this->seed->fill_in_additional_detail_fields();
638 //rrs check for team_id
640 foreach($this->searchFields as $field=>$parms) {
641 $customField = false;
642 // Jenny - Bug 7462: We need a type check here to avoid database errors
643 // when searching for numeric fields. This is a temporary fix until we have
644 // a generic search form validation mechanism.
645 $type = (!empty($this->seed->field_name_map[$field]['type']))?$this->seed->field_name_map[$field]['type']:'';
647 //If range search is enabled for the field, we first check if this is the starting range
648 if(!empty($parms['enable_range_search']) && empty($type))
650 if(preg_match('/^start_range_(.*?)$/', $field, $match))
652 $real_field = $match[1];
653 $start_field = 'start_range_' . $real_field;
654 $end_field = 'end_range_' . $real_field;
656 if(isset($this->searchFields[$start_field]['value']) && isset($this->searchFields[$end_field]['value']))
658 $this->searchFields[$real_field]['value'] = $this->searchFields[$start_field]['value'] . '<>' . $this->searchFields[$end_field]['value'];
659 $this->searchFields[$real_field]['operator'] = 'between';
660 $parms['value'] = $this->searchFields[$real_field]['value'];
661 $parms['operator'] = 'between';
663 $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
664 if($field_type == 'datetimecombo' || $field_type == 'datetime')
669 $field = $real_field;
670 unset($this->searchFields[$end_field]['value']);
672 } else if (preg_match('/^range_(.*?)$/', $field, $match) && isset($this->searchFields[$field]['value'])) {
673 $real_field = $match[1];
675 //Special case for datetime and datetimecombo fields. By setting the type here we allow an actual between search
676 if(in_array($parms['operator'], array('=', 'between', "not_equal", 'less_than', 'greater_than', 'less_than_equals', 'greater_than_equals')))
678 $field_type = isset($this->seed->field_name_map[$real_field]['type']) ? $this->seed->field_name_map[$real_field]['type'] : '';
679 if(strtolower($field_type) == 'readonly' && isset($this->seed->field_name_map[$real_field]['dbType'])) {
680 $field_type = $this->seed->field_name_map[$real_field]['dbType'];
682 if($field_type == 'datetimecombo' || $field_type == 'datetime' || $field_type == 'int')
688 $this->searchFields[$real_field]['value'] = $this->searchFields[$field]['value'];
689 $this->searchFields[$real_field]['operator'] = $this->searchFields[$field]['operator'];
690 $params['value'] = $this->searchFields[$field]['value'];
691 $params['operator'] = $this->searchFields[$field]['operator'];
692 unset($this->searchFields[$field]['value']);
693 $field = $real_field;
695 //Skip this range search field, it is the end field THIS IS NEEDED or the end range date will break the query
700 //Test to mark whether or not the field is a custom field
701 if(!empty($this->seed->field_name_map[$field]['source'])
702 && ($this->seed->field_name_map[$field]['source'] == 'custom_fields' ||
703 //Non-db custom fields, such as custom relates
704 ($this->seed->field_name_map[$field]['source'] == 'non-db'
705 && (!empty($this->seed->field_name_map[$field]['custom_module']) ||
706 isset($this->seed->field_name_map[$field]['ext2']))))){
710 if ($type == 'int' && isset($parms['value']) && !empty($parms['value'])) {
711 require_once ('include/SugarFields/SugarFieldHandler.php');
712 $intField = SugarFieldHandler::getSugarField('int');
713 $newVal = $intField->getSearchWhereValue($parms['value']);
714 $parms['value'] = $newVal;
715 } elseif($type == 'html' && $customField) {
720 if(isset($parms['value']) && $parms['value'] != "") {
722 $operator = $db->isNumericType($type)?'=':'like';
723 if(!empty($parms['operator'])) {
724 $operator = strtolower($parms['operator']);
727 if(is_array($parms['value'])) {
730 // always construct the where clause for multiselects using the 'like' form to handle combinations of multiple $vals and multiple $parms
731 if(!empty($this->seed->field_name_map[$field]['isMultiSelect']) && $this->seed->field_name_map[$field]['isMultiSelect']) {
732 // construct the query for multenums
733 // use the 'like' query as both custom and OOB multienums are implemented with types that cannot be used with an 'in'
734 $operator = 'custom_enum';
735 $table_name = $this->seed->table_name ;
737 $table_name .= "_cstm" ;
738 $db_field = $table_name . "." . $field;
740 foreach($parms['value'] as $val) {
741 if($val != ' ' and $val != '') {
742 $qVal = $db->quote($val);
743 if (!empty($field_value)) {
744 $field_value .= ' or ';
746 $field_value .= "$db_field like '%^$qVal^%'";
748 $field_value .= '('.$db_field . ' IS NULL or '.$db_field."='^^' or ".$db_field."='')";
753 $operator = $operator != 'subquery' ? 'in' : $operator;
754 foreach($parms['value'] as $val) {
755 if($val != ' ' and $val != '') {
756 if (!empty($field_value)) {
759 $field_value .= $db->quoteType($type, $val);
761 // Bug 41209: adding a new operator "isnull" here
762 // to handle the case when blank is selected from dropdown.
763 // In that case, $val is empty.
764 // When $val is empty, we need to use "IS NULL",
765 // as "in (null)" won't work
766 else if ($operator=='in') {
767 $operator = 'isnull';
773 $field_value = $parms['value'];
776 //set db_fields array.
777 if(!isset($parms['db_field'])) {
778 $parms['db_field'] = array($field);
781 //This if-else block handles the shortcut checkbox selections for "My Items" and "Closed Only"
782 if(!empty($parms['my_items'])) {
783 if( $parms['value'] == false ) {
786 //my items is checked.
787 global $current_user;
788 $field_value = $db->quote($current_user->id);
791 } else if(!empty($parms['closed_values']) && is_array($parms['closed_values'])) {
792 if( $parms['value'] == false ) {
796 foreach($parms['closed_values'] as $closed_value)
798 $field_value .= "," . $db->quoted($closed_value);
800 $field_value = substr($field_value, 1);
807 if($field_value != '' || $operator=='isnull') {
809 $this->searchColumns [ strtoupper($field) ] = $field ;
811 foreach ($parms['db_field'] as $db_field) {
812 if (strstr($db_field, '.') === false) {
813 //Try to get the table for relate fields from link defs
814 if ($type == 'relate' && !empty($this->seed->field_name_map[$field]['link'])
815 && !empty($this->seed->field_name_map[$field]['rname'])) {
816 $link = $this->seed->field_name_map[$field]['link'];
817 $relname = $link['relationship'];
818 if (($this->seed->load_relationship($link))){
820 $db_field = $this->seed->field_name_map[$field]['name'];
822 //Best Guess for table name
823 $db_field = strtolower($link['module']) . '.' . $db_field;
828 else if ($type == 'parent') {
829 if (!empty($this->searchFields['parent_type'])) {
830 $parentType = $this->searchFields['parent_type'];
831 $rel_module = $parentType['value'];
832 global $beanFiles, $beanList;
833 if(!empty($beanFiles[$beanList[$rel_module]])) {
834 require_once($beanFiles[$beanList[$rel_module]]);
835 $rel_seed = new $beanList[$rel_module]();
836 $db_field = 'parent_' . $rel_module . '_' . $rel_seed->table_name . '.name';
840 // Relate fields in custom modules and custom relate fields
841 else if ($type == 'relate' && $customField && !empty($this->seed->field_name_map[$field]['module'])) {
842 $db_field = !empty($this->seed->field_name_map[$field]['name'])?$this->seed->field_name_map[$field]['name']:'name';
844 else if(!$customField){
845 if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
846 $db_field = $db->concat($this->seed->table_name, $this->seed->field_name_map[$db_field]['db_concat_fields']);
848 $db_field = $this->seed->table_name . "." . $db_field;
850 if ( !empty($this->seed->field_name_map[$field]['db_concat_fields']) )
851 $db_field = $db->concat($this->seed->table_name . "_cstm.", $this->seed->field_name_map[$db_field]['db_concat_fields']);
853 $db_field = $this->seed->table_name . "_cstm." . $db_field;
858 if($type == 'date') {
859 // The regular expression check is to circumvent special case YYYY-MM
861 if(preg_match('/^\d{4}.\d{1,2}$/', $field_value) != 0) { // preg_match returns number of matches
862 $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m"));
864 $field_value = $timedate->to_db_date($field_value, false);
865 $db_field = $this->seed->db->convert($db_field, "date_format", array("%Y-%m-%d"));
869 if($type == 'datetime' || $type == 'datetimecombo') {
871 if($operator == '=' || $operator == 'between') {
872 // FG - bug45287 - If User asked for a range, takes edges from it.
873 $placeholderPos = strpos($field_value, "<>");
874 if ($placeholderPos !== FALSE && $placeholderPos > 0)
876 $datesLimit = explode("<>", $field_value);
877 $dateStart = $timedate->getDayStartEndGMT($datesLimit[0]);
878 $dateEnd = $timedate->getDayStartEndGMT($datesLimit[1]);
880 $dates['end'] = $dateEnd['end'];
881 $dates['enddate'] = $dateEnd['enddate'];
882 $dates['endtime'] = $dateEnd['endtime'];
886 $dates = $timedate->getDayStartEndGMT($field_value);
888 // FG - bug45287 - Note "start" and "end" are the correct interval at GMT timezone
889 $field_value = array($dates["start"], $dates["end"]);
890 $operator = 'between';
891 } else if($operator == 'not_equal') {
892 $dates = $timedate->getDayStartEndGMT($field_value);
893 $field_value = array($dates["start"], $dates["end"]);
894 $operator = 'date_not_equal';
895 } else if($operator == 'greater_than') {
896 $dates = $timedate->getDayStartEndGMT($field_value);
897 $field_value = $dates["end"];
898 } else if($operator == 'less_than') {
899 $dates = $timedate->getDayStartEndGMT($field_value);
900 $field_value = $dates["start"];
901 } else if($operator == 'greater_than_equals') {
902 $dates = $timedate->getDayStartEndGMT($field_value);
903 $field_value = $dates["start"];
904 } else if($operator == 'less_than_equals') {
905 $dates = $timedate->getDayStartEndGMT($field_value);
906 $field_value = $dates["end"];
908 } catch(Exception $timeException) {
909 //In the event that a date value is given that cannot be correctly processed by getDayStartEndGMT method,
910 //just skip searching on this field and continue. This may occur if user switches locale date formats
911 //in another browser screen, but re-runs a search with the previous format on another screen
912 $GLOBALS['log']->error($timeException->getMessage());
917 if($type == 'decimal' || $type == 'float' || $type == 'currency' || (!empty($parms['enable_range_search']) && empty($parms['is_date_field']))) {
918 require_once('modules/Currencies/Currency.php');
920 //we need to handle formatting either a single value or 2 values in case the 'between' search option is set
921 //start by splitting the string if the between operator exists
922 $fieldARR = explode('<>', $field_value);
923 //set the first pass through boolean
925 foreach($fieldARR as $fv){
926 //reset the field value, it will be rebuild in the foreach loop below
927 $tmpfield_value = unformat_number($fv);
929 if ( $type == 'currency' && stripos($field,'_usdollar')!==FALSE ) {
930 // It's a US Dollar field, we need to do some conversions from the user's local currency
931 $currency_id = $GLOBALS['current_user']->getPreference('currency');
932 if ( empty($currency_id) ) {
935 if ( $currency_id != -99 ) {
936 $currency = new Currency();
937 $currency->retrieve($currency_id);
938 $tmpfield_value = $currency->convertToDollar($tmpfield_value);
941 $values[] = $tmpfield_value;
944 $field_value = join('<>',$values);
946 if(!empty($parms['enable_range_search']) && $parms['operator'] == '=' && $type != 'int')
948 // Databases can't really search for floating point numbers, because they can't be accurately described in binary,
949 // So we have to fuzz out the math a little bit
950 $field_value = array(($field_value - 0.01) , ($field_value + 0.01));
951 $operator = 'between';
956 if($db->supports("case_sensitive") && isset($parms['query_type']) && $parms['query_type'] == 'case_insensitive') {
957 $db_field = 'upper(' . $db_field . ")";
958 $field_value = strtoupper($field_value);
966 //Here we make a last attempt to determine the field type if possible
967 if(empty($type) && isset($parms['db_field']) && isset($parms['db_field'][0]) && isset($this->seed->field_defs[$parms['db_field'][0]]['type']))
969 $type = $this->seed->field_defs[$parms['db_field'][0]]['type'];
972 switch(strtolower($operator)) {
975 if ( isset($parms['subquery_in_clause']) ) {
976 if ( !is_array($parms['subquery_in_clause']) ) {
977 $in = $parms['subquery_in_clause'];
979 elseif ( isset($parms['subquery_in_clause'][$field_value]) ) {
980 $in = $parms['subquery_in_clause'][$field_value];
983 $sq = $parms['subquery'];
986 if (isset($sq['OR'])){
991 if(empty($q) || strlen($q)<2) continue;
995 $where .= " {$db_field} $in ({$q} ".$this->seed->db->quoted($field_value.'%').") ";
998 }elseif(!empty($parms['query_type']) && $parms['query_type'] == 'format'){
999 $stringFormatParams = array(0 => $field_value, 1 => $GLOBALS['current_user']->id);
1000 $where .= "{$db_field} $in (".string_format($parms['subquery'], $stringFormatParams).")";
1002 //Bug#37087: Re-write our sub-query to it is executed first and contents stored in a derived table to avoid mysql executing the query
1003 //outside in. Additional details: http://bugs.mysql.com/bug.php?id=9021
1004 $where .= "{$db_field} $in (select * from ({$parms['subquery']} ".$this->seed->db->quoted($field_value.'%').") {$field}_derived)";
1010 if($type == 'bool' && $field_value == 0) {
1011 // Bug 43452 - FG - Added parenthesis surrounding the OR (without them the WHERE clause would be broken)
1012 $where .= "( " . $db_field . " = '0' OR " . $db_field . " IS NULL )";
1015 //check to see if this is coming from unified search or not
1016 $UnifiedSearch = !empty($parms['force_unifiedsearch']);
1017 if(isset($_REQUEST['action']) && $_REQUEST['action'] == 'UnifiedSearch'){
1018 $UnifiedSearch = true;
1021 //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"
1022 //BUG 45709: Tasks Advanced Search: Contact Name field does not return matches on full names
1023 //Frank: Adding Surabhi's fix back which seem to have gone missing in CottonCandy merge
1024 if(($UnifiedSearch || !empty($this->seed->field_name_map[$field]['db_concat_fields'])) && strpos($db_field, 'last_name') !== false){
1025 //split the string value, and the db field name
1026 $string = explode(' ', $field_value);
1027 $column_name = explode('.', $db_field);
1028 //when a search is done with a space, we concatenate and search against the full name.
1029 if(count($string)>1){
1030 //add where clause against concatenated fields
1031 $where .= $this->seed->db->concat($column_name[0],array('first_name','last_name')) . " LIKE ".$this->seed->db->quoted($field_value.'%');
1032 $where .= ' OR ' . $this->seed->db->concat($column_name[0],array('last_name','first_name')) . " LIKE ".$this->seed->db->quoted($field_value.'%');
1034 //no space was found, add normal where clause
1035 $where .= $db_field . " like ".$this->seed->db->quoted(sql_like_string($field_value, $like_char));
1040 //Check if this is a first_name, last_name search
1041 if(isset($this->seed->field_name_map) && isset($this->seed->field_name_map[$db_field]))
1043 $vardefEntry = $this->seed->field_name_map[$db_field];
1044 if(!empty($vardefEntry['db_concat_fields']) && in_array('first_name', $vardefEntry['db_concat_fields']) && in_array('last_name', $vardefEntry['db_concat_fields']))
1046 if(!empty($GLOBALS['app_list_strings']['salutation_dom']) && is_array($GLOBALS['app_list_strings']['salutation_dom']))
1048 foreach($GLOBALS['app_list_strings']['salutation_dom'] as $salutation)
1050 if(!empty($salutation) && strpos($field_value, $salutation) === 0)
1052 $field_value = trim(substr($field_value, strlen($salutation)));
1060 //field is not last name or this is not from global unified search, so do normal where clause
1061 $where .= $db_field . " like ".$this->seed->db->quoted(sql_like_string($field_value, $like_char));
1066 $where .= $db_field . ' not in ('.$field_value.')';
1069 $where .= $db_field . ' in ('.$field_value.')';
1072 if($type == 'bool' && $field_value == 0) {
1073 $where .= "($db_field = 0 OR $db_field IS NULL)";
1076 $where .= $db_field . " = ".$db->quoteType($type, $field_value);
1079 // tyoung bug 15971 - need to add these special cases into the $where query
1081 $where .= $field_value;
1084 if(!is_array($field_value)) {
1085 $field_value = explode('<>', $field_value);
1087 $field_value[0] = $db->quoteType($type, $field_value[0]);
1088 $field_value[1] = $db->quoteType($type, $field_value[1]);
1089 $where .= "($db_field >= {$field_value[0]} AND $db_field <= {$field_value[1]})";
1091 case 'date_not_equal':
1092 if(!is_array($field_value)) {
1093 $field_value = explode('<>', $field_value);
1095 $field_value[0] = $db->quoteType($type, $field_value[0]);
1096 $field_value[1] = $db->quoteType($type, $field_value[1]);
1097 $where .= "($db_field IS NULL OR $db_field < {$field_value[0]} OR $db_field > {$field_value[1]})";
1100 $this->seed->listview_inner_join[] = $parms['innerjoin'] . " '" . $parms['value'] . "%')";
1103 $field_value = $db->quoteType($type, $field_value);
1104 $where .= "($db_field IS NULL OR $db_field != $field_value)";
1106 case 'greater_than':
1107 $field_value = $db->quoteType($type, $field_value);
1108 $where .= "$db_field > $field_value";
1110 case 'greater_than_equals':
1111 $field_value = $db->quoteType($type, $field_value);
1112 $where .= "$db_field >= $field_value";
1115 $field_value = $db->quoteType($type, $field_value);
1116 $where .= "$db_field < $field_value";
1118 case 'less_than_equals':
1119 $field_value = $db->quoteType($type, $field_value);
1120 $where .= "$db_field <= $field_value";
1127 case 'last_30_days':
1128 case 'next_30_days':
1132 if (!empty($field) && !empty($this->seed->field_name_map[$field]['type'])) {
1133 $where .= $this->parseDateExpression(strtolower($operator), $db_field, $this->seed->field_name_map[$field]['type']);
1135 $where .= $this->parseDateExpression(strtolower($operator), $db_field);
1139 $where .= "($db_field IS NULL OR $db_field = '')";
1140 if ($field_value != '')
1141 $where .= ' OR ' . $db_field . " in (".$field_value.')';
1147 if(!empty($where)) {
1149 array_push($where_clauses, '( '.$where.' )');
1152 array_push($where_clauses, $where);
1158 return $where_clauses;
1164 * isEmptyDropdownField
1166 * This function checks to see if a blank dropdown field was supplied. This scenario will occur where
1167 * a dropdown select is in single selection mode
1169 * @param $value Mixed dropdown value
1171 private function isEmptyDropdownField($name='', $value=array())
1173 $result = is_array($value) && isset($value[0]) && $value[0] == '';
1174 $GLOBALS['log']->debug("Found empty value for {$name} dropdown search key");
1179 * Return the search defs for a particular module.
1184 public static function retrieveSearchDefs($module)
1186 $searchdefs = array();
1187 $searchFields = array();
1189 if(file_exists('custom/modules/'.$module.'/metadata/metafiles.php'))
1191 require('custom/modules/'.$module.'/metadata/metafiles.php');
1193 elseif(file_exists('modules/'.$module.'/metadata/metafiles.php'))
1195 require('modules/'.$module.'/metadata/metafiles.php');
1198 if (file_exists('custom/modules/'.$module.'/metadata/searchdefs.php'))
1200 require('custom/modules/'.$module.'/metadata/searchdefs.php');
1202 elseif (!empty($metafiles[$module]['searchdefs']))
1204 require($metafiles[$module]['searchdefs']);
1206 elseif (file_exists('modules/'.$module.'/metadata/searchdefs.php'))
1208 require('modules/'.$module.'/metadata/searchdefs.php');
1212 if(!empty($metafiles[$module]['searchfields']))
1214 require($metafiles[$module]['searchfields']);
1216 elseif(file_exists('modules/'.$module.'/metadata/SearchFields.php'))
1218 require('modules/'.$module.'/metadata/SearchFields.php');
1220 if(file_exists('custom/modules/'.$module.'/metadata/SearchFields.php'))
1222 require('custom/modules/'.$module.'/metadata/SearchFields.php');
1225 return array('searchdefs' => $searchdefs, 'searchFields' => $searchFields );