A bit better job with access checks for charts.
[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 class ttUser {
30   var $login = null;            // User login.
31   var $name = null;             // User name.
32   var $id = null;               // User id.
33   var $team_id = null;          // Team id.
34   var $role_id = null;          // Role id.
35   var $role_name = null;        // Role name.
36   var $rank = null;             // User role rank.
37   var $client_id = null;        // Client id for client user role.
38   var $behalf_id = null;        // User id, on behalf of whom we are working.
39   var $behalf_name = null;      // User name, on behalf of whom we are working.
40   var $email = null;            // User email.
41   var $lang = null;             // Language.
42   var $decimal_mark = null;     // Decimal separator.
43   var $date_format = null;      // Date format.
44   var $time_format = null;      // Time format.
45   var $week_start = 0;          // Week start day.
46   var $show_holidays = 0;       // Whether to show holidays in calendar.
47   var $tracking_mode = 0;       // Tracking mode.
48   var $project_required = 0;    // Whether project selection is required on time entires.
49   var $task_required = 0;       // Whether task selection is required on time entires.
50   var $record_type = 0;         // Record type (duration vs start and finish, or both).
51   var $punch_mode = 0;          // Whether punch mode is enabled for user.
52   var $allow_overlap = 0;       // Whether to allow overlapping time entries.
53   var $future_entries = 0;      // Whether to allow creating future entries.
54   var $uncompleted_indicators = 0; // Uncompleted time entry indicators (show nowhere or on users page).
55   var $bcc_email = null;        // Bcc email.
56   var $currency = null;         // Currency.
57   var $plugins = null;          // Comma-separated list of enabled plugins.
58   var $config = null;           // Comma-separated list of miscellaneous config options.
59   var $team = null;             // Team name.
60   var $custom_logo = 0;         // Whether to use a custom logo for team.
61   var $lock_spec = null;        // Cron specification for record locking.
62   var $workday_minutes = 480;   // Number of work minutes in a regular day.
63   var $rights = array();        // An array of user rights such as 'track_own_time', etc.
64   var $is_client = false;       // Whether user is a client as determined by missing 'track_own_time' right.
65
66   // Constructor.
67   function __construct($login, $id = null) {
68     if (!$login && !$id) {
69       // nothing to initialize
70       return;
71     }
72
73     $mdb2 = getConnection();
74
75     $sql = "SELECT u.id, u.login, u.name, u.team_id, u.role_id, r.rank, r.name as role_name, r.rights, u.client_id, u.email, t.name as team_name,
76       t.currency, t.lang, t.decimal_mark, t.date_format, t.time_format, t.week_start,
77       t.tracking_mode, t.project_required, t.task_required, t.record_type,
78       t.bcc_email, t.plugins, t.config, t.lock_spec, t.workday_minutes, t.custom_logo
79       FROM tt_users u LEFT JOIN tt_teams t ON (u.team_id = t.id) LEFT JOIN tt_roles r on (r.id = u.role_id) WHERE ";
80     if ($id)
81       $sql .= "u.id = $id";
82     else
83       $sql .= "u.login = ".$mdb2->quote($login);
84     $sql .= " AND u.status = 1";
85
86     $res = $mdb2->query($sql);
87     if (is_a($res, 'PEAR_Error')) {
88       return;
89     }
90
91     $val = $res->fetchRow();
92     if ($val['id'] > 0) {
93       $this->login = $val['login'];
94       $this->name = $val['name'];
95       $this->id = $val['id'];
96       $this->team_id = $val['team_id'];
97       $this->role_id = $val['role_id'];
98       $this->role_name = $val['role_name'];
99       $this->rights = explode(',', $val['rights']);
100       $this->is_client = !in_array('track_own_time', $this->rights);
101       $this->rank = $val['rank'];
102       $this->client_id = $val['client_id'];
103       $this->email = $val['email'];
104       $this->lang = $val['lang'];
105       $this->decimal_mark = $val['decimal_mark'];
106       $this->date_format = $val['date_format'];
107       $this->time_format = $val['time_format'];
108       $this->week_start = $val['week_start'];
109       $this->tracking_mode = $val['tracking_mode'];
110       $this->project_required = $val['project_required'];
111       $this->task_required = $val['task_required'];
112       $this->record_type = $val['record_type'];
113       $this->bcc_email = $val['bcc_email'];
114       $this->team = $val['team_name'];
115       $this->currency = $val['currency'];
116       $this->plugins = $val['plugins'];
117       $this->lock_spec = $val['lock_spec'];
118       $this->workday_minutes = $val['workday_minutes'];
119       $this->custom_logo = $val['custom_logo'];
120
121       $this->config = $val['config'];
122       $config_array = explode(',', $this->config);
123
124       // Set user config options.
125       $this->show_holidays = in_array('show_holidays', $config_array);
126       $this->punch_mode = in_array('punch_mode', $config_array);
127       $this->allow_overlap = in_array('allow_overlap', $config_array);
128       $this->future_entries = in_array('future_entries', $config_array);
129       $this->uncompleted_indicators = in_array('uncompleted_indicators', $config_array);
130
131       // Set "on behalf" id and name.
132       if (isset($_SESSION['behalf_id'])) {
133           $this->behalf_id = $_SESSION['behalf_id'];
134           $this->behalf_name = $_SESSION['behalf_name'];
135       }
136     }
137   }
138
139   // The getActiveUser returns user id on behalf of whom the current user is operating.
140   function getActiveUser() {
141     return ($this->behalf_id ? $this->behalf_id : $this->id);
142   }
143
144   // can - determines whether user has a right to do something.
145   function can($do_something) {
146     return in_array($do_something, $this->rights);
147   }
148
149   // isAdmin - determines whether current user is admin (has right_administer_site).
150   function isAdmin() {
151     return $this->can('administer_site');
152   }
153
154   // isManager - determines whether current user is team manager.
155   // This is a legacy function that we are getting rid of by replacing with rights check.
156   function isManager() {
157     return $this->can('export_data'); // By default this is assigned to managers but not co-managers.
158                                       // Which is sufficient for now until we refactor all calls
159                                       // to this function and then remove it.
160   }
161
162   // isCoManager - determines whether current user is team comanager.
163   // This is a legacy function that we are getting rid of by replacing with rights check.
164   function isCoManager() {
165     return ($this->can('manage_users') && !$this->can('export_data'));
166   }
167
168   // isClient - determines whether current user is a client.
169   function isClient() {
170     return $this->is_client;
171   }
172
173   // canManageTeam - determines whether current user is manager or co-manager.
174   // This is a legacy function that we are getting rid of by replacing with rights check.
175   function canManageTeam() {
176     return $this->can('manage_users'); // By default this is assigned to co-managers (an managers).
177                                        // Which is sufficient for now until we refactor all calls
178                                        // to this function and then remove it.
179   }
180
181   // isPluginEnabled checks whether a plugin is enabled for user.
182   function isPluginEnabled($plugin)
183   {
184     return in_array($plugin, explode(',', $this->plugins));
185   }
186
187   // getAssignedProjects - returns an array of assigned projects.
188   function getAssignedProjects()
189   {
190     $result = array();
191     $mdb2 = getConnection();
192
193     // Do a query with inner join to get assigned projects.
194     $sql = "select p.id, p.name, p.description, p.tasks, upb.rate from tt_projects p
195       inner join tt_user_project_binds upb on (upb.user_id = ".$this->getActiveUser()." and upb.project_id = p.id and upb.status = 1)
196       where p.team_id = $this->team_id and p.status = 1 order by p.name";
197     $res = $mdb2->query($sql);
198     if (!is_a($res, 'PEAR_Error')) {
199       while ($val = $res->fetchRow()) {
200         $result[] = $val;
201       }
202     }
203     return $result;
204   }
205
206   // isDateLocked checks whether a specifc date is locked for modifications.
207   function isDateLocked($date)
208   {
209     if (!$this->isPluginEnabled('lk'))
210       return false; // Locking feature is disabled.
211
212     if (!$this->lock_spec)
213       return false; // There is no lock specification.
214
215     if (!$this->behalf_id && $this->can('override_own_date_lock'))
216       return false; // User is working as self and can override own date lock.
217
218     if ($this->behalf_id && $this->can('override_date_lock'))
219       return false; // User is working on behalf of someone else and can override date lock.
220
221     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.php');
222     require_once(LIBRARY_DIR.'/tdcron/class.tdcron.entry.php');
223
224     // Calculate the last occurrence of a lock.
225     $last = tdCron::getLastOccurrence($this->lock_spec, time());
226     $lockdate = new DateAndTime(DB_DATEFORMAT, strftime('%Y-%m-%d', $last));
227     if ($date->before($lockdate))
228       return true;
229
230     return false;
231   }
232
233   // canOverridePunchMode checks whether a user can override punch mode in a situation.
234   function canOverridePunchMode()
235   {
236     if (!$this->behalf_id && !$this->can('override_own_punch_mode'))
237       return false; // User is working as self and cannot override for self.
238
239     if ($this->behalf_id && !$this->can('override_punch_mode'))
240       return false; // User is working on behalf of someone else and cannot override.
241
242     return true;
243   }
244
245   // getUsers obtains users in a group, as specififed by options.
246   function getUsers($options) {
247
248     $mdb2 = getConnection();
249
250     $skipClients = !isset($options['include_clients']);
251     $includeSelf = isset($options['include_self']);
252
253     $select_part = 'select u.id, u.name';
254     if (!isset($options['include_clients'])) $select_part .= ', r.rights';
255
256     $from_part = ' from tt_users u';
257
258     $left_joins = null;
259     if (isset($options['max_rank']) || $skipClients)
260         $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
261
262     $where_part = " where u.team_id = $this->team_id";
263     if (isset($options['status'])) $where_part .= ' and u.status = '.(int)$options['status'];
264     if ($includeSelf) {
265       $where_part .= " and (u.id = $this->id || r.rank <= ".(int)$options['max_rank'].')';
266     } else {
267       if (isset($options['max_rank'])) $where_part .= ' and r.rank <= '.(int)$options['max_rank'];
268     }
269
270     $sql = $select_part.$from_part.$left_joins.$where_part;
271     $res = $mdb2->query($sql);
272     $user_list = array();
273     if (is_a($res, 'PEAR_Error'))
274       return false;
275
276     while ($val = $res->fetchRow()) {
277       if ($skipClients) {
278         $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
279         if ($isClient)
280           continue; // Skip adding clients.
281       }
282       $user_list[] = $val;
283     }
284
285     if (isset($options['self_first'])) {
286       // Put own entry at the front.
287       $cnt = count($user_list);
288       for($i = 0; $i < $cnt; $i++) {
289         if ($user_list[$i]['id'] == $this->id) {
290           $self = $user_list[$i]; // Found self.
291           array_unshift($user_list, $self); // Put own entry at the front.
292           array_splice($user_list, $i+1, 1); // Remove duplicate.
293         }
294       }
295     }
296     return $user_list;
297   }
298
299   // checkBehalfId checks whether behalf_id is appropriate.
300   // On behalf user must be active and have lower rank.
301   function checkBehalfId() {
302     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
303     $users = $this->getUsers($options);
304     foreach($users as $one_user) {
305       if ($one_user['id'] == $this->behalf_id)
306         return true;
307     }
308
309     return false;
310   }
311
312   // adjustBehalfId attempts to adjust behalf_id and behalf_name to a first found
313   // aapropriate user.
314   //
315   // Needed for situations when use does not have do_own_something right.
316   // Example: has view_charts but does not have view_own_charts.
317   // In this case we still allow access to charts, but set behalf_id to someone else.
318   function adjustBehalfId() {
319     $options = array('status'=>ACTIVE,'max_rank'=>$this->rank-1);
320     $users = $this->getUsers($options);
321     foreach($users as $one_user) {
322       // Fake loop to access first element.
323       $this->behalf_id = $one_user['id'];
324       $this->behalf_name = $one_user['name'];
325       $_SESSION['behalf_id'] = $this->behalf_id;
326       $_SESSION['behalf_name'] = $this->behalf_name;
327       return true;
328     }
329     return false;
330   }
331 }