]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/SavedSearch/SavedSearch.php
Release 6.4.0
[Github/sugarcrm.git] / modules / SavedSearch / SavedSearch.php
1 <?php
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-2011 SugarCRM Inc.
6  * 
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.
13  * 
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
17  * details.
18  * 
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
22  * 02110-1301 USA.
23  * 
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.
26  * 
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.
30  * 
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  ********************************************************************************/
37
38 /*********************************************************************************
39
40  * Description:  TODO: To be written.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45 require_once('include/templates/TemplateGroupChooser.php');
46
47
48 class SavedSearch extends SugarBean {
49         var $db;
50     var $field_name_map;
51
52         // Stored fields
53         var $id;
54         var $date_entered;
55         var $date_modified;
56         var $assigned_user_id;
57         var $assigned_user_name;
58         var $modified_by_name;
59         var $name;
60         var $description;
61         var $content;
62         var $search_module;
63
64         var $object_name = 'SavedSearch';
65         var $table_name = 'saved_search';
66
67         var $module_dir = 'SavedSearch';
68         var $field_defs = array();
69         var $field_defs_map = array();
70
71     var $columns;
72
73         function SavedSearch($columns = array(), $orderBy = null, $sortOrder = 'DESC') {
74                 parent::SugarBean();
75         $this->columns = $columns;
76         $this->orderBy = $orderBy;
77         $this->sortOrder = $sortOrder;
78                 $this->setupCustomFields('SavedSearch');
79                 foreach ($this->field_defs as $field) {
80                         $this->field_name_map[$field['name']] = $field;
81                 }
82
83         }
84
85         // Saved Search Form
86         function getForm($module, $inline = true) {
87             global $db, $current_user, $currentModule, $current_language, $app_strings;
88         $json = getJSONobj();
89
90                 $saved_search_mod_strings = return_module_language($current_language, 'SavedSearch');
91
92                 $query = 'SELECT id, name FROM saved_search
93                                   WHERE
94                                         deleted = \'0\' AND
95                                         assigned_user_id = \'' . $current_user->id . '\' AND
96                                         search_module =  \'' . $module . '\'
97                                   ORDER BY name';
98             $result = $db->query($query, true, "Error filling in saved search list: ");
99
100                 $savedSearchArray['_none'] = $app_strings['LBL_NONE'];
101             while ($row = $db->fetchByAssoc($result, -1, FALSE)) {
102                 $savedSearchArray[$row['id']] = htmlspecialchars($row['name'], ENT_QUOTES);
103             }
104                 $sugarSmarty = new Sugar_Smarty();
105                 $sugarSmarty->assign('SEARCH_MODULE', $module);
106                 $sugarSmarty->assign('MOD', $saved_search_mod_strings);
107                 $sugarSmarty->assign('DELETE', $app_strings['LBL_DELETE_BUTTON_LABEL']);
108         $sugarSmarty->assign('UPDATE', $app_strings['LBL_UPDATE']);
109                 $sugarSmarty->assign('SAVE', $app_strings['LBL_SAVE_BUTTON_LABEL']);
110
111         // Column Chooser
112         $chooser = new TemplateGroupChooser();
113
114         $chooser->args['id'] = 'edit_tabs';
115         $chooser->args['left_size'] = 7;
116         $chooser->args['right_size'] = 7;
117         $chooser->args['values_array'][0] = array();
118         $chooser->args['values_array'][1] = array();
119
120         if(isset($_REQUEST['saved_search_select']) && $_REQUEST['saved_search_select']!='_none') {
121             $this->retrieveSavedSearch($_REQUEST['saved_search_select']);
122         }
123
124         if((!empty($_REQUEST['displayColumns']) && $_REQUEST['displayColumns'] != 'undefined') || (isset($this->contents['displayColumns']) && $this->contents['displayColumns'] != 'undefined')) {
125              // columns to display
126              if(!empty($_REQUEST['displayColumns']) && $_REQUEST['displayColumns'] != 'undefined') $temp_displayColumns = $_REQUEST['displayColumns'];
127              else $temp_displayColumns = $this->contents['displayColumns'];
128              foreach(explode('|', $temp_displayColumns) as $num => $name) {
129                         if (!isset($this->columns[$name])) {
130                                                 // Ignore any column that is not on the list.
131                                 continue;
132                         }
133                     $chooser->args['values_array'][0][$name] = trim(translate($this->columns[$name]['label'], $module), ':');
134              }
135              // columns not displayed
136              foreach(array_diff(array_keys($this->columns), array_values(explode('|', $temp_displayColumns))) as $num => $name) {
137                     $chooser->args['values_array'][1][$name] = trim(translate($this->columns[$name]['label'], $module), ':');
138              }
139         }
140         else {
141              foreach($this->columns as $name => $val) {
142                 if(!empty($val['default']) && $val['default'])
143                     $chooser->args['values_array'][0][$name] = trim(translate($val['label'], $module), ':');
144                 else
145                     $chooser->args['values_array'][1][$name] = trim(translate($val['label'], $module), ':');
146             }
147         }
148
149         if(!empty($_REQUEST['sortOrder'])) $this->sortOrder = $_REQUEST['sortOrder'];
150         if(!empty($_REQUEST['orderBy'])) $this->orderBy = $_REQUEST['orderBy'];
151
152         $chooser->args['left_name'] = 'display_tabs';
153         $chooser->args['right_name'] = 'hide_tabs';
154         $chooser->args['alt_tip'] = $app_strings['LBL_SORT'];
155
156         $chooser->args['left_label'] =  $app_strings['LBL_DISPLAY_COLUMNS'];
157         $chooser->args['right_label'] =  $app_strings['LBL_HIDE_COLUMNS'];
158         $chooser->args['title'] =  '';
159         $sugarSmarty->assign('columnChooser', $chooser->display());
160
161         $sugarSmarty->assign('selectedOrderBy', $this->orderBy);
162         if(empty($this->sortOrder)) $this->sortOrder = 'ASC';
163         $sugarSmarty->assign('selectedSortOrder', $this->sortOrder);
164
165         $lastSavedView = (empty($_SESSION['LastSavedView'][$module]) ? '' : $_SESSION['LastSavedView'][$module]);
166         $sugarSmarty->assign('columnsMeta', $json->encode($this->columns));
167         $sugarSmarty->assign('lastSavedView', $lastSavedView);
168         $sugarSmarty->assign('SAVED_SEARCHES_OPTIONS', get_select_options_with_id($savedSearchArray, $lastSavedView));
169
170         $json = getJSONobj();
171
172         return $sugarSmarty->fetch('modules/SavedSearch/SavedSearchForm.tpl');
173         }
174
175     function getSelect($module) {
176
177
178         global $db, $current_user, $currentModule, $current_lang, $app_strings;
179         $saved_search_mod_strings = return_module_language($current_lang, 'SavedSearch');
180
181         $query = 'SELECT id, name FROM saved_search
182                   WHERE
183                     deleted = \'0\' AND
184                     assigned_user_id = \'' . $current_user->id . '\' AND
185                     search_module =  \'' . $module . '\'
186                   ORDER BY name';
187         $result = $db->query($query, true, "Error filling in saved search list: ");
188
189         $savedSearchArray['_none'] = $app_strings['LBL_NONE'];
190         while ($row = $db->fetchByAssoc($result, -1, FALSE)) {
191             $savedSearchArray[$row['id']] = htmlspecialchars($row['name'], ENT_QUOTES);
192         }
193
194         $sugarSmarty = new Sugar_Smarty();
195         $sugarSmarty->assign('SEARCH_MODULE', $module);
196         $sugarSmarty->assign('MOD', $saved_search_mod_strings);
197
198         if(!empty($_SESSION['LastSavedView'][$module]) && (($_REQUEST['action'] == 'ListView') || ($_REQUEST['action'] == 'index')))
199             $selectedSearch = $_SESSION['LastSavedView'][$module];
200         else
201             $selectedSearch = '';
202
203         $sugarSmarty->assign('SAVED_SEARCHES_OPTIONS', get_select_options_with_id($savedSearchArray, $selectedSearch));
204
205         return $sugarSmarty->fetch('modules/SavedSearch/SavedSearchSelects.tpl');
206     }
207
208     function returnSavedSearch($id, $searchFormTab = 'advanced_search', $showDiv='no') {
209         global $db, $current_user, $currentModule;
210         $this->retrieveSavedSearch($id);
211
212         $header = 'Location: index.php?action=index&module=';
213
214         $saved_search_name = '';
215         $header .= $this->contents['search_module'];
216         if(empty($_SESSION['LastSavedView'])) $_SESSION['LastSavedView'] = array();
217         $_SESSION['LastSavedView'][$this->contents['search_module']] = $id;
218         $saved_search_id = $id;
219         $saved_search_name = $this->name;
220         $search_form_tab = $this->contents['searchFormTab'];
221         $query = $this->contents['query'];
222         $orderBy = empty($this->contents['orderBy'])? 'name' : $this->contents['orderBy'];
223         //Reduce the params to avoid the problems caused by URL max length in IE.
224         header($header . '&saved_search_select=' . $saved_search_id . '&saved_search_select_name=' . $saved_search_name . '&orderBy=' . $orderBy . '&sortOrder=' . $this->contents['sortOrder'] . '&query=' . $query . '&searchFormTab='. $search_form_tab .'&showSSDIV=' . $showDiv);
225 }
226
227     function returnSavedSearchContents($id) {
228                 global $db, $current_user, $currentModule;
229                 $query = 'SELECT id, name, contents, search_module FROM saved_search
230                                   WHERE
231                                         id = \'' . $id . '\'';
232             $result = $db->query($query, true, "Error filling in saved search list: ");
233
234             $header = 'Location: index.php?action=index&module=';
235             $contents = '';
236             $saved_search_name = '';
237             while ($row = $db->fetchByAssoc($result, false)) {
238                 $header .= $row['search_module'];
239             if(empty($_SESSION['LastSavedView'])) $_SESSION['LastSavedView'] = array();
240             $_SESSION['LastSavedView'][$row['search_module']] = $row['id'];
241                 $contents = unserialize(base64_decode($row['contents']));
242                 $saved_search_id = $row['id'];
243             $saved_search_name = $row['name'];
244             }
245
246             return $contents;
247         }
248
249         function handleDelete($id) {
250                 $this->mark_deleted($id);
251                 header("Location: index.php?action=index&module={$_REQUEST['search_module']}&advanced={$_REQUEST['advanced']}&query=true&clear_query=true");
252         }
253
254         function handleSave($prefix, $redirect = true, $useRequired = false, $id = null, $searchModuleBean) {
255
256                 global $current_user, $timedate;
257
258                 $focus = new SavedSearch();
259                 if($id) $focus->retrieve($id);
260
261                 if($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
262                         return null;
263                 }
264
265                 $ignored_inputs = array('PHPSESSID', 'module', 'action', 'saved_search_name', 'saved_search_select', 'advanced', 'Calls_divs', 'ACLRoles_divs');
266
267         $contents = $_REQUEST;
268                 if($id == null) $focus->name = $contents['saved_search_name'];
269                 $focus->search_module = $contents['search_module'];
270
271                 foreach($contents as $input=>$value)
272                 {
273                         if(in_array($input, $ignored_inputs))
274                         {
275                                 unset($contents[$input]);
276                                 continue;
277                         }
278
279                         //Filter date fields to ensure it is saved to DB format, but also avoid empty values
280                         if(!empty($value) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $input, $match))
281                         {
282                            $field = $match[2];
283                            if(isset($searchModuleBean->field_defs[$field]['type']) && empty($searchModuleBean->field_defs[$field]['disable_num_format']))
284                            {
285                                   $type = $searchModuleBean->field_defs[$field]['type'];
286
287                                   //Avoid macro values for the date types
288                                   if(($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && !preg_match('/^\[.*?\]$/', $value))
289                                   {
290                                          $db_format = $timedate->to_db_date($value, false);
291                                          $contents[$input] = $db_format;
292                                   } else if ($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') {
293
294                                         if(preg_match('/[^\d]/', $value)) {
295                                                  require_once('modules/Currencies/Currency.php');
296                                                  $contents[$input] = unformat_number($value);
297                                                  //Flag this value as having been unformatted
298                                                  $contents[$input . '_unformatted_number'] = true;
299                                                  //If the type is of currency and there was a currency symbol (non-digit), save the symbol
300                                                  if($type == 'currency' && preg_match('/^([^\d])/', $value, $match))
301                                                  {
302                                                         $contents[$input . '_currency_symbol'] = $match[1];
303                                                  }
304                                         } else {
305                                                  //unset any flags
306                                                  if(isset($contents[$input . '_unformatted_number']))
307                                                  {
308                                                         unset($contents[$input . '_unformatted_number']);
309                                                  }
310
311                                                  if(isset($contents[$input . '_currency_symbol']))
312                                                  {
313                                                         unset($contents[$input . '_currency_symbol']);
314                                                  }
315                                         }
316                                   }
317                            }
318                         }
319
320                 }
321
322                 $contents['advanced'] = true;
323
324                 $focus->contents = base64_encode(serialize($contents));
325
326                 $focus->assigned_user_id = $current_user->id;
327                 $focus->new_schema = true;
328
329                 $saved_search_id = $focus->save();
330
331                 $GLOBALS['log']->debug("Saved record with id of " . $focus->id);
332                 $orderBy = empty($contents['orderBy'])? 'name' : $contents['orderBy'];
333         $search_query = "&orderBy=" . $orderBy . "&sortOrder=".$contents['sortOrder'] . "&query=" . $_REQUEST['query'] . "&searchFormTab=" . $_REQUEST['searchFormTab'].'&showSSDIV=' . $contents['showSSDIV'];
334
335         if($redirect)
336         {
337                 $this->handleRedirect($focus->search_module, $search_query, $saved_search_id, 'true');
338         }
339     }
340
341         function handleRedirect($return_module, $search_query, $saved_search_id, $advanced = 'false') {
342         $_SESSION['LastSavedView'][$return_module] = $saved_search_id;
343         $return_action = 'index';
344         $ajaxLoad = empty($_REQUEST['ajax_load']) ? "" : "&ajax_load=" . $_REQUEST['ajax_load'];
345         //Reduce the params to avoid the problems caused by URL max length in IE ( the reduced params can be get from saved search according to saved_search_id).
346         header("Location: index.php?action=$return_action&module=$return_module&saved_search_select={$saved_search_id}{$search_query}&advanced={$advanced}$ajaxLoad");
347         die();
348         }
349
350         function fill_in_additional_list_fields() {
351                 global $app_list_strings;
352                 // Fill in the assigned_user_name
353                 $this->search_module = $app_list_strings['moduleList'][$this->contents['search_module']];
354                 $this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
355
356         }
357
358
359     function retrieveSavedSearch($id) {
360         parent::retrieve($id);
361         $this->contents = unserialize(base64_decode($this->contents));
362     }
363
364     function populateRequest(){
365
366         global $timedate;
367
368         if(isset($this->contents['search_module']))
369         {
370            $searchModuleBean = loadBean($this->contents['search_module']);
371         }
372
373         foreach($this->contents as $key=>$val){
374             if($key != 'advanced' && $key != 'module' && !strpos($key, '_ORDER_BY') && $key != 'lvso') {
375                 if(isset($searchModuleBean) && !empty($val) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $key, $match))
376                 {
377                    $field = $match[2];
378                                    if(isset($searchModuleBean->field_defs[$field]['type'])  && empty($searchModuleBean->field_defs[$field]['disable_num_format']))
379                                    {
380                                           $type = $searchModuleBean->field_defs[$field]['type'];
381
382                                           //Avoid macro values for the date types
383                                           if(($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && preg_match('/^\d{4}-\d{2}-\d{2}$/', $val) && !preg_match('/^\[.*?\]$/', $val))
384                                           {
385                                                  $val = $timedate->to_display_date($val, false);
386                                           }  else if (($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') && isset($this->contents[$key . '_unformatted_number']) && preg_match('/^\d+$/', $val)) {
387                                                  require_once('modules/Currencies/Currency.php');
388                                                  $val = format_number($val);
389                                                  if($type == 'currency' && isset($this->contents[$key . '_currency_symbol']))
390                                                  {
391                                                         $val = $this->contents[$key . '_currency_symbol'] . $val;
392                                                  }
393                                           }
394                                    }
395                 }
396
397                 $_REQUEST[$key] = $val;
398                 $_GET[$key] = $val;
399             }
400         }
401
402     }
403 }
404
405 ?>