Introduced DEFAULT_PLUGINS config constant.
[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     // Delete group files.
69     ttAdmin::deleteGroupFiles($group_id);
70
71     // Some things cannot be marked deleted as we don't have the status field for them.
72     // Just delete such things (until we have a better way to deal with them).
73     $tables_to_delete_from = array(
74       'tt_config',
75       'tt_predefined_expenses',
76       'tt_client_project_binds',
77       'tt_project_task_binds'
78     );
79     foreach($tables_to_delete_from as $table) {
80       if (!ttAdmin::deleteGroupEntriesFromTable($group_id, $table))
81         return false;
82     }
83
84     // Now mark status deleted where we can.
85     // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
86     // Reasoning is:
87     //
88     // 1) Users may mark some of them deleted during their work.
89     // If we mark all of them deleted here, we can't recover nicely
90     // as we'll lose track of what was accidentally deleted by user.
91     //
92     // 2) DB maintenance script (Clean up DB from inactive groups) should
93     // get rid of these items permanently eventually.
94     $tables_to_mark_deleted_in = array(
95       'tt_cron',
96       'tt_fav_reports',
97       // 'tt_expense_items',
98       // 'tt_custom_field_log',
99       'tt_custom_field_options',
100       'tt_custom_fields',
101       // 'tt_log',
102       'tt_invoices',
103       'tt_user_project_binds',
104       'tt_users',
105       'tt_clients',
106       'tt_projects',
107       'tt_tasks',
108       'tt_roles'
109     );
110     foreach($tables_to_mark_deleted_in as $table) {
111       if (!ttAdmin::markGroupDeletedInTable($group_id, $table))
112         return false;
113     }
114
115     // Mark group deleted.
116     global $user;
117     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
118     $sql = "update tt_groups set status = null $modified_part where id = $group_id";
119     $affected = $mdb2->exec($sql);
120     if (is_a($affected, 'PEAR_Error')) return false;
121
122     return true;
123   }
124
125   // updateGroup updates a (top) group with new information.
126   static function updateGroup($fields) {
127     $group_id = (int)$fields['group_id'];
128     if (!$group_id) return false; // Nothing to update.
129
130     $mdb2 = getConnection();
131     global $user;
132     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
133
134     // Update group name if it changed.
135     if ($fields['old_group_name'] != $fields['new_group_name']) {
136       $name_part = 'name = '.$mdb2->quote($fields['new_group_name']);
137       $sql = 'update tt_groups set '.$name_part.$modified_part.' where id = '.$group_id;
138       $affected = $mdb2->exec($sql);
139       if (is_a($affected, 'PEAR_Error')) return false;
140     }
141
142     // Update group manager.
143     $user_id = $fields['user_id'];
144     $login_part = 'login = '.$mdb2->quote($fields['new_login']);
145     if ($fields['password1'])
146       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
147     $name_part = ', name = '.$mdb2->quote($fields['user_name']);
148     $email_part = ', email = '.$mdb2->quote($fields['email']);
149     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.' where id = '.$user_id;
150     $affected = $mdb2->exec($sql);
151     if (is_a($affected, 'PEAR_Error')) return false;
152
153     return true;
154   }
155
156   // updateSelf updates admin account with new information.
157   static function updateSelf($fields) {
158     global $user;
159     $mdb2 = getConnection();
160
161     // Update self.
162     $user_id = $user->id;
163     $login_part = 'login = '.$mdb2->quote($fields['login']);
164     if ($fields['password1'])
165       $password_part = ', password = md5('.$mdb2->quote($fields['password1']).')';
166     $name_part = ', name = '.$mdb2->quote($fields['name']);
167     $email_part = ', email = '.$mdb2->quote($fields['email']);
168     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
169     $sql = 'update tt_users set '.$login_part.$password_part.$name_part.$email_part.$modified_part.' where id = '.$user_id;
170     $affected = $mdb2->exec($sql);
171     return (!is_a($affected, 'PEAR_Error'));
172   }
173
174   // getGroupName obtains group name.
175   static function getGroupName($group_id) {
176     $result = array();
177     $mdb2 = getConnection();
178
179     $sql = "select name from tt_groups where id = $group_id";
180
181     $res = $mdb2->query($sql);
182     if (!is_a($res, 'PEAR_Error')) {
183       $val = $res->fetchRow();
184       return $val['name'];
185     }
186
187     return false;
188   }
189
190   // getOrgDetails obtains group name and its top manager details.
191   static function getOrgDetails($group_id) {
192     $mdb2 = getConnection();
193
194     // Note: current code works with properly set top manager (rank 512).
195     // However, we now allow export and import of subgroups, which seems to work well.
196     // In this situation, imported role is no longer "Top manager", and this call fails.
197     // Setting role id manually in database for top user to Top manager resolves the issue.
198     //
199     // TODO: assess whether it is safe / reasonable to promote role during export or import.
200     // The problem is that user having 'export_data' right is not necessarily top user.
201     // And if we do it by rank, what to do for multiple managers situation? First found?
202     // Leaving to manual fixing for now.
203     $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".
204       " from tt_groups g".
205       " inner join tt_users u on (u.group_id = g.id)".
206       " inner join tt_roles r on (r.id = u.role_id and r.rank = 512)". // Fails for partially imported org. See comment above.
207       " where g.id = $group_id";
208
209     $res = $mdb2->query($sql);
210     if (!is_a($res, 'PEAR_Error')) {
211       $val = $res->fetchRow();
212       return $val;
213     }
214
215     return false;
216   }
217
218  // getOrg obtains org_id for group.
219   static function getOrg($group_id) {
220     $mdb2 = getConnection();
221
222     $sql = "select org_id from tt_groups where id = $group_id";
223     $res = $mdb2->query($sql);
224     if (!is_a($res, 'PEAR_Error')) {
225       $val = $res->fetchRow();
226       return $val;
227     }
228
229     return false;
230   }
231
232   // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
233   // It deletes entries in ONE table belonging to a given group.
234   static function deleteGroupEntriesFromTable($group_id, $table_name) {
235     $mdb2 = getConnection();
236
237     $sql = "delete from $table_name where group_id = $group_id";
238     $affected = $mdb2->exec($sql);
239     return (!is_a($affected, 'PEAR_Error'));
240   }
241
242   // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
243   // It updates ONE table by setting status to NULL for all records belonging to a group.
244   static function markGroupDeletedInTable($group_id, $table_name) {
245     $mdb2 = getConnection();
246
247     // Add modified info to sql for some tables, depending on table name.
248     if ($table_name == 'tt_users') {
249       global $user;
250       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
251     }
252
253     $sql = "update $table_name set status = null $modified_part where group_id = $group_id";
254     $affected = $mdb2->exec($sql);
255     return (!is_a($affected, 'PEAR_Error'));
256   }
257
258   // createGroup creates a new top group and returns its id.
259   // It is a helper function for createOrg.
260   static function createGroup($fields) {
261     global $user;
262     $mdb2 = getConnection();
263
264     $group_key = $mdb2->quote(ttRandomString());
265     $name = $mdb2->quote($fields['group_name']);
266     $currency = $mdb2->quote($fields['currency']);
267     $lang = $mdb2->quote($fields['lang']);
268     $created = 'now()';
269     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
270     $created_by = $user->id;
271
272     $sql = "insert into tt_groups (group_key, name, currency, lang, created, created_ip, created_by)".
273       " values($group_key, $name, $currency, $lang, $created, $created_ip, $created_by)";
274     $affected = $mdb2->exec($sql);
275     if (is_a($affected, 'PEAR_Error')) return false;
276
277     $group_id = $mdb2->lastInsertID('tt_groups', 'id');
278
279     // Update org_id with group_id.
280     $sql = "update tt_groups set org_id = $group_id where org_id is NULL and id = $group_id";
281     $affected = $mdb2->exec($sql);
282     if (is_a($affected, 'PEAR_Error')) return false;
283
284     return $group_id;
285   }
286
287   // createOrgManager creates a new user (top manager role) in a group.
288   // It is a helper function for createOrg.
289   static function createOrgManager($fields) {
290     global $user;
291     $mdb2 = getConnection();
292
293     $role_id = ttRoleHelper::getTopManagerRoleID();
294     $login = $mdb2->quote($fields['login']);
295     $password = 'md5('.$mdb2->quote($fields['password']).')';
296     $name = $mdb2->quote($fields['user_name']);
297     $group_id = (int) $fields['group_id'];
298     $org_id = $group_id;
299     $email = $mdb2->quote($fields['email']);
300     $created = 'now()';
301     $created_ip = $mdb2->quote($_SERVER['REMOTE_ADDR']);
302     $created_by = $user->id;
303
304     $columns = '(login, password, name, group_id, org_id, role_id, email, created, created_ip, created_by)';
305     $values = "values($login, $password, $name, $group_id, $org_id, $role_id, $email, $created, $created_ip, $created_by)";
306
307     $sql = "insert into tt_users $columns $values";
308     $affected = $mdb2->exec($sql);
309     return (!is_a($affected, 'PEAR_Error'));
310   }
311
312   // The createOrg function creates an organization in Time Tracker.
313   static function createOrg($fields) {
314     // There are 3 steps that we need to 2 when creating a new organization.
315     //   1. Create a new group with null parent_id.
316     //   2. Create pre-defined roles in it.
317     //   3. Create a top manager account for new group.
318
319     // Create a new group.
320     $group_id = ttAdmin::createGroup($fields);
321     if (!$group_id) return false;
322
323     // Create predefined roles.
324     if (!ttRoleHelper::createPredefinedRoles($group_id, $fields['lang']))
325       return false;
326
327     // Create user.
328     $fields['group_id'] = $group_id;
329     if (!ttAdmin::createOrgManager($fields))
330       return false;
331
332     return true;
333   }
334
335   // deleteGroupFiles deletes files attached to all entities in the entire group.
336   // Note that it is a permanent delete, not "mark deleted" by design.
337   static function deleteGroupFiles($group_id) {
338
339     $org = ttAdmin::getOrg($group_id);
340     $org_id = $org['org_id'];
341
342     // Delete all group files from the database.
343     $mdb2 = getConnection();
344     $sql = "delete from tt_files where org_id = $org_id and group_id = $group_id";
345     $affected = $mdb2->exec($sql);
346     if (is_a($affected, 'PEAR_Error'))
347       return false;
348
349     if ($affected == 0) return true; // Do not call file storage utility.
350
351     // Try to make a call to file storage facility.
352     if (!defined('FILE_STORAGE_URI')) return true; // Nothing to do.
353
354     $deletegroupfiles_uri = FILE_STORAGE_URI.'deletegroupfiles';
355
356     // Obtain site id.
357     $sql = "select param_value as site_id from tt_site_config where param_name = 'locker_id'";
358     $res = $mdb2->query($sql);
359     $val = $res->fetchRow();
360     $site_id = $val['site_id'];
361     if (!$site_id) return true; // Nothing to do.
362
363     // Obtain site key.
364     $sql = "select param_value as site_key from tt_site_config where param_name = 'locker_key'";
365     $res = $mdb2->query($sql);
366     $val = $res->fetchRow();
367     $site_key = $val['site_key'];
368     if (!$site_key) return true; // Can't continue without site key.
369
370     // Obtain org key.
371     $sql = "select group_key as org_key from tt_groups where id = $org_id";
372     $res = $mdb2->query($sql);
373     $val = $res->fetchRow();
374     $org_key = $val['org_key'];
375     if (!$org_key) return true; // Can't continue without org key.
376
377     // Obtain group key.
378     $sql = "select group_key as group_key from tt_groups where id = $group_id";
379     $res = $mdb2->query($sql);
380     $val = $res->fetchRow();
381     $group_key = $val['group_key'];
382     if (!$group_key) return true; // Can't continue without group key.
383
384     $curl_fields = array('site_id' => $site_id,
385       'site_key' => $site_key,
386       'org_id' => $org_id,
387       'org_key' => $org_key,
388       'group_id' => $group_id,
389       'group_key' => $group_key);
390
391     // url-ify the data for the POST.
392     foreach($curl_fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
393     $fields_string = rtrim($fields_string, '&');
394
395     // Open connection.
396     $ch = curl_init();
397
398     // Set the url, number of POST vars, POST data.
399     curl_setopt($ch, CURLOPT_URL, $deletegroupfiles_uri);
400     curl_setopt($ch, CURLOPT_POST, true);
401     curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
402     curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
403
404     // Execute a post request.
405     $result = curl_exec($ch);
406
407     // Close connection.
408     curl_close($ch);
409
410     // Many things can go wrong with a remote call to file storage facility.
411     // By design, we ignore such errors.
412     return true;
413   }
414 }