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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('ttRoleHelper');
31 // Class ttGroupHelper - contains helper functions that operate with groups.
32 // This is a planned replacement for ttTeamHelper as we move forward with subgroups.
35 // The getGroupName function returns group name.
36 static function getGroupName($group_id) {
37 $mdb2 = getConnection();
39 $sql = "select name from tt_groups where id = $group_id and (status = 1 or status = 0)";
40 $res = $mdb2->query($sql);
42 if (!is_a($res, 'PEAR_Error')) {
43 $val = $res->fetchRow();
49 // The getParentGroup determines a parent group for a given group.
50 static function getParentGroup($group_id) {
53 $mdb2 = getConnection();
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);
58 if (!is_a($res, 'PEAR_Error')) {
59 $val = $res->fetchRow();
60 return $val['parent_id'];
65 // The getSubgroupByName obtain an immediate subgroup by name if one exists.
66 static function getSubgroupByName($name) {
69 $mdb2 = getConnection();
70 $parent_id = $user->getGroup();
71 $org_id = $user->org_id;
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'])
84 // The insertSubgroup inserts a new subgroup in database.
85 static function insertSubgroup($fields) {
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'];
95 // We need to inherit attributes from the parent group.
96 $attrs = ttGroupHelper::getGroupAttrs($parent_id);
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)';
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;
127 $sql = 'insert into tt_groups '.$columns.$values;
128 $affected = $mdb2->exec($sql);
129 if (is_a($affected, 'PEAR_Error')) return false;
131 $subgroup_id = $mdb2->lastInsertID('tt_groups', 'id');
133 // Copy roles from the parent group to child group.
134 if (!ttRoleHelper::copyRolesToGroup($subgroup_id))
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) {
149 $mdb2 = getConnection();
150 $org_id = $user->org_id;
153 if (!$user->isGroupValid($group_id))
156 // Keep the logic simple by returning false on first error.
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']))
165 // Now do actual work with all entities.
167 // Delete group files.
168 ttGroupHelper::deleteGroupFiles($group_id);
170 // Some things cannot be marked deleted as we don't have the status field for them.
171 // Just delete such things (until we have a better way to deal with them).
172 $tables_to_delete_from = array(
174 'tt_predefined_expenses',
175 'tt_client_project_binds',
176 'tt_project_task_binds'
178 foreach($tables_to_delete_from as $table) {
179 if (!ttGroupHelper::deleteGroupEntriesFromTable($group_id, $table))
183 // Now mark status deleted where we can.
184 // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
187 // 1) Users may mark some of them deleted during their work.
188 // If we mark all of them deleted here, we can't recover nicely
189 // as we'll lose track of what was accidentally deleted by user.
191 // 2) DB maintenance script (Clean up DB from inactive groups) should
192 // get rid of these items permanently eventually.
193 $tables_to_mark_deleted_in = array(
196 // 'tt_expense_items',
197 // 'tt_custom_field_log',
198 'tt_custom_field_options',
202 'tt_user_project_binds',
209 foreach($tables_to_mark_deleted_in as $table) {
210 if (!ttGroupHelper::markGroupDeletedInTable($group_id, $table))
214 // Mark group deleted.
215 $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
216 $sql = "update tt_groups set status = null $modified_part where id = $group_id and org_id = $org_id";
217 $affected = $mdb2->exec($sql);
218 if (is_a($affected, 'PEAR_Error')) return false;
223 // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
224 // It updates ONE table by setting status to NULL for all records belonging to a group.
225 static function markGroupDeletedInTable($group_id, $table_name) {
227 $mdb2 = getConnection();
229 // Add modified info to sql for some tables, depending on table name.
230 if ($table_name == 'tt_users') {
231 $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
234 $org_id = $user->org_id; // The only security measure we use here for match.
235 $sql = "update $table_name set status = null $modified_part where group_id = $group_id and org_id = $org_id";
236 $affected = $mdb2->exec($sql);
237 return (!is_a($affected, 'PEAR_Error'));
240 // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
241 // It deletes entries in ONE table belonging to a given group.
242 static function deleteGroupEntriesFromTable($group_id, $table_name) {
244 $mdb2 = getConnection();
246 $org_id = $user->org_id; // The only security measure we use here for match.
247 $sql = "delete from $table_name where group_id = $group_id and org_id = $org_id";
248 $affected = $mdb2->exec($sql);
249 return (!is_a($affected, 'PEAR_Error'));
252 // getGroupAttrs obtains all group attributes.
253 static function getGroupAttrs($group_id) {
255 $mdb2 = getConnection();
257 $sql = "select * from tt_groups".
258 " where status = 1 and id = $group_id and org_id = $user->org_id";
259 $res = $mdb2->query($sql);
260 if (!is_a($res, 'PEAR_Error')) {
261 $val = $res->fetchRow();
266 // getRoles obtains all active and inactive roles in current group.
267 static function getRoles() {
269 $mdb2 = getConnection();
271 $group_id = $user->getGroup();
272 $org_id = $user->org_id;
273 $sql = "select * from tt_roles".
274 " where group_id = $group_id and org_id = $org_id and status is not null";
275 $res = $mdb2->query($sql);
276 if (is_a($res, 'PEAR_Error')) return false;
277 while ($val = $res->fetchRow()) {
283 // The getActiveClients returns an array of active clients for a group.
284 static function getActiveClients($all_fields = false)
287 $mdb2 = getConnection();
289 $group_id = $user->getGroup();
290 $org_id = $user->org_id;
292 $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
294 $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
296 $res = $mdb2->query($sql);
298 if (!is_a($res, 'PEAR_Error')) {
299 while ($val = $res->fetchRow()) {
306 // The getInactiveClients returns an array of inactive clients for a group.
307 static function getInactiveClients($all_fields = false)
310 $mdb2 = getConnection();
312 $group_id = $user->getGroup();
313 $org_id = $user->org_id;
315 $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
317 $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
319 $res = $mdb2->query($sql);
321 if (!is_a($res, 'PEAR_Error')) {
322 while ($val = $res->fetchRow()) {
329 // getActiveProjects - returns an array of active projects for a group.
330 static function getActiveProjects($includeFiles = false)
333 $mdb2 = getConnection();
335 $group_id = $user->getGroup();
336 $org_id = $user->org_id;
339 $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
340 $fileJoin = " left join (select distinct entity_id from tt_files".
341 " where entity_type = 'project' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
342 " on (p.id = Sub1.entity_id)";
345 $sql = "select p.id, p.name, p.description, p.tasks $filePart from tt_projects p $fileJoin".
346 " where p.group_id = $group_id and p.org_id = $org_id and p.status = 1 order by upper(p.name)";
347 $res = $mdb2->query($sql);
349 if (!is_a($res, 'PEAR_Error')) {
350 while ($val = $res->fetchRow()) {
357 // getInactiveProjects - returns an array of inactive projects for a group.
358 static function getInactiveProjects($includeFiles = false)
361 $mdb2 = getConnection();
363 $group_id = $user->getGroup();
364 $org_id = $user->org_id;
367 $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
368 $fileJoin = " left join (select distinct entity_id from tt_files".
369 " where entity_type = 'project' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
370 " on (p.id = Sub1.entity_id)";
373 $sql = "select p.id, p.name, p.description, p.tasks $filePart from tt_projects p $fileJoin".
374 " where p.group_id = $group_id and p.org_id = $org_id and p.status = 0 order by upper(p.name)";
375 $res = $mdb2->query($sql);
377 if (!is_a($res, 'PEAR_Error')) {
378 while ($val = $res->fetchRow()) {
385 // getPredefinedExpenses - obtains predefined expenses for a group.
386 static function getPredefinedExpenses() {
388 $mdb2 = getConnection();
390 $group_id = $user->getGroup();
391 $org_id = $user->org_id;
394 $sql = "select id, name, cost from tt_predefined_expenses".
395 " where group_id = $group_id and org_id = $org_id";
396 $res = $mdb2->query($sql);
398 if (!is_a($res, 'PEAR_Error')) {
399 $decimal_mark = $user->getDecimalMark();
400 $replaceDecimalMark = ('.' != $decimal_mark);
402 while ($val = $res->fetchRow()) {
403 if ($replaceDecimalMark)
404 $val['cost'] = str_replace('.', $decimal_mark, $val['cost']);
412 // The getActiveInvoices returns an array of active invoices for a group.
413 static function getActiveInvoices()
416 $mdb2 = getConnection();
418 $group_id = $user->getGroup();
419 $org_id = $user->org_id;
421 $addPaidStatus = $user->isPluginEnabled('ps');
424 if ($user->isClient())
425 $client_part = "and i.client_id = $user->client_id";
427 $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i".
428 " left join tt_clients c on (c.id = i.client_id)".
429 " where i.status = 1 and i.group_id = $group_id and i.org_id = $org_id $client_part order by i.name";
430 $res = $mdb2->query($sql);
432 if (!is_a($res, 'PEAR_Error')) {
433 $dt = new DateAndTime(DB_DATEFORMAT);
434 while ($val = $res->fetchRow()) {
436 $dt->parseVal($val['date']);
437 $val['date'] = $dt->toString($user->getDateFormat());
439 $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
446 // getNotifications - obtains notification descriptions for a group.
447 static function getNotifications() {
449 $mdb2 = getConnection();
451 $group_id = $user->getGroup();
452 $org_id = $user->org_id;
455 $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c".
456 " left join tt_fav_reports fr on (fr.id = c.report_id)".
457 " where c.group_id = $group_id and c.org_id = $org_id and c.status = 1 and fr.status = 1";
458 $res = $mdb2->query($sql);
460 if (!is_a($res, 'PEAR_Error')) {
461 while ($val = $res->fetchRow()) {
469 // The getActiveUsers obtains all active users excluding clients in a given group.
470 static function getActiveUsers($options = null) {
473 $mdb2 = getConnection();
475 $group_id = $user->getGroup();
476 $org_id = $user->org_id;
478 $client_part = " and u.client_id is null";
480 if (isset($options['getAllFields']))
481 $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)";
483 $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)";
484 $res = $mdb2->query($sql);
485 $user_list = array();
486 if (is_a($res, 'PEAR_Error'))
488 while ($val = $res->fetchRow()) {
489 // Localize top manager role name, as it is not localized in db.
490 if ($val['rank'] == 512)
491 $val['role_name'] = $i18n->get('role.top_manager.label');
498 // getActiveTasks - returns an array of active tasks for a group.
499 static function getActiveTasks()
502 $mdb2 = getConnection();
504 $group_id = $user->getGroup();
505 $org_id = $user->org_id;
507 $sql = "select id, name, description from tt_tasks".
508 " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
509 $res = $mdb2->query($sql);
511 if (!is_a($res, 'PEAR_Error')) {
512 while ($val = $res->fetchRow()) {
519 // getInactiveTasks - returns an array of inactive tasks for a group.
520 static function getInactiveTasks()
523 $mdb2 = getConnection();
525 $group_id = $user->getGroup();
526 $org_id = $user->org_id;
528 $sql = "select id, name, description from tt_tasks".
529 " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
530 $res = $mdb2->query($sql);
532 if (!is_a($res, 'PEAR_Error')) {
533 while ($val = $res->fetchRow()) {
540 // getActiveTemplates - returns an array of active templates for a group.
541 static function getActiveTemplates()
544 $mdb2 = getConnection();
546 $group_id = $user->getGroup();
547 $org_id = $user->org_id;
549 $sql = "select id, name, description, content from tt_templates".
550 " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
551 $res = $mdb2->query($sql);
553 if (!is_a($res, 'PEAR_Error')) {
554 while ($val = $res->fetchRow()) {
561 // getInactiveTemplates - returns an array of active templates for a group.
562 static function getInactiveTemplates()
565 $mdb2 = getConnection();
567 $group_id = $user->getGroup();
568 $org_id = $user->org_id;
570 $sql = "select id, name, description from tt_templates".
571 " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
572 $res = $mdb2->query($sql);
574 if (!is_a($res, 'PEAR_Error')) {
575 while ($val = $res->fetchRow()) {
582 // validateCheckboxGroupInput - validates user input in a group of checkboxes
583 // in context of a specific database table.
585 // We need to make sure that input is a set of unique positive integers, and is
586 // "relevant" to the current group (entities exists in table).
588 // It is a safeguard against manipulation of data in posts.
589 static function validateCheckboxGroupInput($input, $table) {
590 // Empty input is valid.
591 if (!$input) return true;
593 // Input containing duplicates is invalid.
594 if (count($input) !== count(array_unique($input))) return false;
596 // Input containing anything but positive integers is invalid.
597 foreach ($input as $single_selection) {
598 if (!is_numeric($single_selection) || $single_selection <= 0) return false;
602 $mdb2 = getConnection();
604 $group_id = $user->getGroup();
605 $org_id = $user->org_id;
607 // Now check the table. It must contain all entities associated with current group and org.
608 $comma_separated = implode(',', $input);
609 $sql = "select count(*) as item_count from $table".
610 " where id in ($comma_separated) and group_id = $group_id and org_id = $org_id and status = 1";
611 $res = $mdb2->query($sql);
612 if (is_a($res, 'PEAR_Error')) return false;
613 $val = $res->fetchRow();
614 if (count($input) != $val['item_count'])
615 return false; // Number of entities in table is different.
617 return true; // All is good.
620 // The getUsers obtains all active and inactive (but not deleted) users in a group.
621 static function getUsers() {
623 $mdb2 = getConnection();
625 $group_id = $user->getGroup();
626 $org_id = $user->org_id;
628 $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)";
629 $res = $mdb2->query($sql);
630 $user_list = array();
631 if (is_a($res, 'PEAR_Error'))
633 while ($val = $res->fetchRow()) {
639 // The getUsersForClient obtains all active and inactive users in a group that are relevant to a client.
640 static function getUsersForClient($options) {
642 $mdb2 = getConnection();
644 $group_id = $user->getGroup();
645 $org_id = $user->org_id;
647 if (isset($options['status']))
648 $where_part = 'where u.status = '.(int)$options['status'];
650 $where_part = 'where u.status is not null';
652 $sql = "select u.id, u.name from tt_user_project_binds upb".
653 " inner join tt_client_project_binds cpb on (upb.project_id = cpb.project_id and cpb.client_id = $user->client_id)".
654 " inner join tt_users u on (u.id = upb.user_id and u.group_id = $group_id and u.org_id = $org_id)".
655 " $where_part group by u.id order by upper(u.name)";
656 $res = $mdb2->query($sql);
657 $user_list = array();
658 if (is_a($res, 'PEAR_Error'))
660 while ($val = $res->fetchRow()) {
666 // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
667 static function getRecentInvoices($client_id) {
669 $mdb2 = getConnection();
671 $group_id = $user->getGroup();
672 $org_id = $user->org_id;
674 $sql = "select i.id, i.name from tt_invoices i".
675 " left join tt_clients c on (c.id = i.client_id)".
676 " where i.group_id = $group_id and i.org_id = $org_id and i.status = 1 and c.id = $client_id".
677 " order by i.id desc limit 3";
678 $res = $mdb2->query($sql);
680 if (!is_a($res, 'PEAR_Error')) {
681 $dt = new DateAndTime(DB_DATEFORMAT);
682 while ($val = $res->fetchRow()) {
689 // deleteGroupFiles deletes files attached to all entities in the entire group.
690 // Note that it is a permanent delete, not "mark deleted" by design.
691 static function deleteGroupFiles($group_id) {
694 $org_id = $user->org_id;
696 // Delete all group files from the database.
697 $mdb2 = getConnection();
698 $sql = "delete from tt_files where org_id = $org_id and group_id = $group_id";
699 $affected = $mdb2->exec($sql);
700 if (is_a($affected, 'PEAR_Error'))
703 if ($affected == 0) return true; // Do not call file storage utility.
705 // Try to make a call to file storage facility.
706 if (!defined('FILE_STORAGE_URI')) return true; // Nothing to do.
708 $deletegroupfiles_uri = FILE_STORAGE_URI.'deletegroupfiles';
711 $sql = "select param_value as site_id from tt_site_config where param_name = 'locker_id'";
712 $res = $mdb2->query($sql);
713 $val = $res->fetchRow();
714 $site_id = $val['site_id'];
715 if (!$site_id) return true; // Nothing to do.
718 $sql = "select param_value as site_key from tt_site_config where param_name = 'locker_key'";
719 $res = $mdb2->query($sql);
720 $val = $res->fetchRow();
721 $site_key = $val['site_key'];
722 if (!$site_key) return true; // Can't continue without site key.
725 $sql = "select group_key as org_key from tt_groups where id = $org_id";
726 $res = $mdb2->query($sql);
727 $val = $res->fetchRow();
728 $org_key = $val['org_key'];
729 if (!$org_key) return true; // Can't continue without org key.
732 $sql = "select group_key as group_key from tt_groups where id = $group_id";
733 $res = $mdb2->query($sql);
734 $val = $res->fetchRow();
735 $group_key = $val['group_key'];
736 if (!$group_key) return true; // Can't continue without group key.
738 $curl_fields = array('site_id' => $site_id,
739 'site_key' => $site_key,
741 'org_key' => $org_key,
742 'group_id' => $group_id,
743 'group_key' => $group_key);
745 // url-ify the data for the POST.
746 foreach($curl_fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
747 $fields_string = rtrim($fields_string, '&');
752 // Set the url, number of POST vars, POST data.
753 curl_setopt($ch, CURLOPT_URL, $deletegroupfiles_uri);
754 curl_setopt($ch, CURLOPT_POST, true);
755 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
756 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
758 // Execute a post request.
759 $result = curl_exec($ch);
764 // Many things can go wrong with a remote call to file storage facility.
765 // By design, we ignore such errors.