White space formatting, also added a TODO comment about a currently not fixed nasty...
[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     $result = array();
37     $mdb2 = getConnection();
38
39     $sql =  "select * from tt_users where id = $user_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     $mdb2 = getConnection();
113
114     $password = $mdb2->quote($fields['password']);
115     if($hash)
116       $password = 'md5('.$password.')';
117     $email = isset($fields['email']) ? $fields['email'] : '';
118     $team_id = (int) $fields['team_id'];
119     $role = (int) $fields['role'];
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
128     $sql = "insert into tt_users (name, login, password, team_id, role, client_id, rate, email $status_f) values (".
129       $mdb2->quote($fields['name']).", ".$mdb2->quote($fields['login']).
130       ", $password, $team_id, $role, ".$mdb2->quote($fields['client_id']).", $rate, ".$mdb2->quote($email)." $status_v)";
131     $affected = $mdb2->exec($sql);
132
133     // Now deal with project assignment.
134     if (!is_a($affected, 'PEAR_Error')) {
135       $sql = "SELECT LAST_INSERT_ID() AS last_id";
136       $res = $mdb2->query($sql);
137       $val = $res->fetchRow();
138       $last_id = $val['last_id'];
139
140       $projects = isset($fields['projects']) ? $fields['projects'] : array();
141       if (count($projects) > 0) {
142         // We have at least one project assigned. Insert corresponding entries in tt_user_project_binds table.
143         foreach($projects as $p) {
144           if(!isset($p['rate']))
145             $p['rate'] = 0;
146           else
147             $p['rate'] = str_replace(',', '.', $p['rate']);
148
149           $sql = "insert into tt_user_project_binds (project_id, user_id, rate, status) values(".$p['id'].",".$last_id.",".$p['rate'].", 1)";
150           $affected = $mdb2->exec($sql);
151         }
152       }
153       return $last_id;
154     }
155     return false;
156   }
157
158   // update - updates a user in database.
159   static function update($user_id, $fields) {
160     global $user;
161     $mdb2 = getConnection();
162
163     // Check parameters.
164     if (!$user_id || !isset($fields['login']))
165       return false;
166
167     // Prepare query parts.
168     if (isset($fields['password']))
169       $pass_part = ', password = md5('.$mdb2->quote($fields['password']).')';
170     if (right_assign_roles & $user->rights) {
171       if (isset($fields['role'])) {
172         $role = (int) $fields['role'];
173         $role_part = ", role = $role";
174       }
175       if (array_key_exists('client_id', $fields)) // Could be NULL.
176         $client_part = ", client_id = ".$mdb2->quote($fields['client_id']);
177     }
178
179     if (array_key_exists('rate', $fields)) {
180       $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
181       if($rate == '') $rate = 0;
182       $rate_part = ", rate = ".$mdb2->quote($rate); 
183     }
184
185     if (isset($fields['status'])) {
186       $status = (int) $fields['status']; 
187       $status_part = ", status = $status";
188     }
189
190     $sql = "update tt_users set login = ".$mdb2->quote($fields['login']).
191       "$pass_part, name = ".$mdb2->quote($fields['name']).
192       "$role_part $client_part $rate_part $status_part, email = ".$mdb2->quote($fields['email']).
193       " where id = $user_id";
194     $affected = $mdb2->exec($sql);
195     if (is_a($affected, 'PEAR_Error')) return false;
196
197     if (array_key_exists('projects', $fields)) {
198       // Deal with project assignments.
199       // Note: we cannot simply delete old project binds and insert new ones because it screws up reporting
200       // (when looking for cost while entries for de-assigned projects exist).
201       // Therefore, we must iterate through all projects and only delete the binds when no time entries are present,
202       // otherwise de-activate the bind (set its status to inactive). This will keep the bind
203       // and its rate in database for reporting.
204
205       $all_projects = ttTeamHelper::getAllProjects($user->team_id);
206       $assigned_projects = isset($fields['projects']) ? $fields['projects'] : array();
207
208       foreach($all_projects as $p) {
209         // Determine if a project is assigned.
210         $assigned = false;
211         $project_id = $p['id'];
212         $rate = '0.00';
213         if (count($assigned_projects) > 0) {
214           foreach ($assigned_projects as $ap) {
215             if ($project_id == $ap['id']) {
216               $assigned = true;
217               if ($ap['rate']) {
218                 $rate = $ap['rate'];
219                 $rate = str_replace(",",".",$rate);
220               }
221               break;
222             }
223           }
224         }
225
226         if (!$assigned) {
227           ttUserHelper::deleteBind($user_id, $project_id);
228         } else {
229           // Here we need to either update or insert new tt_user_project_binds record.
230           // Determine if a record exists.
231           $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
232           $res = $mdb2->query($sql);
233           if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
234           if ($val = $res->fetchRow()) {
235             // Record exists. Update it.
236             $sql = "update tt_user_project_binds set status = 1, rate = $rate where id = ".$val['id'];
237             $affected = $mdb2->exec($sql);
238             if (is_a($affected, 'PEAR_Error')) die ($affected->getMessage());
239           } else {
240             // Record does not exist. Insert it.
241             ttUserHelper::insertBind($user_id, $project_id, $rate, 1);
242           }
243         }
244       }
245     }
246     return true;
247   }
248
249   // markDeleted - marks user and its associated things as deleted.
250   // TODO: address the problem when a deleted user has a scheduled notification configured,
251   // in which case all other notifications may stop working because of MySQL syntax error.
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 user as deleted.
273       $sql = "update tt_users set status = NULL where id = $user_id";
274       $affected = $mdb2->exec($sql);
275       if (is_a($affected, 'PEAR_Error'))
276         return false;
277
278     } elseif ($user->isCoManager()) {
279       // Mark user binds as deleted.
280       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
281       $affected = $mdb2->exec($sql);
282       if (is_a($affected, 'PEAR_Error'))
283         return false;
284
285       // Mark user as deleted.
286       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
287       $affected = $mdb2->exec($sql);
288       if (is_a($affected, 'PEAR_Error'))
289         return false;
290
291     } elseif ($user->isManager()) {
292       $user_count = ttTeamHelper::getUserCount($user->team_id);
293
294       // Marking deleted a manager with active users is not allowed.
295        if (($user_id == $user->id) && ($user_count > 1))
296         return false;
297
298       if (1 == $user_count) {
299         // Mark tasks deleted.
300         if (!ttTeamHelper::markTasksDeleted($user->team_id))
301           return false;
302
303         // Mark projects deleted.
304         $sql = "update tt_projects set status = NULL where team_id = $user->team_id";
305         $affected = $mdb2->exec($sql);
306         if (is_a($affected, 'PEAR_Error'))
307           return false;
308
309         // Mark clients deleted.
310         $sql = "update tt_clients set status = NULL where team_id = $user->team_id";
311         $affected = $mdb2->exec($sql);
312         if (is_a($affected, 'PEAR_Error'))
313           return false;
314
315         // Mark custom fields deleted.
316         $sql = "update tt_custom_fields 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 team deleted.
322         $sql = "update tt_teams set status = NULL where id = $user->team_id";
323         $affected = $mdb2->exec($sql);
324         if (is_a($affected, 'PEAR_Error'))
325           return false;
326       }
327
328       // Mark user binds as deleted.
329       $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
330       $affected = $mdb2->exec($sql);
331       if (is_a($affected, 'PEAR_Error'))
332         return false;
333
334       // Mark user as deleted.
335       $sql = "update tt_users set status = NULL where id = $user_id and team_id = ".$user->team_id;
336       $affected = $mdb2->exec($sql);
337       if (is_a($affected, 'PEAR_Error'))
338         return false;
339     }
340
341     return true;
342   }
343
344   // The delete function permanently deletes a user and all associated data.
345   static function delete($user_id) {
346     $mdb2 = getConnection();
347
348     // Delete custom field log entries for user, if we have them.
349     $sql = "delete from tt_custom_field_log where log_id in
350       (select id from tt_log where user_id = $user_id)";
351     $affected = $mdb2->exec($sql);
352     if (is_a($affected, 'PEAR_Error'))
353       return false;
354
355     // Delete log entries for user.
356     $sql = "delete from tt_log where user_id = $user_id";
357     $affected = $mdb2->exec($sql);
358     if (is_a($affected, 'PEAR_Error'))
359       return false;
360
361     // Delete expense items for user.
362     $sql = "delete from tt_expense_items where user_id = $user_id";
363     $affected = $mdb2->exec($sql);
364     if (is_a($affected, 'PEAR_Error'))
365       return false;
366
367     // Delete user binds.
368     $sql = "delete from tt_user_project_binds where user_id = $user_id";
369     $affected = $mdb2->exec($sql);
370     if (is_a($affected, 'PEAR_Error'))
371       return false;
372
373     // Clean up tt_config table.
374     $sql = "delete from tt_config where user_id = $user_id";
375     $affected = $mdb2->exec($sql);
376     if (is_a($affected, 'PEAR_Error'))
377       return false; 
378
379     // Clean up tt_fav_reports table.
380     $sql = "delete from tt_fav_reports where user_id = $user_id";
381     $affected = $mdb2->exec($sql);
382     if (is_a($affected, 'PEAR_Error'))
383       return false;
384
385     // Delete user.
386     $sql = "delete from tt_users where id = $user_id";
387     $affected = $mdb2->exec($sql);    
388     if (is_a($affected, 'PEAR_Error'))
389       return false;
390
391     return true;
392   }
393
394   // The saveTmpRef saves a temporary reference for user that is used to reset user password.
395   static function saveTmpRef($ref, $user_id) {
396     $mdb2 = getConnection();
397
398     $sql = "delete from tt_tmp_refs where timestamp + 86400 < now()";
399     $affected = $mdb2->exec($sql);
400
401     $sql = "insert into tt_tmp_refs (ref, user_id) values(".$mdb2->quote($ref).", $user_id)";
402     $affected = $mdb2->exec($sql);
403   }
404
405   // The setPassword function updates password for user.
406   static function setPassword($user_id, $password) {
407     $mdb2 = getConnection();
408
409     $sql = "update tt_users set password = md5(".$mdb2->quote($password).") where id = $user_id";
410     $affected = $mdb2->exec($sql);
411
412     return (!is_a($affected, 'PEAR_Error'));
413   }
414
415   // insertBind - inserts a user to project bind into tt_user_project_binds table.
416   static function insertBind($user_id, $project_id, $rate, $status) {
417     $mdb2 = getConnection();
418
419     $sql = "insert into tt_user_project_binds (user_id, project_id, rate, status)
420       values($user_id, $project_id, ".$mdb2->quote($rate).", $status)";
421     $affected = $mdb2->exec($sql);
422     return (!is_a($affected, 'PEAR_Error'));
423   }
424
425   // deleteBind - deactivates user to project bind when time entries exist,
426   // otherwise deletes it entirely.
427   static function deleteBind($user_id, $project_id) {
428     $mdb2 = getConnection();
429
430     $sql = "select count(*) as cnt from tt_log where 
431       user_id = $user_id and project_id = $project_id and status = 1";
432     $res = $mdb2->query($sql);
433     if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
434
435     $count = 0;
436     $val = $res->fetchRow();
437     $count = $val['cnt'];
438
439     if ($count > 0) {
440       // Deactivate user bind.
441       $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
442        $res = $mdb2->query($sql);
443        if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
444        if ($val = $res->fetchRow()) {
445          $sql = "update tt_user_project_binds set status = 0 where id = ".$val['id'];
446          $affected = $mdb2->exec($sql);
447          if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
448        }
449     } else {
450       // Delete user bind.
451       $sql = "delete from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
452       $affected = $mdb2->exec($sql);
453       if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
454     }
455     return true;
456   }
457 }