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