d607ca1bb06d04f54ec5b390932042e2ad68beba
[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 teams.
34 class ttTeamHelper {
35
36   // The getUserCount function returns number of people in team.
37   static function getUserCount($team_id) {
38     $mdb2 = getConnection();
39
40     $sql = "select count(id) as cnt from tt_users where team_id = $team_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 team 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 team.
72   static function getActiveUsers($options = null) {
73     global $user;
74     $mdb2 = getConnection();
75
76     if (isset($options['getAllFields']))
77       $sql = "select * from tt_users where team_id = $user->team_id and status = 1 order by upper(name)";
78     else
79       $sql = "select id, name from tt_users where team_id = $user->team_id and status = 1 order by upper(name)";
80     $res = $mdb2->query($sql);
81     $user_list = array();
82     if (is_a($res, 'PEAR_Error'))
83       return false;
84     while ($val = $res->fetchRow()) {
85       $user_list[] = $val;
86     }
87
88     if (isset($options['putSelfFirst'])) {
89       // Put own entry at the front.
90       $cnt = count($user_list);
91       for($i = 0; $i < $cnt; $i++) {
92         if ($user_list[$i]['id'] == $user->id) {
93           $self = $user_list[$i]; // Found self.
94           array_unshift($user_list, $self); // Put own entry at the front.
95           array_splice($user_list, $i+1, 1); // Remove duplicate.
96         }
97       }
98     }
99     return $user_list;
100   }
101
102   // The getUsers obtains all active and inactive (but not deleted) users in a given team.
103   static function getUsers() {
104     global $user;
105     $mdb2 = getConnection();
106
107     $sql = "select id, name from tt_users where team_id = $user->team_id and (status = 1 or status = 0) order by upper(name)";
108     $res = $mdb2->query($sql);
109     $user_list = array();
110     if (is_a($res, 'PEAR_Error'))
111       return false;
112     while ($val = $res->fetchRow()) {
113       $user_list[] = $val;
114     }
115
116     return $user_list;
117   }
118
119   // The getInactiveUsers obtains all inactive users in a given team.
120   static function getInactiveUsers($team_id, $all_fields = false) {
121     $mdb2 = getConnection();
122
123     if ($all_fields)
124       $sql = "select * from tt_users where team_id = $team_id and status = 0 order by upper(name)";
125     else
126       $sql = "select id, name from tt_users where team_id = $team_id and status = 0 order by upper(name)";
127     $res = $mdb2->query($sql);
128     $result = array();
129     if (!is_a($res, 'PEAR_Error')) {
130       while ($val = $res->fetchRow()) {
131         $result[] = $val;
132       }
133       return $result;
134     }
135     return false;
136   }
137
138   // The getAllUsers obtains all users in a given team.
139   static function getAllUsers($team_id, $all_fields = false) {
140     $mdb2 = getConnection();
141
142     if ($all_fields)
143       $sql = "select * from tt_users where team_id = $team_id order by upper(name)";
144     else
145       $sql = "select id, name from tt_users where team_id = $team_id order by upper(name)";
146     $res = $mdb2->query($sql);
147     $result = array();
148     if (!is_a($res, 'PEAR_Error')) {
149       while ($val = $res->fetchRow()) {
150         $result[] = $val;
151       }
152       return $result;
153     }
154     return false;
155   }
156
157   // getActiveProjects - returns an array of active projects for team.
158   static function getActiveProjects($team_id)
159   {
160     $result = array();
161     $mdb2 = getConnection();
162
163     $sql = "select id, name, description, tasks from tt_projects
164       where team_id = $team_id and status = 1 order by upper(name)";
165     $res = $mdb2->query($sql);
166     $result = array();
167     if (!is_a($res, 'PEAR_Error')) {
168       while ($val = $res->fetchRow()) {
169         $result[] = $val;
170       }
171     }
172     return $result;
173   }
174
175   // getInactiveProjects - returns an array of inactive projects for team.
176   static function getInactiveProjects($team_id)
177   {
178     $result = array();
179     $mdb2 = getConnection();
180
181     $sql = "select id, name, description, tasks from tt_projects
182       where team_id = $team_id and status = 0 order by upper(name)";
183     $res = $mdb2->query($sql);
184     $result = array();
185     if (!is_a($res, 'PEAR_Error')) {
186       while ($val = $res->fetchRow()) {
187         $result[] = $val;
188       }
189     }
190     return $result;
191   }
192
193   // The getAllProjects obtains all projects in a given team.
194   static function getAllProjects($team_id, $all_fields = false) {
195     $mdb2 = getConnection();
196
197     if ($all_fields)
198       $sql = "select * from tt_projects where team_id = $team_id order by status, upper(name)";
199     else
200       $sql = "select id, name from tt_projects where team_id = $team_id order by status, upper(name)";
201     $res = $mdb2->query($sql);
202     $result = array();
203     if (!is_a($res, 'PEAR_Error')) {
204       while ($val = $res->fetchRow()) {
205         $result[] = $val;
206       }
207       return $result;
208     }
209     return false;
210   }
211
212   // getActiveTasks - returns an array of active tasks for team.
213   static function getActiveTasks($team_id)
214   {
215     $result = array();
216     $mdb2 = getConnection();
217
218     $sql = "select id, name, description from tt_tasks where team_id = $team_id and status = 1 order by upper(name)";
219     $res = $mdb2->query($sql);
220     $result = array();
221     if (!is_a($res, 'PEAR_Error')) {
222       while ($val = $res->fetchRow()) {
223         $result[] = $val;
224       }
225     }
226     return $result;
227   }
228
229   // getInactiveTasks - returns an array of inactive tasks for team.
230   static function getInactiveTasks($team_id)
231   {
232     $result = array();
233     $mdb2 = getConnection();
234
235     $sql = "select id, name, description from tt_tasks
236       where team_id = $team_id and status = 0 order by upper(name)";
237     $res = $mdb2->query($sql);
238     $result = array();
239     if (!is_a($res, 'PEAR_Error')) {
240       while ($val = $res->fetchRow()) {
241         $result[] = $val;
242       }
243     }
244     return $result;
245   }
246
247   // The getAllTasks obtains all tasks in a given team.
248   static function getAllTasks($team_id, $all_fields = false) {
249     $mdb2 = getConnection();
250
251     if ($all_fields)
252       $sql = "select * from tt_tasks where team_id = $team_id order by status, upper(name)";
253     else
254       $sql = "select id, name from tt_tasks where team_id = $team_id order by status, upper(name)";
255     $res = $mdb2->query($sql);
256     $result = array();
257     if (!is_a($res, 'PEAR_Error')) {
258       while ($val = $res->fetchRow()) {
259         $result[] = $val;
260       }
261       return $result;
262     }
263     return false;
264   }
265
266   // The getActiveClients returns an array of active clients for team.
267   static function getActiveClients($team_id, $all_fields = false)
268   {
269     $result = array();
270     $mdb2 = getConnection();
271
272     if ($all_fields)
273       $sql = "select * from tt_clients where team_id = $team_id and status = 1 order by upper(name)";
274     else
275       $sql = "select id, name from tt_clients where team_id = $team_id and status = 1 order by upper(name)";
276
277     $res = $mdb2->query($sql);
278     $result = array();
279     if (!is_a($res, 'PEAR_Error')) {
280       while ($val = $res->fetchRow()) {
281         $result[] = $val;
282       }
283     }
284     return $result;
285   }
286
287   // The getInactiveClients returns an array of inactive clients for team.
288   static function getInactiveClients($team_id, $all_fields = false)
289   {
290     $result = array();
291     $mdb2 = getConnection();
292
293     if ($all_fields)
294       $sql = "select * from tt_clients where team_id = $team_id and status = 0 order by upper(name)";
295     else
296       $sql = "select id, name from tt_clients where team_id = $team_id and status = 0 order by upper(name)";
297
298     $res = $mdb2->query($sql);
299     $result = array();
300     if (!is_a($res, 'PEAR_Error')) {
301       while ($val = $res->fetchRow()) {
302         $result[] = $val;
303       }
304     }
305     return $result;
306   }
307
308   // The getAllClients obtains all clients in a given team.
309   static function getAllClients($team_id, $all_fields = false) {
310     $mdb2 = getConnection();
311
312     if ($all_fields)
313       $sql = "select * from tt_clients where team_id = $team_id order by status, upper(name)";
314     else
315       $sql = "select id, name from tt_clients where team_id = $team_id order by status, upper(name)";
316
317     $res = $mdb2->query($sql);
318     $result = array();
319     if (!is_a($res, 'PEAR_Error')) {
320       while ($val = $res->fetchRow()) {
321         $result[] = $val;
322       }
323       return $result;
324     }
325     return false;
326   }
327
328   // The getActiveInvoices returns an array of active invoices for team.
329   static function getActiveInvoices($localizeDates = true)
330   {
331     global $user;
332     $addPaidStatus = $user->isPluginEnabled('ps');
333
334     $result = array();
335     $mdb2 = getConnection();
336
337     if (ROLE_CLIENT == $user->role && $user->client_id)
338       $client_part = " and i.client_id = $user->client_id";
339
340     $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i
341       left join tt_clients c on (c.id = i.client_id)
342       where i.status = 1 and i.team_id = $user->team_id $client_part order by i.name";
343     $res = $mdb2->query($sql);
344     $result = array();
345     if (!is_a($res, 'PEAR_Error')) {
346       $dt = new DateAndTime(DB_DATEFORMAT);
347       while ($val = $res->fetchRow()) {
348         if ($localizeDates) {
349           $dt->parseVal($val['date']);
350           $val['date'] = $dt->toString($user->date_format);
351         }
352         if ($addPaidStatus)
353           $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
354         $result[] = $val;
355       }
356     }
357     return $result;
358   }
359
360   // The getAllInvoices returns an array of all invoices for team.
361   static function getAllInvoices()
362   {
363     global $user;
364
365     $result = array();
366     $mdb2 = getConnection();
367
368     $sql = "select * from tt_invoices where team_id = $user->team_id";
369     $res = $mdb2->query($sql);
370     $result = array();
371     if (!is_a($res, 'PEAR_Error')) {
372       $dt = new DateAndTime(DB_DATEFORMAT);
373       while ($val = $res->fetchRow()) {
374         $result[] = $val;
375       }
376     }
377     return $result;
378   }
379
380   // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
381   static function getRecentInvoices($team_id, $client_id)
382   {
383     global $user;
384
385     $result = array();
386     $mdb2 = getConnection();
387
388     $sql = "select i.id, i.name from tt_invoices i
389       left join tt_clients c on (c.id = i.client_id)
390       where i.team_id = $team_id and i.status = 1 and c.id = $client_id
391       order by i.id desc limit 3";
392     $res = $mdb2->query($sql);
393     $result = array();
394     if (!is_a($res, 'PEAR_Error')) {
395       $dt = new DateAndTime(DB_DATEFORMAT);
396       while ($val = $res->fetchRow()) {
397         $result[] = $val;
398       }
399     }
400     return $result;
401   }
402
403   // getUserToProjectBinds - obtains all user to project binds for a team.
404   static function getUserToProjectBinds($team_id) {
405     $mdb2 = getConnection();
406
407     $result = array();
408     $sql = "select * from tt_user_project_binds where user_id in (select id from tt_users where team_id = $team_id) order by user_id, status, project_id";
409     $res = $mdb2->query($sql);
410     $result = array();
411     if (!is_a($res, 'PEAR_Error')) {
412       while ($val = $res->fetchRow()) {
413         $result[] = $val;
414       }
415       return $result;
416     }
417     return false;
418   }
419
420   // The getAllCustomFields obtains all custom fields in a given team.
421   static function getAllCustomFields($team_id) {
422     $mdb2 = getConnection();
423
424     $sql = "select * from tt_custom_fields where team_id = $team_id order by status";
425
426     $res = $mdb2->query($sql);
427     $result = array();
428     if (!is_a($res, 'PEAR_Error')) {
429       while ($val = $res->fetchRow()) {
430         $result[] = $val;
431       }
432       return $result;
433     }
434     return false;
435   }
436
437   // The getAllCustomFieldOptions obtains all custom field options in a given team.
438   static function getAllCustomFieldOptions($team_id) {
439     $mdb2 = getConnection();
440
441     $sql = "select * from tt_custom_field_options where field_id in (select id from tt_custom_fields where team_id = $team_id) order by id";
442
443     $res = $mdb2->query($sql);
444     $result = array();
445     if (!is_a($res, 'PEAR_Error')) {
446       while ($val = $res->fetchRow()) {
447         $result[] = $val;
448       }
449       return $result;
450     }
451     return false;
452   }
453
454   // The getCustomFieldLog obtains all custom field log entries for a given team.
455   static function getCustomFieldLog($team_id) {
456     $mdb2 = getConnection();
457
458     $sql = "select * from tt_custom_field_log where field_id in (select id from tt_custom_fields where team_id = $team_id) order by id";
459
460     $res = $mdb2->query($sql);
461     $result = array();
462     if (!is_a($res, 'PEAR_Error')) {
463       while ($val = $res->fetchRow()) {
464         $result[] = $val;
465       }
466       return $result;
467     }
468     return false;
469   }
470
471   // getFavReports - obtains all favorite reports for all users in team.
472   static function getFavReports($team_id) {
473     $mdb2 = getConnection();
474
475     $result = array();
476     $sql = "select * from tt_fav_reports where user_id in (select id from tt_users where team_id = $team_id)";
477     $res = $mdb2->query($sql);
478     $result = array();
479     if (!is_a($res, 'PEAR_Error')) {
480       while ($val = $res->fetchRow()) {
481         $result[] = $val;
482       }
483       return $result;
484     }
485     return false;
486   }
487
488   // getExpenseItems - obtains all expense items for all users in team.
489   static function getExpenseItems($team_id) {
490     $mdb2 = getConnection();
491
492     $result = array();
493     $sql = "select * from tt_expense_items where user_id in (select id from tt_users where team_id = $team_id)";
494     $res = $mdb2->query($sql);
495     $result = array();
496     if (!is_a($res, 'PEAR_Error')) {
497       while ($val = $res->fetchRow()) {
498         $result[] = $val;
499       }
500       return $result;
501     }
502     return false;
503   }
504
505   // getPredefinedExpenses - obtains predefined expenses for team.
506   static function getPredefinedExpenses($team_id) {
507     global $user;
508     $replaceDecimalMark = ('.' != $user->decimal_mark);
509
510     $mdb2 = getConnection();
511
512     $result = array();
513     $sql = "select id, name, cost from tt_predefined_expenses where team_id = $team_id";
514     $res = $mdb2->query($sql);
515     $result = array();
516     if (!is_a($res, 'PEAR_Error')) {
517       while ($val = $res->fetchRow()) {
518         if ($replaceDecimalMark)
519           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
520         $result[] = $val;
521       }
522       return $result;
523     }
524     return false;
525   }
526
527   // getNotifications - obtains notification descriptions for team.
528   static function getNotifications($team_id) {
529     $mdb2 = getConnection();
530
531     $result = array();
532     $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c
533       left join tt_fav_reports fr on (fr.id = c.report_id)
534       where c.team_id = $team_id and c.status = 1 and fr.status = 1";
535     $res = $mdb2->query($sql);
536     $result = array();
537     if (!is_a($res, 'PEAR_Error')) {
538       while ($val = $res->fetchRow()) {
539         $result[] = $val;
540       }
541       return $result;
542     }
543     return false;
544   }
545
546   // getMonthlyQuotas - obtains monthly quotas for team.
547   static function getMonthlyQuotas($team_id) {
548     $mdb2 = getConnection();
549
550     $result = array();
551     $sql = "select year, month, quota from tt_monthly_quotas where team_id = $team_id";
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       return $result;
559     }
560     return false;
561   }
562
563   // The getTeams function returns an array of all active teams on the server.
564   static function getTeams() {
565     $result = array();
566     $mdb2 = getConnection();
567
568     $sql =  "select id, name, lang, timestamp from tt_teams where status = 1 order by id desc";
569     $res = $mdb2->query($sql);
570     $result = array();
571     if (!is_a($res, 'PEAR_Error')) {
572       while ($val = $res->fetchRow()) {
573         $val['date'] = substr($val['timestamp'], 0, 10); // Strip the time.
574         $result[] = $val;
575       }
576       return $result;
577     }
578     return false;
579   }
580
581   // The markDeleted function marks the team and everything in it as deleted.
582   static function markDeleted($team_id) {
583
584     // Iterate through team users and mark them as deleted.
585     $users = ttTeamHelper::getAllUsers($team_id);
586     foreach ($users as $one_user) {
587       if (!ttUserHelper::markDeleted($one_user['id'])) return false;
588     }
589
590     // Mark tasks deleted.
591     if (!ttTeamHelper::markTasksDeleted($team_id)) return false;
592
593     $mdb2 = getConnection();
594
595     // Mark projects deleted.
596     $sql = "update tt_projects set status = NULL where team_id = $team_id";
597     $affected = $mdb2->exec($sql);
598     if (is_a($affected, 'PEAR_Error')) return false;
599
600     // Mark clients deleted.
601     $sql = "update tt_clients set status = NULL where team_id = $team_id";
602     $affected = $mdb2->exec($sql);
603     if (is_a($affected, 'PEAR_Error')) return false;
604
605     // Mark custom fields deleted.
606     $sql = "update tt_custom_fields set status = NULL where team_id = $team_id";
607     $affected = $mdb2->exec($sql);
608     if (is_a($affected, 'PEAR_Error')) return false;
609
610     // Mark team deleted.
611     $sql = "update tt_teams set status = NULL where id = $team_id";
612     $affected = $mdb2->exec($sql);
613     if (is_a($affected, 'PEAR_Error')) return false;
614
615     return true;
616   }
617
618   // The getTeamDetails function returns team details.
619   static function getTeamDetails($team_id) {
620     $result = array();
621     $mdb2 = getConnection();
622
623     $role_manager = ROLE_MANAGER;
624     $sql = "select t.name as team_name, u.id as manager_id, u.name as manager_name, u.login as manager_login, u.email as manager_email
625       from tt_teams t
626       inner join tt_users u on (u.team_id = t.id and u.role = $role_manager)
627       where t.id = $team_id";
628
629     $res = $mdb2->query($sql);
630     if (!is_a($res, 'PEAR_Error')) {
631       $val = $res->fetchRow();
632       return $val;
633     }
634
635     return false;
636   }
637
638   // The insert function creates a new team.
639   static function insert($fields) {
640
641     $mdb2 = getConnection();
642
643     $decimal_mark = $fields['decimal_mark'];
644     if ($decimal_mark !== null) {
645       $decimal_mark_f = ', decimal_mark';
646       $decimal_mark_v = ', ' . $mdb2->quote($decimal_mark);
647     } else {
648       $decimal_mark_f = '';
649       $decimal_mark_v = '';
650     }
651
652     $lang = $fields['lang'];
653     if (!$lang) {
654       global $i18n;
655       $lang = $i18n->lang;
656     }
657
658     $date_format = $fields['date_format'];
659     if ($date_format !== null) {
660       $date_format_f = ', date_format';
661       $date_format_v = ', ' . $mdb2->quote($date_format);
662     } elseif (defined('DATE_FORMAT_DEFAULT')) {
663       $date_format_f = ', date_format';
664       $date_format_v = ', ' . $mdb2->quote(DATE_FORMAT_DEFAULT);
665     } else {
666       $date_format_f = '';
667       $date_format_v = '';
668     }
669
670     $time_format = $fields['time_format'];
671     if ($time_format !== null) {
672       $time_format_f = ', time_format';
673       $time_format_v = ', ' . $mdb2->quote($time_format);
674     } elseif (defined('TIME_FORMAT_DEFAULT')) {
675       $time_format_f = ', time_format';
676       $time_format_v = ', ' . $mdb2->quote(TIME_FORMAT_DEFAULT);
677     } else {
678       $time_format_f = '';
679       $time_format_v = '';
680     }
681
682     $week_start = $fields['week_start'];
683     if ($week_start !== null) {
684       $week_start_f = ', week_start';
685       $week_start_v = ', ' . (int)$week_start;
686     } elseif (defined('WEEK_START_DEFAULT')) {
687       $week_start_f = ', week_start';
688       $week_start_v = ', ' . (int)WEEK_START_DEFAULT;
689     } else {
690       $week_start_f = '';
691       $week_start_v = '';
692     }
693
694     $tracking_mode = $fields['tracking_mode'];
695     if ($tracking_mode !== null) {
696       $tracking_mode_f = ', tracking_mode';
697       $tracking_mode_v = ', ' . (int)$tracking_mode;
698     } else {
699       $tracking_mode_f = '';
700       $tracking_mode_v = '';
701     }
702
703     $project_required = $fields['project_required'];
704     if ($project_required !== null) {
705       $project_required_f = ', project_required';
706       $project_required_v = ', ' . (int)$project_required;
707     } else {
708       $project_required_f = '';
709       $project_required_v = '';
710     }
711
712     $task_required = $fields['task_required'];
713     if ($task_required !== null) {
714       $task_required_f = ', task_required';
715       $task_required_v = ', ' . (int)$task_required;
716     } else {
717       $task_required_f = '';
718       $task_required_v = '';
719     }
720
721     $record_type = $fields['record_type'];
722     if ($record_type !== null) {
723       $record_type_f = ', record_type';
724       $record_type_v = ', ' . (int)$record_type;
725     } else {
726       $record_type_f = '';
727       $record_type_v = '';
728     }
729
730     $uncompleted_indicators = $fields['uncompleted_indicators'];
731     if ($uncompleted_indicators !== null) {
732       $uncompleted_indicators_f = ', uncompleted_indicators';
733       $uncompleted_indicators_v = ', ' . (int)$uncompleted_indicators;
734     } else {
735       $uncompleted_indicators_f = '';
736       $uncompleted_indicators_v = '';
737     }
738
739     $bcc_email = $fields['bcc_email'];
740     if ($bcc_email !== null) {
741       $bcc_email_f = ', bcc_email';
742       $bcc_email_v = ', ' . $mdb2->quote($bcc_email);
743     } else {
744       $bcc_email_f = '';
745       $bcc_email_v = '';
746     }
747
748     $plugins = $fields['plugins'];
749     if ($plugins !== null) {
750       $plugins_f = ', plugins';
751       $plugins_v = ', ' . $mdb2->quote($plugins);
752     } else {
753       $plugins_f = '';
754       $plugins_v = '';
755     }
756
757     $lock_spec = $fields['lock_spec'];
758     if ($lock_spec !== null) {
759       $lockspec_f = ', lock_spec';
760       $lockspec_v = ', ' . $mdb2->quote($lock_spec);
761     } else {
762       $lockspec_f = '';
763       $lockspec_v = '';
764     }
765
766     $workday_hours = $fields['workday_hours'];
767     if ($workday_hours !== null) {
768       $workday_hours_f = ', workday_hours';
769       $workday_hours_v = ', ' . (int)$workday_hours;
770     } else {
771       $workday_hours_f = '';
772       $workday_hours_v = '';
773     }
774
775     $sql = "insert into tt_teams (name, currency $decimal_mark_f, lang $date_format_f $time_format_f $week_start_f $tracking_mode_f $project_required_f $task_required_f $record_type_f $uncompleted_indicators_f $bcc_email_f $plugins_f $lockspec_f $workday_hours_f)
776       values(".$mdb2->quote(trim($fields['name'])).
777       ", ".$mdb2->quote(trim($fields['currency']))." $decimal_mark_v, ".$mdb2->quote($lang).
778       "$date_format_v $time_format_v $week_start_v $tracking_mode_v $project_required_v $task_required_v $record_type_v $uncompleted_indicators_v $bcc_email_v $plugins_v $lockspec_v $workday_hours_v)";
779     $affected = $mdb2->exec($sql);
780
781     if (!is_a($affected, 'PEAR_Error')) {
782       $team_id = $mdb2->lastInsertID('tt_teams', 'id');
783       return $team_id;
784     }
785
786     return false;
787   }
788
789   // The update function updates team information.
790   static function update($team_id, $fields)
791   {
792     $mdb2 = getConnection();
793     $name_part = 'name = '.$mdb2->quote($fields['name']);
794     $currency_part = '';
795     $lang_part = '';
796     $decimal_mark_part = '';
797     $date_format_part = '';
798     $time_format_part = '';
799     $week_start_part = '';
800     $tracking_mode_part = '';
801     $task_required_part = ' , task_required = '.(int) $fields['task_required'];
802     $record_type_part = '';
803     $uncompleted_indicators_part = '';
804     $bcc_email_part = '';
805     $plugins_part = '';
806     $lock_spec_part = '';
807     $workday_hours_part = '';
808
809     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
810     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
811     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
812     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
813     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
814     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
815     if (isset($fields['tracking_mode'])) $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
816     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
817     if (isset($fields['uncompleted_indicators'])) $uncompleted_indicators_part = ', uncompleted_indicators = '.(int) $fields['uncompleted_indicators'];
818     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
819     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
820     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
821     if (isset($fields['workday_hours'])) $workday_hours_part = ', workday_hours = '.$mdb2->quote($fields['workday_hours']);
822
823     $sql = "update tt_teams set $name_part $currency_part $lang_part $decimal_mark_part
824       $date_format_part $time_format_part $week_start_part $tracking_mode_part $task_required_part $record_type_part
825       $uncompleted_indicators_part $bcc_email_part $plugins_part $lock_spec_part $workday_hours_part where id = $team_id";
826     $affected = $mdb2->exec($sql);
827     if (is_a($affected, 'PEAR_Error')) return false;
828
829     return true;
830   }
831
832   // The getInactiveTeams is a maintenance function that returns an array of inactive team ids (max 100).
833   static function getInactiveTeams() {
834     $inactive_teams = array();
835     $mdb2 = getConnection();
836
837     // Get all team ids for teams created or modified more than 6 months ago.
838     // $ts = date('Y-m-d', strtotime('-1 year'));
839     $ts = date('Y-m-d', strtotime('-6 month'));
840     $sql =  "select id from tt_teams where timestamp < '$ts' order by id";
841     $res = $mdb2->query($sql);
842
843     $count = 0;
844     if (!is_a($res, 'PEAR_Error')) {
845       while ($val = $res->fetchRow()) {
846         $team_id = $val['id'];
847         if (ttTeamHelper::isTeamActive($team_id) == false) {
848           $count++;
849           $inactive_teams[] = $team_id;
850           // Limit the array size for perfomance by allowing this operation on small chunks only.
851           if ($count >= 100) break;
852         }
853       }
854       return $inactive_teams;
855     }
856     return false;
857   }
858
859   // The isTeamActive determines if a team is using Time Tracker or abandoned it.
860   static function isTeamActive($team_id) {
861     $users = array();
862
863     $mdb2 = getConnection();
864     $sql = "select id from tt_users where team_id = $team_id";
865     $res = $mdb2->query($sql);
866     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
867     while ($val = $res->fetchRow()) {
868       $users[] = $val['id'];
869     }
870     $user_list = implode(',', $users); // This is a comma-separated list of user ids.
871     if (!$user_list)
872       return false; // No users in team.
873
874     $count = 0;
875     $ts = date('Y-m-d', strtotime('-2 years'));
876     $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
877     $res = $mdb2->query($sql);
878     if (!is_a($res, 'PEAR_Error')) {
879       if ($val = $res->fetchRow()) {
880         $count = $val['cnt'];
881       }
882     }
883
884     if ($count == 0)
885       return false;  // No time entries for the last 2 years.
886
887     if ($count <= 5) {
888       // We will consider a team inactive if it has 5 or less time entries made more than 1 year ago.
889       $count_last_year = 0;
890       $ts = date('Y-m-d', strtotime('-1 year'));
891       $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
892       $res = $mdb2->query($sql);
893       if (!is_a($res, 'PEAR_Error')) {
894         if ($val = $res->fetchRow()) {
895           $count_last_year = $val['cnt'];
896         }
897         if ($count_last_year == 0)
898           return false;  // No time entries for the last year and only a few entries before that.
899       }
900     }
901     return true;
902   }
903
904   // The delete function permanently deletes all data for a team.
905   static function delete($team_id) {
906     $mdb2 = getConnection();
907
908     // Delete users.
909     $sql = "select id from tt_users where team_id = $team_id";
910     $res = $mdb2->query($sql);
911     if (is_a($res, 'PEAR_Error')) return false;
912     while ($val = $res->fetchRow()) {
913       $user_id = $val['id'];
914       if (!ttUserHelper::delete($user_id)) return false;
915     }
916
917     // Delete tasks.
918     if (!ttTeamHelper::deleteTasks($team_id)) return false;
919
920     // Delete client to project binds.
921     $sql = "delete from tt_client_project_binds where client_id in (select id from tt_clients where team_id = $team_id)";
922     $affected = $mdb2->exec($sql);
923     if (is_a($affected, 'PEAR_Error')) return false;
924
925     // Delete projects.
926     $sql = "delete from tt_projects where team_id = $team_id";
927     $affected = $mdb2->exec($sql);
928     if (is_a($affected, 'PEAR_Error')) return false;
929
930     // Delete clients.
931     $sql = "delete from tt_clients where team_id = $team_id";
932     $affected = $mdb2->exec($sql);
933     if (is_a($affected, 'PEAR_Error')) return false;
934
935     // Delete invoices.
936     $sql = "delete from tt_invoices where team_id = $team_id";
937     $affected = $mdb2->exec($sql);
938     if (is_a($affected, 'PEAR_Error')) return false;
939
940     // Delete custom fields.
941     if (!ttTeamHelper::deleteCustomFields($team_id)) return false;
942
943     // Delete team.
944     $sql = "delete from tt_teams where id = $team_id";
945     $affected = $mdb2->exec($sql);
946     if (is_a($affected, 'PEAR_Error')) return false;
947
948     return true;
949   }
950
951   // The markTasksDeleted deletes task binds and marks the tasks as deleted for a team.
952   static function markTasksDeleted($team_id) {
953     $mdb2 = getConnection();
954     $sql = "select id from tt_tasks where team_id = $team_id";
955     $res = $mdb2->query($sql);
956     if (is_a($res, 'PEAR_Error')) return false;
957
958     while ($val = $res->fetchRow()) {
959
960       // Delete task binds.
961       $task_id = $val['id'];
962       $sql = "delete from tt_project_task_binds where task_id = $task_id";
963       $affected = $mdb2->exec($sql);
964       if (is_a($affected, 'PEAR_Error')) return false;
965
966       // Mark task as deleted.
967       $sql = "update tt_tasks set status = NULL where id = $task_id";
968       $affected = $mdb2->exec($sql);
969       if (is_a($affected, 'PEAR_Error')) return false;
970     }
971
972     return true;
973   }
974
975   // The deleteTasks deletes all tasks and task binds for an inactive team.
976   static function deleteTasks($team_id) {
977     $mdb2 = getConnection();
978     $sql = "select id from tt_tasks where team_id = $team_id";
979     $res = $mdb2->query($sql);
980     if (is_a($res, 'PEAR_Error')) return false;
981
982     while ($val = $res->fetchRow()) {
983
984       // Delete task binds.
985       $task_id = $val['id'];
986       $sql = "delete from tt_project_task_binds where task_id = $task_id";
987       $affected = $mdb2->exec($sql);
988       if (is_a($affected, 'PEAR_Error')) return false;
989
990       // Delete task.
991       $sql = "delete from tt_tasks where id = $task_id";
992       $affected = $mdb2->exec($sql);
993       if (is_a($affected, 'PEAR_Error')) return false;
994     }
995
996     return true;
997   }
998
999   // The deleteCustomFields cleans up tt_custom_field_log, tt_custom_field_options and tt_custom_fields tables for an inactive team.
1000   static function deleteCustomFields($team_id) {
1001     $mdb2 = getConnection();
1002     $sql = "select id from tt_custom_fields where team_id = $team_id";
1003     $res = $mdb2->query($sql);
1004     if (is_a($res, 'PEAR_Error')) return false;
1005
1006     while ($val = $res->fetchRow()) {
1007       $field_id = $val['id'];
1008
1009       // Clean up tt_custom_field_log.
1010       $sql = "delete from tt_custom_field_log where field_id = $field_id";
1011       $affected = $mdb2->exec($sql);
1012       if (is_a($affected, 'PEAR_Error')) return false;
1013
1014       // Clean up tt_custom_field_options.
1015       $sql = "delete from tt_custom_field_options where field_id = $field_id";
1016       $affected = $mdb2->exec($sql);
1017       if (is_a($affected, 'PEAR_Error')) return false;
1018
1019       // Delete custom field.
1020       $sql = "delete from tt_custom_fields where id = $field_id";
1021       $affected = $mdb2->exec($sql);
1022       if (is_a($affected, 'PEAR_Error')) return false;
1023     }
1024
1025     return true;
1026   }
1027
1028   // enablePlugin either enables or disables a specific plugin for team.
1029   function enablePlugin($plugin, $enable = true)
1030   {
1031     global $user;
1032     if (!$user->canManageTeam())
1033       return false;
1034
1035     $plugin_array = explode(',', $user->plugins);
1036     if ($enable && !in_array($plugin, $plugin_array))
1037       $plugin_array[] = $plugin; // Add plugin to array.
1038
1039     if (!$enable && in_array($plugin, $plugin_array)) {
1040       $key = array_search($plugin, $plugin_array);
1041       if ($key !== false)
1042         unset($plugin_array[$key]); // Remove plugin from array.
1043     }
1044
1045     $plugins = implode(',', $plugin_array);
1046     if ($plugins != $user->plugins) {
1047       return ttTeamHelper::update($user->team_id, array(
1048         'name' => $user->team,
1049         'plugins' => $plugins));
1050     }
1051     return true;
1052   }
1053 }