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