Fixed monthly quotas to properly replace decimal delimiter.
[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 $i18n;
43     // $date is expected as string in DB_DATEFORMAT.
44     $month = date('m', strtotime($date));
45     $day = date('d', strtotime($date));
46     if (in_array($month.'/'.$day, $i18n->holidays))
47       return true;
48
49     return false;
50   }
51
52   // isValidTime validates a value as a time string.
53   static function isValidTime($value) {
54     if (strlen($value)==0 || !isset($value)) return false;
55
56     // 24 hour patterns.
57     if ($value == '24:00' || $value == '2400') return true;
58
59     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
60       return true;
61     }
62     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
63       return true;
64     }
65
66     // 12 hour patterns
67     if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
68       return true;
69     }
70     if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
71       return true;
72     }
73     if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
74       return true;
75     }
76     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
77       return true;
78     }
79
80     return false;
81   }
82
83   // isValidDuration validates a value as a time duration string (in hours and minutes).
84   static function isValidDuration($value) {
85     if (strlen($value) == 0 || !isset($value)) return false;
86
87     if ($value == '24:00' || $value == '2400') return true;
88
89     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
90       return true;
91     }
92     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
93       return true;
94     }
95
96     global $user;
97     $localizedPattern = '/^([0-1]{0,1}[0-9]|2[0-3])?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
98     if (preg_match($localizedPattern, $value )) { // decimal values like 0.5, 1.25h, ... .. 23.9999h (or with comma)
99       return true;
100     }
101
102     return false;
103   }
104
105   // isValidQuota validates a localized value as an hours quota string (in hours and minutes).
106   static function isValidQuota($value) {
107
108     if (strlen($value) == 0 || !isset($value)) return true;
109
110     if (preg_match('/^[0-9]{1,3}h?$/', $value )) { // 000 - 999
111       return true;
112     }
113
114     if (preg_match('/^[0-9]{1,3}:[0-5][0-9]$/', $value )) { // 000:00 - 999:59
115       return true;
116     }
117
118     global $user;
119     $localizedPattern = '/^([0-9]{1,3})?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
120     if (preg_match($localizedPattern, $value )) { // decimal values like 000.5, 999.25h, ... .. 999.9999h (or with comma)
121       return true;
122     }
123
124     return false;
125   }
126
127   // quotaToFloat converts a valid quota value to a float.
128   static function quotaToFloat($value) {
129
130     if (preg_match('/^[0-9]{1,3}h?$/', $value )) { // 000 - 999
131       return (float) $value;
132     }
133
134     if (preg_match('/^[0-9]{1,3}:[0-5][0-9]$/', $value )) { // 000:00 - 999:59
135       $minutes = ttTimeHelper::toMinutes($value);
136       return ($minutes / 60.0);
137     }
138
139     global $user;
140     $localizedPattern = '/^([0-9]{1,3})?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
141     if (preg_match($localizedPattern, $value )) { // decimal values like 000.5, 999.25h, ... .. 999.9999h (or with comma)
142       // Strip optional h in the end.
143       $value = trim($value, 'h');
144       if ($user->decimal_mark == ',')
145         $value = str_replace(',', '.', $value);
146       return (float) $value;
147     }
148
149     return null;
150   }
151
152   // normalizeDuration - converts a valid time duration string to format 00:00.
153   static function normalizeDuration($value, $leadingZero = true) {
154     $time_value = $value;
155
156     // If we have a decimal format - convert to time format 00:00.
157     global $user;
158     if ($user->decimal_mark == ',')
159       $time_value = str_replace (',', '.', $time_value);
160
161     if((strpos($time_value, '.') !== false) || (strpos($time_value, 'h') !== false)) {
162       $val = floatval($time_value);
163       $mins = round($val * 60);
164       $hours = (string)((int)($mins / 60));
165       $mins = (string)($mins % 60);
166       if ($leadingZero && strlen($hours) == 1)
167         $hours = '0'.$hours;
168       if (strlen($mins) == 1)
169         $mins = '0' . $mins;
170       return $hours.':'.$mins;
171     }
172
173     $time_a = explode(':', $time_value);
174     $res = '';
175
176     // 0-99
177     if ((strlen($time_value) >= 1) && (strlen($time_value) <= 2) && !isset($time_a[1])) {
178       $hours = $time_a[0];
179       if ($leadingZero && strlen($hours) == 1)
180         $hours = '0'.$hours;
181        return $hours.':00';
182     }
183
184     // 000-2359 (2400)
185     if ((strlen($time_value) >= 3) && (strlen($time_value) <= 4) && !isset($time_a[1])) {
186       if (strlen($time_value)==3) $time_value = '0'.$time_value;
187       $hours = substr($time_value,0,2);
188       if ($leadingZero && strlen($hours) == 1)
189         $hours = '0'.$hours;
190       return $hours.':'.substr($time_value,2,2);
191     }
192
193     // 0:00-23:59 (24:00)
194     if ((strlen($time_value) >= 4) && (strlen($time_value) <= 5) && isset($time_a[1])) {
195       $hours = $time_a[0];
196       if ($leadingZero && strlen($hours) == 1)
197         $hours = '0'.$hours;
198       return $hours.':'.$time_a[1];
199     }
200
201     return $res;
202   }
203
204   // toMinutes - converts a time string in format 00:00 to a number of minutes.
205   static function toMinutes($value) {
206     $time_a = explode(':', $value);
207     return (int)@$time_a[1] + ((int)@$time_a[0]) * 60;
208   }
209
210   // toAbsDuration - converts a number of minutes to format 0:00
211   // even if $minutes is negative.
212   static function toAbsDuration($minutes, $abbreviate = false){
213     $hours = (string)((int)abs($minutes / 60));
214     $mins = (string) round(abs(fmod($minutes, 60)));
215     if (strlen($mins) == 1)
216       $mins = '0' . $mins;
217     if ($abbreviate && $mins == '00')
218       return $hours;
219
220     return $hours.':'.$mins;
221   }
222
223   // toDuration - calculates duration between start and finish times in 00:00 format.
224   static function toDuration($start, $finish) {
225     $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
226     if ($duration_minutes <= 0) return false;
227
228     return ttTimeHelper::toAbsDuration($duration_minutes);
229   }
230
231   // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
232   static function to12HourFormat($value) {
233     if ('24:00' == $value) return '12:00 AM';
234
235     $time_a = explode(':', $value);
236     if ($time_a[0] > 12)
237       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
238     elseif ($time_a[0] == 12)
239       $res = $value.' PM';
240     elseif ($time_a[0] == 0)
241       $res = '12:'.$time_a[1].' AM';
242     else
243       $res = $value.' AM';
244     return $res;
245   }
246
247   // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
248   // to a 24-hour time format HH:MM.
249   static function to24HourFormat($value) {
250     $res = null;
251
252     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
253     $tmp_val = trim($value);
254
255     // 24 hour patterns.
256     if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
257       // We already have a 24-hour format. Just return it.
258       $res = $tmp_val;
259       return $res;
260     }
261     if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
262       // This is a 24-hour format without a leading zero. Add 0 and return.
263       $res = '0'.$tmp_val;
264       return $res;
265     }
266     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
267       // Single digit. Assuming hour number.
268       $res = '0'.$tmp_val.':00';
269       return $res;
270     }
271     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
272       // Two digit hour number.
273       $res = $tmp_val.':00';
274       return $res;
275     }
276     if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
277       // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
278       $tmp_arr = str_split($tmp_val);
279       $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
280       return $res;
281     }
282     if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
283       // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
284       $tmp_arr = str_split($tmp_val);
285       $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
286       return $res;
287     }
288     // Special handling for midnight.
289     if ($tmp_val == '24:00' || $tmp_val == '2400')
290       return '24:00';
291
292     // 12 hour AM patterns.
293     if (preg_match('/.(am|AM)$/', $tmp_val)) {
294
295       // The $value ends in am or AM. Strip it.
296       $tmp_val = rtrim(substr($tmp_val, 0, -2));
297
298       // Special case to handle 12, 12:MM, and 12MM AM.
299       if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
300         $tmp_val = '00'.substr($tmp_val, 2);
301
302       // We are ready to convert AM time.
303       if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
304         // We already have a 24-hour format. Just return it.
305         $res = $tmp_val;
306         return $res;
307       }
308       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
309         // This is a 24-hour format without a leading zero. Add 0 and return.
310         $res = '0'.$tmp_val;
311         return $res;
312       }
313       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
314         // Single digit. Assuming hour number.
315         $res = '0'.$tmp_val.':00';
316         return $res;
317       }
318       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
319         // Two digit hour number.
320         $res = $tmp_val.':00';
321         return $res;
322       }
323       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
324         // Missing colon. Assume the first digit is the hour, the rest is minutes.
325         $tmp_arr = str_split($tmp_val);
326         $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
327         return $res;
328       }
329       if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
330         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
331         $tmp_arr = str_split($tmp_val);
332         $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
333         return $res;
334       }
335     } // AM cases handling.
336
337     // 12 hour PM patterns.
338     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
339
340       // The $value ends in pm or PM. Strip it.
341       $tmp_val = rtrim(substr($tmp_val, 0, -2));
342
343       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
344         // Single digit. Assuming hour number.
345         $hour = (string)(12 + (int)$tmp_val);
346         $res = $hour.':00';
347         return $res;
348       }
349       if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
350         // Double digit hour.
351         if ('12' != $tmp_val)
352           $tmp_val = (string)(12 + (int)$tmp_val);
353         $res = $tmp_val.':00';
354         return $res;
355       }
356       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
357         // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
358         $tmp_arr = str_split($tmp_val);
359         $hour = (string)(12 + (int)$tmp_arr[0]);
360         $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
361         return $res;
362       }
363       if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
364         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
365         $hour = substr($tmp_val, 0, -2);
366         $min = substr($tmp_val, 2);
367         if ('12' != $hour)
368           $hour = (string)(12 + (int)$hour);
369         $res = $hour.':'.$min;
370         return $res;
371       }
372       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
373         $hour = substr($tmp_val, 0, -3);
374         $min = substr($tmp_val, 2);
375         $hour = (string)(12 + (int)$hour);
376         $res = $hour.':'.$min;
377         return $res;
378       }
379       if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
380         $hour = substr($tmp_val, 0, -3);
381         $min = substr($tmp_val, 3);
382         if ('12' != $hour)
383           $hour = (string)(12 + (int)$hour);
384         $res = $hour.':'.$min;
385         return $res;
386       }
387     } // PM cases handling.
388
389     return $res;
390   }
391
392   // isValidInterval - checks if finish time is greater than start time.
393   static function isValidInterval($start, $finish) {
394     $start = ttTimeHelper::to24HourFormat($start);
395     $finish = ttTimeHelper::to24HourFormat($finish);
396     if ('00:00' == $finish) $finish = '24:00';
397
398     $minutesStart = ttTimeHelper::toMinutes($start);
399     $minutesFinish = ttTimeHelper::toMinutes($finish);
400     if ($minutesFinish > $minutesStart)
401       return true;
402
403     return false;
404   }
405
406   // insert - inserts a time record into log table. Does not deal with custom fields.
407   static function insert($fields)
408   {
409     $mdb2 = getConnection();
410
411     $timestamp = isset($fields['timestamp']) ? $fields['timestamp'] : '';
412     $user_id = $fields['user_id'];
413     $date = $fields['date'];
414     $start = $fields['start'];
415     $finish = $fields['finish'];
416     $duration = $fields['duration'];
417     $client = $fields['client'];
418     $project = $fields['project'];
419     $task = $fields['task'];
420     $invoice = $fields['invoice'];
421     $note = $fields['note'];
422     $billable = $fields['billable'];
423     $paid = $fields['paid'];
424     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
425       $status_f = ', status';
426       $status_v = ', '.$mdb2->quote($fields['status']);
427     }
428
429     $start = ttTimeHelper::to24HourFormat($start);
430     if ($finish) {
431       $finish = ttTimeHelper::to24HourFormat($finish);
432       if ('00:00' == $finish) $finish = '24:00';
433     }
434     $duration = ttTimeHelper::normalizeDuration($duration);
435
436     if (!$timestamp) {
437       $timestamp = date('YmdHis'); //yyyymmddhhmmss
438       // TODO: this timestamp could be illegal if we hit inside DST switch deadzone, such as '2016-03-13 02:30:00'
439       // Anything between 2am and 3am on DST introduction date will not work if we run on a system with DST on.
440       // We need to address this properly to avoid potential complications.
441     }
442
443     if (!$billable) $billable = 0;
444     if (!$paid) $paid = 0;
445
446     if ($duration) {
447       $sql = "insert into tt_log (timestamp, user_id, date, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid $status_f) ".
448         "values ('$timestamp', $user_id, ".$mdb2->quote($date).", '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $status_v)";
449       $affected = $mdb2->exec($sql);
450       if (is_a($affected, 'PEAR_Error'))
451         return false;
452     } else {
453       $duration = ttTimeHelper::toDuration($start, $finish);
454       if ($duration === false) $duration = 0;
455       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
456
457       $sql = "insert into tt_log (timestamp, user_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid $status_f) ".
458         "values ('$timestamp', $user_id, ".$mdb2->quote($date).", '$start', '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $status_v)";
459       $affected = $mdb2->exec($sql);
460       if (is_a($affected, 'PEAR_Error'))
461         return false;
462     }
463
464     $id = $mdb2->lastInsertID('tt_log', 'id');
465     return $id;
466   }
467
468   // update - updates a record in log table. Does not update its custom fields.
469   static function update($fields)
470   {
471     global $user;
472     $mdb2 = getConnection();
473
474     $id = $fields['id'];
475     $date = $fields['date'];
476     $user_id = $fields['user_id'];
477     $client = $fields['client'];
478     $project = $fields['project'];
479     $task = $fields['task'];
480     $start = $fields['start'];
481     $finish = $fields['finish'];
482     $duration = $fields['duration'];
483     $note = $fields['note'];
484
485     $billable_part = '';
486     if ($user->isPluginEnabled('iv')) {
487       $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
488     }
489     $paid_part = '';
490     if ($user->canManageTeam() && $user->isPluginEnabled('ps')) {
491       $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
492     }
493
494     $start = ttTimeHelper::to24HourFormat($start);
495     $finish = ttTimeHelper::to24HourFormat($finish);
496     if ('00:00' == $finish) $finish = '24:00';
497     $duration = ttTimeHelper::normalizeDuration($duration);
498
499     if ($start) $duration = '';
500
501     if ($duration) {
502       $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
503         "comment = ".$mdb2->quote($note)."$billable_part $paid_part, date = '$date' WHERE id = $id";
504       $affected = $mdb2->exec($sql);
505       if (is_a($affected, 'PEAR_Error'))
506         return false;
507     } else {
508       $duration = ttTimeHelper::toDuration($start, $finish);
509       if ($duration === false)
510         $duration = 0;
511       $uncompleted = ttTimeHelper::getUncompleted($user_id);
512       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
513         return false;
514
515       $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
516         "comment = ".$mdb2->quote($note)."$billable_part $paid_part, date = '$date' WHERE id = $id";
517       $affected = $mdb2->exec($sql);
518       if (is_a($affected, 'PEAR_Error'))
519         return false;
520     }
521     return true;
522   }
523
524   // delete - deletes a record from tt_log table and its associated custom field values.
525   static function delete($id, $user_id) {
526     $mdb2 = getConnection();
527
528     $sql = "update tt_log set status = NULL where id = $id and user_id = $user_id";
529     $affected = $mdb2->exec($sql);
530     if (is_a($affected, 'PEAR_Error'))
531       return false;
532
533     $sql = "update tt_custom_field_log set status = NULL where log_id = $id";
534     $affected = $mdb2->exec($sql);
535     if (is_a($affected, 'PEAR_Error'))
536       return false;
537
538     return true;
539   }
540
541   // getTimeForDay - gets total time for a user for a specific date.
542   static function getTimeForDay($user_id, $date) {
543     $mdb2 = getConnection();
544
545     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date = '$date' and status = 1";
546     $res = $mdb2->query($sql);
547     if (!is_a($res, 'PEAR_Error')) {
548       $val = $res->fetchRow();
549       return sec_to_time_fmt_hm($val['sm']);
550     }
551     return false;
552   }
553
554   // getTimeForWeek - gets total time for a user for a given week.
555   static function getTimeForWeek($user_id, $date) {
556     import('Period');
557     $mdb2 = getConnection();
558
559     $period = new Period(INTERVAL_THIS_WEEK, $date);
560     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
561     $res = $mdb2->query($sql);
562     if (!is_a($res, 'PEAR_Error')) {
563       $val = $res->fetchRow();
564       return sec_to_time_fmt_hm($val['sm']);
565     }
566     return 0;
567   }
568
569   // getTimeForMonth - gets total time for a user for a given month.
570   static function getTimeForMonth($user_id, $date){
571     import('Period');
572     $mdb2 = getConnection();
573
574     $period = new Period(INTERVAL_THIS_MONTH, $date);
575     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
576     $res = $mdb2->query($sql);
577     if (!is_a($res, 'PEAR_Error')) {
578       $val = $res->fetchRow();
579       return sec_to_time_fmt_hm($val['sm']);
580     }
581     return 0;
582   }
583
584   // getUncompleted - retrieves an uncompleted record for user, if one exists.
585   static function getUncompleted($user_id) {
586     $mdb2 = getConnection();
587
588     $sql = "select id, start from tt_log  
589       where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
590     $res = $mdb2->query($sql);
591     if (!is_a($res, 'PEAR_Error')) {
592       if (!$res->numRows()) {
593         return false;
594       }
595       if ($val = $res->fetchRow()) {
596         return $val;
597       }
598     }
599     return false;
600   }
601
602   // overlaps - determines if a record overlaps with an already existing record.
603   //
604   // Parameters:
605   //   $user_id - user id for whom to determine overlap
606   //   $date - date
607   //   $start - new record start time
608   //   $finish - new record finish time, may be null
609   //   $record_id - optional record id we may be editing, excluded from overlap set
610   static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
611     // Do not bother checking if we allow overlaps.
612     if (defined('ALLOW_OVERLAP') && ALLOW_OVERLAP == true)
613       return false;
614
615     $mdb2 = getConnection();
616
617     $start = ttTimeHelper::to24HourFormat($start);
618     if ($finish) {
619       $finish = ttTimeHelper::to24HourFormat($finish);
620       if ('00:00' == $finish) $finish = '24:00';
621     }
622     // Handle these 3 overlap situations:
623     // - start time in existing record
624     // - end time in existing record
625     // - record fully encloses existing record
626     $sql = "select id from tt_log  
627       where user_id = $user_id and date = ".$mdb2->quote($date)."
628       and start is not null and duration is not null and status = 1 and (
629       (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
630     if ($finish) {
631       $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
632       or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
633     }
634     $sql .= ")";
635     if ($record_id) {
636       $sql .= " and id <> $record_id";
637     }
638     $res = $mdb2->query($sql);
639     if (!is_a($res, 'PEAR_Error')) {
640       if (!$res->numRows()) {
641         return false;
642       }
643       if ($val = $res->fetchRow()) {
644         return $val;
645       }
646     }
647     return false;
648   }
649
650   // getRecord - retrieves a time record identified by its id.
651   static function getRecord($id, $user_id) {
652     global $user;
653     $sql_time_format = "'%k:%i'"; //  24 hour format.
654     if ('%I:%M %p' == $user->time_format)
655       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
656
657     $mdb2 = getConnection();
658
659     $sql = "select l.id as id, l.timestamp as timestamp, TIME_FORMAT(l.start, $sql_time_format) as start,
660       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
661       TIME_FORMAT(l.duration, '%k:%i') as duration,
662       p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id, l.invoice_id, l.billable, l.paid, l.date
663       from tt_log l
664       left join tt_projects p on (p.id = l.project_id)
665       left join tt_tasks t on (t.id = l.task_id)
666       where l.id = $id and l.user_id = $user_id and l.status = 1";
667     $res = $mdb2->query($sql);
668     if (!is_a($res, 'PEAR_Error')) {
669       if (!$res->numRows()) {
670         return false;
671       }
672       if ($val = $res->fetchRow()) {
673         return $val;
674       }
675     }
676     return false;
677   }
678
679   // getAllRecords - returns all time records for a certain user.
680   static function getAllRecords($user_id) {
681     $result = array();
682
683     $mdb2 = getConnection();
684
685     $sql = "select l.id, l.timestamp, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
686       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
687       TIME_FORMAT(l.duration, '%k:%i') as duration,
688       l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.paid, l.status
689       from tt_log l where l.user_id = $user_id order by l.id";
690     $res = $mdb2->query($sql);
691     if (!is_a($res, 'PEAR_Error')) {
692       while ($val = $res->fetchRow()) {
693         $result[] = $val;
694       }
695     } else return false;
696
697     return $result;
698   }
699
700   // getRecords - returns time records for a user for a given date.
701   static function getRecords($user_id, $date) {
702     global $user;
703     $sql_time_format = "'%k:%i'"; //  24 hour format.
704     if ('%I:%M %p' == $user->time_format)
705       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
706
707     $result = array();
708     $mdb2 = getConnection();
709
710     $client_field = null;
711     if ($user->isPluginEnabled('cl'))
712       $client_field = ", c.name as client";
713
714     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
715       " left join tt_tasks t on (l.task_id = t.id)";
716     if ($user->isPluginEnabled('cl'))
717       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
718
719     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,
720       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
721       TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment, l.billable, l.invoice_id $client_field
722       from tt_log l
723       $left_joins
724       where l.date = '$date' and l.user_id = $user_id and l.status = 1
725       order by l.start, l.id";
726     $res = $mdb2->query($sql);
727     if (!is_a($res, 'PEAR_Error')) {
728       while ($val = $res->fetchRow()) {
729         if($val['duration']=='0:00')
730           $val['finish'] = '';
731         $result[] = $val;
732       }
733     } else return false;
734
735     return $result;
736   }
737 }