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