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