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