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