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