Added description field to tt_roles.
[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   // getActiveRoles - returns an array of active roles for team.
267   static function getActiveRoles($team_id)
268   {
269     $result = array();
270     $mdb2 = getConnection();
271
272     $sql = "select id, name, description from tt_roles where team_id = $team_id and status = 1 order by upper(name)";
273     $res = $mdb2->query($sql);
274     $result = array();
275     if (!is_a($res, 'PEAR_Error')) {
276       while ($val = $res->fetchRow()) {
277         $result[] = $val;
278       }
279     }
280     return $result;
281   }
282
283   // getInactiveRoles - returns an array of inactive roles for team.
284   static function getInactiveRoles($team_id)
285   {
286     $result = array();
287     $mdb2 = getConnection();
288
289     $sql = "select id, name, description from tt_roles
290       where team_id = $team_id and status = 0 order by upper(name)";
291     $res = $mdb2->query($sql);
292     $result = array();
293     if (!is_a($res, 'PEAR_Error')) {
294       while ($val = $res->fetchRow()) {
295         $result[] = $val;
296       }
297     }
298     return $result;
299   }
300
301   // The getActiveClients returns an array of active clients for team.
302   static function getActiveClients($team_id, $all_fields = false)
303   {
304     $result = array();
305     $mdb2 = getConnection();
306
307     if ($all_fields)
308       $sql = "select * from tt_clients where team_id = $team_id and status = 1 order by upper(name)";
309     else
310       $sql = "select id, name from tt_clients where team_id = $team_id and status = 1 order by upper(name)";
311
312     $res = $mdb2->query($sql);
313     $result = array();
314     if (!is_a($res, 'PEAR_Error')) {
315       while ($val = $res->fetchRow()) {
316         $result[] = $val;
317       }
318     }
319     return $result;
320   }
321
322   // The getInactiveClients returns an array of inactive clients for team.
323   static function getInactiveClients($team_id, $all_fields = false)
324   {
325     $result = array();
326     $mdb2 = getConnection();
327
328     if ($all_fields)
329       $sql = "select * from tt_clients where team_id = $team_id and status = 0 order by upper(name)";
330     else
331       $sql = "select id, name from tt_clients where team_id = $team_id and status = 0 order by upper(name)";
332
333     $res = $mdb2->query($sql);
334     $result = array();
335     if (!is_a($res, 'PEAR_Error')) {
336       while ($val = $res->fetchRow()) {
337         $result[] = $val;
338       }
339     }
340     return $result;
341   }
342
343   // The getAllClients obtains all clients in a given team.
344   static function getAllClients($team_id, $all_fields = false) {
345     $mdb2 = getConnection();
346
347     if ($all_fields)
348       $sql = "select * from tt_clients where team_id = $team_id order by status, upper(name)";
349     else
350       $sql = "select id, name from tt_clients where team_id = $team_id order by status, upper(name)";
351
352     $res = $mdb2->query($sql);
353     $result = array();
354     if (!is_a($res, 'PEAR_Error')) {
355       while ($val = $res->fetchRow()) {
356         $result[] = $val;
357       }
358       return $result;
359     }
360     return false;
361   }
362
363   // The getActiveInvoices returns an array of active invoices for team.
364   static function getActiveInvoices($localizeDates = true)
365   {
366     global $user;
367     $addPaidStatus = $user->isPluginEnabled('ps');
368
369     $result = array();
370     $mdb2 = getConnection();
371
372     if (ROLE_CLIENT == $user->role && $user->client_id)
373       $client_part = " and i.client_id = $user->client_id";
374
375     $sql = "select i.id, i.name, i.date, i.client_id, i.status, c.name as client_name from tt_invoices i
376       left join tt_clients c on (c.id = i.client_id)
377       where i.status = 1 and i.team_id = $user->team_id $client_part order by i.name";
378     $res = $mdb2->query($sql);
379     $result = array();
380     if (!is_a($res, 'PEAR_Error')) {
381       $dt = new DateAndTime(DB_DATEFORMAT);
382       while ($val = $res->fetchRow()) {
383         if ($localizeDates) {
384           $dt->parseVal($val['date']);
385           $val['date'] = $dt->toString($user->date_format);
386         }
387         if ($addPaidStatus)
388           $val['paid'] = ttInvoiceHelper::isPaid($val['id']);
389         $result[] = $val;
390       }
391     }
392     return $result;
393   }
394
395   // The getAllInvoices returns an array of all invoices for team.
396   static function getAllInvoices()
397   {
398     global $user;
399
400     $result = array();
401     $mdb2 = getConnection();
402
403     $sql = "select * from tt_invoices where team_id = $user->team_id";
404     $res = $mdb2->query($sql);
405     $result = array();
406     if (!is_a($res, 'PEAR_Error')) {
407       $dt = new DateAndTime(DB_DATEFORMAT);
408       while ($val = $res->fetchRow()) {
409         $result[] = $val;
410       }
411     }
412     return $result;
413   }
414
415   // The getRecentInvoices returns an array of recent invoices (max 3) for a client.
416   static function getRecentInvoices($team_id, $client_id)
417   {
418     global $user;
419
420     $result = array();
421     $mdb2 = getConnection();
422
423     $sql = "select i.id, i.name from tt_invoices i
424       left join tt_clients c on (c.id = i.client_id)
425       where i.team_id = $team_id and i.status = 1 and c.id = $client_id
426       order by i.id desc limit 3";
427     $res = $mdb2->query($sql);
428     $result = array();
429     if (!is_a($res, 'PEAR_Error')) {
430       $dt = new DateAndTime(DB_DATEFORMAT);
431       while ($val = $res->fetchRow()) {
432         $result[] = $val;
433       }
434     }
435     return $result;
436   }
437
438   // getUserToProjectBinds - obtains all user to project binds for a team.
439   static function getUserToProjectBinds($team_id) {
440     $mdb2 = getConnection();
441
442     $result = array();
443     $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";
444     $res = $mdb2->query($sql);
445     $result = array();
446     if (!is_a($res, 'PEAR_Error')) {
447       while ($val = $res->fetchRow()) {
448         $result[] = $val;
449       }
450       return $result;
451     }
452     return false;
453   }
454
455   // The getAllCustomFields obtains all custom fields in a given team.
456   static function getAllCustomFields($team_id) {
457     $mdb2 = getConnection();
458
459     $sql = "select * from tt_custom_fields where team_id = $team_id order by status";
460
461     $res = $mdb2->query($sql);
462     $result = array();
463     if (!is_a($res, 'PEAR_Error')) {
464       while ($val = $res->fetchRow()) {
465         $result[] = $val;
466       }
467       return $result;
468     }
469     return false;
470   }
471
472   // The getAllCustomFieldOptions obtains all custom field options in a given team.
473   static function getAllCustomFieldOptions($team_id) {
474     $mdb2 = getConnection();
475
476     $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";
477
478     $res = $mdb2->query($sql);
479     $result = array();
480     if (!is_a($res, 'PEAR_Error')) {
481       while ($val = $res->fetchRow()) {
482         $result[] = $val;
483       }
484       return $result;
485     }
486     return false;
487   }
488
489   // The getCustomFieldLog obtains all custom field log entries for a given team.
490   static function getCustomFieldLog($team_id) {
491     $mdb2 = getConnection();
492
493     $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";
494
495     $res = $mdb2->query($sql);
496     $result = array();
497     if (!is_a($res, 'PEAR_Error')) {
498       while ($val = $res->fetchRow()) {
499         $result[] = $val;
500       }
501       return $result;
502     }
503     return false;
504   }
505
506   // getFavReports - obtains all favorite reports for all users in team.
507   static function getFavReports($team_id) {
508     $mdb2 = getConnection();
509
510     $result = array();
511     $sql = "select * from tt_fav_reports where user_id in (select id from tt_users where team_id = $team_id)";
512     $res = $mdb2->query($sql);
513     $result = array();
514     if (!is_a($res, 'PEAR_Error')) {
515       while ($val = $res->fetchRow()) {
516         $result[] = $val;
517       }
518       return $result;
519     }
520     return false;
521   }
522
523   // getRoles - obtains all roles defined for team.
524   static function getRoles($team_id) {
525     $mdb2 = getConnection();
526
527     $result = array();
528     $sql = "select * from tt_roles where team_id = $team_id";
529     $res = $mdb2->query($sql);
530     $result = array();
531     if (!is_a($res, 'PEAR_Error')) {
532       while ($val = $res->fetchRow()) {
533         $result[] = $val;
534       }
535       return $result;
536     }
537     return false;
538   }
539
540   // getExpenseItems - obtains all expense items for all users in team.
541   static function getExpenseItems($team_id) {
542     $mdb2 = getConnection();
543
544     $result = array();
545     $sql = "select * from tt_expense_items where user_id in (select id from tt_users where team_id = $team_id)";
546     $res = $mdb2->query($sql);
547     $result = array();
548     if (!is_a($res, 'PEAR_Error')) {
549       while ($val = $res->fetchRow()) {
550         $result[] = $val;
551       }
552       return $result;
553     }
554     return false;
555   }
556
557   // getPredefinedExpenses - obtains predefined expenses for team.
558   static function getPredefinedExpenses($team_id) {
559     global $user;
560     $replaceDecimalMark = ('.' != $user->decimal_mark);
561
562     $mdb2 = getConnection();
563
564     $result = array();
565     $sql = "select id, name, cost from tt_predefined_expenses where team_id = $team_id";
566     $res = $mdb2->query($sql);
567     $result = array();
568     if (!is_a($res, 'PEAR_Error')) {
569       while ($val = $res->fetchRow()) {
570         if ($replaceDecimalMark)
571           $val['cost'] = str_replace('.', $user->decimal_mark, $val['cost']);
572         $result[] = $val;
573       }
574       return $result;
575     }
576     return false;
577   }
578
579   // getNotifications - obtains notification descriptions for team.
580   static function getNotifications($team_id) {
581     $mdb2 = getConnection();
582
583     $result = array();
584     $sql = "select c.id, c.cron_spec, c.email, c.report_condition, fr.name from tt_cron c
585       left join tt_fav_reports fr on (fr.id = c.report_id)
586       where c.team_id = $team_id and c.status = 1 and fr.status = 1";
587     $res = $mdb2->query($sql);
588     $result = array();
589     if (!is_a($res, 'PEAR_Error')) {
590       while ($val = $res->fetchRow()) {
591         $result[] = $val;
592       }
593       return $result;
594     }
595     return false;
596   }
597
598   // getMonthlyQuotas - obtains monthly quotas for team.
599   static function getMonthlyQuotas($team_id) {
600     $mdb2 = getConnection();
601
602     $result = array();
603     $sql = "select year, month, minutes from tt_monthly_quotas where team_id = $team_id";
604     $res = $mdb2->query($sql);
605     $result = array();
606     if (!is_a($res, 'PEAR_Error')) {
607       while ($val = $res->fetchRow()) {
608         $result[] = $val;
609       }
610       return $result;
611     }
612     return false;
613   }
614
615   // The getTeams function returns an array of all active teams on the server.
616   static function getTeams() {
617     $result = array();
618     $mdb2 = getConnection();
619
620     $sql =  "select id, name, lang, timestamp from tt_teams where status = 1 order by id desc";
621     $res = $mdb2->query($sql);
622     $result = array();
623     if (!is_a($res, 'PEAR_Error')) {
624       while ($val = $res->fetchRow()) {
625         $val['date'] = substr($val['timestamp'], 0, 10); // Strip the time.
626         $result[] = $val;
627       }
628       return $result;
629     }
630     return false;
631   }
632
633   // The markDeleted function marks the team and everything in it as deleted.
634   static function markDeleted($team_id) {
635
636     // Iterate through team users and mark them as deleted.
637     $users = ttTeamHelper::getAllUsers($team_id);
638     foreach ($users as $one_user) {
639       if (!ttUserHelper::markDeleted($one_user['id'])) return false;
640     }
641
642     // Mark tasks deleted.
643     if (!ttTeamHelper::markTasksDeleted($team_id)) return false;
644
645     $mdb2 = getConnection();
646
647     // Mark projects deleted.
648     $sql = "update tt_projects set status = NULL where team_id = $team_id";
649     $affected = $mdb2->exec($sql);
650     if (is_a($affected, 'PEAR_Error')) return false;
651
652     // Mark clients deleted.
653     $sql = "update tt_clients set status = NULL where team_id = $team_id";
654     $affected = $mdb2->exec($sql);
655     if (is_a($affected, 'PEAR_Error')) return false;
656
657     // Mark custom fields deleted.
658     $sql = "update tt_custom_fields set status = NULL where team_id = $team_id";
659     $affected = $mdb2->exec($sql);
660     if (is_a($affected, 'PEAR_Error')) return false;
661
662     // Mark team deleted.
663     $sql = "update tt_teams set status = NULL where id = $team_id";
664     $affected = $mdb2->exec($sql);
665     if (is_a($affected, 'PEAR_Error')) return false;
666
667     return true;
668   }
669
670   // The getTeamDetails function returns team details.
671   static function getTeamDetails($team_id) {
672     $result = array();
673     $mdb2 = getConnection();
674
675     $role_manager = ROLE_MANAGER;
676     $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
677       from tt_teams t
678       inner join tt_users u on (u.team_id = t.id and u.role = $role_manager)
679       where t.id = $team_id";
680
681     $res = $mdb2->query($sql);
682     if (!is_a($res, 'PEAR_Error')) {
683       $val = $res->fetchRow();
684       return $val;
685     }
686
687     return false;
688   }
689
690   // The insert function creates a new team.
691   static function insert($fields) {
692
693     $mdb2 = getConnection();
694
695     // Start with team name and currency.
696     $columns = 'name, currency';
697     $values = $mdb2->quote(trim($fields['name'])).', '.$mdb2->quote(trim($fields['currency']));
698
699     if ($fields['decimal_mark']) {
700       $columns .= ', decimal_mark';
701       $values .= ', '.$mdb2->quote($fields['decimal_mark']);
702     }
703
704     $lang = $fields['lang'];
705     if (!$lang) {
706       global $i18n;
707       $lang = $i18n->lang;
708     }
709     $columns .= ', lang';
710     $values .= ', '.$mdb2->quote($lang);
711
712     if ($fields['date_format'] || defined('DATE_FORMAT_DEFAULT')) {
713       $date_format = $fields['date_format'] ? $fields['date_format'] : DATE_FORMAT_DEFAULT;
714       $columns .= ', date_format';
715       $values .= ', '.$mdb2->quote($date_format);
716     }
717
718     if ($fields['time_format'] || defined('TIME_FORMAT_DEFAULT')) {
719       $time_format = $fields['time_format'] ? $fields['time_format'] : TIME_FORMAT_DEFAULT;
720       $columns .= ', time_format';
721       $values .= ', '.$mdb2->quote($time_format);
722     }
723
724     if ($fields['week_start'] || defined('WEEK_START_DEFAULT')) {
725       $week_start = $fields['week_start'] ? $fields['week_start'] : WEEK_START_DEFAULT;
726       $columns .= ', week_start';
727       $values .= ', '.(int)$week_start;
728     }
729
730     if ($fields['tracking_mode']) {
731       $columns .= ', tracking_mode';
732       $values .= ', '.(int)$fields['tracking_mode'];
733     }
734
735     if ($fields['project_required']) {
736       $columns .= ', project_required';
737       $values .= ', '.(int)$fields['project_required'];
738     }
739
740     if ($fields['task_required']) {
741       $columns .= ', task_required';
742       $values .= ', '.(int)$fields['task_required'];
743     }
744
745     if ($fields['record_type']) {
746       $columns .= ', record_type';
747       $values .= ', '.(int)$fields['record_type'];
748     }
749
750     if ($fields['bcc_email']) {
751       $columns .= ', bcc_email';
752       $values .= ', '.$mdb2->quote($fields['bcc_email']);
753     }
754
755     if ($fields['plugins']) {
756       $columns .= ', plugins';
757       $values .= ', '.$mdb2->quote($fields['plugins']);
758     }
759
760     if ($fields['lock_spec']) {
761       $columns .= ', lock_spec';
762       $values .= ', '.$mdb2->quote($fields['lock_spec']);
763     }
764
765     if ($fields['workday_minutes']) {
766       $columns .= ', workday_minutes';
767       $values .= ', '.(int)$fields['workday_minutes'];
768     }
769
770     if ($fields['config']) {
771       $columns .= ', config';
772       $values .= ', '.$mdb2->quote($fields['config']);
773     }
774
775     $sql = "insert into tt_teams ($columns) values($values)";
776     $affected = $mdb2->exec($sql);
777
778     if (!is_a($affected, 'PEAR_Error')) {
779       $team_id = $mdb2->lastInsertID('tt_teams', 'id');
780       return $team_id;
781     }
782
783     return false;
784   }
785
786   // The update function updates team information.
787   static function update($team_id, $fields)
788   {
789     $mdb2 = getConnection();
790     $name_part = 'name = '.$mdb2->quote($fields['name']);
791     $currency_part = '';
792     $lang_part = '';
793     $decimal_mark_part = '';
794     $date_format_part = '';
795     $time_format_part = '';
796     $week_start_part = '';
797     $tracking_mode_part = '';
798     $task_required_part = ' , task_required = '.(int) $fields['task_required'];
799     $record_type_part = '';
800     $bcc_email_part = '';
801     $plugins_part = '';
802     $config_part = '';
803     $lock_spec_part = '';
804     $workday_minutes_part = '';
805
806     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
807     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
808     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
809     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
810     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
811     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
812     if (isset($fields['tracking_mode'])) $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
813     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
814     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
815     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
816     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
817     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
818     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
819
820     $sql = "update tt_teams set $name_part $currency_part $lang_part $decimal_mark_part
821       $date_format_part $time_format_part $week_start_part $tracking_mode_part $task_required_part $record_type_part
822       $bcc_email_part $plugins_part $config_part $lock_spec_part $workday_minutes_part where id = $team_id";
823     $affected = $mdb2->exec($sql);
824     if (is_a($affected, 'PEAR_Error')) return false;
825
826     return true;
827   }
828
829   // The getInactiveTeams is a maintenance function that returns an array of inactive team ids (max 100).
830   static function getInactiveTeams() {
831     $inactive_teams = array();
832     $mdb2 = getConnection();
833
834     // Get all team ids for teams created or modified more than 6 months ago.
835     // $ts = date('Y-m-d', strtotime('-1 year'));
836     $ts = date('Y-m-d', strtotime('-6 month'));
837     $sql =  "select id from tt_teams where timestamp < '$ts' order by id";
838     $res = $mdb2->query($sql);
839
840     $count = 0;
841     if (!is_a($res, 'PEAR_Error')) {
842       while ($val = $res->fetchRow()) {
843         $team_id = $val['id'];
844         if (ttTeamHelper::isTeamActive($team_id) == false) {
845           $count++;
846           $inactive_teams[] = $team_id;
847           // Limit the array size for perfomance by allowing this operation on small chunks only.
848           if ($count >= 100) break;
849         }
850       }
851       return $inactive_teams;
852     }
853     return false;
854   }
855
856   // The isTeamActive determines if a team is using Time Tracker or abandoned it.
857   static function isTeamActive($team_id) {
858     $users = array();
859
860     $mdb2 = getConnection();
861     $sql = "select id from tt_users where team_id = $team_id";
862     $res = $mdb2->query($sql);
863     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
864     while ($val = $res->fetchRow()) {
865       $users[] = $val['id'];
866     }
867     $user_list = implode(',', $users); // This is a comma-separated list of user ids.
868     if (!$user_list)
869       return false; // No users in team.
870
871     $count = 0;
872     $ts = date('Y-m-d', strtotime('-2 years'));
873     $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
874     $res = $mdb2->query($sql);
875     if (!is_a($res, 'PEAR_Error')) {
876       if ($val = $res->fetchRow()) {
877         $count = $val['cnt'];
878       }
879     }
880
881     if ($count == 0)
882       return false;  // No time entries for the last 2 years.
883
884     if ($count <= 5) {
885       // We will consider a team inactive if it has 5 or less time entries made more than 1 year ago.
886       $count_last_year = 0;
887       $ts = date('Y-m-d', strtotime('-1 year'));
888       $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
889       $res = $mdb2->query($sql);
890       if (!is_a($res, 'PEAR_Error')) {
891         if ($val = $res->fetchRow()) {
892           $count_last_year = $val['cnt'];
893         }
894         if ($count_last_year == 0)
895           return false;  // No time entries for the last year and only a few entries before that.
896       }
897     }
898     return true;
899   }
900
901   // The delete function permanently deletes all data for a team.
902   static function delete($team_id) {
903     $mdb2 = getConnection();
904
905     // Delete users.
906     $sql = "select id from tt_users where team_id = $team_id";
907     $res = $mdb2->query($sql);
908     if (is_a($res, 'PEAR_Error')) return false;
909     while ($val = $res->fetchRow()) {
910       $user_id = $val['id'];
911       if (!ttUserHelper::delete($user_id)) return false;
912     }
913
914     // Delete tasks.
915     if (!ttTeamHelper::deleteTasks($team_id)) return false;
916
917     // Delete client to project binds.
918     $sql = "delete from tt_client_project_binds where client_id in (select id from tt_clients where team_id = $team_id)";
919     $affected = $mdb2->exec($sql);
920     if (is_a($affected, 'PEAR_Error')) return false;
921
922     // Delete projects.
923     $sql = "delete from tt_projects where team_id = $team_id";
924     $affected = $mdb2->exec($sql);
925     if (is_a($affected, 'PEAR_Error')) return false;
926
927     // Delete clients.
928     $sql = "delete from tt_clients where team_id = $team_id";
929     $affected = $mdb2->exec($sql);
930     if (is_a($affected, 'PEAR_Error')) return false;
931
932     // Delete invoices.
933     $sql = "delete from tt_invoices where team_id = $team_id";
934     $affected = $mdb2->exec($sql);
935     if (is_a($affected, 'PEAR_Error')) return false;
936
937     // Delete custom fields.
938     if (!ttTeamHelper::deleteCustomFields($team_id)) return false;
939
940     // Delete roles.
941     $sql = "delete from tt_roles where team_id = $team_id";
942     $affected = $mdb2->exec($sql);
943     if (is_a($affected, 'PEAR_Error')) return false;
944
945     // Delete team.
946     $sql = "delete from tt_teams where id = $team_id";
947     $affected = $mdb2->exec($sql);
948     if (is_a($affected, 'PEAR_Error')) return false;
949
950     return true;
951   }
952
953   // The markTasksDeleted deletes task binds and marks the tasks as deleted for a team.
954   static function markTasksDeleted($team_id) {
955     $mdb2 = getConnection();
956     $sql = "select id from tt_tasks where team_id = $team_id";
957     $res = $mdb2->query($sql);
958     if (is_a($res, 'PEAR_Error')) return false;
959
960     while ($val = $res->fetchRow()) {
961
962       // Delete task binds.
963       $task_id = $val['id'];
964       $sql = "delete from tt_project_task_binds where task_id = $task_id";
965       $affected = $mdb2->exec($sql);
966       if (is_a($affected, 'PEAR_Error')) return false;
967
968       // Mark task as deleted.
969       $sql = "update tt_tasks set status = NULL where id = $task_id";
970       $affected = $mdb2->exec($sql);
971       if (is_a($affected, 'PEAR_Error')) return false;
972     }
973
974     return true;
975   }
976
977   // The deleteTasks deletes all tasks and task binds for an inactive team.
978   static function deleteTasks($team_id) {
979     $mdb2 = getConnection();
980     $sql = "select id from tt_tasks where team_id = $team_id";
981     $res = $mdb2->query($sql);
982     if (is_a($res, 'PEAR_Error')) return false;
983
984     while ($val = $res->fetchRow()) {
985
986       // Delete task binds.
987       $task_id = $val['id'];
988       $sql = "delete from tt_project_task_binds where task_id = $task_id";
989       $affected = $mdb2->exec($sql);
990       if (is_a($affected, 'PEAR_Error')) return false;
991
992       // Delete task.
993       $sql = "delete from tt_tasks where id = $task_id";
994       $affected = $mdb2->exec($sql);
995       if (is_a($affected, 'PEAR_Error')) return false;
996     }
997
998     return true;
999   }
1000
1001   // The deleteCustomFields cleans up tt_custom_field_log, tt_custom_field_options and tt_custom_fields tables for an inactive team.
1002   static function deleteCustomFields($team_id) {
1003     $mdb2 = getConnection();
1004     $sql = "select id from tt_custom_fields where team_id = $team_id";
1005     $res = $mdb2->query($sql);
1006     if (is_a($res, 'PEAR_Error')) return false;
1007
1008     while ($val = $res->fetchRow()) {
1009       $field_id = $val['id'];
1010
1011       // Clean up tt_custom_field_log.
1012       $sql = "delete from tt_custom_field_log where field_id = $field_id";
1013       $affected = $mdb2->exec($sql);
1014       if (is_a($affected, 'PEAR_Error')) return false;
1015
1016       // Clean up tt_custom_field_options.
1017       $sql = "delete from tt_custom_field_options where field_id = $field_id";
1018       $affected = $mdb2->exec($sql);
1019       if (is_a($affected, 'PEAR_Error')) return false;
1020
1021       // Delete custom field.
1022       $sql = "delete from tt_custom_fields where id = $field_id";
1023       $affected = $mdb2->exec($sql);
1024       if (is_a($affected, 'PEAR_Error')) return false;
1025     }
1026
1027     return true;
1028   }
1029
1030   // enablePlugin either enables or disables a specific plugin for team.
1031   static function enablePlugin($plugin, $enable = true)
1032   {
1033     global $user;
1034     if (!$user->canManageTeam())
1035       return false;
1036
1037     $plugin_array = explode(',', $user->plugins);
1038     if ($enable && !in_array($plugin, $plugin_array))
1039       $plugin_array[] = $plugin; // Add plugin to array.
1040
1041     if (!$enable && in_array($plugin, $plugin_array)) {
1042       $key = array_search($plugin, $plugin_array);
1043       if ($key !== false)
1044         unset($plugin_array[$key]); // Remove plugin from array.
1045     }
1046
1047     $plugins = implode(',', $plugin_array);
1048     if ($plugins != $user->plugins) {
1049       if (!ttTeamHelper::update($user->team_id, array('name' => $user->team,'plugins' => $plugins)))
1050         return false;
1051       $user->plugins = $plugins;
1052     }
1053
1054     return true;
1055   }
1056 }