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