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 function __construct(){
53 if(!empty($_REQUEST['query_string'])){
54 $query_string = trim($_REQUEST['query_string']);
55 if(!empty($query_string)){
56 $this->query_string = $query_string;
59 $this->cache_search = sugar_cached('modules/unified_search_modules.php');
60 $this->cache_display = sugar_cached('modules/unified_search_modules_display.php');
63 function getDropDownDiv($tpl = 'modules/Home/UnifiedSearchAdvanced.tpl') {
64 global $app_list_strings, $app_strings;
66 if(!file_exists($this->cache_search))
71 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
73 global $mod_strings, $modListHeader, $app_list_strings, $current_user, $app_strings, $beanList;
74 $users_modules = $current_user->getPreference('globalSearch', 'search');
76 // preferences are empty, select all
77 if(empty($users_modules)) {
78 $users_modules = array();
79 foreach($unified_search_modules_display as $module=>$data) {
80 if (!empty($data['visible']) ) {
81 $users_modules[$module] = $beanList[$module];
84 $current_user->setPreference('globalSearch', $users_modules, 0, 'search');
87 $sugar_smarty = new Sugar_Smarty();
89 $modules_to_search = array();
91 foreach($users_modules as $key=>$module)
93 if(ACLController::checkAccess($key, 'list', true))
95 $modules_to_search[$key]['checked'] = true;
99 if(!empty($this->query_string))
101 $sugar_smarty->assign('query_string', securexss($this->query_string));
103 $sugar_smarty->assign('query_string', '');
106 $sugar_smarty->assign('MOD', return_module_language($GLOBALS['current_language'], 'Administration'));
107 $sugar_smarty->assign('APP', $app_strings);
108 $sugar_smarty->assign('USE_SEARCH_GIF', 0);
109 $sugar_smarty->assign('LBL_SEARCH_BUTTON_LABEL', $app_strings['LBL_SEARCH_BUTTON_LABEL']);
111 $json_enabled = array();
112 $json_disabled = array();
114 //Now add the rest of the modules that are searchable via Global Search settings
115 foreach($unified_search_modules_display as $module=>$data)
117 if(!isset($modules_to_search[$module]) && $data['visible'] && ACLController::checkAccess($module, 'list', true))
119 $modules_to_search[$module]['checked'] = false;
120 } else if (isset($modules_to_search[$module]) && !$data['visible']) {
121 unset($modules_to_search[$module]);
125 //Create the two lists (doing it this way preserves the user's ordering choice for enabled modules)
126 foreach($modules_to_search as $module=>$data)
128 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
129 if(!empty($data['checked']))
131 $json_enabled[] = array("module" => $module, 'label' => $label);
133 $json_disabled[] = array("module" => $module, 'label' => $label);
137 $sugar_smarty->assign('enabled_modules', json_encode($json_enabled));
138 $sugar_smarty->assign('disabled_modules', json_encode($json_disabled));
140 $showDiv = $current_user->getPreference('showGSDiv', 'search');
146 $sugar_smarty->assign('SHOWGSDIV', $showDiv);
147 $sugar_smarty->debugging = true;
148 return $sugar_smarty->fetch($tpl);
155 * Search function run when user goes to Show All and runs a search again. This outputs the search results
156 * calling upon the various listview display functions for each module searched on.
158 * Todo: Sync this up with SugarSpot.php search method.
164 $unified_search_modules = $this->getUnifiedSearchModules();
165 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
168 require_once 'include/ListView/ListViewSmarty.php';
170 global $modListHeader, $beanList, $beanFiles, $current_language, $app_strings, $current_user, $mod_strings;
171 $home_mod_strings = return_module_language($current_language, 'Home');
174 $this->query_string = $GLOBALS['db']->quote(securexss(from_html(clean_string($this->query_string, 'UNIFIED_SEARCH'))));
176 if(!empty($_REQUEST['advanced']) && $_REQUEST['advanced'] != 'false') {
177 $modules_to_search = array();
178 if(!empty($_REQUEST['search_modules']))
180 foreach(explode (',', $_REQUEST['search_modules'] ) as $e)
182 $modules_to_search[$e] = $beanList[$e];
186 $current_user->setPreference('showGSDiv', isset($_REQUEST['showGSDiv']) ? $_REQUEST['showGSDiv'] : 'no', 0, 'search');
187 $current_user->setPreference('globalSearch', $modules_to_search, 0, 'search'); // save selections to user preference
189 $users_modules = $current_user->getPreference('globalSearch', 'search');
190 $modules_to_search = array();
192 if(!empty($users_modules)) {
193 // use user's previous selections
194 foreach ( $users_modules as $key => $value ) {
195 if (isset($unified_search_modules_display[$key]) && !empty($unified_search_modules_display[$key]['visible'])) {
196 $modules_to_search[$key] = $beanList[$key];
200 foreach($unified_search_modules_display as $module=>$data) {
201 if (!empty($data['visible']) ) {
202 $modules_to_search[$module] = $beanList[$module];
206 $current_user->setPreference('globalSearch', $modules_to_search, 'search');
210 $templateFile = 'modules/Home/UnifiedSearchAdvancedForm.tpl';
211 if(file_exists('custom/' . $templateFile))
213 $templateFile = 'custom/'.$templateFile;
216 echo $this->getDropDownDiv($templateFile);
218 $module_results = array();
219 $module_counts = array();
220 $has_results = false;
222 if(!empty($this->query_string)) {
223 foreach($modules_to_search as $moduleName => $beanName) {
224 require_once $beanFiles[$beanName] ;
225 $seed = new $beanName();
227 $lv = new ListViewSmarty();
228 $lv->lvd->additionalDetails = false;
229 $mod_strings = return_module_language($current_language, $seed->module_dir);
231 //retrieve the original list view defs and store for processing in case of custom layout changes
232 require('modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
233 $orig_listViewDefs = $listViewDefs;
235 if(file_exists('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php'))
237 require('custom/modules/'.$seed->module_dir.'/metadata/listviewdefs.php');
240 if ( !isset($listViewDefs) || !isset($listViewDefs[$seed->module_dir]) )
245 $unifiedSearchFields = array () ;
246 $innerJoins = array();
247 foreach ( $unified_search_modules[ $moduleName ]['fields'] as $field=>$def )
249 $listViewCheckField = strtoupper($field);
250 //check to see if the field is in listview defs
251 if ( empty($listViewDefs[$seed->module_dir][$listViewCheckField]['default']) ) {
252 //check to see if field is in original list view defs (in case we are using custom layout defs)
253 if (!empty($orig_listViewDefs[$seed->module_dir][$listViewCheckField]['default']) ) {
254 //if we are here then the layout has been customized, but the field is still needed for query creation
255 $listViewDefs[$seed->module_dir][$listViewCheckField] = $orig_listViewDefs[$seed->module_dir][$listViewCheckField];
260 //bug: 34125 we might want to try to use the LEFT JOIN operator instead of the INNER JOIN in the case we are
261 //joining against a field that has not been populated.
262 if(!empty($def['innerjoin']) )
264 if (empty($def['db_field']) )
268 $innerJoins[$field] = $def;
269 $def['innerjoin'] = str_replace('INNER', 'LEFT', $def['innerjoin']);
272 if(isset($seed->field_defs[$field]['type']))
274 $type = $seed->field_defs[$field]['type'];
275 if($type == 'int' && !is_numeric($this->query_string))
281 $unifiedSearchFields[ $moduleName ] [ $field ] = $def ;
282 $unifiedSearchFields[ $moduleName ] [ $field ][ 'value' ] = $this->query_string ;
286 * Use searchForm2->generateSearchWhere() to create the search query, as it can generate SQL for the full set of comparisons required
287 * generateSearchWhere() expects to find the search conditions for a field in the 'value' parameter of the searchFields entry for that field
289 require_once $beanFiles[$beanName] ;
290 $seed = new $beanName();
291 require_once 'include/SearchForm/SearchForm2.php' ;
292 $searchForm = new SearchForm ( $seed, $moduleName ) ;
294 $searchForm->setup (array ( $moduleName => array() ) , $unifiedSearchFields , '' , 'saved_views' /* hack to avoid setup doing further unwanted processing */ ) ;
295 $where_clauses = $searchForm->generateSearchWhere() ;
296 //add inner joins back into the where clause
297 $params = array('custom_select' => "");
298 foreach($innerJoins as $field=>$def) {
299 if (isset ($def['db_field'])) {
300 foreach($def['db_field'] as $dbfield)
301 $where_clauses[] = $dbfield . " LIKE '" . $this->query_string . "%'";
302 $params['custom_select'] .= ", $dbfield";
303 $params['distinct'] = true;
304 //$filterFields[$dbfield] = $dbfield;
308 if (count($where_clauses) > 0)
310 $where = '(('. implode(' ) OR ( ', $where_clauses) . '))';
313 $displayColumns = array();
314 foreach($listViewDefs[$seed->module_dir] as $colName => $param)
316 if(!empty($param['default']) && $param['default'] == true)
318 $param['url_sort'] = true;//bug 27933
319 $displayColumns[$colName] = $param;
323 if(count($displayColumns) > 0)
325 $lv->displayColumns = $displayColumns;
327 $lv->displayColumns = $listViewDefs[$seed->module_dir];
331 $lv->mergeduplicates = false;
332 $lv->multiSelect = false;
335 $lv->showMassupdateFields = false;
341 $lv->overlib = false;
344 $lv->setup($seed, 'include/ListView/ListViewNoMassUpdate.tpl', $where, $params, 0, 10);
346 $module_results[$moduleName] = '<br /><br />' . get_form_header($GLOBALS['app_list_strings']['moduleList'][$seed->module_dir] . ' (' . $lv->data['pageData']['offsets']['total'] . ')', '', false);
347 $module_counts[$moduleName] = $lv->data['pageData']['offsets']['total'];
349 if($lv->data['pageData']['offsets']['total'] == 0) {
350 //$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>';
351 $module_results[$moduleName] .= '<h2>' . $home_mod_strings['LBL_NO_RESULTS_IN_MODULE'] . '</h2>';
354 //$module_results[$moduleName] .= "<li class='noBullet' id='whole_subpanel_{$moduleName}'><div id='div_{$moduleName}'>" . $lv->display(false, false) . '</div></li>';
355 $module_results[$moduleName] .= $lv->display(false, false);
362 foreach($module_counts as $name=>$value) {
363 echo $module_results[$name];
365 } else if(empty($_REQUEST['form_only'])) {
366 echo $home_mod_strings['LBL_NO_RESULTS'];
367 echo $home_mod_strings['LBL_NO_RESULTS_TIPS'];
372 function buildCache()
375 global $beanList, $beanFiles, $dictionary;
377 $supported_modules = array();
379 foreach($beanList as $moduleName=>$beanName)
381 if (!isset($beanFiles[$beanName]))
384 $beanName = BeanFactory::getObjectName($moduleName);
385 $manager = new VardefManager ( );
386 $manager->loadVardef( $moduleName , $beanName ) ;
388 // obtain the field definitions used by generateSearchWhere (duplicate code in view.list.php)
389 if(file_exists('custom/modules/'.$moduleName.'/metadata/metafiles.php')){
390 require('custom/modules/'.$moduleName.'/metadata/metafiles.php');
391 }elseif(file_exists('modules/'.$moduleName.'/metadata/metafiles.php')){
392 require('modules/'.$moduleName.'/metadata/metafiles.php');
396 if(!empty($metafiles[$moduleName]['searchfields']))
398 require $metafiles[$moduleName]['searchfields'] ;
399 } else if(file_exists("modules/{$moduleName}/metadata/SearchFields.php")) {
400 require "modules/{$moduleName}/metadata/SearchFields.php" ;
403 //Load custom SearchFields.php if it exists
404 if(file_exists("custom/modules/{$moduleName}/metadata/SearchFields.php"))
406 require "custom/modules/{$moduleName}/metadata/SearchFields.php" ;
409 //If there are $searchFields are empty, just continue, there are no search fields defined for the module
410 if(empty($searchFields[$moduleName]))
415 $isCustomModule = preg_match('/^([a-z0-9]{1,5})_([a-z0-9_]+)$/i' , $moduleName);
417 //If the bean supports unified search or if it's a custom module bean and unified search is not defined
418 if(!empty($dictionary[$beanName]['unified_search']) || $isCustomModule)
421 foreach ( $dictionary [ $beanName ][ 'fields' ] as $field => $def )
423 // We cannot enable or disable unified_search for email in the vardefs as we don't actually have a vardef entry for 'email'
424 // the searchFields entry for 'email' doesn't correspond to any vardef entry. Instead it contains SQL to directly perform the search.
425 // 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
427 if (strpos($field,'email') !== false)
432 //bug: 38139 - allow phone to be searched through Global Search
433 if (strpos($field,'phone') !== false)
438 if ( !empty($def['unified_search']) && isset ( $searchFields [ $moduleName ] [ $field ] ))
440 $fields [ $field ] = $searchFields [ $moduleName ] [ $field ] ;
444 foreach ($searchFields[$moduleName] as $field => $def)
447 isset($def['force_unifiedsearch'])
448 and $def['force_unifiedsearch']
451 $fields[$field] = $def;
455 if(count($fields) > 0) {
456 $supported_modules [$moduleName] ['fields'] = $fields;
457 if (isset($dictionary[$beanName]['unified_search_default_enabled']) && $dictionary[$beanName]['unified_search_default_enabled'] === TRUE)
459 $supported_modules [$moduleName]['default'] = true;
461 $supported_modules [$moduleName]['default'] = false;
469 ksort($supported_modules);
470 write_array_to_file('unified_search_modules', $supported_modules, $this->cache_search);
477 function modifyGlobalSearchSettings()
479 global $mod_strings, $app_strings, $app_list_strings;
481 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
483 $sugar_smarty = new Sugar_Smarty();
484 $sugar_smarty->assign('APP', $app_strings);
485 $sugar_smarty->assign('MOD', $mod_strings);
487 //Add the translated attribute for display label
488 $json_enabled = array();
489 $json_disabled = array();
490 foreach($unified_search_modules_display as $module=>$data)
492 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
493 if($data['visible'] === true)
495 $json_enabled[] = array("module" => $module, 'label' => $label);
497 $json_disabled[] = array("module" => $module, 'label' => $label);
501 //If the file doesn't exist
502 if(!file_exists($this->cache_search))
507 include($this->cache_search);
509 //Now add any new modules that may have since been added to unified_search_modules.php
510 foreach($unified_search_modules as $module=>$data)
512 if(!isset($unified_search_modules_display[$module]))
514 $label = isset($app_list_strings['moduleList'][$module]) ? $app_list_strings['moduleList'][$module] : $module;
517 $json_enabled[] = array("module" => $module, 'label' => $label);
519 $json_disabled[] = array("module" => $module, 'label' => $label);
524 $sugar_smarty->assign('enabled_modules', json_encode($json_enabled));
525 $sugar_smarty->assign('disabled_modules', json_encode($json_disabled));
527 //uasort($unified_search_modules_display, 'unified_search_modules_cmp');
528 $tpl = 'modules/Administration/templates/GlobalSearchSettings.tpl';
529 if(file_exists('custom/' . $tpl))
531 $tpl = 'custom/' . $tpl;
533 return $sugar_smarty->fetch($tpl);
538 * saveGlobalSearchSettings
539 * This method handles the administrator's request to save the searchable modules selected and stores
540 * the results in the unified_search_modules_display.php file
543 function saveGlobalSearchSettings()
545 if(isset($_REQUEST['enabled_modules']))
547 $unified_search_modules_display = $this->getUnifiedSearchModulesDisplay();
549 $new_unified_search_modules_display = array();
551 foreach(explode (',', $_REQUEST['enabled_modules'] ) as $module)
553 $new_unified_search_modules_display[$module]['visible'] = true;
556 foreach($unified_search_modules_display as $module=>$data)
558 if(!isset($new_unified_search_modules_display[$module]))
560 $new_unified_search_modules_display[$module]['visible'] = false;
564 $this->writeUnifiedSearchModulesDisplayFile($new_unified_search_modules_display);
569 public static function unlinkUnifiedSearchModulesFile() {
570 //clear the unified_search_module.php file
571 $cache_search = sugar_cached('modules/unified_search_modules.php');
572 if(file_exists($cache_search))
574 $GLOBALS['log']->info("unlink {$cache_search}");
575 unlink($cache_search);
581 * getUnifiedSearchModules
583 * Returns the value of the $unified_search_modules variable based on the module's vardefs.php file
584 * and which fields are marked with the unified_search attribute.
586 * @return $unified_search_modules Array of metadata module definitions along with their fields
588 public function getUnifiedSearchModules()
590 //Make directory if it doesn't exist
591 $cachedir = sugar_cached('modules');
592 if(!file_exists($cachedir))
594 mkdir_recursive($cachedir);
597 //Load unified_search_modules.php file
598 $cachedFile = sugar_cached('modules/unified_search_modules.php');
599 if(!file_exists($cachedFile))
605 return $unified_search_modules;
610 * getUnifiedSearchModulesDisplay
612 * Returns the value of the $unified_search_modules_display variable which is based on the $unified_search_modules
613 * entries that have been selected to be allowed for searching.
615 * @return $unified_search_modules_display Array value of modules that have enabled for searching
617 public function getUnifiedSearchModulesDisplay()
619 if(!file_exists('custom/modules/unified_search_modules_display.php'))
621 $unified_search_modules = $this->getUnifiedSearchModules();
623 $unified_search_modules_display = array();
625 if(!empty($unified_search_modules))
627 foreach($unified_search_modules as $module=>$data)
629 $unified_search_modules_display[$module]['visible'] = (isset($data['default']) && $data['default']) ? true : false;
633 $this->writeUnifiedSearchModulesDisplayFile($unified_search_modules_display);
636 include('custom/modules/unified_search_modules_display.php');
637 return $unified_search_modules_display;
641 * writeUnifiedSearchModulesDisplayFile
642 * Private method to handle writing the unified_search_modules_display value to file
644 * @param mixed The array of the unified search modules and their display attributes
645 * @return boolean value indication whether or not file was successfully written
646 * @throws Exception Thrown if the file write operation fails
648 private function writeUnifiedSearchModulesDisplayFile($unified_search_modules_display)
650 if(is_null($unified_search_modules_display) || empty($unified_search_modules_display))
655 if(!write_array_to_file("unified_search_modules_display", $unified_search_modules_display, 'custom/modules/unified_search_modules_display.php'))
657 //Log error message and throw Exception
659 $msg = string_format($app_strings['ERR_FILE_WRITE'], array('custom/modules/unified_search_modules_display.php'));
660 $GLOBALS['log']->error($msg);
661 throw new Exception($msg);
669 function unified_search_modules_cmp($a, $b) {
670 if(!isset($a['translated']) || !isset($b['translated']))
675 $name1 = strtolower($a['translated']);
676 $name2 = strtolower($b['translated']);
678 return $name1 < $name2 ? -1 : 1;