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