]> CyberLeo.Net >> Repos - Github/sugarcrm.git/blob - modules/UserPreferences/UserPreference.php
Release 6.1.4
[Github/sugarcrm.git] / modules / UserPreferences / UserPreference.php
1 <?php
2 if(!defined('sugarEntry') || !sugarEntry) die('Not A Valid Entry Point');
3 /*********************************************************************************
4  * SugarCRM 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: Handles the User Preferences and stores them in a seperate table.
41  * Portions created by SugarCRM are Copyright (C) SugarCRM, Inc.
42  * All Rights Reserved.
43  * Contributor(s): ______________________________________..
44  ********************************************************************************/
45
46 class UserPreference extends SugarBean
47 {
48     public $db;
49     public $field_name_map;
50
51     // Stored fields
52     public $id;
53     public $date_entered;
54     public $date_modified;
55     public $assigned_user_id;
56     public $assigned_user_name;
57     public $name;
58     public $category;
59     public $contents;
60     public $deleted;
61
62     public $object_name = 'UserPreference';
63     public $table_name = 'user_preferences';
64
65     public $disable_row_level_security = true;
66     public $module_dir = 'UserPreferences';
67     public $field_defs = array();
68     public $field_defs_map = array();
69     public $new_schema = true;
70
71     protected $_userFocus;
72
73         // Do not actually declare, use the functions statically
74         public function __construct(
75             User $user = null
76             )
77         {
78                 parent::SugarBean();
79
80                 $this->_userFocus = $user;
81         }
82
83         /**
84          * Get preference by name and category. Lazy loads preferences from the database per category
85          *
86          * @param string $name name of the preference to retreive
87          * @param string $category name of the category to retreive, defaults to global scope
88          * @return mixed the value of the preference (string, array, int etc)
89          */
90         public function getPreference(
91             $name,
92             $category = 'global'
93             )
94         {
95         global $sugar_config;
96
97         $user = $this->_userFocus;
98
99         // if the unique key in session doesn't match the app or prefereces are empty
100                 if(!isset($_SESSION[$user->user_name.'_PREFERENCES'][$category]) || (!empty($_SESSION['unique_key']) && $_SESSION['unique_key'] != $sugar_config['unique_key'])) {
101                         $this->loadPreferences($category);
102                 }
103                 if(isset($_SESSION[$user->user_name.'_PREFERENCES'][$category][$name])) {
104                         return $_SESSION[$user->user_name.'_PREFERENCES'][$category][$name];
105                 }
106
107                 // check to see if a default preference ( i.e. $sugar_config setting ) exists for this value )
108                 // if so, return it
109                 $value = $this->getDefaultPreference($name,$category);
110                 if ( !is_null($value) ) {
111                     return $value;
112                 }
113                 return null;
114         }
115
116         /**
117          * Get preference by name and category from the system settings.
118          *
119          * @param string $name name of the preference to retreive
120          * @param string $category name of the category to retreive, defaults to global scope
121          * @return mixed the value of the preference (string, array, int etc)
122          */
123         public function getDefaultPreference(
124             $name,
125             $category = 'global'
126             )
127         {
128             global $sugar_config;
129
130             // Doesn't support any prefs but global ones
131             if ( $category != 'global' )
132                 return null;
133
134             // First check for name matching $sugar_config variable
135             if ( isset($sugar_config[$name]) )
136                 return $sugar_config[$name];
137
138             // Next, check to see if it's one of the common problem ones
139             if ( isset($sugar_config['default_'.$name]) )
140                 return $sugar_config['default_'.$name];
141             if ( $name == 'datef' )
142                 return $sugar_config['default_date_format'];
143             if ( $name == 'timef' )
144                 return $sugar_config['default_time_format'];
145             if ( $name == 'email_link_type' )
146                 return $sugar_config['email_default_client'];
147         }
148
149         /**
150          * Set preference by name and category. Saving will be done in utils.php -> sugar_cleanup
151          *
152          * @param string $name name of the preference to retreive
153          * @param mixed $value value of the preference to set
154          * @param string $category name of the category to retreive, defaults to global scope
155          */
156         public function setPreference(
157             $name,
158             $value,
159             $category = 'global'
160             )
161         {
162             $user = $this->_userFocus;
163
164                 if ( empty($user->user_name) )
165                     return;
166
167                 if(!isset($_SESSION[$user->user_name.'_PREFERENCES'][$category])) {
168                         if(!$user->loadPreferences($category))
169                 $_SESSION[$user->user_name.'_PREFERENCES'][$category] = array();
170                 }
171
172                 // preferences changed or a new preference, save it to DB
173                 if(!isset($_SESSION[$user->user_name.'_PREFERENCES'][$category][$name])
174                         || (isset($_SESSION[$user->user_name.'_PREFERENCES'][$category][$name]) && $_SESSION[$user->user_name.'_PREFERENCES'][$category][$name] != $value)) {
175                                 $GLOBALS['savePreferencesToDB'] = true;
176                                 if(!isset($GLOBALS['savePreferencesToDBCats'])) $GLOBALS['savePreferencesToDBCats'] = array();
177                                 $GLOBALS['savePreferencesToDBCats'][$category] = true;
178                 }
179
180                 //check to see if the preference being saved is too large
181                 if ($this->isPreferenceSizeTooLarge($category)){
182                         //log error and set error message flag
183                         $GLOBALS['log']->fatal("USERPREFERENCE ERROR 00:: User preference  for user: '$user->user_name' and category '$category' is ".strlen(base64_encode(serialize($value)))." characters long which is too big to save");  //<<----------                            
184
185                         //set global flag to indicate error has ocurred.  This will cause sugar_cleanup() in utils.php to flash a warning message to user.
186                         $_SESSION['USER_PREFRENCE_ERRORS'] = true;
187
188                 }else{
189                         $_SESSION[$user->user_name.'_PREFERENCES'][$category][$name] = $value;
190                 }
191
192         }
193
194         /**
195          * Loads preference by category from database. Saving will be done in utils.php -> sugar_cleanup
196          *
197          * @param string $category name of the category to retreive, defaults to global scope
198          * @return bool successful?
199          */
200         public function loadPreferences(
201             $category = 'global'
202             )
203         {
204         global $sugar_config;
205
206                 $user = $this->_userFocus;
207
208                 if($user->object_name != 'User')
209                         return;
210                 if(!empty($user->id) && (!isset($_SESSION[$user->user_name . '_PREFERENCES'][$category]) || (!empty($_SESSION['unique_key']) && $_SESSION['unique_key'] != $sugar_config['unique_key']))) {
211                         // cn: moving this to only log when valid - throwing errors on install
212                         return $this->reloadPreferences($category);
213                 }
214                 return false;
215         }
216
217         /**
218          * Unconditionally reloads user preferences from the DB and updates the session
219          * @param string $category name of the category to retreive, defaults to global scope
220          * @return bool successful?
221          */
222         public function reloadPreferences($category = 'global')
223         {
224                 $user = $this->_userFocus;
225
226                 if($user->object_name != 'User' || empty($user->id) || empty($user->user_name)) {
227                         return false;
228                 }
229             $GLOBALS['log']->debug('Loading Preferences DB ' . $user->user_name);
230                 if(!isset($_SESSION[$user->user_name . '_PREFERENCES'])) $_SESSION[$user->user_name . '_PREFERENCES'] = array();
231                 if(!isset($user->user_preferences) || !is_array($user->user_preferences)) $user->user_preferences = array();
232                 $result = $GLOBALS['db']->query("SELECT contents FROM user_preferences WHERE assigned_user_id='$user->id' AND category = '" . $category . "' AND deleted = 0", false, 'Failed to load user preferences');
233                 $row = $GLOBALS['db']->fetchByAssoc($result);
234                 if ($row) {
235                     $_SESSION[$user->user_name . '_PREFERENCES'][$category] = unserialize(base64_decode($row['contents']));
236                         $user->user_preferences[$category] = unserialize(base64_decode($row['contents']));
237                         return true;
238                 } else {
239                     $_SESSION[$user->user_name . '_PREFERENCES'][$category] = array();
240                         $user->user_preferences[$category] = array();
241         }
242         return false;
243         }
244
245         /**
246          * Loads users timedate preferences
247          *
248          * @return array 'date' - date format for user ; 'time' - time format for user
249          */
250         public function getUserDateTimePreferences()
251         {
252                 global $sugar_config, $db, $timezones, $timedate, $current_user;
253
254                 $user = $this->_userFocus;
255
256                 $prefDate = array();
257
258                 if(!empty($user) && $this->loadPreferences('global')) {
259                         // forced to set this to a variable to compare b/c empty() wasn't working
260                         $timeZone = $user->getPreference("timezone");
261                         $timeFormat = $user->getPreference("timef");
262                         $dateFormat = $user->getPreference("datef");
263
264                         // cn: bug xxxx cron.php fails because of missing preference when admin hasn't logged in yet
265                         $timeZone = empty($timeZone) ? 'America/Los_Angeles' : $timeZone;
266
267                         if(empty($timeZone)) $timeZone = '';
268                         if(empty($timeFormat)) $timeFormat = $sugar_config['default_time_format'];
269                         if(empty($dateFormat)) $dateFormat = $sugar_config['default_date_format'];
270
271                         $equinox = date('I');
272
273                         $serverHourGmt = date('Z') / 60 / 60;
274
275                         $userOffsetFromServerHour = $user->getPreference("timez");
276
277                         $userHourGmt = $serverHourGmt + $userOffsetFromServerHour;
278
279                         $prefDate['date'] = $dateFormat;
280                         $prefDate['time'] = $timeFormat;
281                         $prefDate['userGmt'] = "(GMT".($timezones[$timeZone]['gmtOffset'] / 60).")";
282                         $prefDate['userGmtOffset'] = $timezones[$timeZone]['gmtOffset'] / 60;
283
284                         return $prefDate;
285                 } else {
286                         $prefDate['date'] = $timedate->get_date_format();
287                         $prefDate['time'] = $timedate->get_time_format();
288
289             if(!empty($user) && $user->object_name == 'User') {
290                 $timeZone = $user->getPreference("timezone");
291                 // cn: bug 9171 - if user has no time zone, cron.php fails for InboundEmail
292                 if(!empty($timeZone)) {
293                         $prefDate['userGmt'] = "(GMT".($timezones[$timeZone]['gmtOffset'] / 60).")";
294                         $prefDate['userGmtOffset'] = $timezones[$timeZone]['gmtOffset'] / 60;
295                 }
296             } else {
297                 $timeZone = $current_user->getPreference("timezone");
298                 if(!empty($timeZone)) {
299                         $prefDate['userGmt'] = "(GMT".($timezones[$timeZone]['gmtOffset'] / 60).")";
300                         $prefDate['userGmtOffset'] = $timezones[$timeZone]['gmtOffset'] / 60;
301                 }
302             }
303
304                         return $prefDate;
305                 }
306         }
307
308         /**
309          * Saves all preferences into the database that are in the session. Expensive, this is called by default in
310          * sugar_cleanup if a setPreference has been called during one round trip.
311          *
312          * @global user will use current_user if no user specificed in $user param
313          * @param user $user User object to retrieve, otherwise user current_user
314          * @param bool $all save all of the preferences? (Dangerous)
315          *
316          */
317         public function savePreferencesToDB(
318             $all = false
319             )
320         {
321         global $sugar_config;
322         $GLOBALS['savePreferencesToDB'] = false;
323
324         $user = $this->_userFocus;
325
326         // these are not the preferences you are looking for [ hand waving ]
327         if(!empty($_SESSION['unique_key']) && $_SESSION['unique_key'] != $sugar_config['unique_key']) return;
328
329         $GLOBALS['log']->debug('Saving Preferences to DB ' . $user->user_name);
330         if(isset($_SESSION[$user->user_name. '_PREFERENCES']) && is_array($_SESSION[$user->user_name. '_PREFERENCES'])) {
331              $GLOBALS['log']->debug("Saving Preferences to DB: {$user->user_name}");
332                         // only save the categories that have been modified or all?
333                         if(!$all && isset($GLOBALS['savePreferencesToDBCats']) && is_array($GLOBALS['savePreferencesToDBCats'])) {
334                                 $catsToSave = array();
335                                 foreach($GLOBALS['savePreferencesToDBCats'] as $category => $value) {
336                     if ( isset($_SESSION[$user->user_name. '_PREFERENCES'][$category]) )
337                         $catsToSave[$category] = $_SESSION[$user->user_name. '_PREFERENCES'][$category];
338                                 }
339                         }
340                         else {
341                                 $catsToSave = $_SESSION[$user->user_name. '_PREFERENCES'];
342                         }
343
344                         foreach ($catsToSave as $category => $contents) {
345                             $focus = new UserPreference($this->_userFocus);
346                             $result = $focus->retrieve_by_string_fields(array(
347                                 'assigned_user_id' => $user->id,
348                                 'category' => $category,
349                                 ));
350                             $focus->assigned_user_id = $user->id; // MFH Bug #13862
351                             $focus->deleted = 0;
352                             $focus->contents = base64_encode(serialize($contents));
353                             $focus->category = $category;
354                                 //save if length is under column max
355                                 if (strlen($focus->contents) > 65535){
356                                         //log error and add to error message
357                                         $GLOBALS['log']->fatal("USERPREFERENCE ERROR:: User preference  for user: '$user->user_name' and category '$focus->category' is ".strlen($focus->contents)." characters long which is too big to save");
358                                         $errors[] = 'category: '.$focus->category.' is '.strlen($focus->contents).' characters long which is too big and will cause the query to fail.';
359                                         //set global flag to indicate error has ocurred.  This will cause sugar_cleanup() in utils.php to flash a warning message to user.
360                                         $_SESSION['USER_PREFRENCE_ERRORS'] = true;
361                                 }else{
362                                         $focus->save();
363                                 }       
364
365                         }
366                 }
367         }
368
369         
370         /**
371          * Checks to see if preference size is too large to store in contents field of userpreference table in database
372          * @return returns true or false by default.  Returns string length number if returnCount value is set to true.
373          * @param string $category category to check
374          * @param bool $returnCount whether to return count or default boolean
375          */
376          function isPreferenceSizeTooLarge($category = 'global',$returnCount=false){
377                 $user = $this->_userFocus;
378                 
379                 //retrieve the user preferences for this category, then serialize and encode the way the string would be stored in db
380                 if(!isset($_SESSION[$user->user_name . '_PREFERENCES'][$category])){
381                         $contents='';  
382                 }else{
383                         $contents = base64_encode(serialize($_SESSION[$user->user_name . '_PREFERENCES'][$category]));
384                 }
385
386                 //log error if string is too large
387                 if (strlen($contents)>65535){
388                         $GLOBALS['log']->fatal("USERPREFERENCE::isPreferenceSizeTooLarge - User preference  for user: '$user->user_name' and category '$category' did not pass size check as it is ".strlen($contents)." characters long which is too big to save.");
389                 }
390                         
391                 //check returnCount flag to see whether we return true/false or actual count of content size
392                 if($returnCount){
393                         return strlen($contents);
394                 }elseif (strlen($contents)>65535){
395                         return true;
396                 }
397                 return false;
398
399         }
400         
401         /**
402          * Resets preferences for a particular user. If $category is null all user preferences will be reset
403          *
404          * @param string $category category to reset
405          */
406         public function resetPreferences(
407             $category = null
408             )
409         {
410         $user = $this->_userFocus;
411
412         $GLOBALS['log']->debug('Reseting Preferences for user ' . $user->user_name);
413
414         $remove_tabs = $this->getPreference('remove_tabs');
415         $favorite_reports = $this->getPreference('favorites', 'Reports');
416         $home_pages = $this->getPreference('pages', 'home');
417         $home_dashlets = $this->getPreference('dashlets', 'home');
418         $ut = $this->getPreference('ut');
419         $timezone = $this->getPreference('timezone');
420
421         $query = "UPDATE user_preferences SET deleted = 1 WHERE assigned_user_id = '" . $user->id . "'";
422         if($category)
423             $query .= " AND category = '" . $category . "'";
424         $this->db->query($query);
425
426
427         if($category) {
428             unset($_SESSION[$user->user_name."_PREFERENCES"][$category]);
429         }
430         else {
431             if(!empty($_COOKIE['sugar_user_theme']) && !headers_sent()){
432                 setcookie('sugar_user_theme', '', time() - 3600); // expire the sugar_user_theme cookie
433             }
434             unset($_SESSION[$user->user_name."_PREFERENCES"]);
435             if($user->id == $GLOBALS['current_user']->id) {
436                 session_destroy();
437             }
438             $this->setPreference('remove_tabs', $remove_tabs);
439             $this->setPreference('favorites', $favorite_reports, 'Reports');
440             $this->setPreference('pages', $home_pages, 'home');
441             $this->setPreference('dashlets', $home_dashlets, 'home');
442             $this->setPreference('ut', $ut);
443             $this->setPreference('timezone', $timezone);
444             $this->savePreferencesToDB();
445             if($user->id == $GLOBALS['current_user']->id) {
446                 SugarApplication::redirect('index.php');
447             }
448         }
449         }
450
451         /**
452          * Updates every user pref with a new key value supports 2 levels deep, use append to
453          * array if you want to append the value to an array
454          */
455         public static function updateAllUserPrefs(
456             $key,
457             $new_value,
458             $sub_key = '',
459             $is_value_array = false,
460             $unset_value = false )
461         {
462         global $current_user, $db;
463
464         // Admin-only function; die if calling as a non-admin
465             if(!is_admin($current_user)){
466             sugar_die('only admins may call this function');
467         }
468
469         // we can skip this if we've already upgraded to the user_preferences format.
470         if ( !array_key_exists('user_preferences',$db->getHelper()->get_columns('users')) )
471             return;
472
473         $result = $db->query("SELECT id, user_preferences, user_name FROM users");
474         while ($row = $db->fetchByAssoc($result)) {
475             $prefs = array();
476             $newprefs = array();
477
478             $prefs = unserialize(base64_decode($row['user_preferences']));
479
480             if(!empty($sub_key)){
481                 if($is_value_array ){
482                     if(!isset($prefs[$key][$sub_key])){
483                         continue;
484                     }
485
486                     if(empty($prefs[$key][$sub_key])){
487                         $prefs[$key][$sub_key] = array();
488                     }
489                     $already_exists = false;
490                     foreach($prefs[$key][$sub_key] as $k=>$value){
491                         if($value == $new_value){
492
493                             $already_exists = true;
494                             if($unset_value){
495                                 unset($prefs[$key][$sub_key][$k]);
496                             }
497                         }
498                     }
499                     if(!$already_exists && !$unset_value){
500                         $prefs[$key][$sub_key][] = $new_value;
501                     }
502                 }
503                 else{
504                     if(!$unset_value)$prefs[$key][$sub_key] = $new_value;
505                 }
506             }
507             else{
508                 if($is_value_array ){
509                     if(!isset($prefs[$key])){
510                         continue;
511                     }
512
513                     if(empty($prefs[$key])){
514                         $prefs[$key] = array();
515                     }
516                     $already_exists = false;
517                     foreach($prefs[$key] as $k=>$value){
518                         if($value == $new_value){
519                             $already_exists = true;
520
521                             if($unset_value){
522                                 unset($prefs[$key][$k]);
523                             }
524                         }
525                     }
526                     if(!$already_exists && !$unset_value){
527
528                         $prefs[$key][] = $new_value;
529                     }
530                 }else{
531                     if(!$unset_value)$prefs[$key] = $new_value;
532                 }
533             }
534
535             $newstr = $GLOBALS['db']->quote(base64_encode(serialize($prefs)));
536             $db->query("UPDATE users SET user_preferences = '{$newstr}' WHERE id = '{$row['id']}'");
537         }
538
539         unset($prefs);
540         unset($newprefs);
541         unset($newstr);
542     }
543 }