Added group key to creating subgroups.
[timetracker.git] / WEB-INF / lib / ttGroupHelper.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 // Class ttGroupHelper - contains helper functions that operate with groups.
32 // This is a planned replacement for ttTeamHelper as we move forward with subgroups.
33 class ttGroupHelper {
34
35   // The getGroupName function returns group name.
36   static function getGroupName($group_id) {
37     $mdb2 = getConnection();
38
39     $sql = "select name from tt_groups where id = $group_id and (status = 1 or status = 0)";
40     $res = $mdb2->query($sql);
41
42     if (!is_a($res, 'PEAR_Error')) {
43       $val = $res->fetchRow();
44       return $val['name'];
45     }
46     return false;
47   }
48
49   // The getParentGroup determines a parent group for a given group.
50   static function getParentGroup($group_id) {
51     global $user;
52
53     $mdb2 = getConnection();
54
55     $sql = "select parent_id from tt_groups where id = $group_id and org_id = $user->org_id and status = 1";
56     $res = $mdb2->query($sql);
57
58     if (!is_a($res, 'PEAR_Error')) {
59       $val = $res->fetchRow();
60       return $val['parent_id'];
61     }
62     return false;
63   }
64
65   // The getSubgroupByName obtain an immediate subgroup by name if one exists.
66   static function getSubgroupByName($name) {
67     global $user;
68
69     $mdb2 = getConnection();
70     $parent_id = $user->getGroup();
71     $org_id = $user->org_id;
72
73     $sql = "select id from tt_groups where parent_id = $parent_id and org_id = $org_id".
74       " and name = ".$mdb2->quote($name)." and status is not null";
75     $res = $mdb2->query($sql);
76     if (!is_a($res, 'PEAR_Error')) {
77       $val = $res->fetchRow();
78       if ($val && $val['id'])
79         return $val;
80     }
81     return false;
82   }
83
84   // The insertSubgroup inserts a new subgroup in database.
85   static function insertSubgroup($fields) {
86     global $user;
87
88     $mdb2 = getConnection();
89     $parent_id = $user->getGroup();
90     $org_id = $user->org_id;
91     $group_key = ttRandomString();
92     $name = $fields['name'];
93     $description = $fields['description'];
94
95     // We need to inherit attributes from the parent group.
96     $attrs = ttGroupHelper::getGroupAttrs($parent_id);
97
98     $columns = '(parent_id, org_id, group_key, name, description, currency, decimal_mark, lang, date_format,'.
99       ' time_format, week_start, tracking_mode, project_required, task_required, record_type, bcc_email,'.
100       ' allow_ip, password_complexity, plugins, lock_spec,'.
101       ' workday_minutes, config, created, created_ip, created_by)';
102
103     $values = " values ($parent_id, $org_id";
104     $values .= ', '.$mdb2->quote($group_key);
105     $values .= ', '.$mdb2->quote($name);
106     $values .= ', '.$mdb2->quote($description);
107     $values .= ', '.$mdb2->quote($attrs['currency']);
108     $values .= ', '.$mdb2->quote($attrs['decimal_mark']);
109     $values .= ', '.$mdb2->quote($attrs['lang']);
110     $values .= ', '.$mdb2->quote($attrs['date_format']);
111     $values .= ', '.$mdb2->quote($attrs['time_format']);
112     $values .= ', '.(int)$attrs['week_start'];
113     $values .= ', '.(int)$attrs['tracking_mode'];
114     $values .= ', '.(int)$attrs['project_required'];
115     $values .= ', '.(int)$attrs['task_required'];
116     $values .= ', '.(int)$attrs['record_type'];
117     $values .= ', '.$mdb2->quote($attrs['bcc_email']);
118     $values .= ', '.$mdb2->quote($attrs['allow_ip']);
119     $values .= ', '.$mdb2->quote($attrs['password_complexity']);
120     $values .= ', '.$mdb2->quote($attrs['plugins']);
121     $values .= ', '.$mdb2->quote($attrs['lock_spec']);
122     $values .= ', '.(int)$attrs['workday_minutes'];
123     $values .= ', '.$mdb2->quote($attrs['config']);
124     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
125     $values .= ')';
126
127     $sql = 'insert into tt_groups '.$columns.$values;
128     $affected = $mdb2->exec($sql);
129     if (is_a($affected, 'PEAR_Error')) return false;
130
131     $subgroup_id = $mdb2->lastInsertID('tt_groups', 'id');
132
133     // Copy roles from the parent group to child group.
134     if (!ttRoleHelper::copyRolesToGroup($subgroup_id))
135       return false;
136     
137     return $subgroup_id;
138   }
139
140   // markGroupDeleted marks a group and everything in it as deleted.
141   // This function is called in context of a logged on user (global $user object).
142   // It uses current user attributes for access checks and in sql queries.
143   // Compare this with admin:
144   //   admin can delete any group.
145   //   user can delete only relevant groups and only if allowed.
146   static function markGroupDeleted($group_id) {
147     global $user;
148
149     $mdb2 = getConnection();
150     $org_id = $user->org_id;
151
152     // Security check.
153     if (!$user->isGroupValid($group_id))
154       return false;
155
156     // Keep the logic simple by returning false on first error.
157
158     // Obtain subgroups and call self recursively on them.
159     $subgroups = $user->getSubgroups($group_id);
160     foreach($subgroups as $subgroup) {
161       if (!ttGroupHelper::markGroupDeleted($subgroup['id']))
162         return false;
163     }
164
165     // Now do actual work with all entities.
166
167     // Some things cannot be marked deleted as we don't have the status field for them.
168     // Just delete such things (until we have a better way to deal with them).
169     $tables_to_delete_from = array(
170       'tt_config',
171       'tt_predefined_expenses',
172       'tt_client_project_binds',
173       'tt_project_task_binds'
174     );
175     foreach($tables_to_delete_from as $table) {
176       if (!ttGroupHelper::deleteGroupEntriesFromTable($group_id, $table))
177         return false;
178     }
179
180     // Now mark status deleted where we can.
181     // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
182     // Reasoning is:
183     //
184     // 1) Users may mark some of them deleted during their work.
185     // If we mark all of them deleted here, we can't recover nicely
186     // as we'll lose track of what was accidentally deleted by user.
187     //
188     // 2) DB maintenance script (Clean up DB from inactive groups) should
189     // get rid of these items permanently eventually.
190     $tables_to_mark_deleted_in = array(
191       'tt_cron',
192       'tt_fav_reports',
193       // 'tt_expense_items',
194       // 'tt_custom_field_log',
195       'tt_custom_field_options',
196       'tt_custom_fields',
197       // 'tt_log',
198       'tt_invoices',
199       'tt_user_project_binds',
200       'tt_users',
201       'tt_clients',
202       'tt_projects',
203       'tt_tasks',
204       'tt_roles'
205     );
206     foreach($tables_to_mark_deleted_in as $table) {
207       if (!ttGroupHelper::markGroupDeletedInTable($group_id, $table))
208         return false;
209     }
210
211     // Mark group deleted.
212     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
213     $sql = "update tt_groups set status = null $modified_part where id = $group_id and org_id = $org_id";
214     $affected = $mdb2->exec($sql);
215     if (is_a($affected, 'PEAR_Error')) return false;
216
217     return true;
218   }
219
220   // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
221   // It updates ONE table by setting status to NULL for all records belonging to a group.
222   static function markGroupDeletedInTable($group_id, $table_name) {
223     global $user;
224     $mdb2 = getConnection();
225
226     // Add modified info to sql for some tables, depending on table name.
227     if ($table_name == 'tt_users') {
228       $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
229     }
230
231     $org_id = $user->org_id; // The only security measure we use here for match.
232     $sql = "update $table_name set status = null $modified_part where group_id = $group_id and org_id = $org_id";
233     $affected = $mdb2->exec($sql);
234     return (!is_a($affected, 'PEAR_Error'));
235   }
236
237   // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
238   // It deletes entries in ONE table belonging to a given group.
239   static function deleteGroupEntriesFromTable($group_id, $table_name) {
240     global $user;
241     $mdb2 = getConnection();
242
243     $org_id = $user->org_id; // The only security measure we use here for match.
244     $sql = "delete from $table_name where group_id = $group_id and org_id = $org_id";
245     $affected = $mdb2->exec($sql);
246     return (!is_a($affected, 'PEAR_Error'));
247   }
248
249   // getGroupAttrs obtains all group attributes.
250   static function getGroupAttrs($group_id) {
251     global $user;
252     $mdb2 = getConnection();
253
254     $sql =  "select * from tt_groups".
255             " where status = 1 and id = $group_id and org_id = $user->org_id";
256     $res = $mdb2->query($sql);
257     if (!is_a($res, 'PEAR_Error')) {
258       $val = $res->fetchRow();
259     }
260     return $val;
261   }
262
263   // getRoles obtains all active and inactive roles in current group.
264   static function getRoles() {
265     global $user;
266     $mdb2 = getConnection();
267
268     $group_id = $user->getGroup();
269     $org_id = $user->org_id;
270     $sql =  "select * from tt_roles".
271       " where group_id = $group_id and org_id = $org_id and status is not null";
272     $res = $mdb2->query($sql);
273     if (is_a($res, 'PEAR_Error')) return false;
274     while ($val = $res->fetchRow()) {
275       $roles[] = $val;
276     }
277     return $roles;
278   }
279
280   // The getActiveClients returns an array of active clients for a group.
281   static function getActiveClients($all_fields = false)
282   {
283     global $user;
284     $mdb2 = getConnection();
285
286     $group_id = $user->getGroup();
287     $org_id = $user->org_id;
288     if ($all_fields)
289       $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
290     else
291       $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
292
293     $res = $mdb2->query($sql);
294     $result = array();
295     if (!is_a($res, 'PEAR_Error')) {
296       while ($val = $res->fetchRow()) {
297         $result[] = $val;
298       }
299     }
300     return $result;
301   }
302
303   // The getInactiveClients returns an array of inactive clients for a group.
304   static function getInactiveClients($all_fields = false)
305   {
306     global $user;
307     $mdb2 = getConnection();
308
309     $group_id = $user->getGroup();
310     $org_id = $user->org_id;
311     if ($all_fields)
312       $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
313     else
314       $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
315
316     $res = $mdb2->query($sql);
317     $result = array();
318     if (!is_a($res, 'PEAR_Error')) {
319       while ($val = $res->fetchRow()) {
320         $result[] = $val;
321       }
322     }
323     return $result;
324   }
325
326   // getActiveProjects - returns an array of active projects for a group.
327   static function getActiveProjects()
328   {
329     global $user;
330     $mdb2 = getConnection();
331
332     $group_id = $user->getGroup();
333     $org_id = $user->org_id;
334
335     $sql = "select id, name, description, tasks from tt_projects".
336       " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
337     $res = $mdb2->query($sql);
338     $result = array();
339     if (!is_a($res, 'PEAR_Error')) {
340       while ($val = $res->fetchRow()) {
341         $result[] = $val;
342       }
343     }
344     return $result;
345   }
346
347   // getInactiveProjects - returns an array of inactive projects for a group.
348   static function getInactiveProjects()
349   {
350     global $user;
351     $mdb2 = getConnection();
352
353     $group_id = $user->getGroup();
354     $org_id = $user->org_id;
355
356     $sql = "select id, name, description, tasks from tt_projects".
357       "  where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
358     $res = $mdb2->query($sql);
359     $result = array();
360     if (!is_a($res, 'PEAR_Error')) {
361       while ($val = $res->fetchRow()) {
362         $result[] = $val;
363       }
364     }
365     return $result;
366   }
367
368   // getPredefinedExpenses - obtains predefined expenses for a group.
369   static function getPredefinedExpenses() {
370     global $user;
371     $mdb2 = getConnection();
372
373     $group_id = $user->getGroup();
374     $org_id = $user->org_id;
375
376     $result = array();
377     $sql = "select id, name, cost from tt_predefined_expenses".
378       " where group_id = $group_id and org_id = $org_id";
379     $res = $mdb2->query($sql);
380     $result = array();
381     if (!is_a($res, 'PEAR_Error')) {
382       $decimal_mark = $user->getDecimalMark();
383       $replaceDecimalMark = ('.' != $decimal_mark);
384
385       while ($val = $res->fetchRow()) {
386         if ($replaceDecimalMark)
387           $val['cost'] = str_replace('.', $decimal_mark, $val['cost']);
388         $result[] = $val;
389       }
390       return $result;
391     }
392     return false;
393   }
394
395   // The getActiveInvoices returns an array of active invoices for a group.
396   static function getActiveInvoices()
397   {
398     global $user;
399     $mdb2 = getConnection();
400
401     $group_id = $user->getGroup();
402     $org_id = $user->org_id;
403
404     $addPaidStatus = $user->isPluginEnabled('ps');
405     $result = array();
406
407     if ($user->isClient())
408       $client_part = "and i.client_id = $user->client_id";
409
410     $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i".
411       " left join tt_clients c on (c.id = i.client_id)".
412       " where i.status = 1 and i.group_id = $group_id and i.org_id = $org_id $client_part order by i.name";
413     $res = $mdb2->query($sql);
414     $result = array();
415     if (!is_a($res, 'PEAR_Error')) {
416       $dt = new DateAndTime(DB_DATEFORMAT);
417       while ($val = $res->fetchRow()) {
418         // Localize date.
419         $dt->parseVal($val['date']);
420         $val['date'] = $dt->toString($user->getDateFormat());
421         if ($addPaidStatus)
422           $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
423         $result[] = $val;
424       }
425     }
426     return $result;
427   }
428
429   // getNotifications - obtains notification descriptions for a group.
430   static function getNotifications() {
431     global $user;
432     $mdb2 = getConnection();
433
434     $group_id = $user->getGroup();
435     $org_id = $user->org_id;
436
437     $result = array();
438     $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c".
439       " left join tt_fav_reports fr on (fr.id = c.report_id)".
440       " where c.group_id = $group_id and c.org_id = $org_id and c.status = 1 and fr.status = 1";
441     $res = $mdb2->query($sql);
442     $result = array();
443     if (!is_a($res, 'PEAR_Error')) {
444       while ($val = $res->fetchRow()) {
445         $result[] = $val;
446       }
447       return $result;
448     }
449     return false;
450   }
451
452   // The getActiveUsers obtains all active users excluding clients in a given group.
453   static function getActiveUsers($options = null) {
454     global $user;
455     global $i18n;
456     $mdb2 = getConnection();
457
458     $group_id = $user->getGroup();
459     $org_id = $user->org_id;
460
461     $client_part = " and u.client_id is null";
462
463     if (isset($options['getAllFields']))
464       $sql = "select u.*, r.name as role_name, r.rank from tt_users u left join tt_roles r on (u.role_id = r.id) where u.group_id = $group_id and u.org_id = $org_id and u.status = 1 $client_part order by upper(u.name)";
465     else
466       $sql = "select u.id, u.name from tt_users u where u.group_id = $group_id and u.org_id = $org_id and u.status = 1 $client_part order by upper(u.name)";
467     $res = $mdb2->query($sql);
468     $user_list = array();
469     if (is_a($res, 'PEAR_Error'))
470       return false;
471     while ($val = $res->fetchRow()) {
472       // Localize top manager role name, as it is not localized in db.
473       if ($val['rank'] == 512)
474         $val['role_name'] = $i18n->get('role.top_manager.label');
475       $user_list[] = $val;
476     }
477
478     return $user_list;
479   }
480
481   // getActiveTasks - returns an array of active tasks for a group.
482   static function getActiveTasks()
483   {
484     global $user;
485     $mdb2 = getConnection();
486
487     $group_id = $user->getGroup();
488     $org_id = $user->org_id;
489
490     $sql = "select id, name, description from tt_tasks".
491       " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
492     $res = $mdb2->query($sql);
493     $result = array();
494     if (!is_a($res, 'PEAR_Error')) {
495       while ($val = $res->fetchRow()) {
496         $result[] = $val;
497       }
498     }
499     return $result;
500   }
501
502   // getInactiveTasks - returns an array of inactive tasks for a group.
503   static function getInactiveTasks()
504   {
505     global $user;
506     $mdb2 = getConnection();
507
508     $group_id = $user->getGroup();
509     $org_id = $user->org_id;
510
511     $sql = "select id, name, description from tt_tasks".
512       " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
513     $res = $mdb2->query($sql);
514     $result = array();
515     if (!is_a($res, 'PEAR_Error')) {
516       while ($val = $res->fetchRow()) {
517         $result[] = $val;
518       }
519     }
520     return $result;
521   }
522
523   // getActiveTemplates - returns an array of active templates for a group.
524   static function getActiveTemplates()
525   {
526     global $user;
527     $mdb2 = getConnection();
528
529     $group_id = $user->getGroup();
530     $org_id = $user->org_id;
531
532     $sql = "select id, name, description, content from tt_templates".
533       " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
534     $res = $mdb2->query($sql);
535     $result = array();
536     if (!is_a($res, 'PEAR_Error')) {
537       while ($val = $res->fetchRow()) {
538         $result[] = $val;
539       }
540     }
541     return $result;
542   }
543
544   // getInactiveTemplates - returns an array of active templates for a group.
545   static function getInactiveTemplates()
546   {
547     global $user;
548     $mdb2 = getConnection();
549
550     $group_id = $user->getGroup();
551     $org_id = $user->org_id;
552
553     $sql = "select id, name, description from tt_templates".
554       " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
555     $res = $mdb2->query($sql);
556     $result = array();
557     if (!is_a($res, 'PEAR_Error')) {
558       while ($val = $res->fetchRow()) {
559         $result[] = $val;
560       }
561     }
562     return $result;
563   }
564
565   // validateCheckboxGroupInput - validates user input in a group of checkboxes
566   // in context of a specific database table.
567   //
568   // We need to make sure that input is a set of unique positive integers, and is
569   // "relevant" to the current group (entities exists in table).
570   //
571   // It is a safeguard against manipulation of data in posts.
572   static function validateCheckboxGroupInput($input, $table) {
573     // Empty input is valid.
574     if (!$input) return true;
575
576     // Input containing duplicates is invalid.
577     if (count($input) !== count(array_unique($input))) return false;
578
579     // Input containing anything but positive integers is invalid.
580     foreach ($input as $single_selection) {
581       if (!is_numeric($single_selection) || $single_selection <= 0) return false;
582     }
583
584     global $user;
585     $mdb2 = getConnection();
586
587     $group_id = $user->getGroup();
588     $org_id = $user->org_id;
589
590     // Now check the table. It must contain all entities associated with current group and org.
591     $comma_separated = implode(',', $input);
592     $sql = "select count(*) as item_count from $table".
593       " where id in ($comma_separated) and group_id = $group_id and org_id = $org_id and status = 1";
594     $res = $mdb2->query($sql);
595     if (is_a($res, 'PEAR_Error')) return false;
596     $val = $res->fetchRow();
597     if (count($input) != $val['item_count'])
598       return false; // Number of entities in table is different.
599
600     return true; // All is good.
601   }
602
603   // The getUsers obtains all active and inactive (but not deleted) users in a group.
604   static function getUsers() {
605     global $user;
606     $mdb2 = getConnection();
607
608     $group_id = $user->getGroup();
609     $org_id = $user->org_id;
610
611     $sql = "select id, name from tt_users where group_id = $group_id and org_id = $org_id and (status = 1 or status = 0) order by upper(name)";
612     $res = $mdb2->query($sql);
613     $user_list = array();
614     if (is_a($res, 'PEAR_Error'))
615       return false;
616     while ($val = $res->fetchRow()) {
617       $user_list[] = $val;
618     }
619     return $user_list;
620   }
621
622   // The getUsersForClient obtains all active and inactive users in a group that are relevant to a client.
623   static function getUsersForClient() {
624     global $user;
625     $mdb2 = getConnection();
626
627     $group_id = $user->getGroup();
628     $org_id = $user->org_id;
629
630     $sql = "select u.id, u.name from tt_user_project_binds upb".
631       " inner join tt_client_project_binds cpb on (upb.project_id = cpb.project_id and cpb.client_id = $user->client_id)".
632       " inner join tt_users u on (u.id = upb.user_id and u.group_id = $group_id and u.org_id = $org_id)".
633       " where (u.status = 1 or u.status = 0)".
634       " group by u.id".
635       " order by upper(u.name)";
636     $res = $mdb2->query($sql);
637     $user_list = array();
638     if (is_a($res, 'PEAR_Error'))
639       return false;
640     while ($val = $res->fetchRow()) {
641       $user_list[] = $val;
642     }
643     return $user_list;
644   }
645
646   // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
647   static function getRecentInvoices($client_id) {
648     global $user;
649     $mdb2 = getConnection();
650
651     $group_id = $user->getGroup();
652     $org_id = $user->org_id;
653
654     $sql = "select i.id, i.name from tt_invoices i".
655       " left join tt_clients c on (c.id = i.client_id)".
656       " where i.group_id = $group_id and i.org_id = $org_id and i.status = 1 and c.id = $client_id".
657       " order by i.id desc limit 3";
658     $res = $mdb2->query($sql);
659     $result = array();
660     if (!is_a($res, 'PEAR_Error')) {
661       $dt = new DateAndTime(DB_DATEFORMAT);
662       while ($val = $res->fetchRow()) {
663         $result[] = $val;
664       }
665     }
666     return $result;
667   }
668 }