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