f5323322e79704e85d954dac2ca2b3e2cd67c1d6
[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('ttRoleHelper');
30
31 // ttAdmin class is used to perform admin tasks.
32 // Used as namespace, as it is a collection of static functions that we call
33 // from admin pages to administer the site as a whole.
34 class ttAdmin {
35
36   // getSubgroups rerurns an array of subgroups for a group.
37   static function getSubgroups($group_id) {
38     $mdb2 = getConnection();
39
40     $subgroups = array();
41     $sql =  "select id from tt_groups where parent_id = $group_id";
42     $res = $mdb2->query($sql);
43     if (!is_a($res, 'PEAR_Error')) {
44       while ($val = $res->fetchRow()) {
45         $subgroups[] = $val;
46       }
47     }
48     return $subgroups;
49   }
50
51   // markGroupDeleted marks a group and everything in it as deleted.
52   // This function is called in context of a logged on admin who may
53   // operate on any group.
54   static function markGroupDeleted($group_id) {
55     $mdb2 = getConnection();
56
57     // Keep the logic simple by returning false on first error.
58
59     // Obtain subgroups and call self recursively on them.
60     $subgroups = ttAdmin::getSubgroups($group_id);
61     foreach($subgroups as $subgroup) {
62       if (!ttAdmin::markGroupDeleted($subgroup['id']))
63         return false;
64     }
65
66     // Now do actual work with all entities.
67
68     // Some things cannot be marked deleted as we don't have the status field for them.
69     // Just delete such things (until we have a better way to deal with them).
70     $tables_to_delete_from = array(
71       'tt_config',
72       'tt_predefined_expenses',
73       'tt_client_project_binds',
74       'tt_project_task_binds'
75     );
76     foreach($tables_to_delete_from as $table) {
77       if (!ttAdmin::deleteGroupEntriesFromTable($group_id, $table))
78         return false;
79     }
80
81     // Now mark status deleted where we can.
82     // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
83     // Reasoning is:
84     //
85     // 1) Users may mark some of them deleted during their work.
86     // If we mark all of them deleted here, we can't recover nicely
87     // as we'll lose track of what was accidentally deleted by user.
88     //
89     // 2) DB maintenance script (Clean up DB from inactive groups) should
90     // get rid of these items permanently eventually.
91     $tables_to_mark_deleted_in = array(
92       'tt_cron',
93       'tt_fav_reports',
94       // 'tt_expense_items',
95       // 'tt_custom_field_log',
96       'tt_custom_field_options',
97       'tt_custom_fields',
98       // 'tt_log',
99       'tt_invoices',
100       'tt_user_project_binds',
101       'tt_users',
102       'tt_clients',
103       'tt_projects',
104       'tt_tasks',
105       'tt_roles'
106     );
107     foreach($tables_to_mark_deleted_in as $table) {
108       if (!ttAdmin::markGroupDeletedInTable($group_id, $table))
109         return false;
110     }
111
112     // Mark group deleted.
113     global $user;
114     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
115     $sql = "update tt_groups set status = null $modified_part where id = $group_id";
116     $affected = $mdb2->exec($sql);
117     if (is_a($affected, 'PEAR_Error')) return false;
118
119     return true;
120   }
121
122   // updateGroup updates a (top) group with new information.
123   static function updateGroup($fields) {
124     $group_id = (int)$fields['group_id'];
125     if (!$group_id) return false; // Nothing to update.
126
127     $mdb2 = getConnection();
128     global $user;
129     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
130
131     // Update group name if it changed.
132     if ($fields['old_group_name'] != $fields['new_group_name']) {
133       $name_part = 'name = '.$mdb2->quote($fields['new_group_name']);
134       $sql = 'update tt_groups set '.$name_part.$modified_part.' where id = '.$group_id;
135       $affected = $mdb2->exec($sql);
136       if (is_a($affected, 'PEAR_Error')) return false;
137     }
138
139     // Update group manager.
140     $user_id = $fields['user_id'];
141     $login_part = 'login = '.$mdb2->quote($fields['new_login']);
142     if ($fields['password1'])
143       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
144     $name_part = ', name = '.$mdb2->quote($fields['user_name']);
145     $email_part = ', email = '.$mdb2->quote($fields['email']);
146     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.' where id = '.$user_id;
147     $affected = $mdb2->exec($sql);
148     if (is_a($affected, 'PEAR_Error')) return false;
149
150     return true;
151   }
152
153   // updateSelf updates admin account with new information.
154   static function updateSelf($fields) {
155     global $user;
156     $mdb2 = getConnection();
157
158     // Update self.
159     $user_id = $user->id;
160     $login_part = 'login = '.$mdb2->quote($fields['login']);
161     if ($fields['password1'])
162       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
163     $name_part = ', name = '.$mdb2->quote($fields['name']);
164     $email_part = ', email = '.$mdb2->quote($fields['email']);
165     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
166     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.' where id = '.$user_id;
167     $affected = $mdb2->exec($sql);
168     return (!is_a($affected, 'PEAR_Error'));
169   }
170
171   // getGroupName obtains group name.
172   static function getGroupName($group_id) {
173     $result = array();
174     $mdb2 = getConnection();
175
176     $sql = "select name from tt_groups where id = $group_id";
177
178     $res = $mdb2->query($sql);
179     if (!is_a($res, 'PEAR_Error')) {
180       $val = $res->fetchRow();
181       return $val['name'];
182     }
183
184     return false;
185   }
186
187   // getOrgDetails obtains group name and its top manager details.
188   static function getOrgDetails($group_id) {
189     $result = array();
190     $mdb2 = getConnection();
191
192     // Note: current code works with properly set top manager (rank 512).
193     // However, we now allow export and import of subgroups, which seems to work well.
194     // In this situation, imported role is no longer "Top manager", and this call fails.
195     // Setting role id manually in database for top user to Top manager resolves the issue.
196     //
197     // TODO: assess whether it is safe / reasonable to promote role during export or import.
198     // The problem is that user having 'export_data' right is not necessarily top user.
199     // And if we do it by rank, what to do for multiple managers situation? First found?
200     // Leaving to manual fixing for now.
201     $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".
202       " from tt_groups g".
203       " inner join tt_users u on (u.group_id = g.id)".
204       " inner join tt_roles r on (r.id = u.role_id and r.rank = 512)". // Fails for partially imported org. See comment above.
205       " where g.id = $group_id";
206
207     $res = $mdb2->query($sql);
208     if (!is_a($res, 'PEAR_Error')) {
209       $val = $res->fetchRow();
210       return $val;
211     }
212
213     return false;
214   }
215
216   // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
217   // It deletes entries in ONE table belonging to a given group.
218   static function deleteGroupEntriesFromTable($group_id, $table_name) {
219     $mdb2 = getConnection();
220
221     $sql = "delete from $table_name where group_id = $group_id";
222     $affected = $mdb2->exec($sql);
223     return (!is_a($affected, 'PEAR_Error'));
224   }
225
226   // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
227   // It updates ONE table by setting status to NULL for all records belonging to a group.
228   static function markGroupDeletedInTable($group_id, $table_name) {
229     $mdb2 = getConnection();
230
231     // Add modified info to sql for some tables, depending on table name.
232     if ($table_name == 'tt_users') {
233       global $user;
234       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
235     }
236
237     $sql = "update $table_name set status = null $modified_part where group_id = $group_id";
238     $affected = $mdb2->exec($sql);
239     return (!is_a($affected, 'PEAR_Error'));
240   }
241
242   // createGroup creates a new top group and returns its id.
243   // It is a helper function for createOrg.
244   static function createGroup($fields) {
245     global $user;
246     $mdb2 = getConnection();
247
248     $group_key = $mdb2->quote(ttRandomString());
249     $name = $mdb2->quote($fields['group_name']);
250     $currency = $mdb2->quote($fields['currency']);
251     $lang = $mdb2->quote($fields['lang']);
252     $created = 'now()';
253     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
254     $created_by = $user->id;
255
256     $sql = "insert into tt_groups (group_key, name, currency, lang, created, created_ip, created_by)".
257       " values($group_key, $name, $currency, $lang, $created, $created_ip, $created_by)";
258     $affected = $mdb2->exec($sql);
259     if (is_a($affected, 'PEAR_Error')) return false;
260
261     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
262
263     // Update org_id with group_id.
264     $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
265     $affected = $mdb2->exec($sql);
266     if (is_a($affected, 'PEAR_Error')) return false;
267
268     return $group_id;
269   }
270
271   // createOrgManager creates a new user (top manager role) in a group.
272   // It is a helper function for createOrg.
273   static function createOrgManager($fields) {
274     global $user;
275     $mdb2 = getConnection();
276
277     $role_id = ttRoleHelper::getTopManagerRoleID();
278     $login = $mdb2->quote($fields['login']);
279     $password = 'md5('.$mdb2->quote($fields['password']).')';
280     $name = $mdb2->quote($fields['user_name']);
281     $group_id = (int) $fields['group_id'];
282     $org_id = $group_id;
283     $email = $mdb2->quote($fields['email']);
284     $created = 'now()';
285     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
286     $created_by = $user->id;
287
288     $columns = '(login, password, name, group_id, org_id, role_id, email, created, created_ip, created_by)';
289     $values = "values($login, $password, $name, $group_id, $org_id, $role_id, $email, $created, $created_ip, $created_by)";
290
291     $sql = "insert into tt_users $columns $values";
292     $affected = $mdb2->exec($sql);
293     return (!is_a($affected, 'PEAR_Error'));
294   }
295
296   // The createOrg function creates an organization in Time Tracker.
297   static function createOrg($fields) {
298     // There are 3 steps that we need to 2 when creating a new organization.
299     //   1. Create a new group with null parent_id.
300     //   2. Create pre-defined roles in it.
301     //   3. Create a top manager account for new group.
302
303     // Create a new group.
304     $group_id = ttAdmin::createGroup($fields);
305     if (!$group_id) return false;
306
307     // Create predefined roles.
308     if (!ttRoleHelper::createPredefinedRoles($group_id, $fields['lang']))
309       return false;
310
311     // Create user.
312     $fields['group_id'] = $group_id;
313     if (!ttAdmin::createOrgManager($fields))
314       return false;
315
316     return true;
317   }
318 }