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