26ced938acf251afc89741aa16687cf9a94f4adf
[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 getUserName function returns user name.
35   static function getUserName($user_id) {
36     $mdb2 = getConnection();
37
38     $sql = "select name from tt_users where id = $user_id and (status = 1 or status = 0)";
39     $res = $mdb2->query($sql);
40
41     if (!is_a($res, 'PEAR_Error')) {
42       $val = $res->fetchRow();
43       return $val['name'];
44     }
45     return false;
46   }
47
48   // The getUserByLogin function obtains data for a user, who is identified by login.
49   static function getUserByLogin($login) {
50     $mdb2 = getConnection();
51
52     $sql = "select id, name from tt_users where login = ".$mdb2->quote($login)." and (status = 1 or status = 0)";
53     $res = $mdb2->query($sql);
54     if (!is_a($res, 'PEAR_Error')) {
55       if ($val = $res->fetchRow()) {
56         return $val;
57       }
58     }
59     return false;
60   }
61
62   // The getUserByEmail function is a helper function that tries to obtain user details identified by email.
63   // This function works only when one such active user exists.
64   static function getUserByEmail($email) {
65     $mdb2 = getConnection();
66
67     $sql = "select login, count(*) as cnt from tt_users where email = ".$mdb2->quote($email)." and status = 1 group by email";
68     $res = $mdb2->query($sql);
69
70     if (is_a($res, 'PEAR_Error'))
71       return false;
72
73     $val = $res->fetchRow();
74     if (1 <> $val['cnt']) {
75       // We either have no users or multiple users with a given email.
76       return false;
77     }
78     return $val['login'];
79   }
80
81   // The getUserIdByTmpRef obtains user id from a temporary reference (used for password resets).
82   static function getUserIdByTmpRef($ref) {
83     $mdb2 = getConnection();
84
85     $sql = "select user_id from tt_tmp_refs where ref = ".$mdb2->quote($ref);
86     $res = $mdb2->query($sql);
87
88     if (!is_a($res, 'PEAR_Error')) {
89       $val = $res->fetchRow();
90       return $val['user_id'];
91     }
92     return false;
93   }
94
95   // insert - inserts a user into database.
96   static function insert($fields, $hash = true) {
97     global $user;
98     $mdb2 = getConnection();
99
100     $password = $mdb2->quote($fields['password']);
101     if($hash)
102       $password = 'md5('.$password.')';
103     $email = isset($fields['email']) ? $fields['email'] : '';
104     $group_id = (int) $fields['group_id'];
105     $org_id = (int) $fields['org_id'];
106     $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
107     $quota_percent = str_replace(',', '.', isset($fields['quota_percent']) ? $fields['quota_percent'] : 100);
108     if($rate == '')
109       $rate = 0;
110     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of deleted acounts.
111       $status_f = ', status';
112       $status_v = ', '.$mdb2->quote($fields['status']);
113     }
114     $created_ip_v = ', '.$mdb2->quote($_SERVER['REMOTE_ADDR']);
115     $created_by_v = ', '.$user->id;
116
117     $sql = "insert into tt_users (name, login, password, group_id, org_id, role_id, client_id, rate, quota_percent, email, created, created_ip, created_by $status_f) values (".
118       $mdb2->quote($fields['name']).", ".$mdb2->quote($fields['login']).
119       ", $password, $group_id, $org_id, ".$mdb2->quote($fields['role_id']).", ".$mdb2->quote($fields['client_id']).", $rate, $quota_percent, ".$mdb2->quote($email).", now() $created_ip_v $created_by_v $status_v)";
120     $affected = $mdb2->exec($sql);
121
122     // Now deal with project assignment.
123     if (!is_a($affected, 'PEAR_Error')) {
124       $last_id = $mdb2->lastInsertID('tt_users', 'id');
125       $projects = isset($fields['projects']) ? $fields['projects'] : array();
126       if (count($projects) > 0) {
127         // We have at least one project assigned. Insert corresponding entries in tt_user_project_binds table.
128         foreach($projects as $p) {
129           if(!isset($p['rate']))
130             $p['rate'] = 0;
131           else
132             $p['rate'] = str_replace(',', '.', $p['rate']);
133
134           $sql = "insert into tt_user_project_binds (project_id, user_id, group_id, org_id, rate, status)".
135             " values(".$p['id'].", $last_id, $group_id, $org_id, ".$p['rate'].", 1)";
136           $affected = $mdb2->exec($sql);
137         }
138       }
139       return $last_id;
140     }
141     return false;
142   }
143
144   // update - updates a user in database.
145   static function update($user_id, $fields) {
146     global $user;
147     $mdb2 = getConnection();
148
149     // Check parameters.
150     if (!$user_id)
151       return false;
152
153     $group_id = $user->getGroup();
154     $org_id = $user->org_id;
155
156     // Prepare query parts.
157     if (isset($fields['login'])) {
158       $login_part = ", login = ".$mdb2->quote($fields['login']);
159     }
160
161     if (isset($fields['password']))
162       $pass_part = ', password = md5('.$mdb2->quote($fields['password']).')';
163
164     if (isset($fields['name']))
165       $name_part = ', name = '.$mdb2->quote($fields['name']);
166
167     if ($user->can('manage_users')) {
168       if (isset($fields['role_id'])) {
169         $role_id = (int) $fields['role_id'];
170         $role_part = ", role_id = $role_id";
171       }
172       if (array_key_exists('client_id', $fields)) // Could be NULL.
173         $client_part = ", client_id = ".$mdb2->quote($fields['client_id']);
174     }
175
176     if (array_key_exists('rate', $fields)) {
177       $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
178       if($rate == '') $rate = 0;
179       $rate_part = ", rate = ".$mdb2->quote($rate); 
180     }
181
182     if (array_key_exists('quota_percent', $fields)) {
183       $quota_percent = str_replace(',', '.', isset($fields['quota_percent']) ? $fields['quota_percent'] : 100);
184       $quota_percent_part = ", quota_percent = ".$mdb2->quote($quota_percent);
185     }
186
187     if (isset($fields['email']))
188       $email_part = ', email = '.$mdb2->quote($fields['email']);
189
190     if (isset($fields['status'])) {
191       $status = (int) $fields['status']; 
192       $status_part = ", status = $status";
193     }
194
195     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
196     $parts = ltrim($login_part.$pass_part.$name_part.$role_part.$client_part.$rate_part.$quota_percent_part.$email_part.$modified_part.$status_part, ',');
197
198     $sql = "update tt_users set $parts".
199       " where id = $user_id and group_id = $group_id and org_id = $org_id";
200     $affected = $mdb2->exec($sql);
201     if (is_a($affected, 'PEAR_Error')) return false;
202
203     if (array_key_exists('projects', $fields)) {
204       // Deal with project assignments.
205       // Note: we cannot simply delete old project binds and insert new ones because it screws up reporting
206       // (when looking for cost while entries for de-assigned projects exist).
207       // Therefore, we must iterate through all projects and only delete the binds when no time entries are present,
208       // otherwise de-activate the bind (set its status to inactive). This will keep the bind
209       // and its rate in database for reporting.
210
211       $all_projects = ttTeamHelper::getAllProjects($user->getGroup());
212       $assigned_projects = isset($fields['projects']) ? $fields['projects'] : array();
213
214       foreach($all_projects as $p) {
215         // Determine if a project is assigned.
216         $assigned = false;
217         $project_id = $p['id'];
218         $rate = '0.00';
219         if (count($assigned_projects) > 0) {
220           foreach ($assigned_projects as $ap) {
221             if ($project_id == $ap['id']) {
222               $assigned = true;
223               if ($ap['rate']) {
224                 $rate = $ap['rate'];
225                 $rate = str_replace(",",".",$rate);
226               }
227               break;
228             }
229           }
230         }
231
232         if (!$assigned) {
233           ttUserHelper::deleteBind($user_id, $project_id);
234         } else {
235           // Here we need to either update or insert new tt_user_project_binds record.
236           // Determine if a record exists.
237           $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
238           $res = $mdb2->query($sql);
239           if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
240           if ($val = $res->fetchRow()) {
241             // Record exists. Update it.
242             $sql = "update tt_user_project_binds set status = 1, rate = $rate where id = ".$val['id'];
243             $affected = $mdb2->exec($sql);
244             if (is_a($affected, 'PEAR_Error')) die ($affected->getMessage());
245           } else {
246             // Record does not exist. Insert it.
247             ttUserHelper::insertBind(array(
248               'user_id' => $user_id,
249               'project_id' => $project_id,
250               'rate' => $rate,
251               'status' => ACTIVE));
252            }
253         }
254       }
255     }
256     return true;
257   }
258
259   // The delete function permanently deletes a user and all associated data.
260   static function delete($user_id) {
261     $mdb2 = getConnection();
262
263     // Delete custom field log entries for user, if we have them.
264     $sql = "delete from tt_custom_field_log where log_id in
265       (select id from tt_log where user_id = $user_id)";
266     $affected = $mdb2->exec($sql);
267     if (is_a($affected, 'PEAR_Error'))
268       return false;
269
270     // Delete log entries for user.
271     $sql = "delete from tt_log where user_id = $user_id";
272     $affected = $mdb2->exec($sql);
273     if (is_a($affected, 'PEAR_Error'))
274       return false;
275
276     // Delete expense items for user.
277     $sql = "delete from tt_expense_items where user_id = $user_id";
278     $affected = $mdb2->exec($sql);
279     if (is_a($affected, 'PEAR_Error'))
280       return false;
281
282     // Delete user binds.
283     $sql = "delete from tt_user_project_binds where user_id = $user_id";
284     $affected = $mdb2->exec($sql);
285     if (is_a($affected, 'PEAR_Error'))
286       return false;
287
288     // Clean up tt_config table.
289     $sql = "delete from tt_config where user_id = $user_id";
290     $affected = $mdb2->exec($sql);
291     if (is_a($affected, 'PEAR_Error'))
292       return false; 
293
294     // Clean up tt_fav_reports table.
295     $sql = "delete from tt_fav_reports where user_id = $user_id";
296     $affected = $mdb2->exec($sql);
297     if (is_a($affected, 'PEAR_Error'))
298       return false;
299
300     // Delete user.
301     $sql = "delete from tt_users where id = $user_id";
302     $affected = $mdb2->exec($sql);    
303     if (is_a($affected, 'PEAR_Error'))
304       return false;
305
306     return true;
307   }
308
309   // The saveTmpRef saves a temporary reference for user that is used to reset user password.
310   static function saveTmpRef($ref, $user_id) {
311     $mdb2 = getConnection();
312
313     $sql = "delete from tt_tmp_refs where created < now() - interval 1 hour";
314     $affected = $mdb2->exec($sql);
315
316     $sql = "insert into tt_tmp_refs (created, ref, user_id) values(now(), ".$mdb2->quote($ref).", $user_id)";
317     $affected = $mdb2->exec($sql);
318   }
319
320   // The setPassword function updates password for user.
321   static function setPassword($user_id, $password) {
322     $mdb2 = getConnection();
323
324     $sql = "update tt_users set password = md5(".$mdb2->quote($password).") where id = $user_id";
325     $affected = $mdb2->exec($sql);
326
327     return (!is_a($affected, 'PEAR_Error'));
328   }
329
330   // insertBind - inserts a user to project bind into tt_user_project_binds table.
331   static function insertBind($fields) {
332     global $user;
333     $mdb2 = getConnection();
334
335     $group_id = $user->getGroup();
336     $org_id = $user->org_id;
337     $user_id = (int) $fields['user_id'];
338     $project_id = (int) $fields['project_id'];
339     $rate = $mdb2->quote($fields['rate']);
340     $status = $mdb2->quote($fields['status']);
341
342     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
343       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
344     $affected = $mdb2->exec($sql);
345     return (!is_a($affected, 'PEAR_Error'));
346   }
347
348   // deleteBind - deactivates user to project bind when time entries exist,
349   // otherwise deletes it entirely.
350   static function deleteBind($user_id, $project_id) {
351     $mdb2 = getConnection();
352
353     $sql = "select count(*) as cnt from tt_log where 
354       user_id = $user_id and project_id = $project_id and status = 1";
355     $res = $mdb2->query($sql);
356     if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
357
358     $count = 0;
359     $val = $res->fetchRow();
360     $count = $val['cnt'];
361
362     if ($count > 0) {
363       // Deactivate user bind.
364       $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
365        $res = $mdb2->query($sql);
366        if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
367        if ($val = $res->fetchRow()) {
368          $sql = "update tt_user_project_binds set status = 0 where id = ".$val['id'];
369          $affected = $mdb2->exec($sql);
370          if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
371        }
372     } else {
373       // Delete user bind.
374       $sql = "delete from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
375       $affected = $mdb2->exec($sql);
376       if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
377     }
378     return true;
379   }
380
381   // updateLastAccess - updates last access info for user in db.
382   static function updateLastAccess() {
383     global $user;
384     $mdb2 = getConnection();
385     $accessed_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
386     $sql = "update tt_users set accessed = now(), accessed_ip = $accessed_ip where id = $user->id";
387     $mdb2->exec($sql);
388   }
389 }