Implemented configurable confirm save option.
[timetracker.git] / WEB-INF / lib / ttUser.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttConfigHelper');
30 import('ttGroupHelper');
31 import('ttGroup');
32
33 class ttUser {
34   var $login = null;            // User login.
35   var $name = null;             // User name.
36   var $id = null;               // User id.
37   var $org_id = null;           // Organization id.
38   var $group_id = null;         // Group id.
39   var $role_id = null;          // Role id.
40   var $role_name = null;        // Role name.
41   var $rank = null;             // User role rank.
42   var $client_id = null;        // Client id for client user role.
43   var $behalf_id = null;        // User id, on behalf of whom we are working.
44   var $behalf_group_id = null;  // Group id, on behalf of which we are working.
45   var $behalf_name = null;      // User name, on behalf of whom we are working.
46   var $group_name = null;       // Group name.
47   var $behalf_group_name = null;// Group name, on behalf of which we are working.
48   var $email = null;            // User email.
49   var $lang = null;             // Language.
50   var $decimal_mark = null;     // Decimal separator.
51   var $date_format = null;      // Date format.
52   var $time_format = null;      // Time format.
53   var $week_start = 0;          // Week start day.
54   var $show_holidays = 0;       // Whether to show holidays in calendar.
55   var $tracking_mode = 0;       // Tracking mode.
56   var $project_required = 0;    // Whether project selection is required on time entires.
57   var $task_required = 0;       // Whether task selection is required on time entires.
58   var $record_type = 0;         // Record type (duration vs start and finish, or both).
59   var $punch_mode = 0;          // Whether punch mode is enabled for user.
60   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
61   var $future_entries = 0;      // Whether to allow creating future entries.
62   var $uncompleted_indicators = 0; // Uncompleted time entry indicators (show nowhere or on users page).
63   var $confirm_save = 0;        // Whether to show warnings for save action when date changed.
64   var $bcc_email = null;        // Bcc email.
65   var $allow_ip = null;         // Specification from where user is allowed access.
66   var $password_complexity = null; // Password complexity example.
67   var $currency = null;         // Currency.
68   var $plugins = null;          // Comma-separated list of enabled plugins.
69   var $config = null;           // Comma-separated list of miscellaneous config options.
70   var $custom_logo = 0;         // Whether to use a custom logo for group.
71   var $lock_spec = null;        // Cron specification for record locking.
72   var $workday_minutes = 480;   // Number of work minutes in a regular day.
73   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
74   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
75   var $minutes_in_unit = 15;    // Number of minutes in unit for Work units plugin.
76   var $first_unit_threshold = 0;// Threshold for 1st unit for Work units plugin.
77   var $unit_totals_only = 0;    // Totals only option for the Work units plugin.
78
79   var $behalfGroup = null;      // A ttGroup instance with on behalf group attributes.
80
81   // Constructor.
82   function __construct($login, $id = null) {
83     if (!$login && !$id) {
84       // nothing to initialize
85       return;
86     }
87
88     $mdb2 = getConnection();
89
90     $sql = "SELECT u.id, u.login, u.name, u.group_id, u.role_id, r.rank, r.name as role_name, r.rights, u.client_id, u.email,
91       g.org_id, g.name as group_name, g.currency, g.lang, g.decimal_mark, g.date_format, g.time_format, g.week_start,
92       g.tracking_mode, g.project_required, g.task_required, g.record_type,
93       g.bcc_email, g.allow_ip, g.password_complexity, g.plugins, g.config, g.lock_spec, g.workday_minutes, g.custom_logo
94       FROM tt_users u LEFT JOIN tt_groups g ON (u.group_id = g.id) LEFT JOIN tt_roles r on (r.id = u.role_id) WHERE ";
95     if ($id)
96       $sql .= "u.id = $id";
97     else
98       $sql .= "u.login = ".$mdb2->quote($login);
99     $sql .= " AND u.status = 1";
100
101     $res = $mdb2->query($sql);
102     if (is_a($res, 'PEAR_Error')) {
103       return;
104     }
105
106     $val = $res->fetchRow();
107     if ($val['id'] > 0) {
108       $this->login = $val['login'];
109       $this->name = $val['name'];
110       $this->id = $val['id'];
111       $this->org_id = $val['org_id'];
112       $this->group_id = $val['group_id'];
113       $this->role_id = $val['role_id'];
114       $this->role_name = $val['role_name'];
115       $this->rights = explode(',', $val['rights']);
116       $this->is_client = !in_array('track_own_time', $this->rights);
117       $this->rank = $val['rank'];
118       $this->client_id = $val['client_id'];
119       $this->email = $val['email'];
120       $this->lang = $val['lang'];
121       $this->decimal_mark = $val['decimal_mark'];
122       $this->date_format = $val['date_format'];
123       $this->time_format = $val['time_format'];
124       $this->week_start = $val['week_start'];
125       $this->tracking_mode = $val['tracking_mode'];
126       $this->project_required = $val['project_required'];
127       $this->task_required = $val['task_required'];
128       $this->record_type = $val['record_type'];
129       $this->bcc_email = $val['bcc_email'];
130       $this->allow_ip = $val['allow_ip'];
131       $this->password_complexity = $val['password_complexity'];
132       $this->group_name = $val['group_name'];
133       $this->currency = $val['currency'];
134       $this->plugins = $val['plugins'];
135       $this->lock_spec = $val['lock_spec'];
136       $this->workday_minutes = $val['workday_minutes'];
137       $this->custom_logo = $val['custom_logo'];
138
139       $this->config = $val['config'];
140       $config = new ttConfigHelper($this->config);
141       // Set user config options.
142       $this->show_holidays = $config->getDefinedValue('show_holidays');
143       $this->punch_mode = $config->getDefinedValue('punch_mode');
144       $this->allow_overlap = $config->getDefinedValue('allow_overlap');
145       $this->future_entries = $config->getDefinedValue('future_entries');
146       $this->uncompleted_indicators = $config->getDefinedValue('uncompleted_indicators');
147       $this->confirm_save = $config->getDefinedValue('confirm_save');
148       if ($this->isPluginEnabled('wu')) {
149         $minutes_in_unit = $config->getIntValue('minutes_in_unit');
150         if ($minutes_in_unit) $this->minutes_in_unit = $minutes_in_unit;
151         $first_unit_threshold = $config->getIntValue('1st_unit_threshold');
152         if ($first_unit_threshold) $this->first_unit_threshold = $first_unit_threshold;
153         $this->unit_totals_only = $config->getDefinedValue('unit_totals_only');
154       }
155       
156       // Set "on behalf" id and name (user).
157       if (isset($_SESSION['behalf_id'])) {
158         $this->behalf_id = $_SESSION['behalf_id'];
159         $this->behalf_name = $_SESSION['behalf_name'];
160       }
161       // Set "on behalf" id and name (group).
162       if (isset($_SESSION['behalf_group_id'])) {
163         $this->behalf_group_id = $_SESSION['behalf_group_id'];
164         $this->behalf_group_name = $_SESSION['behalf_group_name'];
165
166         $this->behalfGroup = new ttGroup($this->behalf_group_id, $this->org_id);
167       }
168     }
169   }
170
171   // The getUser returns user id on behalf of whom the current user is operating.
172   function getUser() {
173     return ($this->behalf_id ? $this->behalf_id : $this->id);
174   }
175
176   // The getGroup returns group id on behalf of which the current user is operating.
177   function getGroup() {
178     return ($this->behalfGroup ? $this->behalfGroup->id : $this->group_id);
179   }
180
181   // getDecimalMark returns decimal mark for active group.
182   function getDecimalMark() {
183     return ($this->behalfGroup ? $this->behalfGroup->decimal_mark : $this->decimal_mark);
184   }
185
186   // getTrackingMode returns tracking mode for active group.
187   function getTrackingMode() {
188     return ($this->behalfGroup ? $this->behalfGroup->tracking_mode : $this->tracking_mode);
189   }
190
191   // getRecordType returns record type for active group.
192   function getRecordType() {
193     return ($this->behalfGroup ? $this->behalfGroup->record_type : $this->record_type);
194   }
195
196   // getPlugins returns plugins string for active group.
197   function getPlugins() {
198     return ($this->behalfGroup ? $this->behalfGroup->plugins : $this->plugins);
199   }
200
201   // getConfig returns config string for active group.
202   function getConfig() {
203     return ($this->behalfGroup ? $this->behalfGroup->config : $this->config);
204   }
205
206   // getConfirmSave returns confirm_save option for user.
207   function getConfirmSave() {
208     return ($this->behalfGroup ? $this->behalfGroup->confirm_save : $this->confirm_save);
209   }
210
211   // can - determines whether user has a right to do something.
212   function can($do_something) {
213     return in_array($do_something, $this->rights);
214   }
215
216   // isClient - determines whether current user is a client.
217   function isClient() {
218     return $this->is_client;
219   }
220
221   // isPluginEnabled checks whether a plugin is enabled for user.
222   function isPluginEnabled($plugin)
223   {
224     return in_array($plugin, explode(',', $this->getPlugins()));
225   }
226
227   // getAssignedProjects - returns an array of assigned projects.
228   function getAssignedProjects()
229   {
230     $result = array();
231     $mdb2 = getConnection();
232
233     $group_id = $this->behalf_group_id ? $this->behalf_group_id : $this->group_id;
234     // Do a query with inner join to get assigned projects.
235     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate from tt_projects p
236       inner join tt_user_project_binds upb on (upb.user_id = ".$this->getUser()." and upb.project_id = p.id and upb.status = 1)
237       where p.group_id = $group_id and p.status = 1 order by p.name";
238     $res = $mdb2->query($sql);
239     if (!is_a($res, 'PEAR_Error')) {
240       while ($val = $res->fetchRow()) {
241         $result[] = $val;
242       }
243     }
244     return $result;
245   }
246
247   // getAssignedTasks - returns an array of assigned tasks.
248   function getAssignedTasks()
249   {
250     // Start with projects;
251     $projects = $this->getAssignedProjects();
252     if (!$projects) return false;
253
254     // Build an array of task ids.
255     $task_ids = array();
256     foreach($projects as $project) {
257       $one_project_tasks = $project['tasks'] ? explode(',', $project['tasks']) : array();
258       $task_ids = array_unique(array_merge($task_ids, $one_project_tasks));
259     }
260     if (!$task_ids) return false;
261
262     // Get task descriptions.
263     $result = array();
264     $mdb2 = getConnection();
265     $tasks = implode(',', $task_ids); // This is a comma-separated list of task ids.
266
267     $sql = "select id, name, description from tt_tasks".
268       " where group_id = $this->group_id and status = 1 and id in ($tasks) order by name";
269     $res = $mdb2->query($sql);
270     if (!is_a($res, 'PEAR_Error')) {
271       while ($val = $res->fetchRow()) {
272         $result[] = $val;
273       }
274     }
275     return $result;
276   }
277
278   // getAssignedClients - returns an array of clients assigned to own projects.
279   function getAssignedClients()
280   {
281     // Start with projects;
282     $projects = $this->getAssignedProjects();
283     if (!$projects) return false;
284     $assigned_project_ids = array();
285     foreach($projects as $project) {
286       $assigned_project_ids[] = $project['id'];
287     }
288
289     $mdb2 = getConnection();
290
291     // Get active clients for group.
292     $clients = array();
293     $sql = "select id, name, address, projects from tt_clients where group_id = $this->group_id and status = 1";
294     $res = $mdb2->query($sql);
295     if (!is_a($res, 'PEAR_Error')) {
296       while ($val = $res->fetchRow()) {
297         $client_project_ids = $val['projects'] ? explode(',', $val['projects']) : array();
298         if (array_intersect($assigned_project_ids, $client_project_ids))
299           $clients[] = $val; // Add client if one of user projects is a client project, too.
300       }
301     }
302     return $clients;
303   }
304
305   // isDateLocked checks whether a specifc date is locked for modifications.
306   function isDateLocked($date)
307   {
308     if (!$this->isPluginEnabled('lk'))
309       return false; // Locking feature is disabled.
310
311     if (!$this->lock_spec)
312       return false; // There is no lock specification.
313
314     if (!$this->behalf_id && $this->can('override_own_date_lock'))
315       return false; // User is working as self and can override own date lock.
316
317     if ($this->behalf_id && $this->can('override_date_lock'))
318       return false; // User is working on behalf of someone else and can override date lock.
319
320     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
321     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
322
323     // Calculate the last occurrence of a lock.
324     $last = tdCron::getLastOccurrence($this->lock_spec, time());
325     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
326     if ($date->before($lockdate))
327       return true;
328
329     return false;
330   }
331
332   // canOverridePunchMode checks whether a user can override punch mode in a situation.
333   function canOverridePunchMode()
334   {
335     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
336       return false; // User is working as self and cannot override for self.
337
338     if ($this->behalf_id && !$this->can('override_punch_mode'))
339       return false; // User is working on behalf of someone else and cannot override.
340
341     return true;
342   }
343
344   // getUsers obtains users in a group, as specififed by options.
345   function getUsers($options) {
346     $mdb2 = getConnection();
347
348     $group_id = $this->getGroup();
349     $org_id = $this->org_id;
350
351     $skipClients = !isset($options['include_clients']);
352     $includeSelf = isset($options['include_self']);
353
354     $select_part = 'select u.id, u.group_id, u.name';
355     if (isset($options['include_login'])) $select_part .= ', u.login';
356     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
357     if (isset($options['include_role'])) $select_part .= ', r.name as role_name, r.rank';
358
359     $from_part = ' from tt_users u';
360
361     $left_joins = null;
362     if (isset($options['max_rank']) || $skipClients || isset($options['include_role']))
363         $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
364
365     $where_part = " where u.org_id = $org_id and u.group_id = $group_id";
366     if (isset($options['status']))
367       $where_part .= ' and u.status = '.(int)$options['status'];
368     else
369       $where_part .= ' and u.status is not null';
370     if ($includeSelf) {
371       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
372     } else {
373       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
374     }
375
376     $order_part = " order by upper(u.name)";
377
378     $sql = $select_part.$from_part.$left_joins.$where_part.$order_part;
379     $res = $mdb2->query($sql);
380     $user_list = array();
381     if (is_a($res, 'PEAR_Error'))
382       return false;
383
384     while ($val = $res->fetchRow()) {
385       if ($skipClients) {
386         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
387         if ($isClient)
388           continue; // Skip adding clients.
389       }
390       $user_list[] = $val;
391     }
392
393     if (isset($options['self_first'])) {
394       // Put own entry at the front.
395       $cnt = count($user_list);
396       for($i = 0; $i < $cnt; $i++) {
397         if ($user_list[$i]['id'] == $this->id) {
398           $self = $user_list[$i]; // Found self.
399           array_unshift($user_list, $self); // Put own entry at the front.
400           array_splice($user_list, $i+1, 1); // Remove duplicate.
401         }
402       }
403     }
404     return $user_list;
405   }
406
407   // getGroupsForDropdown obtains an array of groups to populate "Group" dropdown.
408   // It consists of:
409   //   - User home group.
410   //   - The entire stack of groups all the way down to current on behalf group.
411   //   - All immediate children of the current on behalf group.
412   // This allows user to navigate easily to home group, anything in between, and 1 level below.
413   //
414   // Note 1: group dropdown is, by design, to be placed on all pages where "relevant",
415   // such as users.php, projects.php, tasks.php, etc. But some features may be disabled
416   // in some groups. We should check for feature availability on group change
417   // in post and redirect to feature_disabled.php when this happens.
418   // This will allow us to keep dropdown content consistent on all pages.
419   // Filtering content of the dropdown does not seem right.
420   //
421   // Note 2: Menu should display according to $user home group settings.
422   //         Pages, should look according to $user->behalfGroup settings (if set).
423   //         For example, if home group allows tasks, menu should display Tasks,
424   //         even when we are on behalf of a subgroup without tasks.
425   //
426   // Note 3: Language of all pages should be as in $user home group even when
427   //         subgroups have a different language.
428   function getGroupsForDropdown() {
429     $mdb2 = getConnection();
430
431     // Start with subgroups.
432     $groups = array();
433     $group_id = $this->getGroup();
434     $sql = "select id, name from tt_groups where org_id = $this->org_id and parent_id = $group_id and status = 1";
435     $res = $mdb2->query($sql);
436     if (!is_a($res, 'PEAR_Error')) {
437       while ($val = $res->fetchRow()) {
438         $groups[] = $val;
439       }
440     }
441
442     // Add current on behalf group to the beginning of array.
443     $selected_group_id = ($this->behalf_group_id ? $this->behalf_group_id : $this->group_id);
444     $selected_group_name = ($this->behalf_group_id ? $this->behalf_group_name : $this->group_name);
445     array_unshift($groups,  array('id'=>$selected_group_id,'name'=>$selected_group_name));
446
447     // Iterate all the way to the home group, starting with selected ("on behalf") group.
448     $current_group_id = $selected_group_id;
449     while ($current_group_id != $this->group_id) {
450       $sql = "select parent_id from tt_groups where org_id = $this->org_id and id = $current_group_id and status = 1";
451       $res = $mdb2->query($sql);
452       if (is_a($res, 'PEAR_Error')) return false;
453
454       $val = $res->fetchRow();
455       $parent_id = $val['parent_id'];
456       if ($parent_id) {
457         // Get parent group name.
458         $sql = "select name from tt_groups where org_id = $this->org_id and id = $parent_id and status = 1";
459         $res = $mdb2->query($sql);
460         if (is_a($res, 'PEAR_Error')) return false;
461         $val = $res->fetchRow();
462         if (!$val) return false;
463         array_unshift($groups, array('id'=>$parent_id,'name'=>$val['name']));
464         $current_group_id = $parent_id;
465       } else {
466         return false;
467       }
468     }
469     return $groups;
470   }
471
472   // getSubgroups obtains a list of immediate subgroups.
473   function getSubgroups($group_id = null) {
474     $mdb2 = getConnection();
475
476     if (!$group_id) $group_id = $this->getGroup();
477
478     $sql = "select id, name, description from tt_groups where org_id = $this->org_id".
479       " and parent_id = $group_id and status is not null order by upper(name)";
480     $res = $mdb2->query($sql);
481     if (!is_a($res, 'PEAR_Error')) {
482       while ($val = $res->fetchRow()) {
483         $groups[] = $val;
484       }
485     }
486     return $groups;
487   }
488
489   // getUserDetails function is used to manage users in group and returns user details.
490   // At the moment, the function is used for user edits and deletes.
491   function getUserDetails($user_id) {
492     if (!$this->can('manage_users')) return false;
493
494     $mdb2 = getConnection();
495     $group_id = $this->getGroup();
496     $org_id = $this->org_id;
497
498     // Determine max rank. If we are searching in on behalf group
499     // then rank restriction does not apply.
500     $max_rank = $this->behalfGroup ? MAX_RANK : $this->rank;
501
502     $sql =  "select u.id, u.name, u.login, u.role_id, u.client_id, u.status, u.rate, u.email from tt_users u".
503       " left join tt_roles r on (u.role_id = r.id)".
504       " where u.id = $user_id and u.group_id = $group_id and u.org_id = $org_id and u.status is not null".
505       " and (r.rank < $max_rank or (r.rank = $max_rank and u.id = $this->id))"; // Users with lesser roles or self.
506     $res = $mdb2->query($sql);
507     if (!is_a($res, 'PEAR_Error')) {
508       $val = $res->fetchRow();
509       return $val;
510     }
511     return false;
512   }
513
514   // checkBehalfId checks whether behalf_id is appropriate.
515   // On behalf user must be active and have lower rank if the user is from home group,
516   // otherwise:
517   // - subgroup must ve valid;
518   // - user should be a member of it.
519   function checkBehalfId() {
520     if (!$this->behalf_group_id) {
521       // Checking user from home group.
522       $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
523       $users = $this->getUsers($options);
524       foreach($users as $one_user) {
525         if ($one_user['id'] == $this->behalf_id)
526           return true;
527       }
528     } else {
529       // Checking user from a subgroup.
530       $group_id = $this->behalf_group_id;
531       if (!$this->isSubgroupValid($group_id))
532         return false;
533
534       // So far, so good. Check user now.
535       $options = array('group_id'=>$group_id,'status'=>ACTIVE,'max_rank'=>MAX_RANK);
536       $users = $this->getUsers($options);
537       foreach($users as $one_user) {
538         if ($one_user['id'] == $this->behalf_id)
539           return true;
540       }
541     }
542     return false;
543   }
544
545   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
546   // apropriate user.
547   //
548   // Needed for situations when user does not have do_own_something right.
549   // Example: has view_charts but does not have view_own_charts.
550   // In this case we still allow access to charts, but set behalf_id to someone else.
551   // Another example: working in a subgroup on behalf of someone else.
552   function adjustBehalfId() {
553     $group_id = $this->behalf_group_id ? $this->behalf_group_id : $this->group_id;
554     $rank = $this->getMaxRankForGroup($group_id);
555
556     // Adjust to first found user in group.
557     $options = array('group_id'=>$group_id,'status'=>ACTIVE,'max_rank'=>$rank);
558     $users = $this->getUsers($options);
559     foreach($users as $one_user) {
560       // Fake loop to access first element.
561       $this->behalf_id = $one_user['id'];
562       $this->behalf_name = $one_user['name'];
563       $_SESSION['behalf_id'] = $this->behalf_id;
564       $_SESSION['behalf_name'] = $this->behalf_name;
565       return true;
566     }
567     return false;
568   }
569
570   // updateGroup updates group information with new data.
571   function updateGroup($fields) {
572     if (!($this->can('manage_basic_settings') ||
573       $this->can('manage_advanced_settings') ||
574       $this->can('manage_features'))) return false;
575     // TODO: update the above for subgroup updates.
576
577     $group_id = $fields['group_id'];
578     if ($group_id && !$this->isGroupValid($group_id)) return false;
579
580     $mdb2 = getConnection();
581     if (!$group_id) $group_id = $this->getGroup();
582
583     if (isset($fields['name'])) $name_part = ', name = '.$mdb2->quote($fields['name']);
584     if (isset($fields['description'])) $description_part = ', description = '.$mdb2->quote($fields['description']);
585     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
586     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
587     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
588     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
589     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
590     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
591     if (isset($fields['tracking_mode'])) {
592       $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
593       $project_required_part = ' , project_required = '.(int) $fields['project_required'];
594       $task_required_part = ' , task_required = '.(int) $fields['task_required'];
595     }
596     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
597     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
598     if (isset($fields['allow_ip'])) $allow_ip_part = ', allow_ip = '.$mdb2->quote($fields['allow_ip']);
599     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
600     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
601     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
602     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
603     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
604
605     $parts = trim($name_part.$description_part.$currency_part.$lang_part.$decimal_mark_part.$date_format_part.
606       $time_format_part.$week_start_part.$tracking_mode_part.$task_required_part.$project_required_part.$record_type_part.
607       $bcc_email_part.$allow_ip_part.$plugins_part.$config_part.$lock_spec_part.$workday_minutes_part.$modified_part, ',');
608
609     $sql = "update tt_groups set $parts where id = $group_id and org_id = $this->org_id";
610     $affected = $mdb2->exec($sql);
611     if (is_a($affected, 'PEAR_Error')) return false;
612
613     return true;
614   }
615
616   // markUserDeleted marks a user in group as deleted.
617   function markUserDeleted($user_id) {
618     if (!$this->can('manage_users') || $this->id == $user_id)
619       return false;
620
621     // Make sure we operate on a legit user.
622     $user_details = $this->getUserDetails($user_id);
623     if (!$user_details) return false;
624
625     $mdb2 = getConnection();
626     $group_id = $this->getGroup();
627     $org_id = $this->org_id;
628
629     // Mark user to project binds as deleted.
630     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id".
631       " and group_id = $group_id and org_id = $org_id";
632     $affected = $mdb2->exec($sql);
633     if (is_a($affected, 'PEAR_Error'))
634       return false;
635
636     // Mark user favorite reports as deleted.
637     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id".
638       " and group_id = $group_id and org_id = $org_id";
639     $affected = $mdb2->exec($sql);
640     if (is_a($affected, 'PEAR_Error'))
641       return false;
642
643     // Mark user as deleted.
644     $sql = "update tt_users set status = NULL where id = $user_id".
645       " and group_id = $group_id and org_id = $org_id";
646     $affected = $mdb2->exec($sql);
647     if (is_a($affected, 'PEAR_Error'))
648       return false;
649
650     return true;
651   }
652
653   // enablePlugin either enables or disables a specific plugin for group.
654   function enablePlugin($plugin, $enable = true)
655   {
656     if (!$this->can('manage_advanced_settings'))
657       return false; // Note: enablePlugin is currently only used on week_view.php.
658                     // So, it's not really a plugin we are enabling, but rather week view display options.
659                     // Therefore, a check for manage_advanced_settings, not manage_features.
660
661     $plugin_array = explode(',', $this->plugins);
662     if ($enable && !in_array($plugin, $plugin_array))
663       $plugin_array[] = $plugin; // Add plugin to array.
664
665     if (!$enable && in_array($plugin, $plugin_array)) {
666       $key = array_search($plugin, $plugin_array);
667       if ($key !== false)
668         unset($plugin_array[$key]); // Remove plugin from array.
669     }
670
671     $plugins = implode(',', $plugin_array);
672     if ($plugins != $this->plugins) {
673       if (!$this->updateGroup(array('plugins' => $plugins)))
674         return false;
675       $this->plugins = $plugins;
676     }
677
678     return true;
679   }
680
681   // isUserValid determines if a user is valid for on behalf work.
682   function isUserValid($user_id) {
683     if ($user_id == $this->id)
684       return true;
685     return ($this->getUserDetails($user_id) != null);
686   }
687
688   // isGroupValid determines if a group is valid for user.
689   function isGroupValid($group_id) {
690     if ($group_id == $this->group_id)
691       return true;
692     else
693       return $this->isSubgroupValid($group_id);
694   }
695
696   // isSubgroupValid determines if a subgroup is valid for user.
697   // A subgroup is valid if:
698   //   - user can manage_subgroups;
699   //   - subgroup is either a direct child of user group, or "on the path"
700   //   to it (grand-child, etc.).
701   function isSubgroupValid($subgroup_id) {
702     if (!$this->can('manage_subgroups')) return false; // User cannot manage subgroups.
703
704     $current_group_id = $subgroup_id;
705     while ($parent_group_id = ttGroupHelper::getParentGroup($current_group_id)) {
706       if ($parent_group_id == $this->group_id) {
707         return true; // Found it.
708       }
709       $current_group_id = $parent_group_id;
710     }
711     return false;
712   }
713
714   // getMaxRankForGroup determines effective user rank for a user in a given group.
715   // For home group it is the existing user rank (as per role) minus 1.
716   // For subgroups, if user can "manage_subgroups", it is MAX_RANK.
717   function getMaxRankForGroup($group_id) {
718
719     $max_rank = 0; // Start safely.
720     if ($this->group_id == $group_id) {
721       $max_rank = $this->rank - 1;
722       return $max_rank;
723     }
724
725     if ($this->isSubgroupValid($group_id))
726       $max_rank = MAX_RANK;
727
728     return $max_rank;
729   }
730
731   // getUserPartForHeader constructs a string for user to display on pages header.
732   // It changes with "on behalf" attributes for both user and group.
733   function getUserPartForHeader() {
734     global $i18n;
735     if (!$this->id) return null;
736
737     $user_part = htmlspecialchars($this->name);
738     $user_part .= ' - '.htmlspecialchars($this->role_name);
739     if ($this->behalf_id) {
740       $user_part .= ' <span class="onBehalf">'.$i18n->get('label.on_behalf').' '.htmlspecialchars($this->behalf_name).'</span>';
741     }
742     if ($this->behalf_group_id) {
743       $user_part .= ',  <span class="onBehalf">'.$i18n->get('label.on_behalf').' '.htmlspecialchars($this->behalf_group_name).'</span>';
744     } else {
745       if ($this->group_name) // Note: we did not require group names in the past.
746         $user_part .= ', '.$this->group_name;
747     }
748     return $user_part;
749   }
750
751   // setOnBehalfGroup sets on behalf group for the user in both the object and the session.
752   function setOnBehalfGroup($group_id) {
753
754     // Unset things first.
755     $this->behalf_group_id = null;
756     $this->behalf_group_name = null;
757     $this->behalf_id = null;
758     $this->behalf_name = null;
759     unset($this->behalfGroup);
760     unset($_SESSION['behalf_group_id']);
761     unset($_SESSION['behalf_group_name']);
762     unset($_SESSION['behalf_id']);
763     unset($_SESSION['behalf_name']);
764
765     // Do not do anything if we don't have rights.
766     if (!$this->can('manage_subgroups')) return;
767
768     // No need to set if group is our home group.
769     if ($group_id == $this->group_id) return;
770
771     // No need to set if subgroup is not valid.
772     if (!$this->isSubgroupValid($group_id)) return;
773
774     // We are good to set on behalf group.
775     $onBehalfGroupName = ttGroupHelper::getGroupName($group_id);
776     $_SESSION['behalf_group_id'] = $group_id;
777     $_SESSION['behalf_group_name'] = $onBehalfGroupName;
778     $this->behalf_group_id = $group_id;
779     $this->behalf_group_name = $onBehalfGroupName;
780
781     $this->behalfGroup = new ttGroup($this->behalf_group_id, $this->org_id);
782
783     // Adjust on behalf user.
784     $this->adjustBehalfId();
785     return;
786   }
787
788    // setOnBehalfUser sets on behalf user both the object and the session.
789   function setOnBehalfUser($user_id) {
790
791     // Unset things first.
792     $this->behalf_id = null;
793     $this->behalf_name = null;
794     unset($_SESSION['behalf_id']);
795     unset($_SESSION['behalf_name']);
796
797     // No need to set if user is us.
798     if ($user_id == $this->id) return;
799
800     // No need to set if user id is not valid.
801     if (!$this->isUserValid($user_id)) return;
802
803     // We are good to set on behalf user.
804     $onBehalfUserName = ttUserHelper::getUserName($user_id);
805     $_SESSION['behalf_id'] = $user_id;
806     $_SESSION['behalf_name'] = $onBehalfUserName;
807     $this->behalf_id = $user_id;
808     $this->behalf_name = $onBehalfUserName;
809     return;
810   }
811 }