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