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