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