Cleanup. Removed unused function.
[timetracker.git] / WEB-INF / lib / ttTeamHelper.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('ttUserHelper');
30 import('DateAndTime');
31 import('ttInvoiceHelper');
32
33 // Class ttTeamHelper - contains helper functions that operate with groups.
34 class ttTeamHelper {
35
36   // The getUserCount function returns number of active users in a group.
37   static function getUserCount($group_id) {
38     $mdb2 = getConnection();
39
40     $sql = "select count(id) as cnt from tt_users where group_id = $group_id and status = 1";
41     $res = $mdb2->query($sql);
42
43     if (!is_a($res, 'PEAR_Error')) {
44       $val = $res->fetchRow();
45       return $val['cnt'];
46     }
47     return false;
48   }
49
50   // The getUsersForClient obtains all active and inactive users in a group that are relevant to a client.
51   static function getUsersForClient() {
52     global $user;
53     $mdb2 = getConnection();
54
55     $sql = "select u.id, u.name from tt_user_project_binds upb".
56       " inner join tt_client_project_binds cpb on (upb.project_id = cpb.project_id and cpb.client_id = $user->client_id)".
57       " inner join tt_users u on (u.id = upb.user_id)".
58       " where (u.status = 1 or u.status = 0)".
59       " group by u.id".
60       " order by upper(u.name)";
61     $res = $mdb2->query($sql);
62     $user_list = array();
63     if (is_a($res, 'PEAR_Error'))
64       return false;
65     while ($val = $res->fetchRow()) {
66       $user_list[] = $val;
67     }
68     return $user_list;
69   }
70
71   // The getActiveUsers obtains all active users in a given group.
72   static function getActiveUsers($options = null) {
73     global $user;
74     global $i18n;
75     $mdb2 = getConnection();
76
77     if (isset($options['getAllFields']))
78       $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 = $user->group_id and u.status = 1 order by upper(u.name)";
79     else
80       $sql = "select id, name from tt_users where group_id = $user->group_id and status = 1 order by upper(name)";
81     $res = $mdb2->query($sql);
82     $user_list = array();
83     if (is_a($res, 'PEAR_Error'))
84       return false;
85     while ($val = $res->fetchRow()) {
86       // Localize top manager role name, as it is not localized in db.
87       if ($val['rank'] == 512)
88         $val['role_name'] = $i18n->get('role.top_manager.label');
89       $user_list[] = $val;
90     }
91
92     if (isset($options['putSelfFirst'])) {
93       // Put own entry at the front.
94       $cnt = count($user_list);
95       for($i = 0; $i < $cnt; $i++) {
96         if ($user_list[$i]['id'] == $user->id) {
97           $self = $user_list[$i]; // Found self.
98           array_unshift($user_list, $self); // Put own entry at the front.
99           array_splice($user_list, $i+1, 1); // Remove duplicate.
100         }
101       }
102     }
103     return $user_list;
104   }
105
106   // The swapRolesWith swaps existing user role with that of another user.
107   static function swapRolesWith($user_id) {
108     global $user;
109     $mdb2 = getConnection();
110
111     // Obtain role id for the user we are swapping ourselves with.
112     $sql = "select u.id, u.role_id from tt_users u left join tt_roles r on (u.role_id = r.id) where u.id = $user_id and u.group_id = $user->group_id and u.status = 1 and r.rank < $user->rank";
113     $res = $mdb2->query($sql);
114     if (is_a($res, 'PEAR_Error'))
115       return false;
116     $val = $res->fetchRow();
117     if (!$val['id'] || !$val['role_id'])
118       return false;
119
120     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$mdb2->quote($user->id);
121
122     // Promote user.
123     $sql = "update tt_users set role_id = $user->role_id".$modified_part." where id = $user_id and group_id = $user->group_id";
124     $affected = $mdb2->exec($sql);
125     if (is_a($affected, 'PEAR_Error')) return false;
126
127     // Demote self.
128     $role_id = $val['role_id'];
129     $sql = "update tt_users set role_id = $role_id".$modified_part." where id = $user->id and group_id = $user->group_id";
130     $affected = $mdb2->exec($sql);
131     if (is_a($affected, 'PEAR_Error')) return false;
132
133     return true;
134   }
135
136   // The getUsersForSwap obtains all users a current user can swap roles with.
137   static function getUsersForSwap() {
138     global $user;
139     $mdb2 = getConnection();
140
141     $sql = "select u.id, u.name, r.rank, r.rights from tt_users u left join tt_roles r on (u.role_id = r.id) where u.group_id = $user->group_id and u.status = 1 and r.rank < $user->rank order by upper(u.name)";
142     $res = $mdb2->query($sql);
143     $user_list = array();
144     if (is_a($res, 'PEAR_Error'))
145       return false;
146     while ($val = $res->fetchRow()) {
147       $isClient = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
148       if ($isClient)
149         continue; // Skip adding clients.
150       $user_list[] = $val;
151     }
152
153     return $user_list;
154   }
155
156   // The getUsers obtains all active and inactive (but not deleted) users in a group.
157   static function getUsers() {
158     global $user;
159     $mdb2 = getConnection();
160     $sql = "select id, name from tt_users where group_id = $user->group_id and (status = 1 or status = 0) order by upper(name)";
161     $res = $mdb2->query($sql);
162     $user_list = array();
163     if (is_a($res, 'PEAR_Error'))
164       return false;
165     while ($val = $res->fetchRow()) {
166       $user_list[] = $val;
167     }
168     return $user_list;
169   }
170
171   // The getInactiveUsers obtains all inactive users in a group.
172   static function getInactiveUsers($group_id, $all_fields = false) {
173     $mdb2 = getConnection();
174
175     if ($all_fields)
176       $sql = "select u.*, r.name as role_name from tt_users u left join tt_roles r on (u.role_id = r.id) where u.group_id = $group_id and u.status = 0 order by upper(u.name)";
177     else
178       $sql = "select id, name from tt_users where group_id = $group_id and status = 0 order by upper(name)";
179     $res = $mdb2->query($sql);
180     $result = array();
181     if (!is_a($res, 'PEAR_Error')) {
182       while ($val = $res->fetchRow()) {
183         $result[] = $val;
184       }
185       return $result;
186     }
187     return false;
188   }
189
190   // getActiveProjects - returns an array of active projects for a group.
191   static function getActiveProjects($group_id)
192   {
193     $result = array();
194     $mdb2 = getConnection();
195
196     $sql = "select id, name, description, tasks from tt_projects
197       where group_id = $group_id and status = 1 order by upper(name)";
198     $res = $mdb2->query($sql);
199     $result = array();
200     if (!is_a($res, 'PEAR_Error')) {
201       while ($val = $res->fetchRow()) {
202         $result[] = $val;
203       }
204     }
205     return $result;
206   }
207
208   // getInactiveProjects - returns an array of inactive projects for a group.
209   static function getInactiveProjects($group_id)
210   {
211     $result = array();
212     $mdb2 = getConnection();
213
214     $sql = "select id, name, description, tasks from tt_projects
215       where group_id = $group_id and status = 0 order by upper(name)";
216     $res = $mdb2->query($sql);
217     $result = array();
218     if (!is_a($res, 'PEAR_Error')) {
219       while ($val = $res->fetchRow()) {
220         $result[] = $val;
221       }
222     }
223     return $result;
224   }
225
226   // The getAllProjects obtains all projects in a group.
227   static function getAllProjects($group_id, $all_fields = false) {
228     $mdb2 = getConnection();
229
230     if ($all_fields)
231       $sql = "select * from tt_projects where group_id = $group_id order by status, upper(name)";
232     else
233       $sql = "select id, name from tt_projects where group_id = $group_id order by status, upper(name)";
234     $res = $mdb2->query($sql);
235     $result = array();
236     if (!is_a($res, 'PEAR_Error')) {
237       while ($val = $res->fetchRow()) {
238         $result[] = $val;
239       }
240       return $result;
241     }
242     return false;
243   }
244
245   // getActiveTasks - returns an array of active tasks for a group.
246   static function getActiveTasks($group_id)
247   {
248     $result = array();
249     $mdb2 = getConnection();
250
251     $sql = "select id, name, description from tt_tasks where group_id = $group_id and status = 1 order by upper(name)";
252     $res = $mdb2->query($sql);
253     $result = array();
254     if (!is_a($res, 'PEAR_Error')) {
255       while ($val = $res->fetchRow()) {
256         $result[] = $val;
257       }
258     }
259     return $result;
260   }
261
262   // getInactiveTasks - returns an array of inactive tasks for a group.
263   static function getInactiveTasks($group_id)
264   {
265     $result = array();
266     $mdb2 = getConnection();
267
268     $sql = "select id, name, description from tt_tasks
269       where group_id = $group_id and status = 0 order by upper(name)";
270     $res = $mdb2->query($sql);
271     $result = array();
272     if (!is_a($res, 'PEAR_Error')) {
273       while ($val = $res->fetchRow()) {
274         $result[] = $val;
275       }
276     }
277     return $result;
278   }
279
280   // The getAllTasks obtains all tasks in a group.
281   static function getAllTasks($group_id, $all_fields = false) {
282     $mdb2 = getConnection();
283
284     if ($all_fields)
285       $sql = "select * from tt_tasks where group_id = $group_id order by status, upper(name)";
286     else
287       $sql = "select id, name from tt_tasks where group_id = $group_id order by status, upper(name)";
288     $res = $mdb2->query($sql);
289     $result = array();
290     if (!is_a($res, 'PEAR_Error')) {
291       while ($val = $res->fetchRow()) {
292         $result[] = $val;
293       }
294       return $result;
295     }
296     return false;
297   }
298
299   // getActiveRolesForUser - returns an array of relevant active roles for user with rank less than self.
300   // "Relevant" means that client roles are filtered out if Client plugin is disabled.
301   static function getActiveRolesForUser()
302   {
303     global $user;
304     $result = array();
305     $mdb2 = getConnection();
306
307     $sql = "select id, name, description, rank, rights from tt_roles where group_id = $user->group_id and rank < $user->rank and status = 1 order by rank";
308     $res = $mdb2->query($sql);
309     $result = array();
310     if (!is_a($res, 'PEAR_Error')) {
311       while ($val = $res->fetchRow()) {
312         $val['is_client'] = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have data entry right.
313         if ($val['is_client'] && !$user->isPluginEnabled('cl'))
314           continue; // Skip adding a client role.
315         $result[] = $val;
316       }
317     }
318     return $result;
319   }
320
321   // getActiveRoles - returns an array of active roles for a group.
322   static function getActiveRoles($group_id)
323   {
324     $result = array();
325     $mdb2 = getConnection();
326
327     $sql = "select id, name, description, rank, rights from tt_roles where group_id = $group_id and status = 1 order by rank";
328     $res = $mdb2->query($sql);
329     $result = array();
330     if (!is_a($res, 'PEAR_Error')) {
331       while ($val = $res->fetchRow()) {
332         $val['is_client'] = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have track_own_time right.
333         $result[] = $val;
334       }
335     }
336     return $result;
337   }
338
339   // getInactiveRoles - returns an array of inactive roles for a group.
340   static function getInactiveRoles($group_id)
341   {
342     $result = array();
343     $mdb2 = getConnection();
344
345     $sql = "select id, name, rank, description from tt_roles
346       where group_id = $group_id and status = 0 order by rank";
347     $res = $mdb2->query($sql);
348     $result = array();
349     if (!is_a($res, 'PEAR_Error')) {
350       while ($val = $res->fetchRow()) {
351         $result[] = $val;
352       }
353     }
354     return $result;
355   }
356
357   // getInactiveRolesForUser - returns an array of relevant active roles for user with rank less than self.
358   // "Relevant" means that client roles are filtered out if Client plugin is disabled.
359   static function getInactiveRolesForUser()
360   {
361     global $user;
362     $result = array();
363     $mdb2 = getConnection();
364
365     $sql = "select id, name, description, rank, rights from tt_roles where group_id = $user->group_id and rank < $user->rank and status = 0 order by rank";
366     $res = $mdb2->query($sql);
367     $result = array();
368     if (!is_a($res, 'PEAR_Error')) {
369       while ($val = $res->fetchRow()) {
370         $val['is_client'] = in_array('track_own_time', explode(',', $val['rights'])) ? 0 : 1; // Clients do not have data entry right.
371         if ($val['is_client'] && !$user->isPluginEnabled('cl'))
372           continue; // Skip adding a client role.
373         $result[] = $val;
374       }
375     }
376     return $result;
377   }
378
379   // The getActiveClients returns an array of active clients for a group.
380   static function getActiveClients($group_id, $all_fields = false)
381   {
382     $result = array();
383     $mdb2 = getConnection();
384
385     if ($all_fields)
386       $sql = "select * from tt_clients where group_id = $group_id and status = 1 order by upper(name)";
387     else
388       $sql = "select id, name from tt_clients where group_id = $group_id and status = 1 order by upper(name)";
389
390     $res = $mdb2->query($sql);
391     $result = array();
392     if (!is_a($res, 'PEAR_Error')) {
393       while ($val = $res->fetchRow()) {
394         $result[] = $val;
395       }
396     }
397     return $result;
398   }
399
400   // The getInactiveClients returns an array of inactive clients for a group.
401   static function getInactiveClients($group_id, $all_fields = false)
402   {
403     $result = array();
404     $mdb2 = getConnection();
405
406     if ($all_fields)
407       $sql = "select * from tt_clients where group_id = $group_id and status = 0 order by upper(name)";
408     else
409       $sql = "select id, name from tt_clients where group_id = $group_id and status = 0 order by upper(name)";
410
411     $res = $mdb2->query($sql);
412     $result = array();
413     if (!is_a($res, 'PEAR_Error')) {
414       while ($val = $res->fetchRow()) {
415         $result[] = $val;
416       }
417     }
418     return $result;
419   }
420
421   // The getAllClients obtains all clients in a group.
422   static function getAllClients($group_id, $all_fields = false) {
423     $mdb2 = getConnection();
424
425     if ($all_fields)
426       $sql = "select * from tt_clients where group_id = $group_id order by status, upper(name)";
427     else
428       $sql = "select id, name from tt_clients where group_id = $group_id order by status, upper(name)";
429
430     $res = $mdb2->query($sql);
431     $result = array();
432     if (!is_a($res, 'PEAR_Error')) {
433       while ($val = $res->fetchRow()) {
434         $result[] = $val;
435       }
436       return $result;
437     }
438     return false;
439   }
440
441   // The getActiveInvoices returns an array of active invoices for a group.
442   static function getActiveInvoices($localizeDates = true)
443   {
444     global $user;
445     $addPaidStatus = $user->isPluginEnabled('ps');
446
447     $result = array();
448     $mdb2 = getConnection();
449
450     if ($user->isClient())
451       $client_part = " and i.client_id = $user->client_id";
452
453     $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i
454       left join tt_clients c on (c.id = i.client_id)
455       where i.status = 1 and i.group_id = $user->group_id $client_part order by i.name";
456     $res = $mdb2->query($sql);
457     $result = array();
458     if (!is_a($res, 'PEAR_Error')) {
459       $dt = new DateAndTime(DB_DATEFORMAT);
460       while ($val = $res->fetchRow()) {
461         if ($localizeDates) {
462           $dt->parseVal($val['date']);
463           $val['date'] = $dt->toString($user->date_format);
464         }
465         if ($addPaidStatus)
466           $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
467         $result[] = $val;
468       }
469     }
470     return $result;
471   }
472
473   // The getAllInvoices returns an array of all invoices for a group.
474   static function getAllInvoices()
475   {
476     global $user;
477
478     $result = array();
479     $mdb2 = getConnection();
480
481     $sql = "select * from tt_invoices where group_id = $user->group_id";
482     $res = $mdb2->query($sql);
483     $result = array();
484     if (!is_a($res, 'PEAR_Error')) {
485       $dt = new DateAndTime(DB_DATEFORMAT);
486       while ($val = $res->fetchRow()) {
487         $result[] = $val;
488       }
489     }
490     return $result;
491   }
492
493   // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
494   static function getRecentInvoices($group_id, $client_id)
495   {
496     global $user;
497
498     $result = array();
499     $mdb2 = getConnection();
500
501     $sql = "select i.id, i.name from tt_invoices i
502       left join tt_clients c on (c.id = i.client_id)
503       where i.group_id = $group_id and i.status = 1 and c.id = $client_id
504       order by i.id desc limit 3";
505     $res = $mdb2->query($sql);
506     $result = array();
507     if (!is_a($res, 'PEAR_Error')) {
508       $dt = new DateAndTime(DB_DATEFORMAT);
509       while ($val = $res->fetchRow()) {
510         $result[] = $val;
511       }
512     }
513     return $result;
514   }
515
516   // getUserToProjectBinds - obtains all user to project binds for a group.
517   static function getUserToProjectBinds($group_id) {
518     $mdb2 = getConnection();
519
520     $result = array();
521     $sql = "select * from tt_user_project_binds where user_id in (select id from tt_users where group_id = $group_id) order by user_id, status, project_id";
522     $res = $mdb2->query($sql);
523     $result = array();
524     if (!is_a($res, 'PEAR_Error')) {
525       while ($val = $res->fetchRow()) {
526         $result[] = $val;
527       }
528       return $result;
529     }
530     return false;
531   }
532
533   // The getAllCustomFields obtains all custom fields in a group.
534   static function getAllCustomFields($group_id) {
535     $mdb2 = getConnection();
536
537     $sql = "select * from tt_custom_fields where group_id = $group_id order by status";
538
539     $res = $mdb2->query($sql);
540     $result = array();
541     if (!is_a($res, 'PEAR_Error')) {
542       while ($val = $res->fetchRow()) {
543         $result[] = $val;
544       }
545       return $result;
546     }
547     return false;
548   }
549
550   // The getAllCustomFieldOptions obtains all custom field options in a group.
551   static function getAllCustomFieldOptions($group_id) {
552     $mdb2 = getConnection();
553
554     $sql = "select * from tt_custom_field_options where field_id in (select id from tt_custom_fields where group_id = $group_id) order by id";
555
556     $res = $mdb2->query($sql);
557     $result = array();
558     if (!is_a($res, 'PEAR_Error')) {
559       while ($val = $res->fetchRow()) {
560         $result[] = $val;
561       }
562       return $result;
563     }
564     return false;
565   }
566
567   // The getCustomFieldLog obtains all custom field log entries for a group.
568   static function getCustomFieldLog($group_id) {
569     $mdb2 = getConnection();
570
571     $sql = "select * from tt_custom_field_log where field_id in (select id from tt_custom_fields where group_id = $group_id) order by id";
572
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       return $result;
580     }
581     return false;
582   }
583
584   // getFavReports - obtains all favorite reports for all users in a group.
585   static function getFavReports($group_id) {
586     $mdb2 = getConnection();
587
588     $result = array();
589     $sql = "select * from tt_fav_reports where user_id in (select id from tt_users where group_id = $group_id)";
590     $res = $mdb2->query($sql);
591     $result = array();
592     if (!is_a($res, 'PEAR_Error')) {
593       while ($val = $res->fetchRow()) {
594         $result[] = $val;
595       }
596       return $result;
597     }
598     return false;
599   }
600
601   // getExpenseItems - obtains all expense items for all users in a group.
602   static function getExpenseItems($group_id) {
603     $mdb2 = getConnection();
604
605     $result = array();
606     $sql = "select * from tt_expense_items where user_id in (select id from tt_users where group_id = $group_id)";
607     $res = $mdb2->query($sql);
608     $result = array();
609     if (!is_a($res, 'PEAR_Error')) {
610       while ($val = $res->fetchRow()) {
611         $result[] = $val;
612       }
613       return $result;
614     }
615     return false;
616   }
617
618   // getPredefinedExpenses - obtains predefined expenses for a group.
619   static function getPredefinedExpenses($group_id) {
620     global $user;
621     $replaceDecimalMark = ('.' != $user->decimal_mark);
622
623     $mdb2 = getConnection();
624
625     $result = array();
626     $sql = "select id, name, cost from tt_predefined_expenses where group_id = $group_id";
627     $res = $mdb2->query($sql);
628     $result = array();
629     if (!is_a($res, 'PEAR_Error')) {
630       while ($val = $res->fetchRow()) {
631         if ($replaceDecimalMark)
632           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
633         $result[] = $val;
634       }
635       return $result;
636     }
637     return false;
638   }
639
640   // getNotifications - obtains notification descriptions for a group.
641   static function getNotifications($group_id) {
642     $mdb2 = getConnection();
643
644     $result = array();
645     $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c
646       left join tt_fav_reports fr on (fr.id = c.report_id)
647       where c.group_id = $group_id and c.status = 1 and fr.status = 1";
648     $res = $mdb2->query($sql);
649     $result = array();
650     if (!is_a($res, 'PEAR_Error')) {
651       while ($val = $res->fetchRow()) {
652         $result[] = $val;
653       }
654       return $result;
655     }
656     return false;
657   }
658
659   // getMonthlyQuotas - obtains monthly quotas for a group.
660   static function getMonthlyQuotas($group_id) {
661     $mdb2 = getConnection();
662
663     $result = array();
664     $sql = "select year, month, minutes from tt_monthly_quotas where group_id = $group_id";
665     $res = $mdb2->query($sql);
666     $result = array();
667     if (!is_a($res, 'PEAR_Error')) {
668       while ($val = $res->fetchRow()) {
669         $result[] = $val;
670       }
671       return $result;
672     }
673     return false;
674   }
675
676   // The insert function creates a new group.
677   static function insert($fields) {
678
679     global $user;
680     $mdb2 = getConnection();
681
682     // Start with group name and currency.
683     $columns = 'name, currency';
684     $values = $mdb2->quote(trim($fields['name'])).', '.$mdb2->quote(trim($fields['currency']));
685
686     if ($fields['decimal_mark']) {
687       $columns .= ', decimal_mark';
688       $values .= ', '.$mdb2->quote($fields['decimal_mark']);
689     }
690
691     $lang = $fields['lang'];
692     if (!$lang) {
693       global $i18n;
694       $lang = $i18n->lang;
695     }
696     $columns .= ', lang';
697     $values .= ', '.$mdb2->quote($lang);
698
699     if ($fields['date_format'] || defined('DATE_FORMAT_DEFAULT')) {
700       $date_format = $fields['date_format'] ? $fields['date_format'] : DATE_FORMAT_DEFAULT;
701       $columns .= ', date_format';
702       $values .= ', '.$mdb2->quote($date_format);
703     }
704
705     if ($fields['time_format'] || defined('TIME_FORMAT_DEFAULT')) {
706       $time_format = $fields['time_format'] ? $fields['time_format'] : TIME_FORMAT_DEFAULT;
707       $columns .= ', time_format';
708       $values .= ', '.$mdb2->quote($time_format);
709     }
710
711     if ($fields['week_start'] || defined('WEEK_START_DEFAULT')) {
712       $week_start = $fields['week_start'] ? $fields['week_start'] : WEEK_START_DEFAULT;
713       $columns .= ', week_start';
714       $values .= ', '.(int)$week_start;
715     }
716
717     if ($fields['tracking_mode']) {
718       $columns .= ', tracking_mode';
719       $values .= ', '.(int)$fields['tracking_mode'];
720     }
721
722     if ($fields['project_required']) {
723       $columns .= ', project_required';
724       $values .= ', '.(int)$fields['project_required'];
725     }
726
727     if ($fields['task_required']) {
728       $columns .= ', task_required';
729       $values .= ', '.(int)$fields['task_required'];
730     }
731
732     if ($fields['record_type']) {
733       $columns .= ', record_type';
734       $values .= ', '.(int)$fields['record_type'];
735     }
736
737     if ($fields['bcc_email']) {
738       $columns .= ', bcc_email';
739       $values .= ', '.$mdb2->quote($fields['bcc_email']);
740     }
741
742     if ($fields['plugins']) {
743       $columns .= ', plugins';
744       $values .= ', '.$mdb2->quote($fields['plugins']);
745     }
746
747     if ($fields['lock_spec']) {
748       $columns .= ', lock_spec';
749       $values .= ', '.$mdb2->quote($fields['lock_spec']);
750     }
751
752     if ($fields['workday_minutes']) {
753       $columns .= ', workday_minutes';
754       $values .= ', '.(int)$fields['workday_minutes'];
755     }
756
757     if ($fields['config']) {
758       $columns .= ', config';
759       $values .= ', '.$mdb2->quote($fields['config']);
760     }
761
762     $columns .= ', created, created_ip, created_by';
763     $values .= ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$mdb2->quote($user->id);
764
765     $sql = "insert into tt_groups ($columns) values($values)";
766     $affected = $mdb2->exec($sql);
767
768     if (!is_a($affected, 'PEAR_Error')) {
769       $group_id = $mdb2->lastInsertID('tt_groups', 'id');
770       return $group_id;
771     }
772
773     return false;
774   }
775
776   // The getInactiveGroups is a maintenance function that returns an array of inactive group ids (max 100).
777   static function getInactiveGroups() {
778     $inactive_groups = array();
779     $mdb2 = getConnection();
780
781     // Get all group ids for groups created or modified more than 8 months ago.
782     // $ts = date('Y-m-d', strtotime('-1 year'));
783     $ts = $mdb2->quote(date('Y-m-d', strtotime('-8 month')));
784     $sql =  "select id from tt_groups where created < $ts and (modified is null or modified < $ts) order by id";
785     $res = $mdb2->query($sql);
786
787     $count = 0;
788     if (!is_a($res, 'PEAR_Error')) {
789       while ($val = $res->fetchRow()) {
790         $group_id = $val['id'];
791         if (ttTeamHelper::isGroupActive($group_id) == false) {
792           $count++;
793           $inactive_groups[] = $group_id;
794           // Limit the array size for perfomance by allowing this operation on small chunks only.
795           if ($count >= 100) break;
796         }
797       }
798       return $inactive_groups;
799     }
800     return false;
801   }
802
803   // The isGroupActive determines if a group is using Time Tracker or abandoned it.
804   static function isGroupActive($group_id) {
805     $users = array();
806
807     $mdb2 = getConnection();
808     $sql = "select id from tt_users where group_id = $group_id";
809     $res = $mdb2->query($sql);
810     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
811     while ($val = $res->fetchRow()) {
812       $users[] = $val['id'];
813     }
814     $user_list = implode(',', $users); // This is a comma-separated list of user ids.
815     if (!$user_list)
816       return false; // No users in group.
817
818     $count = 0;
819     $ts = date('Y-m-d', strtotime('-2 years'));
820     $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and created > '$ts'";
821     $res = $mdb2->query($sql);
822     if (!is_a($res, 'PEAR_Error')) {
823       if ($val = $res->fetchRow()) {
824         $count = $val['cnt'];
825       }
826     }
827
828     if ($count == 0)
829       return false;  // No time entries for the last 2 years.
830
831     if ($count <= 5) {
832       // We will consider a group inactive if it has 5 or less time entries made more than 1 year ago.
833       $count_last_year = 0;
834       $ts = date('Y-m-d', strtotime('-1 year'));
835       $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and created > '$ts'";
836       $res = $mdb2->query($sql);
837       if (!is_a($res, 'PEAR_Error')) {
838         if ($val = $res->fetchRow()) {
839           $count_last_year = $val['cnt'];
840         }
841         if ($count_last_year == 0)
842           return false;  // No time entries for the last year and only a few entries before that.
843       }
844     }
845     return true;
846   }
847
848   // The delete function permanently deletes all data for a group.
849   static function delete($group_id) {
850     $mdb2 = getConnection();
851
852     // Delete users.
853     $sql = "select id from tt_users where group_id = $group_id";
854     $res = $mdb2->query($sql);
855     if (is_a($res, 'PEAR_Error')) return false;
856     while ($val = $res->fetchRow()) {
857       $user_id = $val['id'];
858       if (!ttUserHelper::delete($user_id)) return false;
859     }
860
861     // Delete tasks.
862     if (!ttTeamHelper::deleteTasks($group_id)) return false;
863
864     // Delete client to project binds.
865     $sql = "delete from tt_client_project_binds where client_id in (select id from tt_clients where group_id = $group_id)";
866     $affected = $mdb2->exec($sql);
867     if (is_a($affected, 'PEAR_Error')) return false;
868
869     // Delete projects.
870     $sql = "delete from tt_projects where group_id = $group_id";
871     $affected = $mdb2->exec($sql);
872     if (is_a($affected, 'PEAR_Error')) return false;
873
874     // Delete clients.
875     $sql = "delete from tt_clients where group_id = $group_id";
876     $affected = $mdb2->exec($sql);
877     if (is_a($affected, 'PEAR_Error')) return false;
878
879     // Delete invoices.
880     $sql = "delete from tt_invoices where group_id = $group_id";
881     $affected = $mdb2->exec($sql);
882     if (is_a($affected, 'PEAR_Error')) return false;
883
884     // Delete custom fields.
885     if (!ttTeamHelper::deleteCustomFields($group_id)) return false;
886
887     // Delete roles.
888     $sql = "delete from tt_roles where group_id = $group_id";
889     $affected = $mdb2->exec($sql);
890     if (is_a($affected, 'PEAR_Error')) return false;
891
892     // Delete group.
893     $sql = "delete from tt_groups where id = $group_id";
894     $affected = $mdb2->exec($sql);
895     if (is_a($affected, 'PEAR_Error')) return false;
896
897     return true;
898   }
899
900   // The markTasksDeleted deletes task binds and marks the tasks as deleted for a group.
901   static function markTasksDeleted($group_id) {
902     $mdb2 = getConnection();
903     $sql = "select id from tt_tasks where group_id = $group_id";
904     $res = $mdb2->query($sql);
905     if (is_a($res, 'PEAR_Error')) return false;
906
907     while ($val = $res->fetchRow()) {
908
909       // Delete task binds.
910       $task_id = $val['id'];
911       $sql = "delete from tt_project_task_binds where task_id = $task_id";
912       $affected = $mdb2->exec($sql);
913       if (is_a($affected, 'PEAR_Error')) return false;
914
915       // Mark task as deleted.
916       $sql = "update tt_tasks set status = NULL where id = $task_id";
917       $affected = $mdb2->exec($sql);
918       if (is_a($affected, 'PEAR_Error')) return false;
919     }
920
921     return true;
922   }
923
924   // The deleteTasks deletes all tasks and task binds for an inactive group.
925   static function deleteTasks($group_id) {
926     $mdb2 = getConnection();
927     $sql = "select id from tt_tasks where group_id = $group_id";
928     $res = $mdb2->query($sql);
929     if (is_a($res, 'PEAR_Error')) return false;
930
931     while ($val = $res->fetchRow()) {
932
933       // Delete task binds.
934       $task_id = $val['id'];
935       $sql = "delete from tt_project_task_binds where task_id = $task_id";
936       $affected = $mdb2->exec($sql);
937       if (is_a($affected, 'PEAR_Error')) return false;
938
939       // Delete task.
940       $sql = "delete from tt_tasks where id = $task_id";
941       $affected = $mdb2->exec($sql);
942       if (is_a($affected, 'PEAR_Error')) return false;
943     }
944
945     return true;
946   }
947
948   // The deleteCustomFields cleans up tt_custom_field_log, tt_custom_field_options and tt_custom_fields tables for an inactive group.
949   static function deleteCustomFields($group_id) {
950     $mdb2 = getConnection();
951     $sql = "select id from tt_custom_fields where group_id = $group_id";
952     $res = $mdb2->query($sql);
953     if (is_a($res, 'PEAR_Error')) return false;
954
955     while ($val = $res->fetchRow()) {
956       $field_id = $val['id'];
957
958       // Clean up tt_custom_field_log.
959       $sql = "delete from tt_custom_field_log where field_id = $field_id";
960       $affected = $mdb2->exec($sql);
961       if (is_a($affected, 'PEAR_Error')) return false;
962
963       // Clean up tt_custom_field_options.
964       $sql = "delete from tt_custom_field_options where field_id = $field_id";
965       $affected = $mdb2->exec($sql);
966       if (is_a($affected, 'PEAR_Error')) return false;
967
968       // Delete custom field.
969       $sql = "delete from tt_custom_fields where id = $field_id";
970       $affected = $mdb2->exec($sql);
971       if (is_a($affected, 'PEAR_Error')) return false;
972     }
973
974     return true;
975   }
976 }