2e0e695732283d088bc45837fb7a61eed4569b01
[timetracker.git] / WEB-INF / lib / ttAdmin.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('ttUser');
30
31 // ttAdmin class is used to perform admin tasks.
32 class ttAdmin {
33
34   var $err = null; // Error object, passed to us as reference.
35                    // We use it to communicate errors to caller.
36
37   // Constructor.
38   function __construct(&$err = null) {
39     $this->err = $err;
40   }
41
42   // getSubgroups rerurns an array of subgroups for a group.
43   function getSubgroups($group_id) {
44     $mdb2 = getConnection();
45
46     $subgroups = array();
47     $sql =  "select id from tt_groups where parent_id = $group_id";
48     $res = $mdb2->query($sql);
49     if (!is_a($res, 'PEAR_Error')) {
50       while ($val = $res->fetchRow()) {
51         $subgroups[] = $val;
52       }
53     }
54     return $subgroups;
55   }
56
57   // getUsers obtains user ids in a group.
58   function getUsers($group_id) {
59     $mdb2 = getConnection();
60     $sql = "select id from tt_users where group_id = $group_id";
61     $res = $mdb2->query($sql);
62     $users = array();
63     if (!is_a($res, 'PEAR_Error')) {
64       while ($val = $res->fetchRow()) {
65         $users[] = $val;
66       }
67     }
68     return $users;
69   }
70
71   // markUserDeleted marks a user and all things associated with user as deleted.
72   function markUserDeleted($user_id) {
73     $mdb2 = getConnection();
74
75     // Mark user binds as deleted.
76     $sql = "update tt_user_project_binds set status = NULL where user_id = $user_id";
77     $affected = $mdb2->exec($sql);
78     if (is_a($affected, 'PEAR_Error')) return false;
79
80     // Mark favorite reports as deleted.
81     $sql = "update tt_fav_reports set status = NULL where user_id = $user_id";
82     $affected = $mdb2->exec($sql);
83     if (is_a($affected, 'PEAR_Error')) return false;
84
85     // Mark user as deleted.
86     global $user;
87     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
88     $sql = "update tt_users set status = NULL $modified_part where id = $user_id";
89     $affected = $mdb2->exec($sql);
90     if (is_a($affected, 'PEAR_Error')) return false;
91
92     return true;
93   }
94
95   // The markTasksDeleted deletes task binds and marks the tasks as deleted for a group.
96   function markTasksDeleted($group_id) {
97     $mdb2 = getConnection();
98     $sql = "select id from tt_tasks where group_id = $group_id";
99     $res = $mdb2->query($sql);
100     if (is_a($res, 'PEAR_Error')) return false;
101
102     while ($val = $res->fetchRow()) {
103       // Delete task binds.
104       $task_id = $val['id'];
105       $sql = "delete from tt_project_task_binds where task_id = $task_id";
106       $affected = $mdb2->exec($sql);
107       if (is_a($affected, 'PEAR_Error')) return false;
108
109       // Mark task as deleted.
110       $sql = "update tt_tasks set status = NULL where id = $task_id";
111       $affected = $mdb2->exec($sql);
112       if (is_a($affected, 'PEAR_Error')) return false;
113     }
114
115     return true;
116   }
117
118   // markGroupDeleted marks a group and everything in it as deleted.
119   // This function is called in context of a logged on admin who may
120   // operate on any group.
121   static function markGroupDeleted($group_id) {
122     $mdb2 = getConnection();
123
124     // Keep the logic simple by returning false on first error.
125
126     // Obtain subgroups and call self recursively on them.
127     $subgroups = ttAdmin::getSubgroups($group_id);
128     foreach($subgroups as $subgroup) {
129       if (!ttAdmin::markGroupDeleted($subgroup['id']))
130         return false;
131     }
132
133     // Now do actual work with all entities.
134
135     // Some things cannot be marked deleted as we don't have the status field for them.
136     // Just delete such things (until we have a better way to deal with them).
137     $tables_to_delete_from = array(
138       'tt_config',
139       'tt_predefined_expenses',
140       'tt_client_project_binds',
141       'tt_project_task_binds'
142     );
143     foreach($tables_to_delete_from as $table) {
144       if (!ttAdmin::deleteGroupEntriesFromTable($group_id, $table))
145         return false;
146     }
147
148     // Now mark status deleted where we can.
149     // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
150     // Reasoning is:
151     //
152     // 1) Users may mark some of them deleted during their work.
153     // If we mark all of them deleted here, we can't recover nicely
154     // as we'll lose track of what was accidentally deleted by user.
155     //
156     // 2) DB maintenance script (Clean up DB from inactive groups) should
157     // get rid of these items permanently eventually.
158     $tables_to_mark_deleted_in = array(
159       'tt_cron',
160       'tt_fav_reports',
161       // 'tt_expense_items',
162       // 'tt_custom_field_log',
163       'tt_custom_field_options',
164       'tt_custom_fields',
165       // 'tt_log',
166       'tt_invoices',
167       'tt_user_project_binds',
168       'tt_users',
169       'tt_clients',
170       'tt_projects',
171       'tt_tasks',
172       'tt_roles'
173     );
174     foreach($tables_to_mark_deleted_in as $table) {
175       if (!ttAdmin::markGroupDeletedInTable($group_id, $table))
176         return false;
177     }
178
179     // Mark group deleted.
180     global $user;
181     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
182     $sql = "update tt_groups set status = null $modified_part where id = $group_id";
183     $affected = $mdb2->exec($sql);
184     if (is_a($affected, 'PEAR_Error')) return false;
185
186     return true;
187   }
188
189   // validateGroupInfo validates group information entered by user.
190   function validateGroupInfo($fields) {
191     global $i18n;
192     global $auth;
193
194     $result = true;
195
196     if (!ttValidString($fields['new_group_name'])) {
197       $this->err->add($i18n->get('error.field'), $i18n->get('label.group_name'));
198       $result = false;
199     }
200     if (!ttValidString($fields['user_name'])) {
201       $this->err->add($i18n->get('error.field'), $i18n->get('label.manager_name'));
202       $result = false;
203     }
204     if (!ttValidString($fields['new_login'])) {
205       $this->err->add($i18n->get('error.field'), $i18n->get('label.manager_login'));
206       $result = false;
207     }
208
209     // If we change login, it must be unique.
210     if ($fields['new_login'] != $fields['old_login']) {
211       if (ttUserHelper::getUserByLogin($fields['new_login'])) {
212         $this->err->add($i18n->get('error.user_exists'));
213         $result = false;
214       }
215     }
216
217     if (!$auth->isPasswordExternal() && ($fields['password1'] || $fields['password2'])) {
218       if (!ttValidString($fields['password1'])) {
219         $this->err->add($i18n->get('error.field'), $i18n->get('label.password'));
220         $result = false;
221       }
222       if (!ttValidString($fields['password2'])) {
223         $this->err->add($i18n->get('error.field'), $i18n->get('label.confirm_password'));
224         $result = false;
225       }
226       if ($fields['password1'] !== $fields['password2']) {
227         $this->err->add($i18n->get('error.not_equal'), $i18n->get('label.password'), $i18n->get('label.confirm_password'));
228         $result = false;
229       }
230     }
231     if (!ttValidEmail($fields['email'], true)) {
232       $this->err->add($i18n->get('error.field'), $i18n->get('label.email'));
233       $result = false;
234     }
235
236     return $result;
237   }
238
239   // updateGroup validates user input and updates the group with new information.
240   function updateGroup($group_id, $fields) {
241     if (!$this->validateGroupInfo($fields)) return false; // Can't continue as user input is invalid.
242
243     global $user;
244     $mdb2 = getConnection();
245
246     // Update group name if it changed.
247     if ($fields['old_group_name'] != $fields['new_group_name']) {
248       $name_part = 'name = '.$mdb2->quote($fields['new_group_name']);
249       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
250       $sql = 'update tt_groups set '.$name_part.$modified_part.' where id = '.$group_id;
251       $affected = $mdb2->exec($sql);
252       if (is_a($affected, 'PEAR_Error')) return false;
253     }
254
255     // Update group manager.
256     $user_id = $fields['user_id'];
257     $login_part = 'login = '.$mdb2->quote($fields['new_login']);
258     if ($fields['password1'])
259       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
260     $name_part = ', name = '.$mdb2->quote($fields['user_name']);
261     $email_part = ', email = '.$mdb2->quote($fields['email']);
262     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
263     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.'where id = '.$user_id;
264     $affected = $mdb2->exec($sql);
265     if (is_a($affected, 'PEAR_Error')) return false;
266
267     return true;
268   }
269
270   // validateUserInfo validates account information entered by user.
271   function validateUserInfo($fields) {
272     global $i18n;
273     global $user;
274     global $auth;
275
276     $result = true;
277
278     if (!ttValidString($fields['name'])) {
279       $this->err->add($i18n->get('error.field'), $i18n->get('label.person_name'));
280       $result = false;
281     }
282     if (!ttValidString($fields['login'])) {
283       $this->err->add($i18n->get('error.field'), $i18n->get('label.login'));
284       $result = false;
285     }
286     // If we change login, it must be unique.
287     if ($fields['login'] != $user->login) {
288       if (ttUserHelper::getUserByLogin($fields['login'])) {
289         $this->err->add($i18n->get('error.user_exists'));
290         $result = false;
291       }
292     }
293     if (!$auth->isPasswordExternal() && ($fields['password1'] || $fields['password2'])) {
294       if (!ttValidString($fields['password1'])) {
295         $this->err->add($i18n->get('error.field'), $i18n->get('label.password'));
296         $result = false;
297       }
298       if (!ttValidString($fields['password2'])) {
299         $this->err->add($i18n->get('error.field'), $i18n->get('label.confirm_password'));
300         $result = false;
301       }
302       if ($fields['password1'] !== $fields['password2']) {
303         $this->err->add($i18n->get('error.not_equal'), $i18n->get('label.password'), $i18n->get('label.confirm_password'));
304         $result = false;
305       }
306     }
307     if (!ttValidEmail($fields['email'], true)) {
308       $this->err->add($i18n->get('error.field'), $i18n->get('label.email'));
309       $result = false;
310     }
311
312     return $result;
313   }
314
315   // updateSelf validates user input and updates admin account with new information.
316   function updateSelf($fields) {
317     if (!$this->validateUserInfo($fields)) return false; // Can't continue as user input is invalid.
318
319     global $user;
320     global $i18n;
321     $mdb2 = getConnection();
322
323     // Update self.
324     $user_id = $user->id;
325     $login_part = 'login = '.$mdb2->quote($fields['login']);
326     if ($fields['password1'])
327       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
328     $name_part = ', name = '.$mdb2->quote($fields['name']);
329     $email_part = ', email = '.$mdb2->quote($fields['email']);
330     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
331     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.'where id = '.$user_id;
332     $affected = $mdb2->exec($sql);
333     if (is_a($affected, 'PEAR_Error')) {
334       $this->err->add($i18n->get('error.db'));
335       return false;
336     }
337
338     return true;
339   }
340
341   // getGroupDetails obtains group name and its top manager details.
342   static function getGroupDetails($group_id) {
343     $result = array();
344     $mdb2 = getConnection();
345
346     $sql = "select g.name as group_name, u.id as manager_id, u.name as manager_name, u.login as manager_login, u.email as manager_email".
347       " from tt_groups g".
348       " inner join tt_users u on (u.group_id = g.id)".
349       " inner join tt_roles r on (r.id = u.role_id and r.rank = 512)".
350       " where g.id = $group_id";
351
352     $res = $mdb2->query($sql);
353     if (!is_a($res, 'PEAR_Error')) {
354       $val = $res->fetchRow();
355       return $val;
356     }
357
358     return false;
359   }
360
361   // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
362   // It deletes entries in ONE table belonging to a given group.
363   static function deleteGroupEntriesFromTable($group_id, $table_name) {
364     $mdb2 = getConnection();
365
366     $sql = "delete from $table_name where group_id = $group_id";
367     $affected = $mdb2->exec($sql);
368     return (!is_a($affected, 'PEAR_Error'));
369   }
370
371   // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
372   // It updates ONE table by setting status to NULL for all records belonging to a group.
373   static function markGroupDeletedInTable($group_id, $table_name) {
374     $mdb2 = getConnection();
375
376     // Add modified info to sql for some tables, depending on table name.
377     if ($table_name == 'tt_users') {
378       global $user;
379       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
380     }
381
382     $sql = "update $table_name set status = null $modified_part where group_id = $group_id";
383     $affected = $mdb2->exec($sql);
384     return (!is_a($affected, 'PEAR_Error'));
385   }
386 }