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