Improved getUserDetails to not return info for deleted users.
[timetracker.git] / WEB-INF / lib / ttUserHelper.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('ttTeamHelper');
30
31 // Class ttUserHelper contains helper functions for operations with users.
32 class ttUserHelper {
33
34   // The getUserDetails function returns user details.
35   static function getUserDetails($user_id) {
36     global $user;
37     $mdb2 = getConnection();
38
39     $sql =  "select u.*, r.rank from tt_users u left join tt_roles r on (u.role_id = r.id) where u.id = $user_id and u.team_id = $user->team_id and u.status is not null";
40     $res = $mdb2->query($sql);
41
42     if (!is_a($res, 'PEAR_Error')) {
43       $val = $res->fetchRow();
44       return $val;
45     }
46     return false;
47   }
48
49   // The getUserName function returns user name.
50   static function getUserName($user_id) {
51     $mdb2 = getConnection();
52
53     $sql = "select name from tt_users where id = $user_id and (status = 1 or status = 0)";
54     $res = $mdb2->query($sql);
55
56     if (!is_a($res, 'PEAR_Error')) {
57       $val = $res->fetchRow();
58       return $val['name'];
59     }
60     return false;
61   }
62
63   // The getUserByLogin function obtains data for a user, who is identified by login.
64   static function getUserByLogin($login) {
65     $mdb2 = getConnection();
66
67     $sql = "select id, name from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
68     $res = $mdb2->query($sql);
69     if (!is_a($res, 'PEAR_Error')) {
70       if ($val = $res->fetchRow()) {
71         return $val;
72       }
73     }
74     return false;
75   }
76
77   // The getUserByEmail function is a helper function that tries to obtain user details identified by email.
78   // This function works only when one such active user exists.
79   static function getUserByEmail($email) {
80     $mdb2 = getConnection();
81
82     $sql = "select login, count(*) as cnt from tt_users where email = ".$mdb2->quote($email)." and status = 1 group by email";
83     $res = $mdb2->query($sql);
84
85     if (is_a($res, 'PEAR_Error'))
86       return false;
87
88     $val = $res->fetchRow();
89     if (1 <> $val['cnt']) {
90       // We either have no users or multiple users with a given email.
91       return false;
92     }
93     return $val['login'];
94   }
95
96   // The getUserIdByTmpRef obtains user id from a temporary reference (used for password resets).
97   static function getUserIdByTmpRef($ref) {
98     $mdb2 = getConnection();
99
100     $sql = "select user_id from tt_tmp_refs where ref = ".$mdb2->quote($ref);
101     $res = $mdb2->query($sql);
102
103     if (!is_a($res, 'PEAR_Error')) {
104       $val = $res->fetchRow();
105       return $val['user_id'];
106     }
107     return false;
108   }
109
110   // insert - inserts a user into database.
111   static function insert($fields, $hash = true) {
112     global $user;
113     $mdb2 = getConnection();
114
115     $password = $mdb2->quote($fields['password']);
116     if($hash)
117       $password = 'md5('.$password.')';
118     $email = isset($fields['email']) ? $fields['email'] : '';
119     $team_id = (int) $fields['team_id'];
120     $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
121     if($rate == '')
122       $rate = 0;
123     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of deleted acounts.
124       $status_f = ', status';
125       $status_v = ', '.$mdb2->quote($fields['status']);
126     }
127     $created_ip_v = ', '.$mdb2->quote($_SERVER['REMOTE_ADDR']);
128     $created_by_v = ', '.$mdb2->quote($user->id);
129
130     $sql = "insert into tt_users (name, login, password, team_id, role_id, client_id, rate, email, created, created_ip, created_by $status_f) values (".
131       $mdb2->quote($fields['name']).", ".$mdb2->quote($fields['login']).
132       ", $password, $team_id, ".$mdb2->quote($fields['role_id']).", ".$mdb2->quote($fields['client_id']).", $rate, ".$mdb2->quote($email).", now() $created_ip_v $created_by_v $status_v)";
133     $affected = $mdb2->exec($sql);
134
135     // Now deal with project assignment.
136     if (!is_a($affected, 'PEAR_Error')) {
137       $sql = "SELECT LAST_INSERT_ID() AS last_id";
138       $res = $mdb2->query($sql);
139       $val = $res->fetchRow();
140       $last_id = $val['last_id'];
141
142       $projects = isset($fields['projects']) ? $fields['projects'] : array();
143       if (count($projects) > 0) {
144         // We have at least one project assigned. Insert corresponding entries in tt_user_project_binds table.
145         foreach($projects as $p) {
146           if(!isset($p['rate']))
147             $p['rate'] = 0;
148           else
149             $p['rate'] = str_replace(',', '.', $p['rate']);
150
151           $sql = "insert into tt_user_project_binds (project_id, user_id, rate, status) values(".$p['id'].",".$last_id.",".$p['rate'].", 1)";
152           $affected = $mdb2->exec($sql);
153         }
154       }
155       return $last_id;
156     }
157     return false;
158   }
159
160   // update - updates a user in database.
161   static function update($user_id, $fields) {
162     global $user;
163     $mdb2 = getConnection();
164
165     // Check parameters.
166     if (!$user_id || !isset($fields['login']))
167       return false;
168
169     // Prepare query parts.
170     if (isset($fields['password']))
171       $pass_part = ', password = md5('.$mdb2->quote($fields['password']).')';
172     if (in_array('manage_users', $user->rights)) {
173       if (isset($fields['role_id'])) {
174         $role_id = (int) $fields['role_id'];
175         $role_id_part = ", role_id = $role_id";
176       }
177       if (array_key_exists('client_id', $fields)) // Could be NULL.
178         $client_part = ", client_id = ".$mdb2->quote($fields['client_id']);
179     }
180
181     if (array_key_exists('rate', $fields)) {
182       $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
183       if($rate == '') $rate = 0;
184       $rate_part = ", rate = ".$mdb2->quote($rate); 
185     }
186
187     if (isset($fields['status'])) {
188       $status = (int) $fields['status']; 
189       $status_part = ", status = $status";
190     }
191
192     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
193
194     $sql = "update tt_users set login = ".$mdb2->quote($fields['login']).
195       "$pass_part, name = ".$mdb2->quote($fields['name']).
196       "$role_id_part $client_part $rate_part $modified_part $status_part, email = ".$mdb2->quote($fields['email']).
197       " where id = $user_id";
198     $affected = $mdb2->exec($sql);
199     if (is_a($affected, 'PEAR_Error')) return false;
200
201     if (array_key_exists('projects', $fields)) {
202       // Deal with project assignments.
203       // Note: we cannot simply delete old project binds and insert new ones because it screws up reporting
204       // (when looking for cost while entries for de-assigned projects exist).
205       // Therefore, we must iterate through all projects and only delete the binds when no time entries are present,
206       // otherwise de-activate the bind (set its status to inactive). This will keep the bind
207       // and its rate in database for reporting.
208
209       $all_projects = ttTeamHelper::getAllProjects($user->team_id);
210       $assigned_projects = isset($fields['projects']) ? $fields['projects'] : array();
211
212       foreach($all_projects as $p) {
213         // Determine if a project is assigned.
214         $assigned = false;
215         $project_id = $p['id'];
216         $rate = '0.00';
217         if (count($assigned_projects) > 0) {
218           foreach ($assigned_projects as $ap) {
219             if ($project_id == $ap['id']) {
220               $assigned = true;
221               if ($ap['rate']) {
222                 $rate = $ap['rate'];
223                 $rate = str_replace(",",".",$rate);
224               }
225               break;
226             }
227           }
228         }
229
230         if (!$assigned) {
231           ttUserHelper::deleteBind($user_id, $project_id);
232         } else {
233           // Here we need to either update or insert new tt_user_project_binds record.
234           // Determine if a record exists.
235           $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
236           $res = $mdb2->query($sql);
237           if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
238           if ($val = $res->fetchRow()) {
239             // Record exists. Update it.
240             $sql = "update tt_user_project_binds set status = 1, rate = $rate where id = ".$val['id'];
241             $affected = $mdb2->exec($sql);
242             if (is_a($affected, 'PEAR_Error')) die ($affected->getMessage());
243           } else {
244             // Record does not exist. Insert it.
245             ttUserHelper::insertBind($user_id, $project_id, $rate, 1);
246           }
247         }
248       }
249     }
250     return true;
251   }
252
253   // markDeleted - marks user and its associated things as deleted.
254   static function markDeleted($user_id) {
255     $mdb2 = getConnection();
256     global $user;
257
258     // Preliminary checks. Only managers, co-managers, and admin can do this.
259     if (!$user->canManageTeam() && !$user->isAdmin())
260       return false;
261
262     // Tho logic is different depending on who is doing the operation.
263     // Co-manager and admin - mark user deleted.
264     // Manager - mark user deleted. If manager is the only account in team, mark team items deleted.
265
266     // admin part.
267     if ($user->isAdmin()) {
268       // Mark user binds as deleted.
269       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
270       $affected = $mdb2->exec($sql);
271       if (is_a($affected, 'PEAR_Error'))
272         return false;
273
274       // Mark favorite reports as deleted.
275       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
276       $affected = $mdb2->exec($sql);
277       if (is_a($affected, 'PEAR_Error'))
278         return false;
279
280       // Mark user as deleted.
281       $sql = "update tt_users set status = NULL where id = $user_id";
282       $affected = $mdb2->exec($sql);
283       if (is_a($affected, 'PEAR_Error'))
284         return false;
285
286     } elseif ($user->isCoManager()) {
287       // Mark user binds as deleted.
288       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
289       $affected = $mdb2->exec($sql);
290       if (is_a($affected, 'PEAR_Error'))
291         return false;
292
293       // Mark favorite reports as deleted.
294       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
295       $affected = $mdb2->exec($sql);
296       if (is_a($affected, 'PEAR_Error'))
297         return false;
298
299       // Mark user as deleted.
300       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
301       $affected = $mdb2->exec($sql);
302       if (is_a($affected, 'PEAR_Error'))
303         return false;
304
305     } elseif ($user->isManager()) {
306       $user_count = ttTeamHelper::getUserCount($user->team_id);
307
308       // Marking deleted a manager with active users is not allowed.
309        if (($user_id == $user->id) && ($user_count > 1))
310         return false;
311
312       if (1 == $user_count) {
313         // Mark tasks deleted.
314         if (!ttTeamHelper::markTasksDeleted($user->team_id))
315           return false;
316
317         // Mark projects deleted.
318         $sql = "update tt_projects set status = NULL where team_id = $user->team_id";
319         $affected = $mdb2->exec($sql);
320         if (is_a($affected, 'PEAR_Error'))
321           return false;
322
323         // Mark clients deleted.
324         $sql = "update tt_clients set status = NULL where team_id = $user->team_id";
325         $affected = $mdb2->exec($sql);
326         if (is_a($affected, 'PEAR_Error'))
327           return false;
328
329         // Mark custom fields deleted.
330         $sql = "update tt_custom_fields set status = NULL where team_id = $user->team_id";
331         $affected = $mdb2->exec($sql);
332         if (is_a($affected, 'PEAR_Error'))
333           return false;
334  
335         // Mark team deleted.
336         $sql = "update tt_teams set status = NULL where id = $user->team_id";
337         $affected = $mdb2->exec($sql);
338         if (is_a($affected, 'PEAR_Error'))
339           return false;
340       }
341
342       // Mark user binds as deleted.
343       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
344       $affected = $mdb2->exec($sql);
345       if (is_a($affected, 'PEAR_Error'))
346         return false;
347
348       // Mark favorite reports as deleted.
349       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
350       $affected = $mdb2->exec($sql);
351       if (is_a($affected, 'PEAR_Error'))
352         return false;
353
354       // Mark user as deleted.
355       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
356       $affected = $mdb2->exec($sql);
357       if (is_a($affected, 'PEAR_Error'))
358         return false;
359     }
360
361     return true;
362   }
363
364   // The delete function permanently deletes a user and all associated data.
365   static function delete($user_id) {
366     $mdb2 = getConnection();
367
368     // Delete custom field log entries for user, if we have them.
369     $sql = "delete from tt_custom_field_log where log_id in
370       (select id from tt_log where user_id = $user_id)";
371     $affected = $mdb2->exec($sql);
372     if (is_a($affected, 'PEAR_Error'))
373       return false;
374
375     // Delete log entries for user.
376     $sql = "delete from tt_log where user_id = $user_id";
377     $affected = $mdb2->exec($sql);
378     if (is_a($affected, 'PEAR_Error'))
379       return false;
380
381     // Delete expense items for user.
382     $sql = "delete from tt_expense_items where user_id = $user_id";
383     $affected = $mdb2->exec($sql);
384     if (is_a($affected, 'PEAR_Error'))
385       return false;
386
387     // Delete user binds.
388     $sql = "delete from tt_user_project_binds where user_id = $user_id";
389     $affected = $mdb2->exec($sql);
390     if (is_a($affected, 'PEAR_Error'))
391       return false;
392
393     // Clean up tt_config table.
394     $sql = "delete from tt_config where user_id = $user_id";
395     $affected = $mdb2->exec($sql);
396     if (is_a($affected, 'PEAR_Error'))
397       return false; 
398
399     // Clean up tt_fav_reports table.
400     $sql = "delete from tt_fav_reports where user_id = $user_id";
401     $affected = $mdb2->exec($sql);
402     if (is_a($affected, 'PEAR_Error'))
403       return false;
404
405     // Delete user.
406     $sql = "delete from tt_users where id = $user_id";
407     $affected = $mdb2->exec($sql);    
408     if (is_a($affected, 'PEAR_Error'))
409       return false;
410
411     return true;
412   }
413
414   // The saveTmpRef saves a temporary reference for user that is used to reset user password.
415   static function saveTmpRef($ref, $user_id) {
416     $mdb2 = getConnection();
417
418     $sql = "delete from tt_tmp_refs where created < now() - interval 1 hour";
419     $affected = $mdb2->exec($sql);
420
421     $sql = "insert into tt_tmp_refs (created, ref, user_id) values(now(), ".$mdb2->quote($ref).", $user_id)";
422     $affected = $mdb2->exec($sql);
423   }
424
425   // The setPassword function updates password for user.
426   static function setPassword($user_id, $password) {
427     $mdb2 = getConnection();
428
429     $sql = "update tt_users set password = md5(".$mdb2->quote($password).") where id = $user_id";
430     $affected = $mdb2->exec($sql);
431
432     return (!is_a($affected, 'PEAR_Error'));
433   }
434
435   // insertBind - inserts a user to project bind into tt_user_project_binds table.
436   static function insertBind($user_id, $project_id, $rate, $status) {
437     $mdb2 = getConnection();
438
439     $sql = "insert into tt_user_project_binds (user_id, project_id, rate, status)
440       values($user_id, $project_id, ".$mdb2->quote($rate).", $status)";
441     $affected = $mdb2->exec($sql);
442     return (!is_a($affected, 'PEAR_Error'));
443   }
444
445   // deleteBind - deactivates user to project bind when time entries exist,
446   // otherwise deletes it entirely.
447   static function deleteBind($user_id, $project_id) {
448     $mdb2 = getConnection();
449
450     $sql = "select count(*) as cnt from tt_log where 
451       user_id = $user_id and project_id = $project_id and status = 1";
452     $res = $mdb2->query($sql);
453     if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
454
455     $count = 0;
456     $val = $res->fetchRow();
457     $count = $val['cnt'];
458
459     if ($count > 0) {
460       // Deactivate user bind.
461       $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
462        $res = $mdb2->query($sql);
463        if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
464        if ($val = $res->fetchRow()) {
465          $sql = "update tt_user_project_binds set status = 0 where id = ".$val['id'];
466          $affected = $mdb2->exec($sql);
467          if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
468        }
469     } else {
470       // Delete user bind.
471       $sql = "delete from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
472       $affected = $mdb2->exec($sql);
473       if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
474     }
475     return true;
476   }
477
478   // updateLastAccess - updates last access info for user in db.
479   static function updateLastAccess() {
480     global $user;
481     $mdb2 = getConnection();
482     $accessed_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
483     $sql = "update tt_users set accessed = now(), accessed_ip = $accessed_ip where id = $user->id";
484     $mdb2->exec($sql);
485   }
486 }