Refactored ttRoleHelper::getRoleByRank().
[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     if($rate == '')
108       $rate = 0;
109     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of deleted acounts.
110       $status_f = ', status';
111       $status_v = ', '.$mdb2->quote($fields['status']);
112     }
113     $created_ip_v = ', '.$mdb2->quote($_SERVER['REMOTE_ADDR']);
114     $created_by_v = ', '.$user->id;
115
116     $sql = "insert into tt_users (name, login, password, group_id, org_id, role_id, client_id, rate, email, created, created_ip, created_by $status_f) values (".
117       $mdb2->quote($fields['name']).", ".$mdb2->quote($fields['login']).
118       ", $password, $group_id, $org_id, ".$mdb2->quote($fields['role_id']).", ".$mdb2->quote($fields['client_id']).", $rate, ".$mdb2->quote($email).", now() $created_ip_v $created_by_v $status_v)";
119     $affected = $mdb2->exec($sql);
120
121     // Now deal with project assignment.
122     if (!is_a($affected, 'PEAR_Error')) {
123       $last_id = $mdb2->lastInsertID('tt_users', 'id');
124       $projects = isset($fields['projects']) ? $fields['projects'] : array();
125       if (count($projects) > 0) {
126         // We have at least one project assigned. Insert corresponding entries in tt_user_project_binds table.
127         foreach($projects as $p) {
128           if(!isset($p['rate']))
129             $p['rate'] = 0;
130           else
131             $p['rate'] = str_replace(',', '.', $p['rate']);
132
133           $sql = "insert into tt_user_project_binds (project_id, user_id, group_id, org_id, rate, status)".
134             " values(".$p['id'].", $last_id, $group_id, $org_id, ".$p['rate'].", 1)";
135           $affected = $mdb2->exec($sql);
136         }
137       }
138       return $last_id;
139     }
140     return false;
141   }
142
143   // update - updates a user in database.
144   static function update($user_id, $fields) {
145     global $user;
146     $mdb2 = getConnection();
147
148     // Check parameters.
149     if (!$user_id || !isset($fields['login']))
150       return false;
151
152     // Prepare query parts.
153     if (isset($fields['password']))
154       $pass_part = ', password = md5('.$mdb2->quote($fields['password']).')';
155     if (in_array('manage_users', $user->rights)) {
156       if (isset($fields['role_id'])) {
157         $role_id = (int) $fields['role_id'];
158         $role_id_part = ", role_id = $role_id";
159       }
160       if (array_key_exists('client_id', $fields)) // Could be NULL.
161         $client_part = ", client_id = ".$mdb2->quote($fields['client_id']);
162     }
163
164     if (array_key_exists('rate', $fields)) {
165       $rate = str_replace(',', '.', isset($fields['rate']) ? $fields['rate'] : 0);
166       if($rate == '') $rate = 0;
167       $rate_part = ", rate = ".$mdb2->quote($rate); 
168     }
169
170     if (isset($fields['status'])) {
171       $status = (int) $fields['status']; 
172       $status_part = ", status = $status";
173     }
174
175     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
176
177     $sql = "update tt_users set login = ".$mdb2->quote($fields['login']).
178       "$pass_part, name = ".$mdb2->quote($fields['name']).
179       "$role_id_part $client_part $rate_part $modified_part $status_part, email = ".$mdb2->quote($fields['email']).
180       " where id = $user_id";
181     $affected = $mdb2->exec($sql);
182     if (is_a($affected, 'PEAR_Error')) return false;
183
184     if (array_key_exists('projects', $fields)) {
185       // Deal with project assignments.
186       // Note: we cannot simply delete old project binds and insert new ones because it screws up reporting
187       // (when looking for cost while entries for de-assigned projects exist).
188       // Therefore, we must iterate through all projects and only delete the binds when no time entries are present,
189       // otherwise de-activate the bind (set its status to inactive). This will keep the bind
190       // and its rate in database for reporting.
191
192       $all_projects = ttTeamHelper::getAllProjects($user->group_id);
193       $assigned_projects = isset($fields['projects']) ? $fields['projects'] : array();
194
195       foreach($all_projects as $p) {
196         // Determine if a project is assigned.
197         $assigned = false;
198         $project_id = $p['id'];
199         $rate = '0.00';
200         if (count($assigned_projects) > 0) {
201           foreach ($assigned_projects as $ap) {
202             if ($project_id == $ap['id']) {
203               $assigned = true;
204               if ($ap['rate']) {
205                 $rate = $ap['rate'];
206                 $rate = str_replace(",",".",$rate);
207               }
208               break;
209             }
210           }
211         }
212
213         if (!$assigned) {
214           ttUserHelper::deleteBind($user_id, $project_id);
215         } else {
216           // Here we need to either update or insert new tt_user_project_binds record.
217           // Determine if a record exists.
218           $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
219           $res = $mdb2->query($sql);
220           if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
221           if ($val = $res->fetchRow()) {
222             // Record exists. Update it.
223             $sql = "update tt_user_project_binds set status = 1, rate = $rate where id = ".$val['id'];
224             $affected = $mdb2->exec($sql);
225             if (is_a($affected, 'PEAR_Error')) die ($affected->getMessage());
226           } else {
227             // Record does not exist. Insert it.
228             ttUserHelper::insertBind(array(
229               'user_id' => $user_id,
230               'project_id' => $project_id,
231               'group_id' => $user->getGroup(),
232               'org_id' => $user->org_id,
233               'rate' => $rate,
234               'status' => ACTIVE));
235            }
236         }
237       }
238     }
239     return true;
240   }
241
242   // The delete function permanently deletes a user and all associated data.
243   static function delete($user_id) {
244     $mdb2 = getConnection();
245
246     // Delete custom field log entries for user, if we have them.
247     $sql = "delete from tt_custom_field_log where log_id in
248       (select id from tt_log where user_id = $user_id)";
249     $affected = $mdb2->exec($sql);
250     if (is_a($affected, 'PEAR_Error'))
251       return false;
252
253     // Delete log entries for user.
254     $sql = "delete from tt_log where user_id = $user_id";
255     $affected = $mdb2->exec($sql);
256     if (is_a($affected, 'PEAR_Error'))
257       return false;
258
259     // Delete expense items for user.
260     $sql = "delete from tt_expense_items where user_id = $user_id";
261     $affected = $mdb2->exec($sql);
262     if (is_a($affected, 'PEAR_Error'))
263       return false;
264
265     // Delete user binds.
266     $sql = "delete from tt_user_project_binds where user_id = $user_id";
267     $affected = $mdb2->exec($sql);
268     if (is_a($affected, 'PEAR_Error'))
269       return false;
270
271     // Clean up tt_config table.
272     $sql = "delete from tt_config where user_id = $user_id";
273     $affected = $mdb2->exec($sql);
274     if (is_a($affected, 'PEAR_Error'))
275       return false; 
276
277     // Clean up tt_fav_reports table.
278     $sql = "delete from tt_fav_reports where user_id = $user_id";
279     $affected = $mdb2->exec($sql);
280     if (is_a($affected, 'PEAR_Error'))
281       return false;
282
283     // Delete user.
284     $sql = "delete from tt_users where id = $user_id";
285     $affected = $mdb2->exec($sql);    
286     if (is_a($affected, 'PEAR_Error'))
287       return false;
288
289     return true;
290   }
291
292   // The saveTmpRef saves a temporary reference for user that is used to reset user password.
293   static function saveTmpRef($ref, $user_id) {
294     $mdb2 = getConnection();
295
296     $sql = "delete from tt_tmp_refs where created < now() - interval 1 hour";
297     $affected = $mdb2->exec($sql);
298
299     $sql = "insert into tt_tmp_refs (created, ref, user_id) values(now(), ".$mdb2->quote($ref).", $user_id)";
300     $affected = $mdb2->exec($sql);
301   }
302
303   // The setPassword function updates password for user.
304   static function setPassword($user_id, $password) {
305     $mdb2 = getConnection();
306
307     $sql = "update tt_users set password = md5(".$mdb2->quote($password).") where id = $user_id";
308     $affected = $mdb2->exec($sql);
309
310     return (!is_a($affected, 'PEAR_Error'));
311   }
312
313   // insertBind - inserts a user to project bind into tt_user_project_binds table.
314   static function insertBind($fields) {
315     global $user;
316     $mdb2 = getConnection();
317
318     // This may be used during import. Use the following until we have import refactored.
319     $group_id = $fields['group_id'] ? (int) $fields['group_id'] : $user->getGroup();
320     $org_id = $fields['org_id'] ? (int) $fields['org_id'] : $user->org_id;
321
322     $user_id = (int) $fields['user_id'];
323     $project_id = (int) $fields['project_id'];
324     $rate = $mdb2->quote($fields['rate']);
325     $status = $mdb2->quote($fields['status']);
326
327     $sql = "insert into tt_user_project_binds (user_id, project_id, group_id, org_id, rate, status)".
328       " values($user_id, $project_id, $group_id, $org_id, $rate, $status)";
329     $affected = $mdb2->exec($sql);
330     return (!is_a($affected, 'PEAR_Error'));
331   }
332
333   // deleteBind - deactivates user to project bind when time entries exist,
334   // otherwise deletes it entirely.
335   static function deleteBind($user_id, $project_id) {
336     $mdb2 = getConnection();
337
338     $sql = "select count(*) as cnt from tt_log where 
339       user_id = $user_id and project_id = $project_id and status = 1";
340     $res = $mdb2->query($sql);
341     if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
342
343     $count = 0;
344     $val = $res->fetchRow();
345     $count = $val['cnt'];
346
347     if ($count > 0) {
348       // Deactivate user bind.
349       $sql = "select id from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
350        $res = $mdb2->query($sql);
351        if (is_a($res, 'PEAR_Error')) die ($res->getMessage());
352        if ($val = $res->fetchRow()) {
353          $sql = "update tt_user_project_binds set status = 0 where id = ".$val['id'];
354          $affected = $mdb2->exec($sql);
355          if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
356        }
357     } else {
358       // Delete user bind.
359       $sql = "delete from tt_user_project_binds where user_id = $user_id and project_id = $project_id";
360       $affected = $mdb2->exec($sql);
361       if (is_a($affected, 'PEAR_Error')) die ($res->getMessage());
362     }
363     return true;
364   }
365
366   // updateLastAccess - updates last access info for user in db.
367   static function updateLastAccess() {
368     global $user;
369     $mdb2 = getConnection();
370     $accessed_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
371     $sql = "update tt_users set accessed = now(), accessed_ip = $accessed_ip where id = $user->id";
372     $mdb2->exec($sql);
373   }
374 }