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