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