More progress on subgroups, mostly about setting on behalf values properly.
[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
31 class ttUser {
32   var $login = null;            // User login.
33   var $name = null;             // User name.
34   var $id = null;               // User id.
35   var $org_id = null;           // Organization id.
36   var $group_id = null;         // Group id.
37   var $role_id = null;          // Role id.
38   var $role_name = null;        // Role name.
39   var $rank = null;             // User role rank.
40   var $client_id = null;        // Client id for client user role.
41   var $behalf_id = null;        // User id, on behalf of whom we are working.
42   var $behalf_group_id = null;  // Group id, on behalf of which we are working.
43   var $behalf_name = null;      // User name, on behalf of whom we are working.
44   var $group_name = null;       // Group name.
45   var $behalf_group_name = null;// Group name, on behalf of which we are working.
46   var $email = null;            // User email.
47   var $lang = null;             // Language.
48   var $decimal_mark = null;     // Decimal separator.
49   var $date_format = null;      // Date format.
50   var $time_format = null;      // Time format.
51   var $week_start = 0;          // Week start day.
52   var $show_holidays = 0;       // Whether to show holidays in calendar.
53   var $tracking_mode = 0;       // Tracking mode.
54   var $project_required = 0;    // Whether project selection is required on time entires.
55   var $task_required = 0;       // Whether task selection is required on time entires.
56   var $record_type = 0;         // Record type (duration vs start and finish, or both).
57   var $punch_mode = 0;          // Whether punch mode is enabled for user.
58   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
59   var $future_entries = 0;      // Whether to allow creating future entries.
60   var $uncompleted_indicators = 0; // Uncompleted time entry indicators (show nowhere or on users page).
61   var $bcc_email = null;        // Bcc email.
62   var $allow_ip = null;         // Specification from where user is allowed access.
63   var $password_complexity = null; // Password complexity example.
64   var $currency = null;         // Currency.
65   var $plugins = null;          // Comma-separated list of enabled plugins.
66   var $config = null;           // Comma-separated list of miscellaneous config options.
67   var $custom_logo = 0;         // Whether to use a custom logo for group.
68   var $lock_spec = null;        // Cron specification for record locking.
69   var $workday_minutes = 480;   // Number of work minutes in a regular day.
70   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
71   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
72   var $minutes_in_unit = 15;    // Number of minutes in unit for Work units plugin.
73   var $first_unit_threshold = 0;// Threshold for 1st unit for Work units plugin.
74   var $unit_totals_only = 0;    // Totals only option for the Work units plugin.
75
76   // Constructor.
77   function __construct($login, $id = null) {
78     if (!$login && !$id) {
79       // nothing to initialize
80       return;
81     }
82
83     $mdb2 = getConnection();
84
85     $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,
86       g.org_id, g.name as group_name, g.currency, g.lang, g.decimal_mark, g.date_format, g.time_format, g.week_start,
87       g.tracking_mode, g.project_required, g.task_required, g.record_type,
88       g.bcc_email, g.allow_ip, g.password_complexity, g.plugins, g.config, g.lock_spec, g.workday_minutes, g.custom_logo
89       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 ";
90     if ($id)
91       $sql .= "u.id = $id";
92     else
93       $sql .= "u.login = ".$mdb2->quote($login);
94     $sql .= " AND u.status = 1";
95
96     $res = $mdb2->query($sql);
97     if (is_a($res, 'PEAR_Error')) {
98       return;
99     }
100
101     $val = $res->fetchRow();
102     if ($val['id'] > 0) {
103       $this->login = $val['login'];
104       $this->name = $val['name'];
105       $this->id = $val['id'];
106       $this->org_id = $val['org_id'];
107       $this->group_id = $val['group_id'];
108       $this->role_id = $val['role_id'];
109       $this->role_name = $val['role_name'];
110       $this->rights = explode(',', $val['rights']);
111       $this->is_client = !in_array('track_own_time', $this->rights);
112       $this->rank = $val['rank'];
113       $this->client_id = $val['client_id'];
114       $this->email = $val['email'];
115       $this->lang = $val['lang'];
116       $this->decimal_mark = $val['decimal_mark'];
117       $this->date_format = $val['date_format'];
118       $this->time_format = $val['time_format'];
119       $this->week_start = $val['week_start'];
120       $this->tracking_mode = $val['tracking_mode'];
121       $this->project_required = $val['project_required'];
122       $this->task_required = $val['task_required'];
123       $this->record_type = $val['record_type'];
124       $this->bcc_email = $val['bcc_email'];
125       $this->allow_ip = $val['allow_ip'];
126       $this->password_complexity = $val['password_complexity'];
127       $this->group_name = $val['group_name'];
128       $this->currency = $val['currency'];
129       $this->plugins = $val['plugins'];
130       $this->lock_spec = $val['lock_spec'];
131       $this->workday_minutes = $val['workday_minutes'];
132       $this->custom_logo = $val['custom_logo'];
133
134       $this->config = $val['config'];
135       $config = new ttConfigHelper($this->config);
136       // Set user config options.
137       $this->show_holidays = $config->getDefinedValue('show_holidays');
138       $this->punch_mode = $config->getDefinedValue('punch_mode');
139       $this->allow_overlap = $config->getDefinedValue('allow_overlap');
140       $this->future_entries = $config->getDefinedValue('future_entries');
141       $this->uncompleted_indicators = $config->getDefinedValue('uncompleted_indicators');
142       if ($this->isPluginEnabled('wu')) {
143         $minutes_in_unit = $config->getIntValue('minutes_in_unit');
144         if ($minutes_in_unit) $this->minutes_in_unit = $minutes_in_unit;
145         $first_unit_threshold = $config->getIntValue('1st_unit_threshold');
146         if ($first_unit_threshold) $this->first_unit_threshold = $first_unit_threshold;
147         $this->unit_totals_only = $config->getDefinedValue('unit_totals_only');
148       }
149       
150       // Set "on behalf" id and name (user).
151       if (isset($_SESSION['behalf_id'])) {
152           $this->behalf_id = $_SESSION['behalf_id'];
153           $this->behalf_name = $_SESSION['behalf_name'];
154       }
155       // Set "on behalf" id and name (group).
156       if (isset($_SESSION['behalf_group_id'])) {
157           $this->behalf_group_id = $_SESSION['behalf_group_id'];
158           $this->behalf_group_name = $_SESSION['behalf_group_name'];
159       }
160     }
161   }
162
163   // The getActiveUser returns user id on behalf of whom the current user is operating.
164   function getActiveUser() {
165     return ($this->behalf_id ? $this->behalf_id : $this->id);
166   }
167
168   // The getActiveGroup returns group id on behalf of which the current user is operating.
169   function getActiveGroup() {
170     return ($this->behalf_group_id ? $this->behalf_group_id : $this->group_id);
171   }
172
173   // can - determines whether user has a right to do something.
174   function can($do_something) {
175     return in_array($do_something, $this->rights);
176   }
177
178   // isClient - determines whether current user is a client.
179   function isClient() {
180     return $this->is_client;
181   }
182
183   // isPluginEnabled checks whether a plugin is enabled for user.
184   function isPluginEnabled($plugin)
185   {
186     return in_array($plugin, explode(',', $this->plugins));
187   }
188
189   // getAssignedProjects - returns an array of assigned projects.
190   function getAssignedProjects()
191   {
192     $result = array();
193     $mdb2 = getConnection();
194
195     // Do a query with inner join to get assigned projects.
196     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate from tt_projects p
197       inner join tt_user_project_binds upb on (upb.user_id = ".$this->getActiveUser()." and upb.project_id = p.id and upb.status = 1)
198       where p.group_id = $this->group_id and p.status = 1 order by p.name";
199     $res = $mdb2->query($sql);
200     if (!is_a($res, 'PEAR_Error')) {
201       while ($val = $res->fetchRow()) {
202         $result[] = $val;
203       }
204     }
205     return $result;
206   }
207
208   // getAssignedTasks - returns an array of assigned tasks.
209   function getAssignedTasks()
210   {
211     // Start with projects;
212     $projects = $this->getAssignedProjects();
213     if (!$projects) return false;
214
215     // Build an array of task ids.
216     $task_ids = array();
217     foreach($projects as $project) {
218       $one_project_tasks = $project['tasks'] ? explode(',', $project['tasks']) : array();
219       $task_ids = array_unique(array_merge($task_ids, $one_project_tasks));
220     }
221     if (!$task_ids) return false;
222
223     // Get task descriptions.
224     $result = array();
225     $mdb2 = getConnection();
226     $tasks = implode(',', $task_ids); // This is a comma-separated list of task ids.
227
228     $sql = "select id, name, description from tt_tasks".
229       " where group_id = $this->group_id and status = 1 and id in ($tasks) order by name";
230     $res = $mdb2->query($sql);
231     if (!is_a($res, 'PEAR_Error')) {
232       while ($val = $res->fetchRow()) {
233         $result[] = $val;
234       }
235     }
236     return $result;
237   }
238
239   // getAssignedClients - returns an array of clients assigned to own projects.
240   function getAssignedClients()
241   {
242     // Start with projects;
243     $projects = $this->getAssignedProjects();
244     if (!$projects) return false;
245     $assigned_project_ids = array();
246     foreach($projects as $project) {
247       $assigned_project_ids[] = $project['id'];
248     }
249
250     $mdb2 = getConnection();
251
252     // Get active clients for group.
253     $clients = array();
254     $sql = "select id, name, address, projects from tt_clients where group_id = $this->group_id and status = 1";
255     $res = $mdb2->query($sql);
256     if (!is_a($res, 'PEAR_Error')) {
257       while ($val = $res->fetchRow()) {
258         $client_project_ids = $val['projects'] ? explode(',', $val['projects']) : array();
259         if (array_intersect($assigned_project_ids, $client_project_ids))
260           $clients[] = $val; // Add client if one of user projects is a client project, too.
261       }
262     }
263     return $clients;
264   }
265
266   // isDateLocked checks whether a specifc date is locked for modifications.
267   function isDateLocked($date)
268   {
269     if (!$this->isPluginEnabled('lk'))
270       return false; // Locking feature is disabled.
271
272     if (!$this->lock_spec)
273       return false; // There is no lock specification.
274
275     if (!$this->behalf_id && $this->can('override_own_date_lock'))
276       return false; // User is working as self and can override own date lock.
277
278     if ($this->behalf_id && $this->can('override_date_lock'))
279       return false; // User is working on behalf of someone else and can override date lock.
280
281     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
282     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
283
284     // Calculate the last occurrence of a lock.
285     $last = tdCron::getLastOccurrence($this->lock_spec, time());
286     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
287     if ($date->before($lockdate))
288       return true;
289
290     return false;
291   }
292
293   // canOverridePunchMode checks whether a user can override punch mode in a situation.
294   function canOverridePunchMode()
295   {
296     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
297       return false; // User is working as self and cannot override for self.
298
299     if ($this->behalf_id && !$this->can('override_punch_mode'))
300       return false; // User is working on behalf of someone else and cannot override.
301
302     return true;
303   }
304
305   // getUsers obtains users in a group, as specififed by options.
306   function getUsers($options) {
307
308     $mdb2 = getConnection();
309
310     $skipClients = !isset($options['include_clients']);
311     $includeSelf = isset($options['include_self']);
312     $group_id = isset($options['group_id']) ? $options['group_id'] : $this->group_id;
313
314     $select_part = 'select u.id, u.name';
315     if (isset($options['include_login'])) $select_part .= ', u.login';
316     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
317     if (isset($options['include_role'])) $select_part .= ', r.name as role_name, r.rank';
318
319     $from_part = ' from tt_users u';
320
321     $left_joins = null;
322     if (isset($options['max_rank']) || $skipClients || isset($options['include_role']))
323         $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
324
325     $where_part = " where u.org_id = $this->org_id and u.group_id = $group_id";
326     if (isset($options['status']))
327       $where_part .= ' and u.status = '.(int)$options['status'];
328     else
329       $where_part .= ' and u.status is not null';
330     if ($includeSelf) {
331       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
332     } else {
333       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
334     }
335
336     $order_part = " order by upper(u.name)";
337
338     $sql = $select_part.$from_part.$left_joins.$where_part.$order_part;
339     $res = $mdb2->query($sql);
340     $user_list = array();
341     if (is_a($res, 'PEAR_Error'))
342       return false;
343
344     while ($val = $res->fetchRow()) {
345       if ($skipClients) {
346         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
347         if ($isClient)
348           continue; // Skip adding clients.
349       }
350       $user_list[] = $val;
351     }
352
353     if (isset($options['self_first'])) {
354       // Put own entry at the front.
355       $cnt = count($user_list);
356       for($i = 0; $i < $cnt; $i++) {
357         if ($user_list[$i]['id'] == $this->id) {
358           $self = $user_list[$i]; // Found self.
359           array_unshift($user_list, $self); // Put own entry at the front.
360           array_splice($user_list, $i+1, 1); // Remove duplicate.
361         }
362       }
363     }
364     return $user_list;
365   }
366
367   // getGroups obtains an array consisting of:
368   // - A parent group (..) of a currently selected group, if available.
369   // - A currently selected group (.) represented by $behalf_group_id.
370   // - All subgroups (only immediate children) of a currently selected group.
371   function getGroups() {
372     $mdb2 = getConnection();
373
374     $selected_group_id = ($this->behalf_group_id ? $this->behalf_group_id : $this->group_id);
375     $selected_group_name = ($this->behalf_group_id ? $this->behalf_group_name : $this->group_name);
376
377     // Start with parent group.
378     if ($selected_group_id != $this->group_id) {
379       // We are in one of subgroups, and a parent exists.
380       // Get parent group info.
381       $sql = "select parent_id from tt_groups where org_id = $this->org_id and id = $selected_group_id";
382       $res = $mdb2->query($sql);
383       if (!is_a($res, 'PEAR_Error')) {
384         $val = $res->fetchRow();
385         $parent_id = $val['parent_id'];
386         if ($parent_id) {
387           // Get parent group name.
388           $sql = "select name from tt_groups where org_id = $this->org_id and id = $parent_id";
389           $res = $mdb2->query($sql);
390           if (!is_a($res, 'PEAR_Error')) {
391             $val = $res->fetchRow();
392             $groups[] = array('id'=>$parent_id,'name'=>$val['name']);
393           }
394         }
395       }
396     }
397
398     // Add current group.
399     $groups[] = array('id'=>$selected_group_id,'name'=>$selected_group_name);
400
401     // Add subgroups.
402     $sql = "select id, name from tt_groups where org_id = $this->org_id and parent_id = $selected_group_id";
403     $res = $mdb2->query($sql);
404     if (!is_a($res, 'PEAR_Error')) {
405       while ($val = $res->fetchRow()) {
406         $groups[] = array('id'=>$val['id'],'name'=>$val['name']);
407       }
408     }
409     return $groups;
410   }
411
412   // getUser function is used to manage users in group and returns user details.
413   // At the moment, the function is used for user edits and deletes.
414   function getUser($user_id) {
415     if (!$this->can('manage_users')) return false;
416
417     $mdb2 = getConnection();
418
419     $sql =  "select u.id, u.name, u.login, u.role_id, u.client_id, u.status, u.rate, u.email from tt_users u".
420             " left join tt_roles r on (u.role_id = r.id)".
421             " where u.id = $user_id and u.group_id = $this->group_id and u.status is not null".
422             " and (r.rank < $this->rank or (r.rank = $this->rank and u.id = $this->id))"; // Users with lesser roles or self.
423     $res = $mdb2->query($sql);
424     if (!is_a($res, 'PEAR_Error')) {
425       $val = $res->fetchRow();
426       return $val;
427     }
428     return false;
429   }
430
431   // checkBehalfId checks whether behalf_id is appropriate.
432   // On behalf user must be active and have lower rank if the user is from home group,
433   // otherwise:
434   // - subgroup must ve valid;
435   // - user should be a member of it.
436   function checkBehalfId() {
437     if (!$this->behalf_group_id) {
438       // Checking user from home group.
439       $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
440       $users = $this->getUsers($options);
441       foreach($users as $one_user) {
442         if ($one_user['id'] == $this->behalf_id)
443           return true;
444       }
445     } else {
446       // Checking user from a subgroup.
447       $group_id = $this->behalf_group_id;
448       if (!$this->isSubgroupValid($group_id))
449         return false;
450
451       // So far, so good. Check user now.
452       $options = array('group_id'=>$group_id,'status'=>ACTIVE,'max_rank'=>MAX_RANK);
453       $users = $this->getUsers($options);
454       foreach($users as $one_user) {
455         if ($one_user['id'] == $this->behalf_id)
456           return true;
457       }
458     }
459     return false;
460   }
461
462   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
463   // apropriate user.
464   //
465   // Needed for situations when user does not have do_own_something right.
466   // Example: has view_charts but does not have view_own_charts.
467   // In this case we still allow access to charts, but set behalf_id to someone else.
468   // Another example: working in a subgroup on behalf of someone else.
469   function adjustBehalfId() {
470     $group_id = $this->behalf_group_id ? $this->behalf_group_id : $this->group_id;
471     $rank = $this->getMaxRankForGroup($group_id);
472
473     // Adjust to first found user in group.
474     $options = array('group_id'=>$group_id,'status'=>ACTIVE,'max_rank'=>$rank);
475     $users = $this->getUsers($options);
476     foreach($users as $one_user) {
477       // Fake loop to access first element.
478       $this->behalf_id = $one_user['id'];
479       $this->behalf_name = $one_user['name'];
480       $_SESSION['behalf_id'] = $this->behalf_id;
481       $_SESSION['behalf_name'] = $this->behalf_name;
482       return true;
483     }
484     return false;
485   }
486
487   // updateGroup updates group information with new data.
488   function updateGroup($fields) {
489     if (!($this->can('manage_basic_settings') ||
490       $this->can('manage_advanced_settings') ||
491       $this->can('manage_features'))) return false;
492
493     $mdb2 = getConnection();
494
495     if (isset($fields['name'])) $name_part = ', name = '.$mdb2->quote($fields['name']);
496     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
497     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
498     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
499     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
500     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
501     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
502     if (isset($fields['tracking_mode'])) {
503       $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
504       $project_required_part = ' , project_required = '.(int) $fields['project_required'];
505       $task_required_part = ' , task_required = '.(int) $fields['task_required'];
506     }
507     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
508     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
509     if (isset($fields['allow_ip'])) $allow_ip_part = ', allow_ip = '.$mdb2->quote($fields['allow_ip']);
510     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
511     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
512     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
513     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
514     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
515
516     $parts = trim($name_part.$currency_part.$lang_part.$decimal_mark_part.$date_format_part.
517       $time_format_part.$week_start_part.$tracking_mode_part.$task_required_part.$project_required_part.$record_type_part.
518       $bcc_email_part.$allow_ip_part.$plugins_part.$config_part.$lock_spec_part.$workday_minutes_part.$modified_part, ',');
519
520     $sql = "update tt_groups set $parts where id = $this->group_id";
521     $affected = $mdb2->exec($sql);
522     if (is_a($affected, 'PEAR_Error')) return false;
523
524     return true;
525   }
526
527   // markUserDeleted marks a user in group as deleted.
528   function markUserDeleted($user_id) {
529     if (!$this->can('manage_users') || $this->id == $user_id)
530       return false;
531
532     // Make sure we operate on a legit user.
533     $user_details = $this->getUser($user_id);
534     if (!$user_details) return false;
535
536     $mdb2 = getConnection();
537
538     // Mark user to project binds as deleted.
539     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
540     $affected = $mdb2->exec($sql);
541     if (is_a($affected, 'PEAR_Error'))
542       return false;
543
544     // Mark user favorite reports as deleted.
545     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
546     $affected = $mdb2->exec($sql);
547     if (is_a($affected, 'PEAR_Error'))
548       return false;
549
550     // Mark user as deleted.
551     $sql = "update tt_users set status = NULL where id = $user_id and group_id = ".$this->group_id;
552     $affected = $mdb2->exec($sql);
553     if (is_a($affected, 'PEAR_Error'))
554       return false;
555
556     return true;
557   }
558
559   // enablePlugin either enables or disables a specific plugin for group.
560   function enablePlugin($plugin, $enable = true)
561   {
562     if (!$this->can('manage_advanced_settings'))
563       return false; // Note: enablePlugin is currently only used on week_view.php.
564                     // So, it's not really a plugin we are enabling, but rather week view display options.
565                     // Therefore, a check for manage_advanced_settings, not manage_features.
566
567     $plugin_array = explode(',', $this->plugins);
568     if ($enable && !in_array($plugin, $plugin_array))
569       $plugin_array[] = $plugin; // Add plugin to array.
570
571     if (!$enable && in_array($plugin, $plugin_array)) {
572       $key = array_search($plugin, $plugin_array);
573       if ($key !== false)
574         unset($plugin_array[$key]); // Remove plugin from array.
575     }
576
577     $plugins = implode(',', $plugin_array);
578     if ($plugins != $this->plugins) {
579       if (!$this->updateGroup(array('plugins' => $plugins)))
580         return false;
581       $this->plugins = $plugins;
582     }
583
584     return true;
585   }
586
587   // isSubgroupValid determines if a subgroup is valid for user.
588   // A subgroup is valid if:
589   //   - user can manage_subgroups;
590   //   - subgroup is either a direct child of user group, or "on the path"
591   //   to it (grand-child, etc.).
592   function isSubgroupValid($subgroup_id) {
593     if (!$this->can('manage_subgroups')) return false; // User cannot manage subgroups.
594
595     $current_group_id = $subgroup_id;
596     while ($parent_group_id = ttGroupHelper::getParentGroup($current_group_id)) {
597       if ($parent_group_id == $this->group_id) {
598         return true; // Found it.
599       }
600       $current_group_id = $parent_group_id;
601     }
602     return false;
603   }
604
605   // getMaxRankForGroup determines effective user rank for a user in a given group.
606   // For home group it is the existing user rank (as per role) minus 1.
607   // For subgroups, if user can "manage_subgroups", it is MAX_RANK.
608   function getMaxRankForGroup($group_id) {
609
610     $max_rank = 0; // Start safely.
611     if ($this->group_id == $group_id) {
612       $max_rank = $this->rank - 1;
613       return $max_rank;
614     }
615
616     if ($this->isSubgroupValid($group_id))
617       $max_rank = MAX_RANK;
618
619     return $max_rank;
620   }
621 }