f6d8b92df1694916ae7b3ade5528c23e015c8956
[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     // NOTE: this does not work for subgroups with different WEEKEND_START_DAY
37     // as the setting is per server. Example: a parent group in USA, with a subgroup
38     // in Saudi Arabia. Their weekends are the same.
39     // Decided NOT to introduce a configurable WEEKEND_START_DAY for groups in UI
40     // to keep UI simple, for now. See also Calendar class with the same issue.
41     $weekDay = date('w', strtotime($date));
42     return ($weekDay == WEEKEND_START_DAY || $weekDay == (WEEKEND_START_DAY + 1) % 7);
43   }
44
45   // isHoliday determines if $date falls on a holiday.
46   static function isHoliday($date) {
47     global $user;
48
49     $holidays = $user->getHolidays();
50     if (!$holidays)
51       return false;
52
53     $holiday_dates = explode(',', $holidays);
54     foreach ($holiday_dates as $holiDateSpec) {
55       if (ttTimeHelper::holidayMatch($date, $holiDateSpec))
56         return true;
57     }
58     return false;
59   }
60
61   // holidayMatch determines if $date matches a single $holiDateSpec.
62   static function holidayMatch($date, $holiDateSpec) {
63
64    $dateArray = explode('-', $date);
65    $holiDateSpecArray = explode('-', $holiDateSpec);
66
67    // Check year.
68    for($i = 0; $i < 4; $i++) {
69      if ($dateArray[0][$i] != $holiDateSpecArray[0][$i] && $holiDateSpecArray[0][$i] != '*') // * means any digit matches
70        return false;
71    }
72    // Check month.
73    if ($dateArray[1] != $holiDateSpecArray[1])
74      return false;
75    // Check day.
76    if ($dateArray[2] != $holiDateSpecArray[2])
77      return false;
78
79     return true;
80   }
81
82   // dateInDatabaseFormat prepares a date string in DB_DATEFORMAT out of year, month, and day.
83   static function dateInDatabaseFormat($year, $month, $day) {
84     $date = "$year-";
85     if (strlen($month) == 1) $date .= '0';
86     $date .= "$month-";
87     if (strlen($day) == 1) $date .= '0';
88     $date .= $day;
89     return $date;
90   }
91
92   // isValidTime validates a value as a time string.
93   static function isValidTime($value) {
94     if (strlen($value)==0 || !isset($value)) return false;
95
96     // 24 hour patterns.
97     if ($value == '24:00' || $value == '2400') return true;
98
99     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
100       return true;
101     }
102     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
103       return true;
104     }
105
106     // 12 hour patterns
107     if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
108       return true;
109     }
110     if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
111       return true;
112     }
113     if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
114       return true;
115     }
116     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
117       return true;
118     }
119
120     return false;
121   }
122
123   // isValidDuration validates a value as a time duration string (in hours and minutes).
124   static function isValidDuration($value) {
125     if (strlen($value) == 0 || !isset($value)) return false;
126
127     if ($value == '24:00' || $value == '2400') return true;
128
129     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
130       return true;
131     }
132     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
133       return true;
134     }
135
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       return true;
140     }
141
142     return false;
143   }
144
145   // postedDurationToMinutes - converts a value representing a duration
146   // (usually enetered in a form by a user) to an integer number of minutes.
147   //
148   // Parameters:
149   //   $duration - user entered duration string. Valid strings are:
150   //               3 or 3h - means 3 hours. Note: h and m letters are not localized.
151   //               0.25 or 0.25h or .25 or .25h - means a quarter of hour.
152   //               0,25 or 0,25h or ,25 or ,25h - same as above for users with comma ad decimal mark.
153   //               1:30 - means 1 hour 30 minutes.
154   //               25m - means 25 minutes.
155   //   $max - maximum number of minutes that is valid.
156   //
157   //   At the moment, we have 2 variations of duration types:
158   //   1) A duration within a day, such as in a time entry.
159   //   These are less or equal to 24*60 minutes.
160   //
161   //   2) A duration of a monthly quota, with max value of 31*24*60 minutes.
162   //
163   // This function is generic to be used for both types.
164   //
165   // Returns false if the value cannot be converted.
166   static function postedDurationToMinutes($duration, $max = 1440) {
167     // Handle empty value.
168     if (!isset($duration) || strlen($duration) == 0)
169       return null; // Value is not set. Caller decides whether it is valid or not.
170
171     // We allow negative durations, similar to negative expenses (installments).
172     $signMultiplier = ttStartsWith($duration, '-') ? -1 : 1;
173     if ($signMultiplier == -1) $duration = ltrim($duration, '-');
174
175     // Handle whole hours.
176     if (preg_match('/^\d{1,3}h?$/', $duration )) { // 0 - 999, 0h - 999h
177       $minutes = 60 * trim($duration, 'h');
178       return $minutes > $max ? false : $signMultiplier * $minutes;
179     }
180
181     // Handle a normalized duration value.
182     if (preg_match('/^\d{1,3}:[0-5][0-9]$/', $duration )) { // 0:00 - 999:59
183       $time_array = explode(':', $duration);
184       $minutes = (int)@$time_array[1] + ((int)@$time_array[0]) * 60;
185       return $minutes > $max ? false : $signMultiplier * $minutes;
186     }
187
188     // Handle localized fractional hours.
189     global $user;
190     $localizedPattern = '/^(\d{1,3})?['.$user->getDecimalMark().'][0-9]{1,4}h?$/';
191     if (preg_match($localizedPattern, $duration )) { // decimal values like .5, 1.25h, ... .. 999.9999h (or with comma)
192         if ($user->getDecimalMark() == ',')
193           $duration = str_replace (',', '.', $duration);
194
195         $minutes = (int)round(60 * floatval($duration));
196         return $minutes > $max ? false : $signMultiplier * $minutes;
197     }
198
199     // Handle minutes. Some users enter durations like 10m (meaning 10 minutes).
200     if (preg_match('/^\d{1,5}m$/', $duration )) { // 0m - 99999m
201       $minutes = (int) trim($duration, 'm');
202       return $minutes > $max ? false : $signMultiplier * $minutes;
203     }
204
205     // Everything else is not a valid duration.
206     return false;
207   }
208
209   // minutesToDuration converts an integer number of minutes into duration string.
210   // Formats returned HH:MM, HHH:MM, HH, or HHH.
211   static function minutesToDuration($minutes, $abbreviate = false) {
212     $sign = $minutes >= 0 ? '' : '-';
213     $minutes = abs($minutes);
214
215     $hours = (string) (int)($minutes / 60);
216     $mins = (string) round(fmod($minutes, 60));
217     if (strlen($mins) == 1)
218       $mins = '0' . $mins;
219     if ($abbreviate && $mins == '00')
220       return $sign.$hours;
221
222     return $sign.$hours.':'.$mins;
223   }
224
225   // toMinutes - converts a time string in format 00:00 to a number of minutes.
226   static function toMinutes($value) {
227     $signMultiplier = ttStartsWith($value, '-') ? -1 : 1;
228     if ($signMultiplier == -1) $value = ltrim($value, '-');
229
230     $time_a = explode(':', $value);
231     return $signMultiplier * ((int)@$time_a[1] + ((int)@$time_a[0]) * 60);
232   }
233
234   // toAbsDuration - converts a number of minutes to format 0:00
235   // even if $minutes is negative.
236   static function toAbsDuration($minutes, $abbreviate = false){
237     $hours = (string)((int)abs($minutes / 60));
238     $mins = (string) round(abs(fmod($minutes, 60)));
239     if (strlen($mins) == 1)
240       $mins = '0' . $mins;
241     if ($abbreviate && $mins == '00')
242       return $hours;
243
244     return $hours.':'.$mins;
245   }
246
247   // toDuration - calculates duration between start and finish times in 00:00 format.
248   static function toDuration($start, $finish) {
249     $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
250     if ($duration_minutes <= 0) return false;
251
252     return ttTimeHelper::toAbsDuration($duration_minutes);
253   }
254
255   // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
256   static function to12HourFormat($value) {
257     if ('24:00' == $value) return '12:00 AM';
258
259     $time_a = explode(':', $value);
260     if ($time_a[0] > 12)
261       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
262     elseif ($time_a[0] == 12)
263       $res = $value.' PM';
264     elseif ($time_a[0] == 0)
265       $res = '12:'.$time_a[1].' AM';
266     else
267       $res = $value.' AM';
268     return $res;
269   }
270
271   // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
272   // to a 24-hour time format HH:MM.
273   static function to24HourFormat($value) {
274     $res = null;
275
276     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
277     $tmp_val = trim($value);
278
279     // 24 hour patterns.
280     if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
281       // We already have a 24-hour format. Just return it.
282       $res = $tmp_val;
283       return $res;
284     }
285     if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
286       // This is a 24-hour format without a leading zero. Add 0 and return.
287       $res = '0'.$tmp_val;
288       return $res;
289     }
290     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
291       // Single digit. Assuming hour number.
292       $res = '0'.$tmp_val.':00';
293       return $res;
294     }
295     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
296       // Two digit hour number.
297       $res = $tmp_val.':00';
298       return $res;
299     }
300     if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
301       // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
302       $tmp_arr = str_split($tmp_val);
303       $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
304       return $res;
305     }
306     if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
307       // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
308       $tmp_arr = str_split($tmp_val);
309       $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
310       return $res;
311     }
312     // Special handling for midnight.
313     if ($tmp_val == '24:00' || $tmp_val == '2400')
314       return '24:00';
315
316     // 12 hour AM patterns.
317     if (preg_match('/.(am|AM)$/', $tmp_val)) {
318
319       // The $value ends in am or AM. Strip it.
320       $tmp_val = rtrim(substr($tmp_val, 0, -2));
321
322       // Special case to handle 12, 12:MM, and 12MM AM.
323       if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
324         $tmp_val = '00'.substr($tmp_val, 2);
325
326       // We are ready to convert AM time.
327       if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
328         // We already have a 24-hour format. Just return it.
329         $res = $tmp_val;
330         return $res;
331       }
332       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
333         // This is a 24-hour format without a leading zero. Add 0 and return.
334         $res = '0'.$tmp_val;
335         return $res;
336       }
337       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
338         // Single digit. Assuming hour number.
339         $res = '0'.$tmp_val.':00';
340         return $res;
341       }
342       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
343         // Two digit hour number.
344         $res = $tmp_val.':00';
345         return $res;
346       }
347       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
348         // Missing colon. Assume the first digit is the hour, the rest is minutes.
349         $tmp_arr = str_split($tmp_val);
350         $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
351         return $res;
352       }
353       if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
354         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
355         $tmp_arr = str_split($tmp_val);
356         $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
357         return $res;
358       }
359     } // AM cases handling.
360
361     // 12 hour PM patterns.
362     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
363
364       // The $value ends in pm or PM. Strip it.
365       $tmp_val = rtrim(substr($tmp_val, 0, -2));
366
367       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
368         // Single digit. Assuming hour number.
369         $hour = (string)(12 + (int)$tmp_val);
370         $res = $hour.':00';
371         return $res;
372       }
373       if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
374         // Double digit hour.
375         if ('12' != $tmp_val)
376           $tmp_val = (string)(12 + (int)$tmp_val);
377         $res = $tmp_val.':00';
378         return $res;
379       }
380       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
381         // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
382         $tmp_arr = str_split($tmp_val);
383         $hour = (string)(12 + (int)$tmp_arr[0]);
384         $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
385         return $res;
386       }
387       if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
388         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
389         $hour = substr($tmp_val, 0, -2);
390         $min = substr($tmp_val, 2);
391         if ('12' != $hour)
392           $hour = (string)(12 + (int)$hour);
393         $res = $hour.':'.$min;
394         return $res;
395       }
396       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
397         $hour = substr($tmp_val, 0, -3);
398         $min = substr($tmp_val, 2);
399         $hour = (string)(12 + (int)$hour);
400         $res = $hour.':'.$min;
401         return $res;
402       }
403       if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
404         $hour = substr($tmp_val, 0, -3);
405         $min = substr($tmp_val, 3);
406         if ('12' != $hour)
407           $hour = (string)(12 + (int)$hour);
408         $res = $hour.':'.$min;
409         return $res;
410       }
411     } // PM cases handling.
412
413     return $res;
414   }
415
416   // isValidInterval - checks if finish time is greater than start time.
417   static function isValidInterval($start, $finish) {
418     $start = ttTimeHelper::to24HourFormat($start);
419     $finish = ttTimeHelper::to24HourFormat($finish);
420     if ('00:00' == $finish) $finish = '24:00';
421
422     $minutesStart = ttTimeHelper::toMinutes($start);
423     $minutesFinish = ttTimeHelper::toMinutes($finish);
424     if ($minutesFinish > $minutesStart)
425       return true;
426
427     return false;
428   }
429
430   // insert - inserts a time record into tt_log table. Does not deal with custom fields.
431   static function insert($fields)
432   {
433     global $user;
434     $mdb2 = getConnection();
435
436     $user_id = (int) $fields['user_id'];
437     $group_id = (int) $fields['group_id'];
438     $org_id = (int) $fields['org_id'];
439     $date = $fields['date'];
440     $start = $fields['start'];
441     $finish = $fields['finish'];
442     $duration = $fields['duration'];
443     if ($duration) {
444       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
445       $duration = ttTimeHelper::minutesToDuration($minutes);
446     }
447     $client = $fields['client'];
448     $project = $fields['project'];
449     $task = $fields['task'];
450     $invoice = $fields['invoice'];
451     $note = $fields['note'];
452     $billable = $fields['billable'];
453     $paid = $fields['paid'];
454     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
455       $status_f = ', status';
456       $status_v = ', '.$mdb2->quote($fields['status']);
457     }
458
459     $start = ttTimeHelper::to24HourFormat($start);
460     if ($finish) {
461       $finish = ttTimeHelper::to24HourFormat($finish);
462       if ('00:00' == $finish) $finish = '24:00';
463     }
464
465     $created_v = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
466
467     if (!$billable) $billable = 0;
468     if (!$paid) $paid = 0;
469
470     if ($duration) {
471       $sql = "insert into tt_log (user_id, group_id, org_id, date, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
472         "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
473       $affected = $mdb2->exec($sql);
474       if (is_a($affected, 'PEAR_Error'))
475         return false;
476     } else {
477       $duration = ttTimeHelper::toDuration($start, $finish);
478       if ($duration === false) $duration = 0;
479       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
480
481       $sql = "insert into tt_log (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
482         "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$start', '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
483       $affected = $mdb2->exec($sql);
484       if (is_a($affected, 'PEAR_Error'))
485         return false;
486     }
487
488     $id = $mdb2->lastInsertID('tt_log', 'id');
489     return $id;
490   }
491
492   // update - updates a record in log table. Does not update its custom fields.
493   static function update($fields)
494   {
495     global $user;
496     $mdb2 = getConnection();
497
498     $id = $fields['id'];
499     $date = $fields['date'];
500     $user_id = $fields['user_id'];
501     $client = $fields['client'];
502     $project = $fields['project'];
503     $task = $fields['task'];
504     $start = $fields['start'];
505     $finish = $fields['finish'];
506     $duration = $fields['duration'];
507     if ($duration) {
508       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
509       $duration = ttTimeHelper::minutesToDuration($minutes);
510     }
511     $note = $fields['note'];
512
513     $billable_part = '';
514     if ($user->isPluginEnabled('iv')) {
515       $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
516     }
517     $paid_part = '';
518     if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
519       $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
520     }
521     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
522
523     $start = ttTimeHelper::to24HourFormat($start);
524     $finish = ttTimeHelper::to24HourFormat($finish);
525     if ('00:00' == $finish) $finish = '24:00';
526     
527     if ($start) $duration = '';
528
529     if ($duration) {
530       $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
531         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
532       $affected = $mdb2->exec($sql);
533       if (is_a($affected, 'PEAR_Error'))
534         return false;
535     } else {
536       $duration = ttTimeHelper::toDuration($start, $finish);
537       if ($duration === false)
538         $duration = 0;
539       $uncompleted = ttTimeHelper::getUncompleted($user_id);
540       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
541         return false;
542
543       $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
544         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
545       $affected = $mdb2->exec($sql);
546       if (is_a($affected, 'PEAR_Error'))
547         return false;
548     }
549     return true;
550   }
551
552   // delete - deletes a record from tt_log table and its associated custom field values.
553   static function delete($id) {
554     global $user;
555     $mdb2 = getConnection();
556
557     // Delete associated files.
558     if ($user->isPluginEnabled('at')) {
559       import('ttFileHelper');
560       global $err;
561       $fileHelper = new ttFileHelper($err);
562       if (!$fileHelper->deleteEntityFiles($id, 'time'))
563         return false;
564     }
565
566     $user_id = $user->getUser();
567     $group_id = $user->getGroup();
568     $org_id = $user->org_id;
569
570     $sql = "update tt_log set status = null".
571       " where id = $id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
572     $affected = $mdb2->exec($sql);
573     if (is_a($affected, 'PEAR_Error'))
574       return false;
575
576     $sql = "update tt_custom_field_log set status = null".
577       " where log_id = $id and group_id = $group_id and org_id = $org_id";
578     $affected = $mdb2->exec($sql);
579     if (is_a($affected, 'PEAR_Error'))
580       return false;
581
582     return true;
583   }
584
585   // getTimeForDay - gets total time for a user for a specific date.
586   static function getTimeForDay($date) {
587     global $user;
588     $mdb2 = getConnection();
589
590     $user_id = $user->getUser();
591     $group_id = $user->getGroup();
592     $org_id = $user->org_id;
593
594     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
595       " where user_id = $user_id and group_id = $group_id and org_id = $org_id and date = '$date' and status = 1";
596     $res = $mdb2->query($sql);
597     if (!is_a($res, 'PEAR_Error')) {
598       $val = $res->fetchRow();
599       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
600     }
601     return false;
602   }
603
604   // getTimeForWeek - gets total time for a user for a given week.
605   static function getTimeForWeek($date) {
606     global $user;
607     import('Period');
608     $mdb2 = getConnection();
609
610     $user_id = $user->getUser();
611     $group_id = $user->getGroup();
612     $org_id = $user->org_id;
613
614     $period = new Period(INTERVAL_THIS_WEEK, $date);
615     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
616       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
617       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
618     $res = $mdb2->query($sql);
619     if (!is_a($res, 'PEAR_Error')) {
620       $val = $res->fetchRow();
621       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
622     }
623     return false;
624   }
625
626   // getTimeForMonth - gets total time for a user for a given month.
627   static function getTimeForMonth($date) {
628     global $user;
629     import('Period');
630     $mdb2 = getConnection();
631
632     $user_id = $user->getUser();
633     $group_id = $user->getGroup();
634     $org_id = $user->org_id;
635
636     $period = new Period(INTERVAL_THIS_MONTH, $date);
637     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
638       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
639       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
640     $res = $mdb2->query($sql);
641     if (!is_a($res, 'PEAR_Error')) {
642       $val = $res->fetchRow();
643       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
644     }
645     return false;
646   }
647
648   // getUncompleted - retrieves an uncompleted record for user, if one exists.
649   static function getUncompleted($user_id) {
650     $mdb2 = getConnection();
651
652     $sql = "select id, start from tt_log  
653       where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
654     $res = $mdb2->query($sql);
655     if (!is_a($res, 'PEAR_Error')) {
656       if (!$res->numRows()) {
657         return false;
658       }
659       if ($val = $res->fetchRow()) {
660         return $val;
661       }
662     }
663     return false;
664   }
665
666   // overlaps - determines if a record overlaps with an already existing record.
667   //
668   // Parameters:
669   //   $user_id - user id for whom to determine overlap
670   //   $date - date
671   //   $start - new record start time
672   //   $finish - new record finish time, may be null
673   //   $record_id - optional record id we may be editing, excluded from overlap set
674   static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
675     // Do not bother checking if we allow overlaps.
676     global $user;
677     if ($user->allow_overlap) return false;
678
679     $mdb2 = getConnection();
680
681     $start = ttTimeHelper::to24HourFormat($start);
682     if ($finish) {
683       $finish = ttTimeHelper::to24HourFormat($finish);
684       if ('00:00' == $finish) $finish = '24:00';
685     }
686     // Handle these 3 overlap situations:
687     // - start time in existing record
688     // - end time in existing record
689     // - record fully encloses existing record
690     $sql = "select id from tt_log  
691       where user_id = $user_id and date = ".$mdb2->quote($date)."
692       and start is not null and duration is not null and status = 1 and (
693       (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
694     if ($finish) {
695       $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
696       or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
697     }
698     $sql .= ")";
699     if ($record_id) {
700       $sql .= " and id <> $record_id";
701     }
702     $res = $mdb2->query($sql);
703     if (!is_a($res, 'PEAR_Error')) {
704       if (!$res->numRows()) {
705         return false;
706       }
707       if ($val = $res->fetchRow()) {
708         return $val;
709       }
710     }
711     return false;
712   }
713
714   // getRecord - retrieves a time record identified by its id.
715   static function getRecord($id) {
716     global $user;
717
718     $user_id = $user->getUser();
719     $group_id = $user->getGroup();
720     $org_id = $user->org_id;
721
722     $sql_time_format = "'%k:%i'"; //  24 hour format.
723     if ('%I:%M %p' == $user->time_format)
724       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
725
726     $mdb2 = getConnection();
727
728     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
729       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
730       " TIME_FORMAT(l.duration, '%k:%i') as duration,".
731       " p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id,".
732       " l.timesheet_id, l.invoice_id, l.billable, l.approved, l.paid, l.date from tt_log l".
733       " left join tt_projects p on (p.id = l.project_id)".
734       " left join tt_tasks t on (t.id = l.task_id)".
735       " where l.id = $id and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
736     $res = $mdb2->query($sql);
737     if (!is_a($res, 'PEAR_Error')) {
738       if (!$res->numRows()) {
739         return false;
740       }
741       if ($val = $res->fetchRow()) {
742         return $val;
743       }
744     }
745     return false;
746   }
747
748   // getRecordForFileView - retrieves a time record identified by its id for
749   // attachment view operation.
750   //
751   // It is different from getRecord, as we want users with appropriate rights
752   // to be able to see other users files, without changing "on behalf" user.
753   // For example, viewing reports for all users and their attached files
754   // from report links.
755   static function getRecordForFileView($id) {
756     // There are several possible situations:
757     //
758     // Record is ours. Check "view_own_reports" or "view_all_reports".
759     // Record is for the current on behalf user. Check "view_reports" or "view_all_reports".
760     // Record is for someone else. Check "view_reports" or "view_all_reports" and rank.
761     //
762     // It looks like the best way is to use 2 queries, obtain user_id first, then check rank.
763
764     global $user;
765
766     $group_id = $user->getGroup();
767     $org_id = $user->org_id;
768
769     $mdb2 = getConnection();
770
771     // Obtain user_id for the time record.
772     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved from tt_log l ".
773       " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
774     $res = $mdb2->query($sql);
775     if (is_a($res, 'PEAR_Error')) return false;
776     if (!$res->numRows()) return false;
777
778     $val = $res->fetchRow();
779     $user_id = $val['user_id'];
780
781     // If record is ours.
782     if ($user_id == $user->id) {
783       if ($user->can('view_own_reports') || $user->can('view_all_reports')) {
784         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
785         return $val;
786       }
787       return false; // No rights.
788     }
789
790     // If record belongs to a user we impersonate.
791     if ($user->behalfUser && $user_id == $user->behalfUser->id) {
792       if ($user->can('view_reports') || $user->can('view_all_reports')) {
793         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
794         return $val;
795       }
796       return false; // No rights.
797     }
798
799     // Record belongs to someone else. We need to check user rank.
800     if (!($user->can('view_reports') || $user->can('view_all_reports'))) return false;
801     $max_rank = $user->can('view_all_reports') ? MAX_RANK : $user->getMaxRankForGroup($group_id);
802
803     $left_joins = ' left join tt_users u on (l.user_id = u.id)';
804     $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
805
806     $where_part = " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
807     $where_part .= " and r.rank <= $max_rank";
808
809     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved".
810       " from tt_log l $left_joins $where_part";
811     $res = $mdb2->query($sql);
812     if (!is_a($res, 'PEAR_Error')) {
813       if (!$res->numRows()) {
814         return false;
815       }
816       if ($val = $res->fetchRow()) {
817         $val['can_edit'] = false;
818         return $val;
819       }
820     }
821     return false;
822   }
823
824   // getAllRecords - returns all time records for a certain user.
825   static function getAllRecords($user_id) {
826     $result = array();
827
828     $mdb2 = getConnection();
829
830     $sql = "select l.id, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
831       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
832       TIME_FORMAT(l.duration, '%k:%i') as duration,
833       l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.paid, l.status
834       from tt_log l where l.user_id = $user_id order by l.id";
835     $res = $mdb2->query($sql);
836     if (!is_a($res, 'PEAR_Error')) {
837       while ($val = $res->fetchRow()) {
838         $result[] = $val;
839       }
840     } else return false;
841
842     return $result;
843   }
844
845   // getRecords - returns time records for a user for a given date.
846   static function getRecords($date, $includeFiles = false) {
847     global $user;
848     $mdb2 = getConnection();
849
850     $user_id = $user->getUser();
851     $group_id = $user->getGroup();
852     $org_id = $user->org_id;
853
854     $sql_time_format = "'%k:%i'"; //  24 hour format.
855     if ('%I:%M %p' == $user->getTimeFormat())
856       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
857
858     $client_field = null;
859     if ($user->isPluginEnabled('cl'))
860       $client_field = ", c.name as client";
861
862     $include_cf_1 = $user->isPluginEnabled('cf');
863     if ($include_cf_1) {
864       $custom_fields = new CustomFields();
865       $cf_1_type = $custom_fields->fields[0]['type'];
866       if ($cf_1_type == CustomFields::TYPE_TEXT) {
867         $custom_field = ", cfl.value as cf_1";
868       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
869         $custom_field = ", cfo.value as cf_1";
870       }
871     }
872
873     if ($includeFiles) {
874       $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
875       $fileJoin =  " left join (select distinct entity_id from tt_files".
876       " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
877       " on (l.id = Sub1.entity_id)";
878     }
879
880     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
881       " left join tt_tasks t on (l.task_id = t.id)";
882     if ($user->isPluginEnabled('cl'))
883       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
884     if ($include_cf_1) {
885       if ($cf_1_type == CustomFields::TYPE_TEXT)
886         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
887       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
888         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
889           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
890       }
891     }
892     $left_joins .= $fileJoin;
893
894     $result = array();
895     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
896       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
897       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
898       " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field $filePart from tt_log l $left_joins".
899       " where l.date = '$date' and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
900       " order by l.start, l.id";
901     $res = $mdb2->query($sql);
902     if (!is_a($res, 'PEAR_Error')) {
903       while ($val = $res->fetchRow()) {
904         if($val['duration']=='0:00')
905           $val['finish'] = '';
906         $result[] = $val;
907       }
908     } else return false;
909
910     return $result;
911   }
912
913   // canAdd determines if we can add a record in case there is a limit.
914   static function canAdd() {
915     $mdb2 = getConnection();
916     $sql = "select param_value from tt_site_config where param_name = 'exp_date'";
917     $res = $mdb2->query($sql);
918     $val = $res->fetchRow();
919     if (!$val) return true; // No expiration date.
920
921     if (strtotime($val['param_value']) > time())
922       return true; // Expiration date exists but not reached.
923
924     return false;
925   }
926 }