SavedSearch::fill_in_additional_list_fields()   A
last analyzed

Complexity

Conditions 1
Paths 1

Size

Total Lines 7
Code Lines 4

Duplication

Lines 0
Ratio 0 %

Code Coverage

Tests 5
CRAP Score 1
Metric Value
cc 1
eloc 4
nc 1
nop 0
dl 0
loc 7
ccs 5
cts 5
cp 1
crap 1
rs 9.4285
1
<?php
2 1
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-2013 SugarCRM Inc.
6
7
 * SuiteCRM is an extension to SugarCRM Community Edition developed by Salesagility Ltd.
8
 * Copyright (C) 2011 - 2014 Salesagility Ltd.
9
 *
10
 * This program is free software; you can redistribute it and/or modify it under
11
 * the terms of the GNU Affero General Public License version 3 as published by the
12
 * Free Software Foundation with the addition of the following permission added
13
 * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK
14
 * IN WHICH THE COPYRIGHT IS OWNED BY SUGARCRM, SUGARCRM DISCLAIMS THE WARRANTY
15
 * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
16
 *
17
 * This program is distributed in the hope that it will be useful, but WITHOUT
18
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
19
 * FOR A PARTICULAR PURPOSE.  See the GNU Affero General Public License for more
20
 * details.
21
 *
22
 * You should have received a copy of the GNU Affero General Public License along with
23
 * this program; if not, see http://www.gnu.org/licenses or write to the Free
24
 * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA
25
 * 02110-1301 USA.
26
 *
27
 * You can contact SugarCRM, Inc. headquarters at 10050 North Wolfe Road,
28
 * SW2-130, Cupertino, CA 95014, USA. or at email address [email protected].
29
 *
30
 * The interactive user interfaces in modified source and object code versions
31
 * of this program must display Appropriate Legal Notices, as required under
32
 * Section 5 of the GNU Affero General Public License version 3.
33
 *
34
 * In accordance with Section 7(b) of the GNU Affero General Public License version 3,
35
 * these Appropriate Legal Notices must retain the display of the "Powered by
36
 * SugarCRM" logo and "Supercharged by SuiteCRM" logo. If the display of the logos is not
37
 * reasonably feasible for  technical reasons, the Appropriate Legal Notices must
38
 * display the words  "Powered by SugarCRM" and "Supercharged by SuiteCRM".
39
 ********************************************************************************/
40
41
/*********************************************************************************
42
43
 * Description:  TODO: To be written.
44
 * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
45
 * All Rights Reserved.
46
 * Contributor(s): ______________________________________..
47
 ********************************************************************************/
48 1
require_once('include/templates/TemplateGroupChooser.php');
49
50
51
class SavedSearch extends SugarBean {
52
	var $db;
53
    var $field_name_map;
54
55
	// Stored fields
56
	var $id;
57
	var $date_entered;
58
	var $date_modified;
59
	var $assigned_user_id;
60
	var $assigned_user_name;
61
	var $modified_by_name;
62
	var $name;
63
	var $description;
64
	var $content;
65
	var $search_module;
66
67
	var $object_name = 'SavedSearch';
68
	var $table_name = 'saved_search';
69
70
	var $module_dir = 'SavedSearch';
71
	var $field_defs = array();
72
	var $field_defs_map = array();
73
74
    var $columns;
75
76 15
    public function __construct($columns = array(), $orderBy = null, $sortOrder = 'DESC') {
77 15
		parent::__construct();
78 15
        $this->columns = $columns;
79 15
        $this->orderBy = $orderBy;
80 15
        $this->sortOrder = $sortOrder;
81 15
		$this->setupCustomFields('SavedSearch');
82 15
		foreach ($this->field_defs as $field) {
83 15
			$this->field_name_map[$field['name']] = $field;
84
		}
85
86 15
	}
87
88
	/**
89
	 * @deprecated deprecated since version 7.6, PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code, use __construct instead
90
	 */
91
	public function SavedSearch($columns = array(), $orderBy = null, $sortOrder = 'DESC'){
92
		$deprecatedMessage = 'PHP4 Style Constructors are deprecated and will be remove in 7.8, please update your code';
93
		if(isset($GLOBALS['log'])) {
94
			$GLOBALS['log']->deprecated($deprecatedMessage);
95
		}
96
		else {
97
			trigger_error($deprecatedMessage, E_USER_DEPRECATED);
98
		}
99
		self::__construct($columns, $orderBy, $sortOrder);
100
	}
101
102
	// Saved Search Form
103 2
	function getForm($module, $inline = true) {
104 2
	    global $db, $current_user, $currentModule, $current_language, $app_strings;
105 2
        $json = getJSONobj();
106
107 2
		$saved_search_mod_strings = return_module_language($current_language, 'SavedSearch');
108
109
		$query = 'SELECT id, name FROM saved_search
110
				  WHERE
111
					deleted = \'0\' AND
112 2
				  	assigned_user_id = \'' . $current_user->id . '\' AND
113 2
					search_module =  \'' . $module . '\'
114 2
				  ORDER BY name';
115 2
	    $result = $db->query($query, true, "Error filling in saved search list: ");
116
117 2
		$savedSearchArray['_none'] = $app_strings['LBL_NONE'];
118 2
	    while ($row = $db->fetchByAssoc($result, -1, FALSE)) {
119
	        $savedSearchArray[$row['id']] = htmlspecialchars($row['name'], ENT_QUOTES);
120
	    }
121 2
		$sugarSmarty = new Sugar_Smarty();
122 2
		$sugarSmarty->assign('SEARCH_MODULE', $module);
123 2
		$sugarSmarty->assign('MOD', $saved_search_mod_strings);
124 2
		$sugarSmarty->assign('DELETE', $app_strings['LBL_DELETE_BUTTON_LABEL']);
125 2
        $sugarSmarty->assign('UPDATE', $app_strings['LBL_UPDATE']);
126 2
		$sugarSmarty->assign('SAVE', $app_strings['LBL_SAVE_BUTTON_LABEL']);
127
128
        // Column Chooser
129 2
        $chooser = new TemplateGroupChooser();
130
131 2
        $chooser->args['id'] = 'edit_tabs';
132 2
        $chooser->args['left_size'] = 7;
133 2
        $chooser->args['right_size'] = 7;
134 2
        $chooser->args['values_array'][0] = array();
135 2
        $chooser->args['values_array'][1] = array();
136
137 2
        if(isset($_REQUEST['saved_search_select']) && $_REQUEST['saved_search_select']!='_none') {
138
            $this->retrieveSavedSearch($_REQUEST['saved_search_select']);
139
        }
140
141 2
        if((!empty($_REQUEST['displayColumns']) && $_REQUEST['displayColumns'] != 'undefined') || (isset($this->contents['displayColumns']) && $this->contents['displayColumns'] != 'undefined')) {
142
             // columns to display
143
             if(!empty($_REQUEST['displayColumns']) && $_REQUEST['displayColumns'] != 'undefined') $temp_displayColumns = $_REQUEST['displayColumns'];
144
             else $temp_displayColumns = $this->contents['displayColumns'];
145
             foreach(explode('|', $temp_displayColumns) as $num => $name) {
146
             		if (!isset($this->columns[$name])) {
147
						// Ignore any column that is not on the list.
148
             			continue;
149
             		}
150
                    $chooser->args['values_array'][0][$name] = trim(translate($this->columns[$name]['label'], $module), ':');
151
             }
152
             // columns not displayed
153
             foreach(array_diff(array_keys($this->columns), array_values(explode('|', $temp_displayColumns))) as $num => $name) {
154
                    $chooser->args['values_array'][1][$name] = trim(translate($this->columns[$name]['label'], $module), ':');
155
             }
156
        }
157
        else {
158 2
             foreach($this->columns as $name => $val) {
159 2
                if(!empty($val['default']) && $val['default'])
160 1
                    $chooser->args['values_array'][0][$name] = trim(translate($val['label'], $module), ':');
161
                else
162 2
                    $chooser->args['values_array'][1][$name] = trim(translate($val['label'], $module), ':');
163
            }
164
        }
165
166 2
        if(!empty($_REQUEST['sortOrder'])) $this->sortOrder = $_REQUEST['sortOrder'];
167 2
        if(!empty($_REQUEST['orderBy'])) $this->orderBy = $_REQUEST['orderBy'];
168
169 2
        $chooser->args['left_name'] = 'display_tabs';
170 2
        $chooser->args['right_name'] = 'hide_tabs';
171 2
        $chooser->args['alt_tip'] = $app_strings['LBL_SORT'];
172
173 2
        $chooser->args['left_label'] =  $app_strings['LBL_DISPLAY_COLUMNS'];
174 2
        $chooser->args['right_label'] =  $app_strings['LBL_HIDE_COLUMNS'];
175 2
        $chooser->args['title'] =  '';
176 2
        $sugarSmarty->assign('columnChooser', $chooser->display());
177
178 2
        $sugarSmarty->assign('selectedOrderBy', $this->orderBy);
179 2
        if(empty($this->sortOrder)) $this->sortOrder = 'ASC';
180 2
        $sugarSmarty->assign('selectedSortOrder', $this->sortOrder);
181
182 2
        $lastSavedView = (empty($_SESSION['LastSavedView'][$module]) ? '' : $_SESSION['LastSavedView'][$module]);
183 2
        $sugarSmarty->assign('columnsMeta', $json->encode($this->columns));
184 2
        $sugarSmarty->assign('lastSavedView', $lastSavedView);
185 2
        $sugarSmarty->assign('SAVED_SEARCHES_OPTIONS', get_select_options_with_id($savedSearchArray, $lastSavedView));
186
187 2
        $json = getJSONobj();
188
189 2
        return $sugarSmarty->fetch('modules/SavedSearch/SavedSearchForm.tpl');
190
	}
191
192 5
    function getSelect($module) {
193
194
195 5
        global $db, $current_user, $currentModule, $current_lang, $app_strings;
196 5
        $saved_search_mod_strings = return_module_language($current_lang, 'SavedSearch');
197
198
        $query = 'SELECT id, name FROM saved_search
199
                  WHERE
200
                    deleted = \'0\' AND
201 5
                    assigned_user_id = \'' . $current_user->id . '\' AND
202 5
                    search_module =  \'' . $module . '\'
203 5
                  ORDER BY name';
204 5
        $result = $db->query($query, true, "Error filling in saved search list: ");
205
206 5
        $savedSearchArray['_none'] = $app_strings['LBL_NONE'];
207 5
        while ($row = $db->fetchByAssoc($result, -1, FALSE)) {
208
            $savedSearchArray[$row['id']] = htmlspecialchars($row['name'], ENT_QUOTES);
209
        }
210
211 5
        $sugarSmarty = new Sugar_Smarty();
212 5
        $sugarSmarty->assign('SEARCH_MODULE', $module);
213 5
        $sugarSmarty->assign('MOD', $saved_search_mod_strings);
214
215 5
        if(!empty($_SESSION['LastSavedView'][$module]) && (($_REQUEST['action'] == 'ListView') || ($_REQUEST['action'] == 'index')))
216
            $selectedSearch = $_SESSION['LastSavedView'][$module];
217
        else
218 5
            $selectedSearch = '';
219
220 5
        $sugarSmarty->assign('SAVED_SEARCHES_OPTIONS', get_select_options_with_id($savedSearchArray, $selectedSearch));
221
222 5
        return $sugarSmarty->fetch('modules/SavedSearch/SavedSearchSelects.tpl');
223
    }
224
225 1
    function returnSavedSearch($id, $searchFormTab = 'advanced_search', $showDiv='no') {
226 1
        global $db, $current_user, $currentModule;
227 1
        $this->retrieveSavedSearch($id);
228
229 1
        $header = 'Location: index.php?action=index&module=';
230
231 1
        $saved_search_name = '';
232 1
        $header .= $this->contents['search_module'];
233 1
        if(empty($_SESSION['LastSavedView'])) $_SESSION['LastSavedView'] = array();
234 1
        $_SESSION['LastSavedView'][$this->contents['search_module']] = $id;
235 1
        $saved_search_id = $id;
236 1
        $saved_search_name = $this->name;
237 1
        $search_form_tab = $this->contents['searchFormTab'];
238 1
        $query = $this->contents['query'];
239 1
        $orderBy = empty($this->contents['orderBy'])? 'name' : $this->contents['orderBy'];
240
        //Reduce the params to avoid the problems caused by URL max length in IE.
241 1
        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);
242 1
}
243
244 1
    function returnSavedSearchContents($id) {
245 1
		global $db, $current_user, $currentModule;
246
		$query = 'SELECT id, name, contents, search_module FROM saved_search
247
				  WHERE
248 1
				  	id = \'' . $id . '\'';
249 1
	    $result = $db->query($query, true, "Error filling in saved search list: ");
250
251 1
	    $header = 'Location: index.php?action=index&module=';
252 1
	    $contents = '';
253 1
	    $saved_search_name = '';
254 1
	    while ($row = $db->fetchByAssoc($result, false)) {
255
	        $header .= $row['search_module'];
256
            if(empty($_SESSION['LastSavedView'])) $_SESSION['LastSavedView'] = array();
257
            $_SESSION['LastSavedView'][$row['search_module']] = $row['id'];
258
	        $contents = unserialize(base64_decode($row['contents']));
259
	        $saved_search_id = $row['id'];
260
            $saved_search_name = $row['name'];
261
	    }
262
263 1
	    return $contents;
264
	}
265
266 1
	function handleDelete($id) {
267 1
		$this->mark_deleted($id);
268 1
		header("Location: index.php?action=index&module={$_REQUEST['search_module']}&advanced={$_REQUEST['advanced']}&query=true&clear_query=true");
269 1
	}
270
271 1
	function handleSave($prefix, $redirect = true, $useRequired = false, $id = null, $searchModuleBean) {
272
273 1
		global $current_user, $timedate;
274
275 1
		$focus = new SavedSearch();
276 1
		if($id) $focus->retrieve($id);
277
278 1
		if($useRequired && !checkRequired($prefix, array_keys($focus->required_fields))) {
279
			return null;
280
		}
281
282 1
		$ignored_inputs = array('PHPSESSID', 'module', 'action', 'saved_search_name', 'saved_search_select', 'advanced', 'Calls_divs', 'ACLRoles_divs');
283
284 1
        $contents = $_REQUEST;
285 1
		if($id == null) $focus->name = $contents['saved_search_name'];
286 1
		$focus->search_module = $contents['search_module'];
287
288 1
		foreach($contents as $input=>$value)
289
		{
290 1
			if(in_array($input, $ignored_inputs))
291
			{
292
				unset($contents[$input]);
293
				continue;
294
			}
295
296
			//Filter date fields to ensure it is saved to DB format, but also avoid empty values
297 1
			if(!empty($value) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $input, $match))
298
			{
299
			   $field = $match[2];
300
			   if(isset($searchModuleBean->field_defs[$field]['type']) && empty($searchModuleBean->field_defs[$field]['disable_num_format']))
301
			   {
302
			   	  $type = $searchModuleBean->field_defs[$field]['type'];
303
304
			   	  //Avoid macro values for the date types
305
			   	  if(($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && !preg_match('/^\[.*?\]$/', $value))
306
			   	  {
307
			   	  	 $db_format = $timedate->to_db_date($value, false);
308
			   	  	 $contents[$input] = $db_format;
309
			   	  } else if ($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') {
310
311
			   	  	if(preg_match('/[^\d]/', $value)) {
312
				   	  	 require_once('modules/Currencies/Currency.php');
313
				   	  	 $contents[$input] = unformat_number($value);
314
				   	  	 //Flag this value as having been unformatted
315
				   	  	 $contents[$input . '_unformatted_number'] = true;
316
				   	  	 //If the type is of currency and there was a currency symbol (non-digit), save the symbol
317
				   	  	 if($type == 'currency' && preg_match('/^([^\d])/', $value, $match))
318
				   	  	 {
319
				   	  	 	$contents[$input . '_currency_symbol'] = $match[1];
320
				   	  	 }
321
			   	  	} else {
322
			   	  		 //unset any flags
323
			   	  		 if(isset($contents[$input . '_unformatted_number']))
324
			   	  		 {
325
			   	  		 	unset($contents[$input . '_unformatted_number']);
326
			   	  		 }
327
328
			   	  		 if(isset($contents[$input . '_currency_symbol']))
329
			   	  		 {
330 1
			   	  		 	unset($contents[$input . '_currency_symbol']);
331
			   	  		 }
332
			   	  	}
333
			   	  }
334
			   }
335
			}
336
337
		}
338
339 1
		$contents['advanced'] = true;
340
341 1
		$focus->contents = base64_encode(serialize($contents));
342
343 1
		$focus->assigned_user_id = $current_user->id;
344 1
		$focus->new_schema = true;
345
346 1
		$saved_search_id = $focus->save();
347
348 1
		$GLOBALS['log']->debug("Saved record with id of " . $focus->id);
349 1
		$orderBy = empty($contents['orderBy'])? 'name' : $contents['orderBy'];
350 1
        $search_query = "&orderBy=" . $orderBy . "&sortOrder=".$contents['sortOrder'] . "&query=" . $_REQUEST['query'] . "&searchFormTab=" . $_REQUEST['searchFormTab'].'&showSSDIV=' . $contents['showSSDIV'];
351
352 1
        if($redirect)
353
        {
354
        	$this->handleRedirect($focus->search_module, $search_query, $saved_search_id, 'true');
355
        }
356 1
    }
357
358
	function handleRedirect($return_module, $search_query, $saved_search_id, $advanced = 'false') {
359
        $_SESSION['LastSavedView'][$return_module] = $saved_search_id;
360
        $return_action = 'index';
361
        $ajaxLoad = empty($_REQUEST['ajax_load']) ? "" : "&ajax_load=" . $_REQUEST['ajax_load'];
362
        //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).
363
        header("Location: index.php?action=$return_action&module=$return_module&saved_search_select={$saved_search_id}{$search_query}&advanced={$advanced}$ajaxLoad");
364
        die();
365
	}
366
367 1
	function fill_in_additional_list_fields() {
368 1
		global $app_list_strings;
369
		// Fill in the assigned_user_name
370 1
		$this->search_module = $app_list_strings['moduleList'][$this->contents['search_module']];
371 1
		$this->assigned_user_name = get_assigned_user_name($this->assigned_user_id);
372
373 1
	}
374
375
376 1
    function retrieveSavedSearch($id) {
377 1
        parent::retrieve($id);
378 1
        $this->contents = unserialize(base64_decode($this->contents));
379 1
    }
380
381 1
    function populateRequest(){
382
383 1
    	global $timedate;
384
385 1
        if(isset($this->contents['search_module']))
386
        {
387 1
           $searchModuleBean = loadBean($this->contents['search_module']);
0 ignored issues
show
Deprecated Code introduced by
The function loadBean() has been deprecated with message: use SugarModule::loadBean() instead

This function has been deprecated. The supplier of the file has supplied an explanatory message.

The explanatory message should give you some clue as to whether and when the function will be removed from the class and what other function to use instead.

Loading history...
388
        }
389
390 1
        foreach($this->contents as $key=>$val){
391 1
            if($key != 'advanced' && $key != 'module' && !strpos($key, '_ORDER_BY') && $key != 'lvso') {
392 1
            	if(isset($searchModuleBean) && !empty($val) && preg_match('/^(start_range_|end_range_|range_)?(.*?)(_advanced|_basic)$/', $key, $match))
393
            	{
394
            	   $field = $match[2];
395
				   if(isset($searchModuleBean->field_defs[$field]['type'])  && empty($searchModuleBean->field_defs[$field]['disable_num_format']))
396
				   {
397
				   	  $type = $searchModuleBean->field_defs[$field]['type'];
398
399
				   	  //Avoid macro values for the date types
400
				   	  if(($type == 'date' || $type == 'datetime' || $type == 'datetimecombo') && preg_match('/^\d{4}-\d{2}-\d{2}$/', $val) && !preg_match('/^\[.*?\]$/', $val))
401
				   	  {
402
				   	  	 $val = $timedate->to_display_date($val, false);
403
				   	  }  else if (($type == 'int' || $type == 'currency' || $type == 'decimal' || $type == 'float') && isset($this->contents[$key . '_unformatted_number']) && preg_match('/^\d+$/', $val)) {
404
				   	  	 require_once('modules/Currencies/Currency.php');
405
				   	  	 $val = format_number($val);
406
				   	  	 if($type == 'currency' && isset($this->contents[$key . '_currency_symbol']))
407
				   	  	 {
408
				   	  	 	$val = $this->contents[$key . '_currency_symbol'] . $val;
409
				   	  	 }
410
				   	  }
411
				   }
412
            	}
413
414 1
                $_REQUEST[$key] = $val;
415 1
                $_GET[$key] = $val;
416
            }
417
        }
418
419 1
    }
420
}
421
422
?>