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