A bit of refactoring.
[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     global $user;
38     $mdb2 = getConnection();
39
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);
42
43     if (!is_a($res, 'PEAR_Error')) {
44       $val = $res->fetchRow();
45       return $val['name'];
46     }
47     return false;
48   }
49
50   // The getParentGroup determines a parent group for a given group.
51   static function getParentGroup($group_id) {
52     global $user;
53
54     $mdb2 = getConnection();
55
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);
58
59     if (!is_a($res, 'PEAR_Error')) {
60       $val = $res->fetchRow();
61       return $val['parent_id'];
62     }
63     return false;
64   }
65
66   // The getSubgroupByName obtain an immediate subgroup by name if one exists.
67   static function getSubgroupByName($name) {
68     global $user;
69
70     $mdb2 = getConnection();
71     $parent_id = $user->getGroup();
72     $org_id = $user->org_id;
73
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'])
80         return $val;
81     }
82     return false;
83   }
84
85   // The insertSubgroup inserts a new subgroup in database.
86   static function insertSubgroup($fields) {
87     global $user;
88
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'];
95
96     // We need to inherit attributes from the parent group.
97     $attrs = ttGroupHelper::getGroupAttrs($parent_id);
98
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)';
103
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;
126     $values .= ')';
127
128     $sql = 'insert into tt_groups '.$columns.$values;
129     $affected = $mdb2->exec($sql);
130     if (is_a($affected, 'PEAR_Error')) return false;
131
132     $subgroup_id = $mdb2->lastInsertID('tt_groups', 'id');
133
134     // Copy roles from the parent group to child group.
135     if (!ttRoleHelper::copyRolesToGroup($subgroup_id))
136       return false;
137     
138     return $subgroup_id;
139   }
140
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) {
148     global $user;
149
150     $mdb2 = getConnection();
151     $org_id = $user->org_id;
152
153     // Security check.
154     if (!$user->isGroupValid($group_id))
155       return false;
156
157     // Keep the logic simple by returning false on first error.
158
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']))
163         return false;
164     }
165
166     // Now do actual work with all entities.
167
168     // Delete group files.
169     ttGroupHelper::deleteGroupFiles($group_id);
170
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(
174       'tt_config',
175       'tt_predefined_expenses',
176       'tt_client_project_binds',
177       'tt_project_task_binds'
178     );
179     foreach($tables_to_delete_from as $table) {
180       if (!ttGroupHelper::deleteGroupEntriesFromTable($group_id, $table))
181         return false;
182     }
183
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.
186     // Reasoning is:
187     //
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.
191     //
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(
195       'tt_cron',
196       'tt_fav_reports',
197       // 'tt_expense_items',
198       // 'tt_custom_field_log',
199       'tt_custom_field_options',
200       'tt_custom_fields',
201       // 'tt_log',
202       'tt_invoices',
203       'tt_user_project_binds',
204       'tt_users',
205       'tt_clients',
206       'tt_projects',
207       'tt_tasks',
208       'tt_roles'
209     );
210     foreach($tables_to_mark_deleted_in as $table) {
211       if (!ttGroupHelper::markGroupDeletedInTable($group_id, $table))
212         return false;
213     }
214
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;
220
221     return true;
222   }
223
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) {
227     global $user;
228     $mdb2 = getConnection();
229
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;
233     }
234
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'));
239   }
240
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) {
244     global $user;
245     $mdb2 = getConnection();
246
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'));
251   }
252
253   // getGroupAttrs obtains all group attributes.
254   static function getGroupAttrs($group_id) {
255     global $user;
256     $mdb2 = getConnection();
257
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();
263     }
264     return $val;
265   }
266
267   // getRoles obtains all active and inactive roles in current group.
268   static function getRoles() {
269     global $user;
270     $mdb2 = getConnection();
271
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()) {
279       $roles[] = $val;
280     }
281     return $roles;
282   }
283
284   // The getActiveClients returns an array of active clients for a group.
285   static function getActiveClients($all_fields = false)
286   {
287     global $user;
288     $mdb2 = getConnection();
289
290     $group_id = $user->getGroup();
291     $org_id = $user->org_id;
292     if ($all_fields)
293       $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 1 order by upper(name)";
294     else
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)";
296
297     $res = $mdb2->query($sql);
298     $result = array();
299     if (!is_a($res, 'PEAR_Error')) {
300       while ($val = $res->fetchRow()) {
301         $result[] = $val;
302       }
303     }
304     return $result;
305   }
306
307   // The getInactiveClients returns an array of inactive clients for a group.
308   static function getInactiveClients($all_fields = false)
309   {
310     global $user;
311     $mdb2 = getConnection();
312
313     $group_id = $user->getGroup();
314     $org_id = $user->org_id;
315     if ($all_fields)
316       $sql = "select * from tt_clients where group_id = $group_id and org_id = $org_id and status = 0 order by upper(name)";
317     else
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)";
319
320     $res = $mdb2->query($sql);
321     $result = array();
322     if (!is_a($res, 'PEAR_Error')) {
323       while ($val = $res->fetchRow()) {
324         $result[] = $val;
325       }
326     }
327     return $result;
328   }
329
330   // getActiveProjects - returns an array of active projects for a group.
331   static function getActiveProjects($includeFiles = false)
332   {
333     global $user;
334     $mdb2 = getConnection();
335
336     $group_id = $user->getGroup();
337     $org_id = $user->org_id;
338
339     if ($includeFiles) {
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)";
344     }
345
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);
349     $result = array();
350     if (!is_a($res, 'PEAR_Error')) {
351       while ($val = $res->fetchRow()) {
352         $result[] = $val;
353       }
354     }
355     return $result;
356   }
357
358   // getInactiveProjects - returns an array of inactive projects for a group.
359   static function getInactiveProjects($includeFiles = false)
360   {
361     global $user;
362     $mdb2 = getConnection();
363
364     $group_id = $user->getGroup();
365     $org_id = $user->org_id;
366
367     if ($includeFiles) {
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)";
372     }
373
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);
377     $result = array();
378     if (!is_a($res, 'PEAR_Error')) {
379       while ($val = $res->fetchRow()) {
380         $result[] = $val;
381       }
382     }
383     return $result;
384   }
385
386   // getPredefinedExpenses - obtains predefined expenses for a group.
387   static function getPredefinedExpenses() {
388     global $user;
389     $mdb2 = getConnection();
390
391     $group_id = $user->getGroup();
392     $org_id = $user->org_id;
393
394     $result = array();
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);
398     $result = array();
399     if (!is_a($res, 'PEAR_Error')) {
400       $decimal_mark = $user->getDecimalMark();
401       $replaceDecimalMark = ('.' != $decimal_mark);
402
403       while ($val = $res->fetchRow()) {
404         if ($replaceDecimalMark)
405           $val['cost'] = str_replace('.', $decimal_mark, $val['cost']);
406         $result[] = $val;
407       }
408       return $result;
409     }
410     return false;
411   }
412
413   // The getActiveInvoices returns an array of active invoices for a group.
414   static function getActiveInvoices()
415   {
416     global $user;
417     $mdb2 = getConnection();
418
419     $group_id = $user->getGroup();
420     $org_id = $user->org_id;
421
422     $addPaidStatus = $user->isPluginEnabled('ps');
423     $result = array();
424
425     if ($user->isClient())
426       $client_part = "and i.client_id = $user->client_id";
427
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);
432     $result = array();
433     if (!is_a($res, 'PEAR_Error')) {
434       $dt = new DateAndTime(DB_DATEFORMAT);
435       while ($val = $res->fetchRow()) {
436         // Localize date.
437         $dt->parseVal($val['date']);
438         $val['date'] = $dt->toString($user->getDateFormat());
439         if ($addPaidStatus)
440           $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
441         $result[] = $val;
442       }
443     }
444     return $result;
445   }
446
447   // getNotifications - obtains notification descriptions for a group.
448   static function getNotifications() {
449     global $user;
450     $mdb2 = getConnection();
451
452     $group_id = $user->getGroup();
453     $org_id = $user->org_id;
454
455     $result = array();
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);
460     $result = array();
461     if (!is_a($res, 'PEAR_Error')) {
462       while ($val = $res->fetchRow()) {
463         $result[] = $val;
464       }
465       return $result;
466     }
467     return false;
468   }
469
470   // The getActiveUsers obtains all active users excluding clients in a given group.
471   static function getActiveUsers($options = null) {
472     global $user;
473     global $i18n;
474     $mdb2 = getConnection();
475
476     $group_id = $user->getGroup();
477     $org_id = $user->org_id;
478
479     $client_part = " and u.client_id is null";
480
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)";
483     else
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'))
488       return false;
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');
493       $user_list[] = $val;
494     }
495
496     return $user_list;
497   }
498
499   // getActiveTasks - returns an array of active tasks for a group.
500   static function getActiveTasks()
501   {
502     global $user;
503     $mdb2 = getConnection();
504
505     $group_id = $user->getGroup();
506     $org_id = $user->org_id;
507
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);
511     $result = array();
512     if (!is_a($res, 'PEAR_Error')) {
513       while ($val = $res->fetchRow()) {
514         $result[] = $val;
515       }
516     }
517     return $result;
518   }
519
520   // getInactiveTasks - returns an array of inactive tasks for a group.
521   static function getInactiveTasks()
522   {
523     global $user;
524     $mdb2 = getConnection();
525
526     $group_id = $user->getGroup();
527     $org_id = $user->org_id;
528
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);
532     $result = array();
533     if (!is_a($res, 'PEAR_Error')) {
534       while ($val = $res->fetchRow()) {
535         $result[] = $val;
536       }
537     }
538     return $result;
539   }
540
541   // getActiveTemplates - returns an array of active templates for a group.
542   static function getActiveTemplates()
543   {
544     global $user;
545     $mdb2 = getConnection();
546
547     $group_id = $user->getGroup();
548     $org_id = $user->org_id;
549
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);
553     $result = array();
554     if (!is_a($res, 'PEAR_Error')) {
555       while ($val = $res->fetchRow()) {
556         $result[] = $val;
557       }
558     }
559     return $result;
560   }
561
562   // getInactiveTemplates - returns an array of active templates for a group.
563   static function getInactiveTemplates()
564   {
565     global $user;
566     $mdb2 = getConnection();
567
568     $group_id = $user->getGroup();
569     $org_id = $user->org_id;
570
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);
574     $result = array();
575     if (!is_a($res, 'PEAR_Error')) {
576       while ($val = $res->fetchRow()) {
577         $result[] = $val;
578       }
579     }
580     return $result;
581   }
582
583   // validateCheckboxGroupInput - validates user input in a group of checkboxes
584   // in context of a specific database table.
585   //
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).
588   //
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;
593
594     // Input containing duplicates is invalid.
595     if (count($input) !== count(array_unique($input))) return false;
596
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;
600     }
601
602     global $user;
603     $mdb2 = getConnection();
604
605     $group_id = $user->getGroup();
606     $org_id = $user->org_id;
607
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.
617
618     return true; // All is good.
619   }
620
621   // The getUsers obtains all active and inactive (but not deleted) users in a group.
622   static function getUsers() {
623     global $user;
624     $mdb2 = getConnection();
625
626     $group_id = $user->getGroup();
627     $org_id = $user->org_id;
628
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'))
633       return false;
634     while ($val = $res->fetchRow()) {
635       $user_list[] = $val;
636     }
637     return $user_list;
638   }
639
640   // The getUsersForClient obtains all active and inactive users in a group that are relevant to a client.
641   static function getUsersForClient($options) {
642     global $user;
643     $mdb2 = getConnection();
644
645     $group_id = $user->getGroup();
646     $org_id = $user->org_id;
647
648     if (isset($options['status']))
649       $where_part = 'where u.status = '.(int)$options['status'];
650     else
651       $where_part = 'where u.status is not null';
652
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'))
660       return false;
661     while ($val = $res->fetchRow()) {
662       $user_list[] = $val;
663     }
664     return $user_list;
665   }
666
667   // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
668   static function getRecentInvoices($client_id) {
669     global $user;
670     $mdb2 = getConnection();
671
672     $group_id = $user->getGroup();
673     $org_id = $user->org_id;
674
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);
680     $result = array();
681     if (!is_a($res, 'PEAR_Error')) {
682       $dt = new DateAndTime(DB_DATEFORMAT);
683       while ($val = $res->fetchRow()) {
684         $result[] = $val;
685       }
686     }
687     return $result;
688   }
689
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) {
693
694     global $user;
695     $org_id = $user->org_id;
696
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'))
702       return false;
703
704     if ($affected == 0) return true; // Do not call file storage utility.
705
706     // Try to make a call to file storage facility.
707     if (!defined('FILE_STORAGE_URI')) return true; // Nothing to do.
708
709     $deletegroupfiles_uri = FILE_STORAGE_URI.'deletegroupfiles';
710
711     // Obtain site id.
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.
717
718     // Obtain site key.
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.
724
725     // Obtain org 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.
731
732     // Obtain group 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.
738
739     $curl_fields = array('site_id' => $site_id,
740       'site_key' => $site_key,
741       'org_id' => $org_id,
742       'org_key' => $org_key,
743       'group_id' => $group_id,
744       'group_key' => $group_key);
745
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, '&');
749
750     // Open connection.
751     $ch = curl_init();
752
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);
758
759     // Execute a post request.
760     $result = curl_exec($ch);
761
762     // Close connection.
763     curl_close($ch);
764
765     // Many things can go wrong with a remote call to file storage facility.
766     // By design, we ignore such errors.
767     return true;
768   }
769 }