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