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