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