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) {
38 $mdb2 = getConnection();
40 $sql = "select name from tt_groups where id = $group_id and org_id = $user->org_id and (status = 1 or status = 0)";
41 $res = $mdb2->query($sql);
43 if (!is_a($res, 'PEAR_Error')) {
44 $val = $res->fetchRow();
50 // The getParentGroup determines a parent group for a given group.
51 static function getParentGroup($group_id) {
54 $mdb2 = getConnection();
56 $sql = "select parent_id from tt_groups where id = $group_id and org_id = $user->org_id and status = 1";
57 $res = $mdb2->query($sql);
59 if (!is_a($res, 'PEAR_Error')) {
60 $val = $res->fetchRow();
61 return $val['parent_id'];
66 // The getSubgroupByName obtain an immediate subgroup by name if one exists.
67 static function getSubgroupByName($name) {
70 $mdb2 = getConnection();
71 $parent_id = $user->getGroup();
72 $org_id = $user->org_id;
74 $sql = "select id from tt_groups where parent_id = $parent_id and org_id = $org_id".
75 " and name = ".$mdb2->quote($name)." and status is not null";
76 $res = $mdb2->query($sql);
77 if (!is_a($res, 'PEAR_Error')) {
78 $val = $res->fetchRow();
79 if ($val && $val['id'])
85 // The insertSubgroup inserts a new subgroup in database.
86 static function insertSubgroup($fields) {
89 $mdb2 = getConnection();
90 $parent_id = $user->getGroup();
91 $org_id = $user->org_id;
92 $group_key = ttRandomString();
93 $name = $fields['name'];
94 $description = $fields['description'];
96 // We need to inherit attributes from the parent group.
97 $attrs = ttGroupHelper::getGroupAttrs($parent_id);
99 $columns = '(parent_id, org_id, group_key, name, description, currency, decimal_mark, lang, date_format,'.
100 ' time_format, week_start, tracking_mode, project_required, task_required, record_type, bcc_email,'.
101 ' allow_ip, password_complexity, plugins, lock_spec,'.
102 ' workday_minutes, config, created, created_ip, created_by)';
104 $values = " values ($parent_id, $org_id";
105 $values .= ', '.$mdb2->quote($group_key);
106 $values .= ', '.$mdb2->quote($name);
107 $values .= ', '.$mdb2->quote($description);
108 $values .= ', '.$mdb2->quote($attrs['currency']);
109 $values .= ', '.$mdb2->quote($attrs['decimal_mark']);
110 $values .= ', '.$mdb2->quote($attrs['lang']);
111 $values .= ', '.$mdb2->quote($attrs['date_format']);
112 $values .= ', '.$mdb2->quote($attrs['time_format']);
113 $values .= ', '.(int)$attrs['week_start'];
114 $values .= ', '.(int)$attrs['tracking_mode'];
115 $values .= ', '.(int)$attrs['project_required'];
116 $values .= ', '.(int)$attrs['task_required'];
117 $values .= ', '.(int)$attrs['record_type'];
118 $values .= ', '.$mdb2->quote($attrs['bcc_email']);
119 $values .= ', '.$mdb2->quote($attrs['allow_ip']);
120 $values .= ', '.$mdb2->quote($attrs['password_complexity']);
121 $values .= ', '.$mdb2->quote($attrs['plugins']);
122 $values .= ', '.$mdb2->quote($attrs['lock_spec']);
123 $values .= ', '.(int)$attrs['workday_minutes'];
124 $values .= ', '.$mdb2->quote($attrs['config']);
125 $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
128 $sql = 'insert into tt_groups '.$columns.$values;
129 $affected = $mdb2->exec($sql);
130 if (is_a($affected, 'PEAR_Error')) return false;
132 $subgroup_id = $mdb2->lastInsertID('tt_groups', 'id');
134 // Copy roles from the parent group to child group.
135 if (!ttRoleHelper::copyRolesToGroup($subgroup_id))
141 // markGroupDeleted marks a group and everything in it as deleted.
142 // This function is called in context of a logged on user (global $user object).
143 // It uses current user attributes for access checks and in sql queries.
144 // Compare this with admin:
145 // admin can delete any group.
146 // user can delete only relevant groups and only if allowed.
147 static function markGroupDeleted($group_id) {
150 $mdb2 = getConnection();
151 $org_id = $user->org_id;
154 if (!$user->isGroupValid($group_id))
157 // Keep the logic simple by returning false on first error.
159 // Obtain subgroups and call self recursively on them.
160 $subgroups = $user->getSubgroups($group_id);
161 foreach($subgroups as $subgroup) {
162 if (!ttGroupHelper::markGroupDeleted($subgroup['id']))
166 // Now do actual work with all entities.
168 // Delete group files.
169 ttGroupHelper::deleteGroupFiles($group_id);
171 // Some things cannot be marked deleted as we don't have the status field for them.
172 // Just delete such things (until we have a better way to deal with them).
173 $tables_to_delete_from = array(
175 'tt_predefined_expenses',
176 'tt_client_project_binds',
177 'tt_project_task_binds'
179 foreach($tables_to_delete_from as $table) {
180 if (!ttGroupHelper::deleteGroupEntriesFromTable($group_id, $table))
184 // Now mark status deleted where we can.
185 // Note: we don't mark tt_log, tt_custom_field_lod, or tt_expense_items deleted here.
188 // 1) Users may mark some of them deleted during their work.
189 // If we mark all of them deleted here, we can't recover nicely
190 // as we'll lose track of what was accidentally deleted by user.
192 // 2) DB maintenance script (Clean up DB from inactive groups) should
193 // get rid of these items permanently eventually.
194 $tables_to_mark_deleted_in = array(
197 // 'tt_expense_items',
198 // 'tt_custom_field_log',
199 'tt_custom_field_options',
203 'tt_user_project_binds',
210 foreach($tables_to_mark_deleted_in as $table) {
211 if (!ttGroupHelper::markGroupDeletedInTable($group_id, $table))
215 // Mark group deleted.
216 $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
217 $sql = "update tt_groups set status = null $modified_part where id = $group_id and org_id = $org_id";
218 $affected = $mdb2->exec($sql);
219 if (is_a($affected, 'PEAR_Error')) return false;
224 // markGroupDeletedInTable is a generic helper function for markGroupDeleted.
225 // It updates ONE table by setting status to NULL for all records belonging to a group.
226 static function markGroupDeletedInTable($group_id, $table_name) {
228 $mdb2 = getConnection();
230 // Add modified info to sql for some tables, depending on table name.
231 if ($table_name == 'tt_users') {
232 $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
235 $org_id = $user->org_id; // The only security measure we use here for match.
236 $sql = "update $table_name set status = null $modified_part where group_id = $group_id and org_id = $org_id";
237 $affected = $mdb2->exec($sql);
238 return (!is_a($affected, 'PEAR_Error'));
241 // deleteGroupEntriesFromTable is a generic helper function for markGroupDeleted.
242 // It deletes entries in ONE table belonging to a given group.
243 static function deleteGroupEntriesFromTable($group_id, $table_name) {
245 $mdb2 = getConnection();
247 $org_id = $user->org_id; // The only security measure we use here for match.
248 $sql = "delete from $table_name where group_id = $group_id and org_id = $org_id";
249 $affected = $mdb2->exec($sql);
250 return (!is_a($affected, 'PEAR_Error'));
253 // getGroupAttrs obtains all group attributes.
254 static function getGroupAttrs($group_id) {
256 $mdb2 = getConnection();
258 $sql = "select * from tt_groups".
259 " where status = 1 and id = $group_id and org_id = $user->org_id";
260 $res = $mdb2->query($sql);
261 if (!is_a($res, 'PEAR_Error')) {
262 $val = $res->fetchRow();
267 // getRoles obtains all active and inactive roles in current group.
268 static function getRoles() {
270 $mdb2 = getConnection();
272 $group_id = $user->getGroup();
273 $org_id = $user->org_id;
274 $sql = "select * from tt_roles".
275 " where group_id = $group_id and org_id = $org_id and status is not null";
276 $res = $mdb2->query($sql);
277 if (is_a($res, 'PEAR_Error')) return false;
278 while ($val = $res->fetchRow()) {
284 // The getActiveClients returns an array of active clients for a group.
285 static function getActiveClients($all_fields = false)
288 $mdb2 = getConnection();
290 $group_id = $user->getGroup();
291 $org_id = $user->org_id;
293 $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
295 $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
297 $res = $mdb2->query($sql);
299 if (!is_a($res, 'PEAR_Error')) {
300 while ($val = $res->fetchRow()) {
307 // The getInactiveClients returns an array of inactive clients for a group.
308 static function getInactiveClients($all_fields = false)
311 $mdb2 = getConnection();
313 $group_id = $user->getGroup();
314 $org_id = $user->org_id;
316 $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
318 $sql = "select id, name from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
320 $res = $mdb2->query($sql);
322 if (!is_a($res, 'PEAR_Error')) {
323 while ($val = $res->fetchRow()) {
330 // getActiveProjects - returns an array of active projects for a group.
331 static function getActiveProjects($includeFiles = false)
334 $mdb2 = getConnection();
336 $group_id = $user->getGroup();
337 $org_id = $user->org_id;
340 $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
341 $fileJoin = " left join (select distinct entity_id from tt_files".
342 " where entity_type = 'project' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
343 " on (p.id = Sub1.entity_id)";
346 $sql = "select p.id, p.name, p.description, p.tasks $filePart from tt_projects p $fileJoin".
347 " where p.group_id = $group_id and p.org_id = $org_id and p.status = 1 order by upper(p.name)";
348 $res = $mdb2->query($sql);
350 if (!is_a($res, 'PEAR_Error')) {
351 while ($val = $res->fetchRow()) {
358 // getInactiveProjects - returns an array of inactive projects for a group.
359 static function getInactiveProjects($includeFiles = false)
362 $mdb2 = getConnection();
364 $group_id = $user->getGroup();
365 $org_id = $user->org_id;
368 $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
369 $fileJoin = " left join (select distinct entity_id from tt_files".
370 " where entity_type = 'project' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
371 " on (p.id = Sub1.entity_id)";
374 $sql = "select p.id, p.name, p.description, p.tasks $filePart from tt_projects p $fileJoin".
375 " where p.group_id = $group_id and p.org_id = $org_id and p.status = 0 order by upper(p.name)";
376 $res = $mdb2->query($sql);
378 if (!is_a($res, 'PEAR_Error')) {
379 while ($val = $res->fetchRow()) {
386 // getPredefinedExpenses - obtains predefined expenses for a group.
387 static function getPredefinedExpenses() {
389 $mdb2 = getConnection();
391 $group_id = $user->getGroup();
392 $org_id = $user->org_id;
395 $sql = "select id, name, cost from tt_predefined_expenses".
396 " where group_id = $group_id and org_id = $org_id";
397 $res = $mdb2->query($sql);
399 if (!is_a($res, 'PEAR_Error')) {
400 $decimal_mark = $user->getDecimalMark();
401 $replaceDecimalMark = ('.' != $decimal_mark);
403 while ($val = $res->fetchRow()) {
404 if ($replaceDecimalMark)
405 $val['cost'] = str_replace('.', $decimal_mark, $val['cost']);
413 // The getActiveInvoices returns an array of active invoices for a group.
414 static function getActiveInvoices()
417 $mdb2 = getConnection();
419 $group_id = $user->getGroup();
420 $org_id = $user->org_id;
422 $addPaidStatus = $user->isPluginEnabled('ps');
425 if ($user->isClient())
426 $client_part = "and i.client_id = $user->client_id";
428 $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i".
429 " left join tt_clients c on (c.id = i.client_id)".
430 " where i.status = 1 and i.group_id = $group_id and i.org_id = $org_id $client_part order by i.name";
431 $res = $mdb2->query($sql);
433 if (!is_a($res, 'PEAR_Error')) {
434 $dt = new DateAndTime(DB_DATEFORMAT);
435 while ($val = $res->fetchRow()) {
437 $dt->parseVal($val['date']);
438 $val['date'] = $dt->toString($user->getDateFormat());
440 $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
447 // getNotifications - obtains notification descriptions for a group.
448 static function getNotifications() {
450 $mdb2 = getConnection();
452 $group_id = $user->getGroup();
453 $org_id = $user->org_id;
456 $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c".
457 " left join tt_fav_reports fr on (fr.id = c.report_id)".
458 " where c.group_id = $group_id and c.org_id = $org_id and c.status = 1 and fr.status = 1";
459 $res = $mdb2->query($sql);
461 if (!is_a($res, 'PEAR_Error')) {
462 while ($val = $res->fetchRow()) {
470 // The getActiveUsers obtains all active users excluding clients in a given group.
471 static function getActiveUsers($options = null) {
474 $mdb2 = getConnection();
476 $group_id = $user->getGroup();
477 $org_id = $user->org_id;
479 $client_part = " and u.client_id is null";
481 if (isset($options['getAllFields']))
482 $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)";
484 $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)";
485 $res = $mdb2->query($sql);
486 $user_list = array();
487 if (is_a($res, 'PEAR_Error'))
489 while ($val = $res->fetchRow()) {
490 // Localize top manager role name, as it is not localized in db.
491 if ($val['rank'] == 512)
492 $val['role_name'] = $i18n->get('role.top_manager.label');
499 // getActiveTasks - returns an array of active tasks for a group.
500 static function getActiveTasks()
503 $mdb2 = getConnection();
505 $group_id = $user->getGroup();
506 $org_id = $user->org_id;
508 $sql = "select id, name, description from tt_tasks".
509 " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
510 $res = $mdb2->query($sql);
512 if (!is_a($res, 'PEAR_Error')) {
513 while ($val = $res->fetchRow()) {
520 // getInactiveTasks - returns an array of inactive tasks for a group.
521 static function getInactiveTasks()
524 $mdb2 = getConnection();
526 $group_id = $user->getGroup();
527 $org_id = $user->org_id;
529 $sql = "select id, name, description from tt_tasks".
530 " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
531 $res = $mdb2->query($sql);
533 if (!is_a($res, 'PEAR_Error')) {
534 while ($val = $res->fetchRow()) {
541 // getActiveTemplates - returns an array of active templates for a group.
542 static function getActiveTemplates()
545 $mdb2 = getConnection();
547 $group_id = $user->getGroup();
548 $org_id = $user->org_id;
550 $sql = "select id, name, description, content from tt_templates".
551 " where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
552 $res = $mdb2->query($sql);
554 if (!is_a($res, 'PEAR_Error')) {
555 while ($val = $res->fetchRow()) {
562 // getInactiveTemplates - returns an array of active templates for a group.
563 static function getInactiveTemplates()
566 $mdb2 = getConnection();
568 $group_id = $user->getGroup();
569 $org_id = $user->org_id;
571 $sql = "select id, name, description from tt_templates".
572 " where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
573 $res = $mdb2->query($sql);
575 if (!is_a($res, 'PEAR_Error')) {
576 while ($val = $res->fetchRow()) {
583 // validateCheckboxGroupInput - validates user input in a group of checkboxes
584 // in context of a specific database table.
586 // We need to make sure that input is a set of unique positive integers, and is
587 // "relevant" to the current group (entities exists in table).
589 // It is a safeguard against manipulation of data in posts.
590 static function validateCheckboxGroupInput($input, $table) {
591 // Empty input is valid.
592 if (!$input) return true;
594 // Input containing duplicates is invalid.
595 if (count($input) !== count(array_unique($input))) return false;
597 // Input containing anything but positive integers is invalid.
598 foreach ($input as $single_selection) {
599 if (!is_numeric($single_selection) || $single_selection <= 0) return false;
603 $mdb2 = getConnection();
605 $group_id = $user->getGroup();
606 $org_id = $user->org_id;
608 // Now check the table. It must contain all entities associated with current group and org.
609 $comma_separated = implode(',', $input);
610 $sql = "select count(*) as item_count from $table".
611 " where id in ($comma_separated) and group_id = $group_id and org_id = $org_id and status = 1";
612 $res = $mdb2->query($sql);
613 if (is_a($res, 'PEAR_Error')) return false;
614 $val = $res->fetchRow();
615 if (count($input) != $val['item_count'])
616 return false; // Number of entities in table is different.
618 return true; // All is good.
621 // The getUsers obtains all active and inactive (but not deleted) users in a group.
622 static function getUsers() {
624 $mdb2 = getConnection();
626 $group_id = $user->getGroup();
627 $org_id = $user->org_id;
629 $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)";
630 $res = $mdb2->query($sql);
631 $user_list = array();
632 if (is_a($res, 'PEAR_Error'))
634 while ($val = $res->fetchRow()) {
640 // The getUsersForClient obtains all active and inactive users in a group that are relevant to a client.
641 static function getUsersForClient($options) {
643 $mdb2 = getConnection();
645 $group_id = $user->getGroup();
646 $org_id = $user->org_id;
648 if (isset($options['status']))
649 $where_part = 'where u.status = '.(int)$options['status'];
651 $where_part = 'where u.status is not null';
653 $sql = "select u.id, u.name from tt_user_project_binds upb".
654 " inner join tt_client_project_binds cpb on (upb.project_id = cpb.project_id and cpb.client_id = $user->client_id)".
655 " inner join tt_users u on (u.id = upb.user_id and u.group_id = $group_id and u.org_id = $org_id)".
656 " $where_part group by u.id order by upper(u.name)";
657 $res = $mdb2->query($sql);
658 $user_list = array();
659 if (is_a($res, 'PEAR_Error'))
661 while ($val = $res->fetchRow()) {
667 // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
668 static function getRecentInvoices($client_id) {
670 $mdb2 = getConnection();
672 $group_id = $user->getGroup();
673 $org_id = $user->org_id;
675 $sql = "select i.id, i.name from tt_invoices i".
676 " left join tt_clients c on (c.id = i.client_id)".
677 " where i.group_id = $group_id and i.org_id = $org_id and i.status = 1 and c.id = $client_id".
678 " order by i.id desc limit 3";
679 $res = $mdb2->query($sql);
681 if (!is_a($res, 'PEAR_Error')) {
682 $dt = new DateAndTime(DB_DATEFORMAT);
683 while ($val = $res->fetchRow()) {
690 // deleteGroupFiles deletes files attached to all entities in the entire group.
691 // Note that it is a permanent delete, not "mark deleted" by design.
692 static function deleteGroupFiles($group_id) {
695 $org_id = $user->org_id;
697 // Delete all group files from the database.
698 $mdb2 = getConnection();
699 $sql = "delete from tt_files where org_id = $org_id and group_id = $group_id";
700 $affected = $mdb2->exec($sql);
701 if (is_a($affected, 'PEAR_Error'))
704 if ($affected == 0) return true; // Do not call file storage utility.
706 // Try to make a call to file storage facility.
707 if (!defined('FILE_STORAGE_URI')) return true; // Nothing to do.
709 $deletegroupfiles_uri = FILE_STORAGE_URI.'deletegroupfiles';
712 $sql = "select param_value as site_id from tt_site_config where param_name = 'locker_id'";
713 $res = $mdb2->query($sql);
714 $val = $res->fetchRow();
715 $site_id = $val['site_id'];
716 if (!$site_id) return true; // Nothing to do.
719 $sql = "select param_value as site_key from tt_site_config where param_name = 'locker_key'";
720 $res = $mdb2->query($sql);
721 $val = $res->fetchRow();
722 $site_key = $val['site_key'];
723 if (!$site_key) return true; // Can't continue without site key.
726 $sql = "select group_key as org_key from tt_groups where id = $org_id";
727 $res = $mdb2->query($sql);
728 $val = $res->fetchRow();
729 $org_key = $val['org_key'];
730 if (!$org_key) return true; // Can't continue without org key.
733 $sql = "select group_key as group_key from tt_groups where id = $group_id";
734 $res = $mdb2->query($sql);
735 $val = $res->fetchRow();
736 $group_key = $val['group_key'];
737 if (!$group_key) return true; // Can't continue without group key.
739 $curl_fields = array('site_id' => $site_id,
740 'site_key' => $site_key,
742 'org_key' => $org_key,
743 'group_id' => $group_id,
744 'group_key' => $group_key);
746 // url-ify the data for the POST.
747 foreach($curl_fields as $key=>$value) { $fields_string .= $key.'='.$value.'&'; }
748 $fields_string = rtrim($fields_string, '&');
753 // Set the url, number of POST vars, POST data.
754 curl_setopt($ch, CURLOPT_URL, $deletegroupfiles_uri);
755 curl_setopt($ch, CURLOPT_POST, true);
756 curl_setopt($ch, CURLOPT_POSTFIELDS, $fields_string);
757 curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
759 // Execute a post request.
760 $result = curl_exec($ch);
765 // Many things can go wrong with a remote call to file storage facility.
766 // By design, we ignore such errors.