2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4 * SugarCRM Community Edition is a customer relationship management program developed by
5 * SugarCRM, Inc. Copyright (C) 2004-2012 SugarCRM Inc.
7 * This program is free software; you can redistribute it and/or modify it under
8 * the terms of the GNU Affero General Public License version 3 as published by the
9 * Free Software Foundation with the addition of the following permission added
10 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
11 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
12 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
14 * This program is distributed in the hope that it will be useful, but WITHOUT
15 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
16 * FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
19 * You should have received a copy of the GNU Affero General Public License along with
20 * this program; if not, see http://www.gnu.org/licenses or write to the Free
21 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
24 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
25 * SW2-130, Cupertino, CA 95014, USA. or at email address contact@sugarcrm.com.
27 * The interactive user interfaces in modified source and object code versions
28 * of this program must display Appropriate Legal Notices, as required under
29 * Section 5 of the GNU Affero General Public License version 3.
31 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
32 * these Appropriate Legal Notices must retain the display of the "Powered by
33 * SugarCRM" logo. If the display of the logo is not reasonably feasible for
34 * technical reasons, the Appropriate Legal Notices must display the words
35 * "Powered by SugarCRM".
36 ********************************************************************************/
38 /*********************************************************************************
40 * Description: TODO: To be written.
41 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42 * All Rights Reserved.
43 * Contributor(s): ______________________________________..
44 ********************************************************************************/
48 class UnifiedSearchAdvanced {
50 var $query_string = '';
52 /* path to search form */
53 var $searchFormPath = 'include/SearchForm/SearchForm2.php';
55 /*search form class name*/
56 var $searchFormClass = 'SearchForm';
58 function __construct(){
59 if(!empty($_REQUEST['query_string'])){
60 $query_string = trim($_REQUEST['query_string']);
61 if(!empty($query_string)){
62 $this->query_string = $query_string;
65 $this->cache_search = sugar_cached('modules/unified_search_modules.php');
66 $this->cache_display = sugar_cached('modules/unified_search_modules_display.php');
69 function getDropDownDiv($tpl = 'modules/Home/UnifiedSearchAdvanced.tpl') {
70 global $app_list_strings, $app_strings;
72 if(!file_exists($this->cache_search))
77 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
79 global $mod_strings, $modListHeader, $app_list_strings, $current_user, $app_strings, $beanList;
80 $users_modules = $current_user->getPreference('globalSearch', 'search');
82 // preferences are empty, select all
83 if(empty($users_modules)) {
84 $users_modules = array();
85 foreach($unified_search_modules_display as $module=>$data) {
86 if (!empty($data['visible']) ) {
87 $users_modules[$module] = $beanList[$module];
90 $current_user->setPreference('globalSearch', $users_modules, 0, 'search');
93 $sugar_smarty = new Sugar_Smarty();
95 $modules_to_search = array();
97 foreach($users_modules as $key=>$module)
99 if(ACLController::checkAccess($key, 'list', true))
101 $modules_to_search[$key]['checked'] = true;
105 if(!empty($this->query_string))
107 $sugar_smarty->assign('query_string', securexss($this->query_string));
109 $sugar_smarty->assign('query_string', '');
112 $sugar_smarty->assign('MOD', return_module_language($GLOBALS['current_language'], 'Administration'));
113 $sugar_smarty->assign('APP', $app_strings);
114 $sugar_smarty->assign('USE_SEARCH_GIF', 0);
115 $sugar_smarty->assign('LBL_SEARCH_BUTTON_LABEL', $app_strings['LBL_SEARCH_BUTTON_LABEL']);
117 $json_enabled = array();
118 $json_disabled = array();
120 //Now add the rest of the modules that are searchable via Global Search settings
121 foreach($unified_search_modules_display as $module=>$data)
123 if(!isset($modules_to_search[$module]) && $data['visible'] && ACLController::checkAccess($module, 'list', true))
125 $modules_to_search[$module]['checked'] = false;
126 } else if (isset($modules_to_search[$module]) && !$data['visible']) {
127 unset($modules_to_search[$module]);
131 //Create the two lists (doing it this way preserves the user's ordering choice for enabled modules)
132 foreach($modules_to_search as $module=>$data)
134 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
135 if(!empty($data['checked']))
137 $json_enabled[] = array("module" => $module, 'label' => $label);
139 $json_disabled[] = array("module" => $module, 'label' => $label);
143 $sugar_smarty->assign('enabled_modules', json_encode($json_enabled));
144 $sugar_smarty->assign('disabled_modules', json_encode($json_disabled));
146 $showDiv = $current_user->getPreference('showGSDiv', 'search');
152 $sugar_smarty->assign('SHOWGSDIV', $showDiv);
153 $sugar_smarty->debugging = true;
154 return $sugar_smarty->fetch($tpl);
161 * Search function run when user goes to Show All and runs a search again. This outputs the search results
162 * calling upon the various listview display functions for each module searched on.
164 * Todo: Sync this up with SugarSpot.php search method.
170 $unified_search_modules = $this->getUnifiedSearchModules();
171 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
174 require_once 'include/ListView/ListViewSmarty.php';
176 global $modListHeader, $beanList, $beanFiles, $current_language, $app_strings, $current_user, $mod_strings;
177 $home_mod_strings = return_module_language($current_language, 'Home');
179 $this->query_string = $GLOBALS['db']->quote(securexss(from_html(clean_string($this->query_string, 'UNIFIED_SEARCH'))));
181 if(!empty($_REQUEST['advanced']) && $_REQUEST['advanced'] != 'false') {
182 $modules_to_search = array();
183 if(!empty($_REQUEST['search_modules']))
185 foreach(explode (',', $_REQUEST['search_modules'] ) as $e)
187 $modules_to_search[$e] = $beanList[$e];
191 $current_user->setPreference('showGSDiv', isset($_REQUEST['showGSDiv']) ? $_REQUEST['showGSDiv'] : 'no', 0, 'search');
192 $current_user->setPreference('globalSearch', $modules_to_search, 0, 'search'); // save selections to user preference
194 $users_modules = $current_user->getPreference('globalSearch', 'search');
195 $modules_to_search = array();
197 if(!empty($users_modules)) {
198 // use user's previous selections
199 foreach ( $users_modules as $key => $value ) {
200 if (isset($unified_search_modules_display[$key]) && !empty($unified_search_modules_display[$key]['visible'])) {
201 $modules_to_search[$key] = $beanList[$key];
205 foreach($unified_search_modules_display as $module=>$data) {
206 if (!empty($data['visible']) ) {
207 $modules_to_search[$module] = $beanList[$module];
211 $current_user->setPreference('globalSearch', $modules_to_search, 'search');
215 $templateFile = 'modules/Home/UnifiedSearchAdvancedForm.tpl';
216 if(file_exists('custom/' . $templateFile))
218 $templateFile = 'custom/'.$templateFile;
221 echo $this->getDropDownDiv($templateFile);
223 $module_results = array();
224 $module_counts = array();
225 $has_results = false;
227 if(!empty($this->query_string)) {
228 foreach($modules_to_search as $moduleName => $beanName) {
229 require_once $beanFiles[$beanName] ;
230 $seed = new $beanName();
232 $lv = new ListViewSmarty();
233 $lv->lvd->additionalDetails = false;
234 $mod_strings = return_module_language($current_language, $seed->module_dir);
236 //retrieve the original list view defs and store for processing in case of custom layout changes
237 require('modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
238 $orig_listViewDefs = $listViewDefs;
240 if(file_exists('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php'))
242 require('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
245 if ( !isset($listViewDefs) || !isset($listViewDefs[$seed->module_dir]) )
250 $unifiedSearchFields = array () ;
251 $innerJoins = array();
252 foreach ( $unified_search_modules[ $moduleName ]['fields'] as $field=>$def )
254 $listViewCheckField = strtoupper($field);
255 //check to see if the field is in listview defs
256 if ( empty($listViewDefs[$seed->module_dir][$listViewCheckField]['default']) ) {
257 //check to see if field is in original list view defs (in case we are using custom layout defs)
258 if (!empty($orig_listViewDefs[$seed->module_dir][$listViewCheckField]['default']) ) {
259 //if we are here then the layout has been customized, but the field is still needed for query creation
260 $listViewDefs[$seed->module_dir][$listViewCheckField] = $orig_listViewDefs[$seed->module_dir][$listViewCheckField];
265 //bug: 34125 we might want to try to use the LEFT JOIN operator instead of the INNER JOIN in the case we are
266 //joining against a field that has not been populated.
267 if(!empty($def['innerjoin']) )
269 if (empty($def['db_field']) )
273 $innerJoins[$field] = $def;
274 $def['innerjoin'] = str_replace('INNER', 'LEFT', $def['innerjoin']);
277 if(isset($seed->field_defs[$field]['type']))
279 $type = $seed->field_defs[$field]['type'];
280 if($type == 'int' && !is_numeric($this->query_string))
286 $unifiedSearchFields[ $moduleName ] [ $field ] = $def ;
287 $unifiedSearchFields[ $moduleName ] [ $field ][ 'value' ] = $this->query_string ;
291 * Use searchForm2->generateSearchWhere() to create the search query, as it can generate SQL for the full set of comparisons required
292 * generateSearchWhere() expects to find the search conditions for a field in the 'value' parameter of the searchFields entry for that field
294 require_once $beanFiles[$beanName] ;
295 $seed = new $beanName();
297 require_once $this->searchFormPath;
298 $searchForm = new $this->searchFormClass ( $seed, $moduleName ) ;
300 $searchForm->setup (array ( $moduleName => array() ) , $unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
301 $where_clauses = $searchForm->generateSearchWhere() ;
302 //add inner joins back into the where clause
303 $params = array('custom_select' => "");
304 foreach($innerJoins as $field=>$def) {
305 if (isset ($def['db_field'])) {
306 foreach($def['db_field'] as $dbfield)
307 $where_clauses[] = $dbfield . " LIKE '" . $this->query_string . "%'";
308 $params['custom_select'] .= ", $dbfield";
309 $params['distinct'] = true;
310 //$filterFields[$dbfield] = $dbfield;
314 if (count($where_clauses) > 0)
316 $where = '(('. implode(' ) OR ( ', $where_clauses) . '))';
320 /* Clear $where from prev. module
321 if in current module $where_clauses */
324 $displayColumns = array();
325 foreach($listViewDefs[$seed->module_dir] as $colName => $param)
327 if(!empty($param['default']) && $param['default'] == true)
329 $param['url_sort'] = true;//bug 27933
330 $displayColumns[$colName] = $param;
334 if(count($displayColumns) > 0)
336 $lv->displayColumns = $displayColumns;
338 $lv->displayColumns = $listViewDefs[$seed->module_dir];
342 $lv->mergeduplicates = false;
343 $lv->multiSelect = false;
346 $lv->showMassupdateFields = false;
349 $lv->setup($seed, 'include/ListView/ListViewNoMassUpdate.tpl', $where, $params, 0, 10);
351 $module_results[$moduleName] = '<br /><br />' . get_form_header($GLOBALS['app_list_strings']['moduleList'][$seed->module_dir] . ' (' . $lv->data['pageData']['offsets']['total'] . ')', '', false);
352 $module_counts[$moduleName] = $lv->data['pageData']['offsets']['total'];
354 if($lv->data['pageData']['offsets']['total'] == 0) {
355 //$module_results[$moduleName] .= "<li class='noBullet' id='whole_subpanel_{$moduleName}'><div id='div_{$moduleName}'><h2>" . $home_mod_strings['LBL_NO_RESULTS_IN_MODULE'] . '</h2></div></li>';
356 $module_results[$moduleName] .= '<h2>' . $home_mod_strings['LBL_NO_RESULTS_IN_MODULE'] . '</h2>';
359 //$module_results[$moduleName] .= "<li class='noBullet' id='whole_subpanel_{$moduleName}'><div id='div_{$moduleName}'>" . $lv->display(false, false) . '</div></li>';
360 $module_results[$moduleName] .= $lv->display(false, false);
367 foreach($module_counts as $name=>$value) {
368 echo $module_results[$name];
370 } else if(empty($_REQUEST['form_only'])) {
371 echo $home_mod_strings['LBL_NO_RESULTS'];
372 echo $home_mod_strings['LBL_NO_RESULTS_TIPS'];
377 function buildCache()
380 global $beanList, $beanFiles, $dictionary;
382 $supported_modules = array();
384 foreach($beanList as $moduleName=>$beanName)
386 if (!isset($beanFiles[$beanName]))
389 $beanName = BeanFactory::getObjectName($moduleName);
390 $manager = new VardefManager ( );
391 $manager->loadVardef( $moduleName , $beanName ) ;
393 // obtain the field definitions used by generateSearchWhere (duplicate code in view.list.php)
394 if(file_exists('custom/modules/'.$moduleName.'/metadata/metafiles.php')){
395 require('custom/modules/'.$moduleName.'/metadata/metafiles.php');
396 }elseif(file_exists('modules/'.$moduleName.'/metadata/metafiles.php')){
397 require('modules/'.$moduleName.'/metadata/metafiles.php');
401 if(!empty($metafiles[$moduleName]['searchfields']))
403 require $metafiles[$moduleName]['searchfields'] ;
404 } else if(file_exists("modules/{$moduleName}/metadata/SearchFields.php")) {
405 require "modules/{$moduleName}/metadata/SearchFields.php" ;
408 //Load custom SearchFields.php if it exists
409 if(file_exists("custom/modules/{$moduleName}/metadata/SearchFields.php"))
411 require "custom/modules/{$moduleName}/metadata/SearchFields.php" ;
414 //If there are $searchFields are empty, just continue, there are no search fields defined for the module
415 if(empty($searchFields[$moduleName]))
420 $isCustomModule = preg_match('/^([a-z0-9]{1,5})_([a-z0-9_]+)$/i' , $moduleName);
422 //If the bean supports unified search or if it's a custom module bean and unified search is not defined
423 if(!empty($dictionary[$beanName]['unified_search']) || $isCustomModule)
426 foreach ( $dictionary [ $beanName ][ 'fields' ] as $field => $def )
428 // We cannot enable or disable unified_search for email in the vardefs as we don't actually have a vardef entry for 'email'
429 // the searchFields entry for 'email' doesn't correspond to any vardef entry. Instead it contains SQL to directly perform the search.
430 // So as a proxy we allow any field in the vardefs that has a name starting with 'email...' to be tagged with the 'unified_search' parameter
432 if (strpos($field,'email') !== false)
437 //bug: 38139 - allow phone to be searched through Global Search
438 if (strpos($field,'phone') !== false)
443 if ( !empty($def['unified_search']) && isset ( $searchFields [ $moduleName ] [ $field ] ))
445 $fields [ $field ] = $searchFields [ $moduleName ] [ $field ] ;
449 foreach ($searchFields[$moduleName] as $field => $def)
452 isset($def['force_unifiedsearch'])
453 and $def['force_unifiedsearch']
456 $fields[$field] = $def;
460 if(count($fields) > 0) {
461 $supported_modules [$moduleName] ['fields'] = $fields;
462 if (isset($dictionary[$beanName]['unified_search_default_enabled']) && $dictionary[$beanName]['unified_search_default_enabled'] === TRUE)
464 $supported_modules [$moduleName]['default'] = true;
466 $supported_modules [$moduleName]['default'] = false;
474 ksort($supported_modules);
475 write_array_to_file('unified_search_modules', $supported_modules, $this->cache_search);
479 * Retrieve the enabled and disabled modules used for global search.
483 function retrieveEnabledAndDisabledModules()
485 global $app_list_strings;
487 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
488 //Add the translated attribute for display label
489 $json_enabled = array();
490 $json_disabled = array();
491 foreach($unified_search_modules_display as $module=>$data)
493 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
494 if($data['visible'] === true)
496 $json_enabled[] = array("module" => $module, 'label' => $label);
500 $json_disabled[] = array("module" => $module, 'label' => $label);
504 //If the file doesn't exist
505 if(!file_exists($this->cache_search))
510 include($this->cache_search);
512 //Now add any new modules that may have since been added to unified_search_modules.php
513 foreach($unified_search_modules as $module=>$data)
515 if(!isset($unified_search_modules_display[$module]))
517 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
520 $json_enabled[] = array("module" => $module, 'label' => $label);
522 $json_disabled[] = array("module" => $module, 'label' => $label);
527 return array('enabled' => $json_enabled, 'disabled' => $json_disabled);
532 * saveGlobalSearchSettings
533 * This method handles the administrator's request to save the searchable modules selected and stores
534 * the results in the unified_search_modules_display.php file
537 function saveGlobalSearchSettings()
539 if(isset($_REQUEST['enabled_modules']))
541 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
543 $new_unified_search_modules_display = array();
545 foreach(explode (',', $_REQUEST['enabled_modules'] ) as $module)
547 $new_unified_search_modules_display[$module]['visible'] = true;
550 foreach($unified_search_modules_display as $module=>$data)
552 if(!isset($new_unified_search_modules_display[$module]))
554 $new_unified_search_modules_display[$module]['visible'] = false;
558 $this->writeUnifiedSearchModulesDisplayFile($new_unified_search_modules_display);
563 public static function unlinkUnifiedSearchModulesFile() {
564 //clear the unified_search_module.php file
565 $cache_search = sugar_cached('modules/unified_search_modules.php');
566 if(file_exists($cache_search))
568 $GLOBALS['log']->info("unlink {$cache_search}");
569 unlink($cache_search);
575 * getUnifiedSearchModules
577 * Returns the value of the $unified_search_modules variable based on the module's vardefs.php file
578 * and which fields are marked with the unified_search attribute.
580 * @return $unified_search_modules Array of metadata module definitions along with their fields
582 public function getUnifiedSearchModules()
584 //Make directory if it doesn't exist
585 $cachedir = sugar_cached('modules');
586 if(!file_exists($cachedir))
588 mkdir_recursive($cachedir);
591 //Load unified_search_modules.php file
592 $cachedFile = sugar_cached('modules/unified_search_modules.php');
593 if(!file_exists($cachedFile))
599 return $unified_search_modules;
604 * getUnifiedSearchModulesDisplay
606 * Returns the value of the $unified_search_modules_display variable which is based on the $unified_search_modules
607 * entries that have been selected to be allowed for searching.
609 * @return $unified_search_modules_display Array value of modules that have enabled for searching
611 public function getUnifiedSearchModulesDisplay()
613 if(!file_exists('custom/modules/unified_search_modules_display.php'))
615 $unified_search_modules = $this->getUnifiedSearchModules();
617 $unified_search_modules_display = array();
619 if(!empty($unified_search_modules))
621 foreach($unified_search_modules as $module=>$data)
623 $unified_search_modules_display[$module]['visible'] = (isset($data['default']) && $data['default']) ? true : false;
627 $this->writeUnifiedSearchModulesDisplayFile($unified_search_modules_display);
630 include('custom/modules/unified_search_modules_display.php');
631 return $unified_search_modules_display;
635 * writeUnifiedSearchModulesDisplayFile
636 * Private method to handle writing the unified_search_modules_display value to file
638 * @param mixed The array of the unified search modules and their display attributes
639 * @return boolean value indication whether or not file was successfully written
640 * @throws Exception Thrown if the file write operation fails
642 private function writeUnifiedSearchModulesDisplayFile($unified_search_modules_display)
644 if(is_null($unified_search_modules_display) || empty($unified_search_modules_display))
649 if(!write_array_to_file("unified_search_modules_display", $unified_search_modules_display, 'custom/modules/unified_search_modules_display.php'))
651 //Log error message and throw Exception
653 $msg = string_format($app_strings['ERR_FILE_WRITE'], array('custom/modules/unified_search_modules_display.php'));
654 $GLOBALS['log']->error($msg);
655 throw new Exception($msg);
663 function unified_search_modules_cmp($a, $b) {
664 if(!isset($a['translated']) || !isset($b['translated']))
669 $name1 = strtolower($a['translated']);
670 $name2 = strtolower($b['translated']);
672 return $name1 < $name2 ? -1 : 1;