Added audit info to user creation operation.
[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";
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     $sql = "update tt_users set login = ".$mdb2->quote($fields['login']).
193       "$pass_part, name = ".$mdb2->quote($fields['name']).
194       "$role_id_part $client_part $rate_part $status_part, email = ".$mdb2->quote($fields['email']).
195       " where id = $user_id";
196     $affected = $mdb2->exec($sql);
197     if (is_a($affected, 'PEAR_Error')) return false;
198
199     if (array_key_exists('projects', $fields)) {
200       // Deal with project assignments.
201       // Note: we cannot simply delete old project binds and insert new ones because it screws up reporting
202       // (when looking for cost while entries for de-assigned projects exist).
203       // Therefore, we must iterate through all projects and only delete the binds when no time entries are present,
204       // otherwise de-activate the bind (set its status to inactive). This will keep the bind
205       // and its rate in database for reporting.
206
207       $all_projects = ttTeamHelper::getAllProjects($user->team_id);
208       $assigned_projects = isset($fields['projects']) ? $fields['projects'] : array();
209
210       foreach($all_projects as $p) {
211         // Determine if a project is assigned.
212         $assigned = false;
213         $project_id = $p['id'];
214         $rate = '0.00';
215         if (count($assigned_projects) > 0) {
216           foreach ($assigned_projects as $ap) {
217             if ($project_id == $ap['id']) {
218               $assigned = true;
219               if ($ap['rate']) {
220                 $rate = $ap['rate'];
221                 $rate = str_replace(",",".",$rate);
222               }
223               break;
224             }
225           }
226         }
227
228         if (!$assigned) {
229           ttUserHelper::deleteBind($user_id, $project_id);
230         } else {
231           // Here we need to either update or insert new tt_user_project_binds record.
232           // Determine if a record exists.
233           $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
234           $res = $mdb2->query($sql);
235           if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
236           if ($val = $res->fetchRow()) {
237             // Record exists. Update it.
238             $sql = "update tt_user_project_binds set status = 1, rate = $rate where id = ".$val['id'];
239             $affected = $mdb2->exec($sql);
240             if (is_a($affected, 'PEAR_Error')) die ($affected->getMessage());
241           } else {
242             // Record does not exist. Insert it.
243             ttUserHelper::insertBind($user_id, $project_id, $rate, 1);
244           }
245         }
246       }
247     }
248     return true;
249   }
250
251   // markDeleted - marks user and its associated things as deleted.
252   static function markDeleted($user_id) {
253     $mdb2 = getConnection();
254     global $user;
255
256     // Preliminary checks. Only managers, co-managers, and admin can do this.
257     if (!$user->canManageTeam() && !$user->isAdmin())
258       return false;
259
260     // Tho logic is different depending on who is doing the operation.
261     // Co-manager and admin - mark user deleted.
262     // Manager - mark user deleted. If manager is the only account in team, mark team items deleted.
263
264     // admin part.
265     if ($user->isAdmin()) {
266       // Mark user binds as deleted.
267       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
268       $affected = $mdb2->exec($sql);
269       if (is_a($affected, 'PEAR_Error'))
270         return false;
271
272       // Mark favorite reports as deleted.
273       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
274       $affected = $mdb2->exec($sql);
275       if (is_a($affected, 'PEAR_Error'))
276         return false;
277
278       // Mark user as deleted.
279       $sql = "update tt_users set status = NULL where id = $user_id";
280       $affected = $mdb2->exec($sql);
281       if (is_a($affected, 'PEAR_Error'))
282         return false;
283
284     } elseif ($user->isCoManager()) {
285       // Mark user binds as deleted.
286       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
287       $affected = $mdb2->exec($sql);
288       if (is_a($affected, 'PEAR_Error'))
289         return false;
290
291       // Mark favorite reports as deleted.
292       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
293       $affected = $mdb2->exec($sql);
294       if (is_a($affected, 'PEAR_Error'))
295         return false;
296
297       // Mark user as deleted.
298       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
299       $affected = $mdb2->exec($sql);
300       if (is_a($affected, 'PEAR_Error'))
301         return false;
302
303     } elseif ($user->isManager()) {
304       $user_count = ttTeamHelper::getUserCount($user->team_id);
305
306       // Marking deleted a manager with active users is not allowed.
307        if (($user_id == $user->id) && ($user_count > 1))
308         return false;
309
310       if (1 == $user_count) {
311         // Mark tasks deleted.
312         if (!ttTeamHelper::markTasksDeleted($user->team_id))
313           return false;
314
315         // Mark projects deleted.
316         $sql = "update tt_projects set status = NULL where team_id = $user->team_id";
317         $affected = $mdb2->exec($sql);
318         if (is_a($affected, 'PEAR_Error'))
319           return false;
320
321         // Mark clients deleted.
322         $sql = "update tt_clients set status = NULL where team_id = $user->team_id";
323         $affected = $mdb2->exec($sql);
324         if (is_a($affected, 'PEAR_Error'))
325           return false;
326
327         // Mark custom fields deleted.
328         $sql = "update tt_custom_fields set status = NULL where team_id = $user->team_id";
329         $affected = $mdb2->exec($sql);
330         if (is_a($affected, 'PEAR_Error'))
331           return false;
332  
333         // Mark team deleted.
334         $sql = "update tt_teams set status = NULL where id = $user->team_id";
335         $affected = $mdb2->exec($sql);
336         if (is_a($affected, 'PEAR_Error'))
337           return false;
338       }
339
340       // Mark user binds as deleted.
341       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
342       $affected = $mdb2->exec($sql);
343       if (is_a($affected, 'PEAR_Error'))
344         return false;
345
346       // Mark favorite reports as deleted.
347       $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
348       $affected = $mdb2->exec($sql);
349       if (is_a($affected, 'PEAR_Error'))
350         return false;
351
352       // Mark user as deleted.
353       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
354       $affected = $mdb2->exec($sql);
355       if (is_a($affected, 'PEAR_Error'))
356         return false;
357     }
358
359     return true;
360   }
361
362   // The delete function permanently deletes a user and all associated data.
363   static function delete($user_id) {
364     $mdb2 = getConnection();
365
366     // Delete custom field log entries for user, if we have them.
367     $sql = "delete from tt_custom_field_log where log_id in
368       (select id from tt_log where user_id = $user_id)";
369     $affected = $mdb2->exec($sql);
370     if (is_a($affected, 'PEAR_Error'))
371       return false;
372
373     // Delete log entries for user.
374     $sql = "delete from tt_log where user_id = $user_id";
375     $affected = $mdb2->exec($sql);
376     if (is_a($affected, 'PEAR_Error'))
377       return false;
378
379     // Delete expense items for user.
380     $sql = "delete from tt_expense_items where user_id = $user_id";
381     $affected = $mdb2->exec($sql);
382     if (is_a($affected, 'PEAR_Error'))
383       return false;
384
385     // Delete user binds.
386     $sql = "delete from tt_user_project_binds where user_id = $user_id";
387     $affected = $mdb2->exec($sql);
388     if (is_a($affected, 'PEAR_Error'))
389       return false;
390
391     // Clean up tt_config table.
392     $sql = "delete from tt_config where user_id = $user_id";
393     $affected = $mdb2->exec($sql);
394     if (is_a($affected, 'PEAR_Error'))
395       return false; 
396
397     // Clean up tt_fav_reports table.
398     $sql = "delete from tt_fav_reports where user_id = $user_id";
399     $affected = $mdb2->exec($sql);
400     if (is_a($affected, 'PEAR_Error'))
401       return false;
402
403     // Delete user.
404     $sql = "delete from tt_users where id = $user_id";
405     $affected = $mdb2->exec($sql);    
406     if (is_a($affected, 'PEAR_Error'))
407       return false;
408
409     return true;
410   }
411
412   // The saveTmpRef saves a temporary reference for user that is used to reset user password.
413   static function saveTmpRef($ref, $user_id) {
414     $mdb2 = getConnection();
415
416     $sql = "delete from tt_tmp_refs where timestamp + 86400 < now()";
417     $affected = $mdb2->exec($sql);
418
419     $sql = "insert into tt_tmp_refs (ref, user_id) values(".$mdb2->quote($ref).", $user_id)";
420     $affected = $mdb2->exec($sql);
421   }
422
423   // The setPassword function updates password for user.
424   static function setPassword($user_id, $password) {
425     $mdb2 = getConnection();
426
427     $sql = "update tt_users set password = md5(".$mdb2->quote($password).") where id = $user_id";
428     $affected = $mdb2->exec($sql);
429
430     return (!is_a($affected, 'PEAR_Error'));
431   }
432
433   // insertBind - inserts a user to project bind into tt_user_project_binds table.
434   static function insertBind($user_id, $project_id, $rate, $status) {
435     $mdb2 = getConnection();
436
437     $sql = "insert into tt_user_project_binds (user_id, project_id, rate, status)
438       values($user_id, $project_id, ".$mdb2->quote($rate).", $status)";
439     $affected = $mdb2->exec($sql);
440     return (!is_a($affected, 'PEAR_Error'));
441   }
442
443   // deleteBind - deactivates user to project bind when time entries exist,
444   // otherwise deletes it entirely.
445   static function deleteBind($user_id, $project_id) {
446     $mdb2 = getConnection();
447
448     $sql = "select count(*) as cnt from tt_log where 
449       user_id = $user_id and project_id = $project_id and status = 1";
450     $res = $mdb2->query($sql);
451     if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
452
453     $count = 0;
454     $val = $res->fetchRow();
455     $count = $val['cnt'];
456
457     if ($count > 0) {
458       // Deactivate user bind.
459       $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
460        $res = $mdb2->query($sql);
461        if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
462        if ($val = $res->fetchRow()) {
463          $sql = "update tt_user_project_binds set status = 0 where id = ".$val['id'];
464          $affected = $mdb2->exec($sql);
465          if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
466        }
467     } else {
468       // Delete user bind.
469       $sql = "delete from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
470       $affected = $mdb2->exec($sql);
471       if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
472     }
473     return true;
474   }
475 }