3cef8b449046a96229a49f478a85a9017d02cfce
[timetracker.git] / WEB-INF / lib / ttTimeHelper.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('DateAndTime');
30
31 // The ttTimeHelper is a class to help with time-related values.
32 class ttTimeHelper {
33
34   // isWeekend determines if $date falls on weekend.
35   static function isWeekend($date) {
36     $weekDay = date('w', strtotime($date));
37     return ($weekDay == WEEKEND_START_DAY || $weekDay == (WEEKEND_START_DAY + 1) % 7);
38   }
39
40   // isHoliday determines if $date falls on a holiday.
41   static function isHoliday($date) {
42     global $user;
43     global $i18n;
44
45     if (!$user->show_holidays) return false;
46
47     // $date is expected as string in DB_DATEFORMAT.
48     $month = date('m', strtotime($date));
49     $day = date('d', strtotime($date));
50     if (in_array($month.'/'.$day, $i18n->holidays))
51       return true;
52
53     return false;
54   }
55
56   // isValidTime validates a value as a time string.
57   static function isValidTime($value) {
58     if (strlen($value)==0 || !isset($value)) return false;
59
60     // 24 hour patterns.
61     if ($value == '24:00' || $value == '2400') return true;
62
63     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
64       return true;
65     }
66     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
67       return true;
68     }
69
70     // 12 hour patterns
71     if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
72       return true;
73     }
74     if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
75       return true;
76     }
77     if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
78       return true;
79     }
80     if (preg_match('/^(0[1-9]|1[0-2]):?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 01:00 - 12:59 am, 0100 - 1259 am
81       return true;
82     }
83
84     return false;
85   }
86
87   // isValidDuration validates a value as a time duration string (in hours and minutes).
88   static function isValidDuration($value) {
89     if (strlen($value) == 0 || !isset($value)) return false;
90
91     if ($value == '24:00' || $value == '2400') return true;
92
93     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
94       return true;
95     }
96     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
97       return true;
98     }
99
100     global $user;
101     $localizedPattern = '/^([0-1]{0,1}[0-9]|2[0-3])?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
102     if (preg_match($localizedPattern, $value )) { // decimal values like 0.5, 1.25h, ... .. 23.9999h (or with comma)
103       return true;
104     }
105
106     return false;
107   }
108
109   // postedDurationToMinutes - converts a value representing a duration
110   // (usually enetered in a form by a user) to an integer number of minutes.
111   //
112   // Parameters:
113   //   $duration - user entered duration string. Valid strings are:
114   //               3 or 3h - means 3 hours. Note: h and m letters are not localized.
115   //               0.25 or 0.25h or .25 or .25h - means a quarter of hour.
116   //               0,25 or 0,25h or ,25 or ,25h - same as above for users with comma ad decimal mark.
117   //               1:30 - means 1 hour 30 minutes.
118   //               25m - means 25 minutes.
119   //   $max - maximum number of minutes that is valid.
120   //
121   //   At the moment, we have 2 variations of duration types:
122   //   1) A duration within a day, such as in a time entry.
123   //   These are less or equal to 24*60 minutes.
124   //
125   //   2) A duration of a monthly quota, with max value of 31*24*60 minutes.
126   //
127   // This function is generic to be used for both types.
128   //
129   // Returns false if the value cannot be converted.
130   static function postedDurationToMinutes($duration, $max = 1440) {
131     // Handle empty value.
132     if (!isset($duration) || strlen($duration) == 0)
133       return null; // Value is not set. Caller decides whether it is valid or not.
134
135     // We allow negative durations, similar to negative expenses (installments).
136     $signMultiplier = ttStartsWith($duration, '-') ? -1 : 1;
137     if ($signMultiplier == -1) $duration = ltrim($duration, '-');
138
139     // Handle whole hours.
140     if (preg_match('/^\d{1,3}h?$/', $duration )) { // 0 - 999, 0h - 999h
141       $minutes = 60 * trim($duration, 'h');
142       return $minutes > $max ? false : $signMultiplier * $minutes;
143     }
144
145     // Handle a normalized duration value.
146     if (preg_match('/^\d{1,3}:[0-5][0-9]$/', $duration )) { // 0:00 - 999:59
147       $time_array = explode(':', $duration);
148       $minutes = (int)@$time_array[1] + ((int)@$time_array[0]) * 60;
149       return $minutes > $max ? false : $signMultiplier * $minutes;
150     }
151
152     // Handle localized fractional hours.
153     global $user;
154     $localizedPattern = '/^(\d{1,3})?['.$user->getDecimalMark().'][0-9]{1,4}h?$/';
155     if (preg_match($localizedPattern, $duration )) { // decimal values like .5, 1.25h, ... .. 999.9999h (or with comma)
156         if ($user->getDecimalMark() == ',')
157           $duration = str_replace (',', '.', $duration);
158
159         $minutes = (int)round(60 * floatval($duration));
160         return $minutes > $max ? false : $signMultiplier * $minutes;
161     }
162
163     // Handle minutes. Some users enter durations like 10m (meaning 10 minutes).
164     if (preg_match('/^\d{1,5}m$/', $duration )) { // 0m - 99999m
165       $minutes = (int) trim($duration, 'm');
166       return $minutes > $max ? false : $signMultiplier * $minutes;
167     }
168
169     // Everything else is not a valid duration.
170     return false;
171   }
172
173   // minutesToDuration converts an integer number of minutes into duration string.
174   // Formats returned HH:MM, HHH:MM, HH, or HHH.
175   static function minutesToDuration($minutes, $abbreviate = false) {
176     $sign = $minutes > 0 ? '' : '-';
177     $minutes = abs($minutes);
178
179     $hours = (string) (int)($minutes / 60);
180     $mins = (string) round(fmod($minutes, 60));
181     if (strlen($mins) == 1)
182       $mins = '0' . $mins;
183     if ($abbreviate && $mins == '00')
184       return $sign.$hours;
185
186     return $sign.$hours.':'.$mins;
187   }
188
189   // toMinutes - converts a time string in format 00:00 to a number of minutes.
190   static function toMinutes($value) {
191     $time_a = explode(':', $value);
192     return (int)@$time_a[1] + ((int)@$time_a[0]) * 60;
193   }
194
195   // toAbsDuration - converts a number of minutes to format 0:00
196   // even if $minutes is negative.
197   static function toAbsDuration($minutes, $abbreviate = false){
198     $hours = (string)((int)abs($minutes / 60));
199     $mins = (string) round(abs(fmod($minutes, 60)));
200     if (strlen($mins) == 1)
201       $mins = '0' . $mins;
202     if ($abbreviate && $mins == '00')
203       return $hours;
204
205     return $hours.':'.$mins;
206   }
207
208   // toDuration - calculates duration between start and finish times in 00:00 format.
209   static function toDuration($start, $finish) {
210     $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
211     if ($duration_minutes <= 0) return false;
212
213     return ttTimeHelper::toAbsDuration($duration_minutes);
214   }
215
216   // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
217   static function to12HourFormat($value) {
218     if ('24:00' == $value) return '12:00 AM';
219
220     $time_a = explode(':', $value);
221     if ($time_a[0] > 12)
222       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
223     elseif ($time_a[0] == 12)
224       $res = $value.' PM';
225     elseif ($time_a[0] == 0)
226       $res = '12:'.$time_a[1].' AM';
227     else
228       $res = $value.' AM';
229     return $res;
230   }
231
232   // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
233   // to a 24-hour time format HH:MM.
234   static function to24HourFormat($value) {
235     $res = null;
236
237     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
238     $tmp_val = trim($value);
239
240     // 24 hour patterns.
241     if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
242       // We already have a 24-hour format. Just return it.
243       $res = $tmp_val;
244       return $res;
245     }
246     if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
247       // This is a 24-hour format without a leading zero. Add 0 and return.
248       $res = '0'.$tmp_val;
249       return $res;
250     }
251     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
252       // Single digit. Assuming hour number.
253       $res = '0'.$tmp_val.':00';
254       return $res;
255     }
256     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
257       // Two digit hour number.
258       $res = $tmp_val.':00';
259       return $res;
260     }
261     if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
262       // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
263       $tmp_arr = str_split($tmp_val);
264       $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
265       return $res;
266     }
267     if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
268       // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
269       $tmp_arr = str_split($tmp_val);
270       $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
271       return $res;
272     }
273     // Special handling for midnight.
274     if ($tmp_val == '24:00' || $tmp_val == '2400')
275       return '24:00';
276
277     // 12 hour AM patterns.
278     if (preg_match('/.(am|AM)$/', $tmp_val)) {
279
280       // The $value ends in am or AM. Strip it.
281       $tmp_val = rtrim(substr($tmp_val, 0, -2));
282
283       // Special case to handle 12, 12:MM, and 12MM AM.
284       if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
285         $tmp_val = '00'.substr($tmp_val, 2);
286
287       // We are ready to convert AM time.
288       if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
289         // We already have a 24-hour format. Just return it.
290         $res = $tmp_val;
291         return $res;
292       }
293       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
294         // This is a 24-hour format without a leading zero. Add 0 and return.
295         $res = '0'.$tmp_val;
296         return $res;
297       }
298       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
299         // Single digit. Assuming hour number.
300         $res = '0'.$tmp_val.':00';
301         return $res;
302       }
303       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
304         // Two digit hour number.
305         $res = $tmp_val.':00';
306         return $res;
307       }
308       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
309         // Missing colon. Assume the first digit is the hour, the rest is minutes.
310         $tmp_arr = str_split($tmp_val);
311         $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
312         return $res;
313       }
314       if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
315         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
316         $tmp_arr = str_split($tmp_val);
317         $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
318         return $res;
319       }
320     } // AM cases handling.
321
322     // 12 hour PM patterns.
323     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
324
325       // The $value ends in pm or PM. Strip it.
326       $tmp_val = rtrim(substr($tmp_val, 0, -2));
327
328       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
329         // Single digit. Assuming hour number.
330         $hour = (string)(12 + (int)$tmp_val);
331         $res = $hour.':00';
332         return $res;
333       }
334       if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
335         // Double digit hour.
336         if ('12' != $tmp_val)
337           $tmp_val = (string)(12 + (int)$tmp_val);
338         $res = $tmp_val.':00';
339         return $res;
340       }
341       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
342         // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
343         $tmp_arr = str_split($tmp_val);
344         $hour = (string)(12 + (int)$tmp_arr[0]);
345         $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
346         return $res;
347       }
348       if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
349         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
350         $hour = substr($tmp_val, 0, -2);
351         $min = substr($tmp_val, 2);
352         if ('12' != $hour)
353           $hour = (string)(12 + (int)$hour);
354         $res = $hour.':'.$min;
355         return $res;
356       }
357       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
358         $hour = substr($tmp_val, 0, -3);
359         $min = substr($tmp_val, 2);
360         $hour = (string)(12 + (int)$hour);
361         $res = $hour.':'.$min;
362         return $res;
363       }
364       if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
365         $hour = substr($tmp_val, 0, -3);
366         $min = substr($tmp_val, 3);
367         if ('12' != $hour)
368           $hour = (string)(12 + (int)$hour);
369         $res = $hour.':'.$min;
370         return $res;
371       }
372     } // PM cases handling.
373
374     return $res;
375   }
376
377   // isValidInterval - checks if finish time is greater than start time.
378   static function isValidInterval($start, $finish) {
379     $start = ttTimeHelper::to24HourFormat($start);
380     $finish = ttTimeHelper::to24HourFormat($finish);
381     if ('00:00' == $finish) $finish = '24:00';
382
383     $minutesStart = ttTimeHelper::toMinutes($start);
384     $minutesFinish = ttTimeHelper::toMinutes($finish);
385     if ($minutesFinish > $minutesStart)
386       return true;
387
388     return false;
389   }
390
391   // insert - inserts a time record into tt_log table. Does not deal with custom fields.
392   static function insert($fields)
393   {
394     global $user;
395     $mdb2 = getConnection();
396
397     $user_id = (int) $fields['user_id'];
398     $group_id = (int) $fields['group_id'];
399     $org_id = (int) $fields['org_id'];
400     $date = $fields['date'];
401     $start = $fields['start'];
402     $finish = $fields['finish'];
403     $duration = $fields['duration'];
404     if ($duration) {
405       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
406       $duration = ttTimeHelper::minutesToDuration($minutes);
407     }
408     $client = $fields['client'];
409     $project = $fields['project'];
410     $task = $fields['task'];
411     $invoice = $fields['invoice'];
412     $note = $fields['note'];
413     $billable = $fields['billable'];
414     $paid = $fields['paid'];
415     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
416       $status_f = ', status';
417       $status_v = ', '.$mdb2->quote($fields['status']);
418     }
419
420     $start = ttTimeHelper::to24HourFormat($start);
421     if ($finish) {
422       $finish = ttTimeHelper::to24HourFormat($finish);
423       if ('00:00' == $finish) $finish = '24:00';
424     }
425
426     $created_v = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
427
428     if (!$billable) $billable = 0;
429     if (!$paid) $paid = 0;
430
431     if ($duration) {
432       $sql = "insert into tt_log (user_id, group_id, org_id, date, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
433         "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
434       $affected = $mdb2->exec($sql);
435       if (is_a($affected, 'PEAR_Error'))
436         return false;
437     } else {
438       $duration = ttTimeHelper::toDuration($start, $finish);
439       if ($duration === false) $duration = 0;
440       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
441
442       $sql = "insert into tt_log (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
443         "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$start', '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
444       $affected = $mdb2->exec($sql);
445       if (is_a($affected, 'PEAR_Error'))
446         return false;
447     }
448
449     $id = $mdb2->lastInsertID('tt_log', 'id');
450     return $id;
451   }
452
453   // update - updates a record in log table. Does not update its custom fields.
454   static function update($fields)
455   {
456     global $user;
457     $mdb2 = getConnection();
458
459     $id = $fields['id'];
460     $date = $fields['date'];
461     $user_id = $fields['user_id'];
462     $client = $fields['client'];
463     $project = $fields['project'];
464     $task = $fields['task'];
465     $start = $fields['start'];
466     $finish = $fields['finish'];
467     $duration = $fields['duration'];
468     if ($duration) {
469       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
470       $duration = ttTimeHelper::minutesToDuration($minutes);
471     }
472     $note = $fields['note'];
473
474     $billable_part = '';
475     if ($user->isPluginEnabled('iv')) {
476       $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
477     }
478     $paid_part = '';
479     if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
480       $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
481     }
482     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
483
484     $start = ttTimeHelper::to24HourFormat($start);
485     $finish = ttTimeHelper::to24HourFormat($finish);
486     if ('00:00' == $finish) $finish = '24:00';
487     
488     if ($start) $duration = '';
489
490     if ($duration) {
491       $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
492         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
493       $affected = $mdb2->exec($sql);
494       if (is_a($affected, 'PEAR_Error'))
495         return false;
496     } else {
497       $duration = ttTimeHelper::toDuration($start, $finish);
498       if ($duration === false)
499         $duration = 0;
500       $uncompleted = ttTimeHelper::getUncompleted($user_id);
501       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
502         return false;
503
504       $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
505         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
506       $affected = $mdb2->exec($sql);
507       if (is_a($affected, 'PEAR_Error'))
508         return false;
509     }
510     return true;
511   }
512
513   // delete - deletes a record from tt_log table and its associated custom field values.
514   static function delete($id) {
515     global $user;
516     $mdb2 = getConnection();
517
518     // Delete associated files.
519     if ($user->isPluginEnabled('at')) {
520       import('ttFileHelper');
521       global $err;
522       $fileHelper = new ttFileHelper($err);
523       if (!$fileHelper->deleteEntityFiles($id, 'time'))
524         return false;
525     }
526
527     $user_id = $user->getUser();
528     $group_id = $user->getGroup();
529     $org_id = $user->org_id;
530
531     $sql = "update tt_log set status = null".
532       " where id = $id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
533     $affected = $mdb2->exec($sql);
534     if (is_a($affected, 'PEAR_Error'))
535       return false;
536
537     $sql = "update tt_custom_field_log set status = null".
538       " where log_id = $id and group_id = $group_id and org_id = $org_id";
539     $affected = $mdb2->exec($sql);
540     if (is_a($affected, 'PEAR_Error'))
541       return false;
542
543     return true;
544   }
545
546   // getTimeForDay - gets total time for a user for a specific date.
547   static function getTimeForDay($date) {
548     global $user;
549     $mdb2 = getConnection();
550
551     $user_id = $user->getUser();
552     $group_id = $user->getGroup();
553     $org_id = $user->org_id;
554
555     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
556       " where user_id = $user_id and group_id = $group_id and org_id = $org_id and date = '$date' and status = 1";
557     $res = $mdb2->query($sql);
558     if (!is_a($res, 'PEAR_Error')) {
559       $val = $res->fetchRow();
560       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
561     }
562     return false;
563   }
564
565   // getTimeForWeek - gets total time for a user for a given week.
566   static function getTimeForWeek($date) {
567     global $user;
568     import('Period');
569     $mdb2 = getConnection();
570
571     $user_id = $user->getUser();
572     $group_id = $user->getGroup();
573     $org_id = $user->org_id;
574
575     $period = new Period(INTERVAL_THIS_WEEK, $date);
576     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
577       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
578       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
579     $res = $mdb2->query($sql);
580     if (!is_a($res, 'PEAR_Error')) {
581       $val = $res->fetchRow();
582       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
583     }
584     return false;
585   }
586
587   // getTimeForMonth - gets total time for a user for a given month.
588   static function getTimeForMonth($date) {
589     global $user;
590     import('Period');
591     $mdb2 = getConnection();
592
593     $user_id = $user->getUser();
594     $group_id = $user->getGroup();
595     $org_id = $user->org_id;
596
597     $period = new Period(INTERVAL_THIS_MONTH, $date);
598     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
599       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
600       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
601     $res = $mdb2->query($sql);
602     if (!is_a($res, 'PEAR_Error')) {
603       $val = $res->fetchRow();
604       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
605     }
606     return false;
607   }
608
609   // getUncompleted - retrieves an uncompleted record for user, if one exists.
610   static function getUncompleted($user_id) {
611     $mdb2 = getConnection();
612
613     $sql = "select id, start from tt_log  
614       where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
615     $res = $mdb2->query($sql);
616     if (!is_a($res, 'PEAR_Error')) {
617       if (!$res->numRows()) {
618         return false;
619       }
620       if ($val = $res->fetchRow()) {
621         return $val;
622       }
623     }
624     return false;
625   }
626
627   // overlaps - determines if a record overlaps with an already existing record.
628   //
629   // Parameters:
630   //   $user_id - user id for whom to determine overlap
631   //   $date - date
632   //   $start - new record start time
633   //   $finish - new record finish time, may be null
634   //   $record_id - optional record id we may be editing, excluded from overlap set
635   static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
636     // Do not bother checking if we allow overlaps.
637     global $user;
638     if ($user->allow_overlap) return false;
639
640     $mdb2 = getConnection();
641
642     $start = ttTimeHelper::to24HourFormat($start);
643     if ($finish) {
644       $finish = ttTimeHelper::to24HourFormat($finish);
645       if ('00:00' == $finish) $finish = '24:00';
646     }
647     // Handle these 3 overlap situations:
648     // - start time in existing record
649     // - end time in existing record
650     // - record fully encloses existing record
651     $sql = "select id from tt_log  
652       where user_id = $user_id and date = ".$mdb2->quote($date)."
653       and start is not null and duration is not null and status = 1 and (
654       (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
655     if ($finish) {
656       $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
657       or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
658     }
659     $sql .= ")";
660     if ($record_id) {
661       $sql .= " and id <> $record_id";
662     }
663     $res = $mdb2->query($sql);
664     if (!is_a($res, 'PEAR_Error')) {
665       if (!$res->numRows()) {
666         return false;
667       }
668       if ($val = $res->fetchRow()) {
669         return $val;
670       }
671     }
672     return false;
673   }
674
675   // getRecord - retrieves a time record identified by its id.
676   static function getRecord($id) {
677     global $user;
678
679     $user_id = $user->getUser();
680     $group_id = $user->getGroup();
681     $org_id = $user->org_id;
682
683     $sql_time_format = "'%k:%i'"; //  24 hour format.
684     if ('%I:%M %p' == $user->time_format)
685       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
686
687     $mdb2 = getConnection();
688
689     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
690       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
691       " TIME_FORMAT(l.duration, '%k:%i') as duration,".
692       " p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id,".
693       " l.timesheet_id, l.invoice_id, l.billable, l.approved, l.paid, l.date from tt_log l".
694       " left join tt_projects p on (p.id = l.project_id)".
695       " left join tt_tasks t on (t.id = l.task_id)".
696       " where l.id = $id and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
697     $res = $mdb2->query($sql);
698     if (!is_a($res, 'PEAR_Error')) {
699       if (!$res->numRows()) {
700         return false;
701       }
702       if ($val = $res->fetchRow()) {
703         return $val;
704       }
705     }
706     return false;
707   }
708
709   // getRecordForFileView - retrieves a time record identified by its id for
710   // attachment view operation.
711   //
712   // It is different from getRecord, as we want users with appropriate rights
713   // to be able to see other users files, without changing "on behalf" user.
714   // For example, viewing reports for all users and their attached files
715   // from report links.
716   static function getRecordForFileView($id) {
717     // There are several possible situations:
718     //
719     // Record is ours. Check "view_own_reports" or "view_all_reports".
720     // Record is for the current on behalf user. Check "view_reports" or "view_all_reports".
721     // Record is for someone else. Check "view_reports" or "view_all_reports" and rank.
722     //
723     // It looks like the best way is to use 2 queries, obtain user_id first, then check rank.
724
725     global $user;
726
727     $group_id = $user->getGroup();
728     $org_id = $user->org_id;
729
730     $mdb2 = getConnection();
731
732     // Obtain user_id for the time record.
733     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved from tt_log l ".
734       " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
735     $res = $mdb2->query($sql);
736     if (is_a($res, 'PEAR_Error')) return false;
737     if (!$res->numRows()) return false;
738
739     $val = $res->fetchRow();
740     $user_id = $val['user_id'];
741
742     // If record is ours.
743     if ($user_id == $user->id) {
744       if ($user->can('view_own_reports') || $user->can('view_all_reports')) {
745         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
746         return $val;
747       }
748       return false; // No rights.
749     }
750
751     // If record belongs to a user we impersonate.
752     if ($user->behalfUser && $user_id == $user->behalfUser->id) {
753       if ($user->can('view_reports') || $user->can('view_all_reports')) {
754         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
755         return $val;
756       }
757       return false; // No rights.
758     }
759
760     // Record belongs to someone else. We need to check user rank.
761     if (!($user->can('view_reports') || $user->can('view_all_reports'))) return false;
762     $max_rank = $user->can('view_all_reports') ? MAX_RANK : $user->getMaxRankForGroup($group_id);
763
764     $left_joins = ' left join tt_users u on (l.user_id = u.id)';
765     $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
766
767     $where_part = " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
768     $where_part .= " and r.rank <= $max_rank";
769
770     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved".
771       " from tt_log l $left_joins $where_part";
772     $res = $mdb2->query($sql);
773     if (!is_a($res, 'PEAR_Error')) {
774       if (!$res->numRows()) {
775         return false;
776       }
777       if ($val = $res->fetchRow()) {
778         $val['can_edit'] = false;
779         return $val;
780       }
781     }
782     return false;
783   }
784
785   // getAllRecords - returns all time records for a certain user.
786   static function getAllRecords($user_id) {
787     $result = array();
788
789     $mdb2 = getConnection();
790
791     $sql = "select l.id, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
792       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
793       TIME_FORMAT(l.duration, '%k:%i') as duration,
794       l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.paid, l.status
795       from tt_log l where l.user_id = $user_id order by l.id";
796     $res = $mdb2->query($sql);
797     if (!is_a($res, 'PEAR_Error')) {
798       while ($val = $res->fetchRow()) {
799         $result[] = $val;
800       }
801     } else return false;
802
803     return $result;
804   }
805
806   // getRecords - returns time records for a user for a given date.
807   static function getRecords($user_id, $date) {
808     // TODO: merge getRecords and getRecordsWithFiles into one function.
809     global $user;
810     $mdb2 = getConnection();
811
812     $group_id = $user->getGroup();
813     $org_id = $user->org_id;
814
815     $sql_time_format = "'%k:%i'"; //  24 hour format.
816     if ('%I:%M %p' == $user->getTimeFormat())
817       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
818
819     $client_field = null;
820     if ($user->isPluginEnabled('cl'))
821       $client_field = ", c.name as client";
822
823     $include_cf_1 = $user->isPluginEnabled('cf');
824     if ($include_cf_1) {
825       $custom_fields = new CustomFields();
826       $cf_1_type = $custom_fields->fields[0]['type'];
827       if ($cf_1_type == CustomFields::TYPE_TEXT) {
828         $custom_field = ", cfl.value as cf_1";
829       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
830         $custom_field = ", cfo.value as cf_1";
831       }
832     }
833
834     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
835       " left join tt_tasks t on (l.task_id = t.id)";
836     if ($user->isPluginEnabled('cl'))
837       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
838     if ($include_cf_1) {
839       if ($cf_1_type == CustomFields::TYPE_TEXT)
840         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
841       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
842         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
843           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
844       }
845     }
846
847     $result = array();
848     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
849       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
850       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
851       " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field from tt_log l $left_joins".
852       " where l.date = '$date' and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
853       " order by l.start, l.id";
854     $res = $mdb2->query($sql);
855     if (!is_a($res, 'PEAR_Error')) {
856       while ($val = $res->fetchRow()) {
857         if($val['duration']=='0:00')
858           $val['finish'] = '';
859         $result[] = $val;
860       }
861     } else return false;
862
863     return $result;
864   }
865
866   // getRecordsWithFiles - returns time records for a user for a given date
867   // with information whether they have attached files (has_files property).
868   // A separate fiunction from getRecords because sql here is more complex.
869   static function getRecordsWithFiles($user_id, $date) {
870     global $user;
871     $mdb2 = getConnection();
872
873     $group_id = $user->getGroup();
874     $org_id = $user->org_id;
875
876     $sql_time_format = "'%k:%i'"; //  24 hour format.
877     if ('%I:%M %p' == $user->getTimeFormat())
878       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
879
880     $client_field = null;
881     if ($user->isPluginEnabled('cl'))
882       $client_field = ", c.name as client";
883
884     $include_cf_1 = $user->isPluginEnabled('cf');
885     if ($include_cf_1) {
886       $custom_fields = new CustomFields();
887       $cf_1_type = $custom_fields->fields[0]['type'];
888       if ($cf_1_type == CustomFields::TYPE_TEXT) {
889         $custom_field = ", cfl.value as cf_1";
890       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
891         $custom_field = ", cfo.value as cf_1";
892       }
893     }
894
895     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
896       " left join tt_tasks t on (l.task_id = t.id)";
897     if ($user->isPluginEnabled('cl'))
898       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
899     if ($include_cf_1) {
900       if ($cf_1_type == CustomFields::TYPE_TEXT)
901         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
902       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
903         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
904           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
905       }
906     }
907
908     $left_joins .= " left join (select distinct entity_id from tt_files".
909       " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
910       " on (l.id = Sub1.entity_id)";
911
912     $result = array();
913     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
914       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
915       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
916       " if(Sub1.entity_id is null, 0, 1) as has_files,".
917       " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field from tt_log l $left_joins".
918       " where l.date = '$date' and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
919       " order by l.start, l.id";
920     $res = $mdb2->query($sql);
921     if (!is_a($res, 'PEAR_Error')) {
922       while ($val = $res->fetchRow()) {
923         if($val['duration']=='0:00')
924           $val['finish'] = '';
925         $result[] = $val;
926       }
927     } else return false;
928
929     return $result;
930   }
931
932   // canAdd determines if we can add a record in case there is a limit.
933   static function canAdd() {
934     $mdb2 = getConnection();
935     $sql = "select param_value from tt_site_config where param_name = 'exp_date'";
936     $res = $mdb2->query($sql);
937     $val = $res->fetchRow();
938     if (!$val) return true; // No expiration date.
939
940     if (strtotime($val['param_value']) > time())
941       return true; // Expiration date exists but not reached.
942
943     return false;
944   }
945 }