Some refactoring.
[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 projects deleted.
679     $sql = "update tt_projects 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 clients deleted.
684     $sql = "update tt_clients 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 custom fields deleted.
689     $sql = "update tt_custom_fields 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 team deleted.
694     $sql = "update tt_teams set status = NULL where id = $team_id";
695     $affected = $mdb2->exec($sql);
696     if (is_a($affected, 'PEAR_Error')) return false;
697
698     return true;
699   }
700
701   // The getTeamDetails function returns team details.
702   static function getTeamDetails($team_id) {
703     $result = array();
704     $mdb2 = getConnection();
705
706     $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
707       from tt_teams t
708       inner join tt_users u on (u.team_id = t.id)
709       inner join tt_roles r on (r.id = u.role_id and r.rank = 512)
710       where t.id = $team_id";
711
712     $res = $mdb2->query($sql);
713     if (!is_a($res, 'PEAR_Error')) {
714       $val = $res->fetchRow();
715       return $val;
716     }
717
718     return false;
719   }
720
721   // The insert function creates a new team.
722   static function insert($fields) {
723
724     $mdb2 = getConnection();
725
726     // Start with team name and currency.
727     $columns = 'name, currency';
728     $values = $mdb2->quote(trim($fields['name'])).', '.$mdb2->quote(trim($fields['currency']));
729
730     if ($fields['decimal_mark']) {
731       $columns .= ', decimal_mark';
732       $values .= ', '.$mdb2->quote($fields['decimal_mark']);
733     }
734
735     $lang = $fields['lang'];
736     if (!$lang) {
737       global $i18n;
738       $lang = $i18n->lang;
739     }
740     $columns .= ', lang';
741     $values .= ', '.$mdb2->quote($lang);
742
743     if ($fields['date_format'] || defined('DATE_FORMAT_DEFAULT')) {
744       $date_format = $fields['date_format'] ? $fields['date_format'] : DATE_FORMAT_DEFAULT;
745       $columns .= ', date_format';
746       $values .= ', '.$mdb2->quote($date_format);
747     }
748
749     if ($fields['time_format'] || defined('TIME_FORMAT_DEFAULT')) {
750       $time_format = $fields['time_format'] ? $fields['time_format'] : TIME_FORMAT_DEFAULT;
751       $columns .= ', time_format';
752       $values .= ', '.$mdb2->quote($time_format);
753     }
754
755     if ($fields['week_start'] || defined('WEEK_START_DEFAULT')) {
756       $week_start = $fields['week_start'] ? $fields['week_start'] : WEEK_START_DEFAULT;
757       $columns .= ', week_start';
758       $values .= ', '.(int)$week_start;
759     }
760
761     if ($fields['tracking_mode']) {
762       $columns .= ', tracking_mode';
763       $values .= ', '.(int)$fields['tracking_mode'];
764     }
765
766     if ($fields['project_required']) {
767       $columns .= ', project_required';
768       $values .= ', '.(int)$fields['project_required'];
769     }
770
771     if ($fields['task_required']) {
772       $columns .= ', task_required';
773       $values .= ', '.(int)$fields['task_required'];
774     }
775
776     if ($fields['record_type']) {
777       $columns .= ', record_type';
778       $values .= ', '.(int)$fields['record_type'];
779     }
780
781     if ($fields['bcc_email']) {
782       $columns .= ', bcc_email';
783       $values .= ', '.$mdb2->quote($fields['bcc_email']);
784     }
785
786     if ($fields['plugins']) {
787       $columns .= ', plugins';
788       $values .= ', '.$mdb2->quote($fields['plugins']);
789     }
790
791     if ($fields['lock_spec']) {
792       $columns .= ', lock_spec';
793       $values .= ', '.$mdb2->quote($fields['lock_spec']);
794     }
795
796     if ($fields['workday_minutes']) {
797       $columns .= ', workday_minutes';
798       $values .= ', '.(int)$fields['workday_minutes'];
799     }
800
801     if ($fields['config']) {
802       $columns .= ', config';
803       $values .= ', '.$mdb2->quote($fields['config']);
804     }
805
806     $sql = "insert into tt_teams ($columns) values($values)";
807     $affected = $mdb2->exec($sql);
808
809     if (!is_a($affected, 'PEAR_Error')) {
810       $team_id = $mdb2->lastInsertID('tt_teams', 'id');
811       return $team_id;
812     }
813
814     return false;
815   }
816
817   // The update function updates team information.
818   static function update($team_id, $fields)
819   {
820     $mdb2 = getConnection();
821     $name_part = 'name = '.$mdb2->quote($fields['name']);
822     $currency_part = '';
823     $lang_part = '';
824     $decimal_mark_part = '';
825     $date_format_part = '';
826     $time_format_part = '';
827     $week_start_part = '';
828     $tracking_mode_part = '';
829     $task_required_part = ' , task_required = '.(int) $fields['task_required'];
830     $record_type_part = '';
831     $bcc_email_part = '';
832     $plugins_part = '';
833     $config_part = '';
834     $lock_spec_part = '';
835     $workday_minutes_part = '';
836
837     if (isset($fields['currency'])) $currency_part = ', currency = '.$mdb2->quote($fields['currency']);
838     if (isset($fields['lang'])) $lang_part = ', lang = '.$mdb2->quote($fields['lang']);
839     if (isset($fields['decimal_mark'])) $decimal_mark_part = ', decimal_mark = '.$mdb2->quote($fields['decimal_mark']);
840     if (isset($fields['date_format'])) $date_format_part = ', date_format = '.$mdb2->quote($fields['date_format']);
841     if (isset($fields['time_format'])) $time_format_part = ', time_format = '.$mdb2->quote($fields['time_format']);
842     if (isset($fields['week_start'])) $week_start_part = ', week_start = '.(int) $fields['week_start'];
843     if (isset($fields['tracking_mode'])) $tracking_mode_part = ', tracking_mode = '.(int) $fields['tracking_mode'];
844     if (isset($fields['record_type'])) $record_type_part = ', record_type = '.(int) $fields['record_type'];
845     if (isset($fields['bcc_email'])) $bcc_email_part = ', bcc_email = '.$mdb2->quote($fields['bcc_email']);
846     if (isset($fields['plugins'])) $plugins_part = ', plugins = '.$mdb2->quote($fields['plugins']);
847     if (isset($fields['config'])) $config_part = ', config = '.$mdb2->quote($fields['config']);
848     if (isset($fields['lock_spec'])) $lock_spec_part = ', lock_spec = '.$mdb2->quote($fields['lock_spec']);
849     if (isset($fields['workday_minutes'])) $workday_minutes_part = ', workday_minutes = '.$mdb2->quote($fields['workday_minutes']);
850
851     $sql = "update tt_teams set $name_part $currency_part $lang_part $decimal_mark_part
852       $date_format_part $time_format_part $week_start_part $tracking_mode_part $task_required_part $record_type_part
853       $bcc_email_part $plugins_part $config_part $lock_spec_part $workday_minutes_part where id = $team_id";
854     $affected = $mdb2->exec($sql);
855     if (is_a($affected, 'PEAR_Error')) return false;
856
857     return true;
858   }
859
860   // The getInactiveTeams is a maintenance function that returns an array of inactive team ids (max 100).
861   static function getInactiveTeams() {
862     $inactive_teams = array();
863     $mdb2 = getConnection();
864
865     // Get all team ids for teams created or modified more than 6 months ago.
866     // $ts = date('Y-m-d', strtotime('-1 year'));
867     $ts = date('Y-m-d', strtotime('-6 month'));
868     $sql =  "select id from tt_teams where timestamp < '$ts' order by id";
869     $res = $mdb2->query($sql);
870
871     $count = 0;
872     if (!is_a($res, 'PEAR_Error')) {
873       while ($val = $res->fetchRow()) {
874         $team_id = $val['id'];
875         if (ttTeamHelper::isTeamActive($team_id) == false) {
876           $count++;
877           $inactive_teams[] = $team_id;
878           // Limit the array size for perfomance by allowing this operation on small chunks only.
879           if ($count >= 100) break;
880         }
881       }
882       return $inactive_teams;
883     }
884     return false;
885   }
886
887   // The isTeamActive determines if a team is using Time Tracker or abandoned it.
888   static function isTeamActive($team_id) {
889     $users = array();
890
891     $mdb2 = getConnection();
892     $sql = "select id from tt_users where team_id = $team_id";
893     $res = $mdb2->query($sql);
894     if (is_a($res, 'PEAR_Error')) die($res->getMessage());
895     while ($val = $res->fetchRow()) {
896       $users[] = $val['id'];
897     }
898     $user_list = implode(',', $users); // This is a comma-separated list of user ids.
899     if (!$user_list)
900       return false; // No users in team.
901
902     $count = 0;
903     $ts = date('Y-m-d', strtotime('-2 years'));
904     $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
905     $res = $mdb2->query($sql);
906     if (!is_a($res, 'PEAR_Error')) {
907       if ($val = $res->fetchRow()) {
908         $count = $val['cnt'];
909       }
910     }
911
912     if ($count == 0)
913       return false;  // No time entries for the last 2 years.
914
915     if ($count <= 5) {
916       // We will consider a team inactive if it has 5 or less time entries made more than 1 year ago.
917       $count_last_year = 0;
918       $ts = date('Y-m-d', strtotime('-1 year'));
919       $sql = "select count(*) as cnt from tt_log where user_id in ($user_list) and timestamp > '$ts'";
920       $res = $mdb2->query($sql);
921       if (!is_a($res, 'PEAR_Error')) {
922         if ($val = $res->fetchRow()) {
923           $count_last_year = $val['cnt'];
924         }
925         if ($count_last_year == 0)
926           return false;  // No time entries for the last year and only a few entries before that.
927       }
928     }
929     return true;
930   }
931
932   // The delete function permanently deletes all data for a team.
933   static function delete($team_id) {
934     $mdb2 = getConnection();
935
936     // Delete users.
937     $sql = "select id from tt_users where team_id = $team_id";
938     $res = $mdb2->query($sql);
939     if (is_a($res, 'PEAR_Error')) return false;
940     while ($val = $res->fetchRow()) {
941       $user_id = $val['id'];
942       if (!ttUserHelper::delete($user_id)) return false;
943     }
944
945     // Delete tasks.
946     if (!ttTeamHelper::deleteTasks($team_id)) return false;
947
948     // Delete client to project binds.
949     $sql = "delete from tt_client_project_binds where client_id in (select id from tt_clients where team_id = $team_id)";
950     $affected = $mdb2->exec($sql);
951     if (is_a($affected, 'PEAR_Error')) return false;
952
953     // Delete projects.
954     $sql = "delete from tt_projects where team_id = $team_id";
955     $affected = $mdb2->exec($sql);
956     if (is_a($affected, 'PEAR_Error')) return false;
957
958     // Delete clients.
959     $sql = "delete from tt_clients where team_id = $team_id";
960     $affected = $mdb2->exec($sql);
961     if (is_a($affected, 'PEAR_Error')) return false;
962
963     // Delete invoices.
964     $sql = "delete from tt_invoices where team_id = $team_id";
965     $affected = $mdb2->exec($sql);
966     if (is_a($affected, 'PEAR_Error')) return false;
967
968     // Delete custom fields.
969     if (!ttTeamHelper::deleteCustomFields($team_id)) return false;
970
971     // Delete roles.
972     $sql = "delete from tt_roles where team_id = $team_id";
973     $affected = $mdb2->exec($sql);
974     if (is_a($affected, 'PEAR_Error')) return false;
975
976     // Delete team.
977     $sql = "delete from tt_teams where id = $team_id";
978     $affected = $mdb2->exec($sql);
979     if (is_a($affected, 'PEAR_Error')) return false;
980
981     return true;
982   }
983
984   // The markTasksDeleted deletes task binds and marks the tasks as deleted for a team.
985   static function markTasksDeleted($team_id) {
986     $mdb2 = getConnection();
987     $sql = "select id from tt_tasks where team_id = $team_id";
988     $res = $mdb2->query($sql);
989     if (is_a($res, 'PEAR_Error')) return false;
990
991     while ($val = $res->fetchRow()) {
992
993       // Delete task binds.
994       $task_id = $val['id'];
995       $sql = "delete from tt_project_task_binds where task_id = $task_id";
996       $affected = $mdb2->exec($sql);
997       if (is_a($affected, 'PEAR_Error')) return false;
998
999       // Mark task as deleted.
1000       $sql = "update tt_tasks set status = NULL where id = $task_id";
1001       $affected = $mdb2->exec($sql);
1002       if (is_a($affected, 'PEAR_Error')) return false;
1003     }
1004
1005     return true;
1006   }
1007
1008   // The deleteTasks deletes all tasks and task binds for an inactive team.
1009   static function deleteTasks($team_id) {
1010     $mdb2 = getConnection();
1011     $sql = "select id from tt_tasks where team_id = $team_id";
1012     $res = $mdb2->query($sql);
1013     if (is_a($res, 'PEAR_Error')) return false;
1014
1015     while ($val = $res->fetchRow()) {
1016
1017       // Delete task binds.
1018       $task_id = $val['id'];
1019       $sql = "delete from tt_project_task_binds where task_id = $task_id";
1020       $affected = $mdb2->exec($sql);
1021       if (is_a($affected, 'PEAR_Error')) return false;
1022
1023       // Delete task.
1024       $sql = "delete from tt_tasks where id = $task_id";
1025       $affected = $mdb2->exec($sql);
1026       if (is_a($affected, 'PEAR_Error')) return false;
1027     }
1028
1029     return true;
1030   }
1031
1032   // The deleteCustomFields cleans up tt_custom_field_log, tt_custom_field_options and tt_custom_fields tables for an inactive team.
1033   static function deleteCustomFields($team_id) {
1034     $mdb2 = getConnection();
1035     $sql = "select id from tt_custom_fields where team_id = $team_id";
1036     $res = $mdb2->query($sql);
1037     if (is_a($res, 'PEAR_Error')) return false;
1038
1039     while ($val = $res->fetchRow()) {
1040       $field_id = $val['id'];
1041
1042       // Clean up tt_custom_field_log.
1043       $sql = "delete from tt_custom_field_log where field_id = $field_id";
1044       $affected = $mdb2->exec($sql);
1045       if (is_a($affected, 'PEAR_Error')) return false;
1046
1047       // Clean up tt_custom_field_options.
1048       $sql = "delete from tt_custom_field_options where field_id = $field_id";
1049       $affected = $mdb2->exec($sql);
1050       if (is_a($affected, 'PEAR_Error')) return false;
1051
1052       // Delete custom field.
1053       $sql = "delete from tt_custom_fields where id = $field_id";
1054       $affected = $mdb2->exec($sql);
1055       if (is_a($affected, 'PEAR_Error')) return false;
1056     }
1057
1058     return true;
1059   }
1060
1061   // enablePlugin either enables or disables a specific plugin for team.
1062   static function enablePlugin($plugin, $enable = true)
1063   {
1064     global $user;
1065     if (!$user->can('manage_features'))
1066       return false;
1067
1068     $plugin_array = explode(',', $user->plugins);
1069     if ($enable && !in_array($plugin, $plugin_array))
1070       $plugin_array[] = $plugin; // Add plugin to array.
1071
1072     if (!$enable && in_array($plugin, $plugin_array)) {
1073       $key = array_search($plugin, $plugin_array);
1074       if ($key !== false)
1075         unset($plugin_array[$key]); // Remove plugin from array.
1076     }
1077
1078     $plugins = implode(',', $plugin_array);
1079     if ($plugins != $user->plugins) {
1080       if (!ttTeamHelper::update($user->team_id, array('name' => $user->team,'plugins' => $plugins)))
1081         return false;
1082       $user->plugins = $plugins;
1083     }
1084
1085     return true;
1086   }
1087 }