e498cde0e822302559ec427d678d71c0287aeddc
[timetracker.git] / WEB-INF / lib / ttUser.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 import('ttConfigHelper');
30
31 class ttUser {
32   var $login = null;            // User login.
33   var $name = null;             // User name.
34   var $id = null;               // User id.
35   var $group_id = null;         // Group id.
36   var $role_id = null;          // Role id.
37   var $role_name = null;        // Role name.
38   var $rank = null;             // User role rank.
39   var $client_id = null;        // Client id for client user role.
40   var $behalf_id = null;        // User id, on behalf of whom we are working.
41   var $behalf_name = null;      // User name, on behalf of whom we are working.
42   var $email = null;            // User email.
43   var $lang = null;             // Language.
44   var $decimal_mark = null;     // Decimal separator.
45   var $date_format = null;      // Date format.
46   var $time_format = null;      // Time format.
47   var $week_start = 0;          // Week start day.
48   var $show_holidays = 0;       // Whether to show holidays in calendar.
49   var $tracking_mode = 0;       // Tracking mode.
50   var $project_required = 0;    // Whether project selection is required on time entires.
51   var $task_required = 0;       // Whether task selection is required on time entires.
52   var $record_type = 0;         // Record type (duration vs start and finish, or both).
53   var $punch_mode = 0;          // Whether punch mode is enabled for user.
54   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
55   var $future_entries = 0;      // Whether to allow creating future entries.
56   var $uncompleted_indicators = 0; // Uncompleted time entry indicators (show nowhere or on users page).
57   var $bcc_email = null;        // Bcc email.
58   var $allow_ip = null;         // Specification from where user is allowed access.
59   var $password_complexity = null; // Password complexity example.
60   var $currency = null;         // Currency.
61   var $plugins = null;          // Comma-separated list of enabled plugins.
62   var $config = null;           // Comma-separated list of miscellaneous config options.
63   var $group = null;            // Group name.
64   var $custom_logo = 0;         // Whether to use a custom logo for group.
65   var $lock_spec = null;        // Cron specification for record locking.
66   var $workday_minutes = 480;   // Number of work minutes in a regular day.
67   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
68   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
69   var $minutes_in_unit = 15;    // Number of minutes in unit for Work units plugin.
70   var $first_unit_threshold = 0;// Threshold for 1st unit for Work units plugin.
71   var $unit_totals_only = 0;    // Totlas only option for the Work units plugin.
72
73   // Constructor.
74   function __construct($login, $id = null) {
75     if (!$login && !$id) {
76       // nothing to initialize
77       return;
78     }
79
80     $mdb2 = getConnection();
81
82     $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, g.name as group_name,
83       g.currency, g.lang, g.decimal_mark, g.date_format, g.time_format, g.week_start,
84       g.tracking_mode, g.project_required, g.task_required, g.record_type,
85       g.bcc_email, g.allow_ip, g.password_complexity, g.plugins, g.config, g.lock_spec, g.workday_minutes, g.custom_logo
86       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 ";
87     if ($id)
88       $sql .= "u.id = $id";
89     else
90       $sql .= "u.login = ".$mdb2->quote($login);
91     $sql .= " AND u.status = 1";
92
93     $res = $mdb2->query($sql);
94     if (is_a($res, 'PEAR_Error')) {
95       return;
96     }
97
98     $val = $res->fetchRow();
99     if ($val['id'] > 0) {
100       $this->login = $val['login'];
101       $this->name = $val['name'];
102       $this->id = $val['id'];
103       $this->group_id = $val['group_id'];
104       $this->role_id = $val['role_id'];
105       $this->role_name = $val['role_name'];
106       $this->rights = explode(',', $val['rights']);
107       $this->is_client = !in_array('track_own_time', $this->rights);
108       $this->rank = $val['rank'];
109       $this->client_id = $val['client_id'];
110       $this->email = $val['email'];
111       $this->lang = $val['lang'];
112       $this->decimal_mark = $val['decimal_mark'];
113       $this->date_format = $val['date_format'];
114       $this->time_format = $val['time_format'];
115       $this->week_start = $val['week_start'];
116       $this->tracking_mode = $val['tracking_mode'];
117       $this->project_required = $val['project_required'];
118       $this->task_required = $val['task_required'];
119       $this->record_type = $val['record_type'];
120       $this->bcc_email = $val['bcc_email'];
121       $this->allow_ip = $val['allow_ip'];
122       $this->password_complexity = $val['password_complexity'];
123       $this->group = $val['group_name'];
124       $this->currency = $val['currency'];
125       $this->plugins = $val['plugins'];
126       $this->lock_spec = $val['lock_spec'];
127       $this->workday_minutes = $val['workday_minutes'];
128       $this->custom_logo = $val['custom_logo'];
129
130       $this->config = $val['config'];
131       $config = new ttConfigHelper($this->config);
132       // Set user config options.
133       $this->show_holidays = $config->getDefinedValue('show_holidays');
134       $this->punch_mode = $config->getDefinedValue('punch_mode');
135       $this->allow_overlap = $config->getDefinedValue('allow_overlap');
136       $this->future_entries = $config->getDefinedValue('future_entries');
137       $this->uncompleted_indicators = $config->getDefinedValue('uncompleted_indicators');
138       if ($this->isPluginEnabled('wu')) {
139         $minutes_in_unit = $config->getIntValue('minutes_in_unit');
140         if ($minutes_in_unit) $this->minutes_in_unit = $minutes_in_unit;
141         $first_unit_threshold = $config->getIntValue('1st_unit_threshold');
142         if ($first_unit_threshold) $this->first_unit_threshold = $first_unit_threshold;
143         $this->unit_totals_only = $config->getDefinedValue('unit_totals_only');
144       }
145       
146       // Set "on behalf" id and name.
147       if (isset($_SESSION['behalf_id'])) {
148           $this->behalf_id = $_SESSION['behalf_id'];
149           $this->behalf_name = $_SESSION['behalf_name'];
150       }
151     }
152   }
153
154   // The getActiveUser returns user id on behalf of whom the current user is operating.
155   function getActiveUser() {
156     return ($this->behalf_id ? $this->behalf_id : $this->id);
157   }
158
159   // can - determines whether user has a right to do something.
160   function can($do_something) {
161     return in_array($do_something, $this->rights);
162   }
163
164   // isClient - determines whether current user is a client.
165   function isClient() {
166     return $this->is_client;
167   }
168
169   // isPluginEnabled checks whether a plugin is enabled for user.
170   function isPluginEnabled($plugin)
171   {
172     return in_array($plugin, explode(',', $this->plugins));
173   }
174
175   // getAssignedProjects - returns an array of assigned projects.
176   function getAssignedProjects()
177   {
178     $result = array();
179     $mdb2 = getConnection();
180
181     // Do a query with inner join to get assigned projects.
182     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate from tt_projects p
183       inner join tt_user_project_binds upb on (upb.user_id = ".$this->getActiveUser()." and upb.project_id = p.id and upb.status = 1)
184       where p.group_id = $this->group_id and p.status = 1 order by p.name";
185     $res = $mdb2->query($sql);
186     if (!is_a($res, 'PEAR_Error')) {
187       while ($val = $res->fetchRow()) {
188         $result[] = $val;
189       }
190     }
191     return $result;
192   }
193
194   // getAssignedTasks - returns an array of assigned tasks.
195   function getAssignedTasks()
196   {
197     // Start with projects;
198     $projects = $this->getAssignedProjects();
199     if (!$projects) return false;
200
201     // Build an array of task ids.
202     $task_ids = array();
203     foreach($projects as $project) {
204       $one_project_tasks = $project['tasks'] ? explode(',', $project['tasks']) : array();
205       $task_ids = array_unique(array_merge($task_ids, $one_project_tasks));
206     }
207     if (!$task_ids) return false;
208
209     // Get task descriptions.
210     $result = array();
211     $mdb2 = getConnection();
212     $tasks = implode(',', $task_ids); // This is a comma-separated list of task ids.
213
214     $sql = "select id, name, description from tt_tasks".
215       " where group_id = $this->group_id and status = 1 and id in ($tasks) order by name";
216     $res = $mdb2->query($sql);
217     if (!is_a($res, 'PEAR_Error')) {
218       while ($val = $res->fetchRow()) {
219         $result[] = $val;
220       }
221     }
222     return $result;
223   }
224
225   // getAssignedClients - returns an array of clients assigned to own projects.
226   function getAssignedClients()
227   {
228     // Start with projects;
229     $projects = $this->getAssignedProjects();
230     if (!$projects) return false;
231     $assigned_project_ids = array();
232     foreach($projects as $project) {
233       $assigned_project_ids[] = $project['id'];
234     }
235
236     $mdb2 = getConnection();
237
238     // Get active clients for group.
239     $clients = array();
240     $sql = "select id, name, address, projects from tt_clients where group_id = $this->group_id and status = 1";
241     $res = $mdb2->query($sql);
242     if (!is_a($res, 'PEAR_Error')) {
243       while ($val = $res->fetchRow()) {
244         $client_project_ids = $val['projects'] ? explode(',', $val['projects']) : array();
245         if (array_intersect($assigned_project_ids, $client_project_ids))
246           $clients[] = $val; // Add client if one of user projects is a client project, too.
247       }
248     }
249     return $clients;
250   }
251
252   // isDateLocked checks whether a specifc date is locked for modifications.
253   function isDateLocked($date)
254   {
255     if (!$this->isPluginEnabled('lk'))
256       return false; // Locking feature is disabled.
257
258     if (!$this->lock_spec)
259       return false; // There is no lock specification.
260
261     if (!$this->behalf_id && $this->can('override_own_date_lock'))
262       return false; // User is working as self and can override own date lock.
263
264     if ($this->behalf_id && $this->can('override_date_lock'))
265       return false; // User is working on behalf of someone else and can override date lock.
266
267     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
268     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
269
270     // Calculate the last occurrence of a lock.
271     $last = tdCron::getLastOccurrence($this->lock_spec, time());
272     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
273     if ($date->before($lockdate))
274       return true;
275
276     return false;
277   }
278
279   // canOverridePunchMode checks whether a user can override punch mode in a situation.
280   function canOverridePunchMode()
281   {
282     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
283       return false; // User is working as self and cannot override for self.
284
285     if ($this->behalf_id && !$this->can('override_punch_mode'))
286       return false; // User is working on behalf of someone else and cannot override.
287
288     return true;
289   }
290
291   // getUsers obtains users in a group, as specififed by options.
292   function getUsers($options) {
293
294     $mdb2 = getConnection();
295
296     $skipClients = !isset($options['include_clients']);
297     $includeSelf = isset($options['include_self']);
298
299     $select_part = 'select u.id, u.name';
300     if (isset($options['include_login'])) $select_part .= ', u.login';
301     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
302     if (isset($options['include_role'])) $select_part .= ', r.name as role_name, r.rank';
303
304     $from_part = ' from tt_users u';
305
306     $left_joins = null;
307     if (isset($options['max_rank']) || $skipClients || isset($options['include_role']))
308         $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
309
310     $where_part = " where u.group_id = $this->group_id";
311     if (isset($options['status']))
312       $where_part .= ' and u.status = '.(int)$options['status'];
313     else
314       $where_part .= ' and u.status is not null';
315     if ($includeSelf) {
316       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
317     } else {
318       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
319     }
320
321     $order_part = " order by upper(u.name)";
322
323     $sql = $select_part.$from_part.$left_joins.$where_part.$order_part;
324     $res = $mdb2->query($sql);
325     $user_list = array();
326     if (is_a($res, 'PEAR_Error'))
327       return false;
328
329     while ($val = $res->fetchRow()) {
330       if ($skipClients) {
331         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
332         if ($isClient)
333           continue; // Skip adding clients.
334       }
335       $user_list[] = $val;
336     }
337
338     if (isset($options['self_first'])) {
339       // Put own entry at the front.
340       $cnt = count($user_list);
341       for($i = 0; $i < $cnt; $i++) {
342         if ($user_list[$i]['id'] == $this->id) {
343           $self = $user_list[$i]; // Found self.
344           array_unshift($user_list, $self); // Put own entry at the front.
345           array_splice($user_list, $i+1, 1); // Remove duplicate.
346         }
347       }
348     }
349     return $user_list;
350   }
351
352   // getUser function is used to manage users in group and returns user details.
353   // At the moment, the function is used for user edits and deletes.
354   function getUser($user_id) {
355     if (!$this->can('manage_users')) return false;
356
357     $mdb2 = getConnection();
358
359     $sql =  "select u.id, u.name, u.login, u.role_id, u.client_id, u.status, u.rate, u.email from tt_users u".
360             " left join tt_roles r on (u.role_id = r.id)".
361             " where u.id = $user_id and u.group_id = $this->group_id and u.status is not null".
362             " and (r.rank < $this->rank or (r.rank = $this->rank and u.id = $this->id))"; // Users with lesser roles or self.
363     $res = $mdb2->query($sql);
364     if (!is_a($res, 'PEAR_Error')) {
365       $val = $res->fetchRow();
366       return $val;
367     }
368     return false;
369   }
370
371   // checkBehalfId checks whether behalf_id is appropriate.
372   // On behalf user must be active and have lower rank.
373   function checkBehalfId() {
374     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
375     $users = $this->getUsers($options);
376     foreach($users as $one_user) {
377       if ($one_user['id'] == $this->behalf_id)
378         return true;
379     }
380     return false;
381   }
382
383   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
384   // apropriate user.
385   //
386   // Needed for situations when user does not have do_own_something right.
387   // Example: has view_charts but does not have view_own_charts.
388   // In this case we still allow access to charts, but set behalf_id to someone else.
389   function adjustBehalfId() {
390     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
391     $users = $this->getUsers($options);
392     foreach($users as $one_user) {
393       // Fake loop to access first element.
394       $this->behalf_id = $one_user['id'];
395       $this->behalf_name = $one_user['name'];
396       $_SESSION['behalf_id'] = $this->behalf_id;
397       $_SESSION['behalf_name'] = $this->behalf_name;
398       return true;
399     }
400     return false;
401   }
402
403   // updateGroup updates group information with new data.
404   function updateGroup($fields) {
405     if (!($this->can('manage_basic_settings') ||
406       $this->can('manage_advanced_settings') ||
407       $this->can('manage_features'))) return false;
408
409     $mdb2 = getConnection();
410
411     if (isset($fields['name'])) $name_part = ', name = '.$mdb2->quote($fields['name']);
412     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
413     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
414     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
415     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
416     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
417     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
418     if (isset($fields['tracking_mode'])) {
419       $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
420       $project_required_part = ' , project_required = '.(int) $fields['project_required'];
421       $task_required_part = ' , task_required = '.(int) $fields['task_required'];
422     }
423     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
424     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
425     if (isset($fields['allow_ip'])) $allow_ip_part = ', allow_ip = '.$mdb2->quote($fields['allow_ip']);
426     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
427     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
428     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
429     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
430     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($this->id);
431
432     $parts = trim($name_part.$currency_part.$lang_part.$decimal_mark_part.$date_format_part.
433       $time_format_part.$week_start_part.$tracking_mode_part.$task_required_part.$project_required_part.$record_type_part.
434       $bcc_email_part.$allow_ip_part.$plugins_part.$config_part.$lock_spec_part.$workday_minutes_part.$modified_part, ',');
435
436     $sql = "update tt_groups set $parts where id = $this->group_id";
437     $affected = $mdb2->exec($sql);
438     if (is_a($affected, 'PEAR_Error')) return false;
439
440     return true;
441   }
442
443   // markUserDeleted marks a user in group as deleted.
444   function markUserDeleted($user_id) {
445     if (!$this->can('manage_users') || $this->id == $user_id)
446       return false;
447
448     // Make sure we operate on a legit user.
449     $user_details = $this->getUser($user_id);
450     if (!$user_details) return false;
451
452     $mdb2 = getConnection();
453
454     // Mark user to project binds as deleted.
455     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
456     $affected = $mdb2->exec($sql);
457     if (is_a($affected, 'PEAR_Error'))
458       return false;
459
460     // Mark user favorite reports as deleted.
461     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
462     $affected = $mdb2->exec($sql);
463     if (is_a($affected, 'PEAR_Error'))
464       return false;
465
466     // Mark user as deleted.
467     $sql = "update tt_users set status = NULL where id = $user_id and group_id = ".$this->group_id;
468     $affected = $mdb2->exec($sql);
469     if (is_a($affected, 'PEAR_Error'))
470       return false;
471
472     return true;
473   }
474
475   // enablePlugin either enables or disables a specific plugin for group.
476   function enablePlugin($plugin, $enable = true)
477   {
478     if (!$this->can('manage_advanced_settings'))
479       return false; // Note: enablePlugin is currently only used on week_view.php.
480                     // So, it's not really a plugin we are enabling, but rather week view display options.
481                     // Therefore, a check for manage_advanced_settings, not manage_features.
482
483     $plugin_array = explode(',', $this->plugins);
484     if ($enable && !in_array($plugin, $plugin_array))
485       $plugin_array[] = $plugin; // Add plugin to array.
486
487     if (!$enable && in_array($plugin, $plugin_array)) {
488       $key = array_search($plugin, $plugin_array);
489       if ($key !== false)
490         unset($plugin_array[$key]); // Remove plugin from array.
491     }
492
493     $plugins = implode(',', $plugin_array);
494     if ($plugins != $this->plugins) {
495       if (!$this->updateGroup(array('plugins' => $plugins)))
496         return false;
497       $this->plugins = $plugins;
498     }
499
500     return true;
501   }
502 }