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