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