Finished refactoring ttAdmin class.
[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     $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".
193       " from tt_groups g".
194       " inner join tt_users u on (u.group_id = g.id)".
195       " inner join tt_roles r on (r.id = u.role_id and r.rank = 512)".
196       " where g.id = $group_id";
197
198     $res = $mdb2->query($sql);
199     if (!is_a($res, 'PEAR_Error')) {
200       $val = $res->fetchRow();
201       return $val;
202     }
203
204     return false;
205   }
206
207   // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
208   // It deletes entries in ONE table belonging to a given group.
209   static function deleteGroupEntriesFromTable($group_id, $table_name) {
210     $mdb2 = getConnection();
211
212     $sql = "delete from $table_name where group_id = $group_id";
213     $affected = $mdb2->exec($sql);
214     return (!is_a($affected, 'PEAR_Error'));
215   }
216
217   // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
218   // It updates ONE table by setting status to NULL for all records belonging to a group.
219   static function markGroupDeletedInTable($group_id, $table_name) {
220     $mdb2 = getConnection();
221
222     // Add modified info to sql for some tables, depending on table name.
223     if ($table_name == 'tt_users') {
224       global $user;
225       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
226     }
227
228     $sql = "update $table_name set status = null $modified_part where group_id = $group_id";
229     $affected = $mdb2->exec($sql);
230     return (!is_a($affected, 'PEAR_Error'));
231   }
232
233   // createGroup creates a new top group and returns its id.
234   // It is a helper function for createOrg.
235   static function createGroup($fields) {
236     global $user;
237     $mdb2 = getConnection();
238
239     $name = $mdb2->quote($fields['group_name']);
240     $currency = $mdb2->quote($fields['currency']);
241     $lang = $mdb2->quote($fields['lang']);
242     $created = 'now()';
243     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
244     $created_by = $user->id;
245
246     $sql = "insert into tt_groups (name, currency, lang, created, created_ip, created_by)".
247       " values($name, $currency, $lang, $created, $created_ip, $created_by)";
248     $affected = $mdb2->exec($sql);
249     if (is_a($affected, 'PEAR_Error')) return false;
250
251     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
252
253     // Update org_id with group_id.
254     $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
255     $affected = $mdb2->exec($sql);
256     if (is_a($affected, 'PEAR_Error')) return false;
257
258     return $group_id;
259   }
260
261   // createOrgManager creates a new user (top manager role) in a group.
262   // It is a helper function for createOrg.
263   static function createOrgManager($fields) {
264     global $user;
265     $mdb2 = getConnection();
266
267     $role_id = ttRoleHelper::getTopManagerRoleID();
268     $login = $mdb2->quote($fields['login']);
269     $password = 'md5('.$mdb2->quote($fields['password']).')';
270     $name = $mdb2->quote($fields['user_name']);
271     $group_id = (int) $fields['group_id'];
272     $org_id = $group_id;
273     $email = $mdb2->quote($fields['email']);
274     $created = 'now()';
275     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
276     $created_by = $user->id;
277
278     $columns = '(login, password, name, group_id, org_id, role_id, email, created, created_ip, created_by)';
279     $values = "values($login, $password, $name, $group_id, $org_id, $role_id, $email, $created, $created_ip, $created_by)";
280
281     $sql = "insert into tt_users $columns $values";
282     $affected = $mdb2->exec($sql);
283     return (!is_a($affected, 'PEAR_Error'));
284   }
285
286   // The createOrg function creates an organization in Time Tracker.
287   static function createOrg($fields) {
288     // There are 3 steps that we need to 2 when creating a new organization.
289     //   1. Create a new group with null parent_id.
290     //   2. Create pre-defined roles in it.
291     //   3. Create a top manager account for new group.
292
293     // Create a new group.
294     $group_id = ttAdmin::createGroup($fields);
295     if (!$group_id) return false;
296
297     // Create predefined roles.
298     if (!ttRoleHelper::createPredefinedRoles($group_id, $fields['lang']))
299       return false;
300
301     // Create user.
302     $fields['group_id'] = $group_id;
303     if (!ttAdmin::createOrgManager($fields))
304       return false;
305
306     return true;
307   }
308 }