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