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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 import('DateAndTime');
31 // The ttTimeHelper is a class to help with time-related values.
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);
40 // isHoliday determines if $date falls on a holiday.
41 static function isHoliday($date) {
44 $holidays = $user->getHolidays();
48 $holiday_dates = explode(',', $holidays);
49 foreach ($holiday_dates as $holiDateSpec) {
50 if (ttTimeHelper::holidayMatch($date, $holiDateSpec))
56 // holidayMatch determines if $date matches a single $holiDateSpec.
57 static function holidayMatch($date, $holiDateSpec) {
59 $dateArray = explode('-', $date);
60 $holiDateSpecArray = explode('-', $holiDateSpec);
63 if ($dateArray[0] != $holiDateSpecArray[0] && $holiDateSpecArray[0] != '****') // **** means all years.
66 if ($dateArray[1] != $holiDateSpecArray[1])
69 if ($dateArray[2] != $holiDateSpecArray[2])
75 // dateInDatabaseFormat prepares a date string in DB_DATEFORMAT out of year, month, and day.
76 static function dateInDatabaseFormat($year, $month, $day) {
78 if (strlen($month) == 1) $date .= '0';
80 if (strlen($day) == 1) $date .= '0';
85 // isValidTime validates a value as a time string.
86 static function isValidTime($value) {
87 if (strlen($value)==0 || !isset($value)) return false;
90 if ($value == '24:00' || $value == '2400') return true;
92 if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
95 if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
100 if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
103 if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
106 if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
109 if (preg_match('/^(0[1-9]|1[0-2]):?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 01:00 - 12:59 am, 0100 - 1259 am
116 // isValidDuration validates a value as a time duration string (in hours and minutes).
117 static function isValidDuration($value) {
118 if (strlen($value) == 0 || !isset($value)) return false;
120 if ($value == '24:00' || $value == '2400') return true;
122 if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
125 if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
130 $localizedPattern = '/^([0-1]{0,1}[0-9]|2[0-3])?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
131 if (preg_match($localizedPattern, $value )) { // decimal values like 0.5, 1.25h, ... .. 23.9999h (or with comma)
138 // postedDurationToMinutes - converts a value representing a duration
139 // (usually enetered in a form by a user) to an integer number of minutes.
142 // $duration - user entered duration string. Valid strings are:
143 // 3 or 3h - means 3 hours. Note: h and m letters are not localized.
144 // 0.25 or 0.25h or .25 or .25h - means a quarter of hour.
145 // 0,25 or 0,25h or ,25 or ,25h - same as above for users with comma ad decimal mark.
146 // 1:30 - means 1 hour 30 minutes.
147 // 25m - means 25 minutes.
148 // $max - maximum number of minutes that is valid.
150 // At the moment, we have 2 variations of duration types:
151 // 1) A duration within a day, such as in a time entry.
152 // These are less or equal to 24*60 minutes.
154 // 2) A duration of a monthly quota, with max value of 31*24*60 minutes.
156 // This function is generic to be used for both types.
158 // Returns false if the value cannot be converted.
159 static function postedDurationToMinutes($duration, $max = 1440) {
160 // Handle empty value.
161 if (!isset($duration) || strlen($duration) == 0)
162 return null; // Value is not set. Caller decides whether it is valid or not.
164 // We allow negative durations, similar to negative expenses (installments).
165 $signMultiplier = ttStartsWith($duration, '-') ? -1 : 1;
166 if ($signMultiplier == -1) $duration = ltrim($duration, '-');
168 // Handle whole hours.
169 if (preg_match('/^\d{1,3}h?$/', $duration )) { // 0 - 999, 0h - 999h
170 $minutes = 60 * trim($duration, 'h');
171 return $minutes > $max ? false : $signMultiplier * $minutes;
174 // Handle a normalized duration value.
175 if (preg_match('/^\d{1,3}:[0-5][0-9]$/', $duration )) { // 0:00 - 999:59
176 $time_array = explode(':', $duration);
177 $minutes = (int)@$time_array[1] + ((int)@$time_array[0]) * 60;
178 return $minutes > $max ? false : $signMultiplier * $minutes;
181 // Handle localized fractional hours.
183 $localizedPattern = '/^(\d{1,3})?['.$user->getDecimalMark().'][0-9]{1,4}h?$/';
184 if (preg_match($localizedPattern, $duration )) { // decimal values like .5, 1.25h, ... .. 999.9999h (or with comma)
185 if ($user->getDecimalMark() == ',')
186 $duration = str_replace (',', '.', $duration);
188 $minutes = (int)round(60 * floatval($duration));
189 return $minutes > $max ? false : $signMultiplier * $minutes;
192 // Handle minutes. Some users enter durations like 10m (meaning 10 minutes).
193 if (preg_match('/^\d{1,5}m$/', $duration )) { // 0m - 99999m
194 $minutes = (int) trim($duration, 'm');
195 return $minutes > $max ? false : $signMultiplier * $minutes;
198 // Everything else is not a valid duration.
202 // minutesToDuration converts an integer number of minutes into duration string.
203 // Formats returned HH:MM, HHH:MM, HH, or HHH.
204 static function minutesToDuration($minutes, $abbreviate = false) {
205 $sign = $minutes >= 0 ? '' : '-';
206 $minutes = abs($minutes);
208 $hours = (string) (int)($minutes / 60);
209 $mins = (string) round(fmod($minutes, 60));
210 if (strlen($mins) == 1)
212 if ($abbreviate && $mins == '00')
215 return $sign.$hours.':'.$mins;
218 // toMinutes - converts a time string in format 00:00 to a number of minutes.
219 static function toMinutes($value) {
220 $signMultiplier = ttStartsWith($value, '-') ? -1 : 1;
221 if ($signMultiplier == -1) $value = ltrim($value, '-');
223 $time_a = explode(':', $value);
224 return $signMultiplier * ((int)@$time_a[1] + ((int)@$time_a[0]) * 60);
227 // toAbsDuration - converts a number of minutes to format 0:00
228 // even if $minutes is negative.
229 static function toAbsDuration($minutes, $abbreviate = false){
230 $hours = (string)((int)abs($minutes / 60));
231 $mins = (string) round(abs(fmod($minutes, 60)));
232 if (strlen($mins) == 1)
234 if ($abbreviate && $mins == '00')
237 return $hours.':'.$mins;
240 // toDuration - calculates duration between start and finish times in 00:00 format.
241 static function toDuration($start, $finish) {
242 $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
243 if ($duration_minutes <= 0) return false;
245 return ttTimeHelper::toAbsDuration($duration_minutes);
248 // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
249 static function to12HourFormat($value) {
250 if ('24:00' == $value) return '12:00 AM';
252 $time_a = explode(':', $value);
254 $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
255 elseif ($time_a[0] == 12)
257 elseif ($time_a[0] == 0)
258 $res = '12:'.$time_a[1].' AM';
264 // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
265 // to a 24-hour time format HH:MM.
266 static function to24HourFormat($value) {
269 // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
270 $tmp_val = trim($value);
273 if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
274 // We already have a 24-hour format. Just return it.
278 if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
279 // This is a 24-hour format without a leading zero. Add 0 and return.
283 if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
284 // Single digit. Assuming hour number.
285 $res = '0'.$tmp_val.':00';
288 if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
289 // Two digit hour number.
290 $res = $tmp_val.':00';
293 if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
294 // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
295 $tmp_arr = str_split($tmp_val);
296 $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
299 if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
300 // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
301 $tmp_arr = str_split($tmp_val);
302 $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
305 // Special handling for midnight.
306 if ($tmp_val == '24:00' || $tmp_val == '2400')
309 // 12 hour AM patterns.
310 if (preg_match('/.(am|AM)$/', $tmp_val)) {
312 // The $value ends in am or AM. Strip it.
313 $tmp_val = rtrim(substr($tmp_val, 0, -2));
315 // Special case to handle 12, 12:MM, and 12MM AM.
316 if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
317 $tmp_val = '00'.substr($tmp_val, 2);
319 // We are ready to convert AM time.
320 if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
321 // We already have a 24-hour format. Just return it.
325 if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
326 // This is a 24-hour format without a leading zero. Add 0 and return.
330 if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
331 // Single digit. Assuming hour number.
332 $res = '0'.$tmp_val.':00';
335 if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
336 // Two digit hour number.
337 $res = $tmp_val.':00';
340 if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
341 // Missing colon. Assume the first digit is the hour, the rest is minutes.
342 $tmp_arr = str_split($tmp_val);
343 $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
346 if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
347 // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
348 $tmp_arr = str_split($tmp_val);
349 $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
352 } // AM cases handling.
354 // 12 hour PM patterns.
355 if (preg_match('/.(pm|PM)$/', $tmp_val)) {
357 // The $value ends in pm or PM. Strip it.
358 $tmp_val = rtrim(substr($tmp_val, 0, -2));
360 if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
361 // Single digit. Assuming hour number.
362 $hour = (string)(12 + (int)$tmp_val);
366 if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
367 // Double digit hour.
368 if ('12' != $tmp_val)
369 $tmp_val = (string)(12 + (int)$tmp_val);
370 $res = $tmp_val.':00';
373 if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
374 // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
375 $tmp_arr = str_split($tmp_val);
376 $hour = (string)(12 + (int)$tmp_arr[0]);
377 $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
380 if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
381 // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
382 $hour = substr($tmp_val, 0, -2);
383 $min = substr($tmp_val, 2);
385 $hour = (string)(12 + (int)$hour);
386 $res = $hour.':'.$min;
389 if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
390 $hour = substr($tmp_val, 0, -3);
391 $min = substr($tmp_val, 2);
392 $hour = (string)(12 + (int)$hour);
393 $res = $hour.':'.$min;
396 if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
397 $hour = substr($tmp_val, 0, -3);
398 $min = substr($tmp_val, 3);
400 $hour = (string)(12 + (int)$hour);
401 $res = $hour.':'.$min;
404 } // PM cases handling.
409 // isValidInterval - checks if finish time is greater than start time.
410 static function isValidInterval($start, $finish) {
411 $start = ttTimeHelper::to24HourFormat($start);
412 $finish = ttTimeHelper::to24HourFormat($finish);
413 if ('00:00' == $finish) $finish = '24:00';
415 $minutesStart = ttTimeHelper::toMinutes($start);
416 $minutesFinish = ttTimeHelper::toMinutes($finish);
417 if ($minutesFinish > $minutesStart)
423 // insert - inserts a time record into tt_log table. Does not deal with custom fields.
424 static function insert($fields)
427 $mdb2 = getConnection();
429 $user_id = (int) $fields['user_id'];
430 $group_id = (int) $fields['group_id'];
431 $org_id = (int) $fields['org_id'];
432 $date = $fields['date'];
433 $start = $fields['start'];
434 $finish = $fields['finish'];
435 $duration = $fields['duration'];
437 $minutes = ttTimeHelper::postedDurationToMinutes($duration);
438 $duration = ttTimeHelper::minutesToDuration($minutes);
440 $client = $fields['client'];
441 $project = $fields['project'];
442 $task = $fields['task'];
443 $invoice = $fields['invoice'];
444 $note = $fields['note'];
445 $billable = $fields['billable'];
446 $paid = $fields['paid'];
447 if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
448 $status_f = ', status';
449 $status_v = ', '.$mdb2->quote($fields['status']);
452 $start = ttTimeHelper::to24HourFormat($start);
454 $finish = ttTimeHelper::to24HourFormat($finish);
455 if ('00:00' == $finish) $finish = '24:00';
458 $created_v = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
460 if (!$billable) $billable = 0;
461 if (!$paid) $paid = 0;
464 $sql = "insert into tt_log (user_id, group_id, org_id, date, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
465 "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
466 $affected = $mdb2->exec($sql);
467 if (is_a($affected, 'PEAR_Error'))
470 $duration = ttTimeHelper::toDuration($start, $finish);
471 if ($duration === false) $duration = 0;
472 if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
474 $sql = "insert into tt_log (user_id, group_id, org_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment, billable, paid, created, created_ip, created_by $status_f) ".
475 "values ($user_id, $group_id, $org_id, ".$mdb2->quote($date).", '$start', '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable, $paid $created_v $status_v)";
476 $affected = $mdb2->exec($sql);
477 if (is_a($affected, 'PEAR_Error'))
481 $id = $mdb2->lastInsertID('tt_log', 'id');
485 // update - updates a record in log table. Does not update its custom fields.
486 static function update($fields)
489 $mdb2 = getConnection();
492 $date = $fields['date'];
493 $user_id = $fields['user_id'];
494 $client = $fields['client'];
495 $project = $fields['project'];
496 $task = $fields['task'];
497 $start = $fields['start'];
498 $finish = $fields['finish'];
499 $duration = $fields['duration'];
501 $minutes = ttTimeHelper::postedDurationToMinutes($duration);
502 $duration = ttTimeHelper::minutesToDuration($minutes);
504 $note = $fields['note'];
507 if ($user->isPluginEnabled('iv')) {
508 $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
511 if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
512 $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
514 $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
516 $start = ttTimeHelper::to24HourFormat($start);
517 $finish = ttTimeHelper::to24HourFormat($finish);
518 if ('00:00' == $finish) $finish = '24:00';
520 if ($start) $duration = '';
523 $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
524 "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
525 $affected = $mdb2->exec($sql);
526 if (is_a($affected, 'PEAR_Error'))
529 $duration = ttTimeHelper::toDuration($start, $finish);
530 if ($duration === false)
532 $uncompleted = ttTimeHelper::getUncompleted($user_id);
533 if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
536 $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
537 "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
538 $affected = $mdb2->exec($sql);
539 if (is_a($affected, 'PEAR_Error'))
545 // delete - deletes a record from tt_log table and its associated custom field values.
546 static function delete($id) {
548 $mdb2 = getConnection();
550 // Delete associated files.
551 if ($user->isPluginEnabled('at')) {
552 import('ttFileHelper');
554 $fileHelper = new ttFileHelper($err);
555 if (!$fileHelper->deleteEntityFiles($id, 'time'))
559 $user_id = $user->getUser();
560 $group_id = $user->getGroup();
561 $org_id = $user->org_id;
563 $sql = "update tt_log set status = null".
564 " where id = $id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
565 $affected = $mdb2->exec($sql);
566 if (is_a($affected, 'PEAR_Error'))
569 $sql = "update tt_custom_field_log set status = null".
570 " where log_id = $id and group_id = $group_id and org_id = $org_id";
571 $affected = $mdb2->exec($sql);
572 if (is_a($affected, 'PEAR_Error'))
578 // getTimeForDay - gets total time for a user for a specific date.
579 static function getTimeForDay($date) {
581 $mdb2 = getConnection();
583 $user_id = $user->getUser();
584 $group_id = $user->getGroup();
585 $org_id = $user->org_id;
587 $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
588 " where user_id = $user_id and group_id = $group_id and org_id = $org_id and date = '$date' and status = 1";
589 $res = $mdb2->query($sql);
590 if (!is_a($res, 'PEAR_Error')) {
591 $val = $res->fetchRow();
592 return ttTimeHelper::minutesToDuration($val['sm'] / 60);
597 // getTimeForWeek - gets total time for a user for a given week.
598 static function getTimeForWeek($date) {
601 $mdb2 = getConnection();
603 $user_id = $user->getUser();
604 $group_id = $user->getGroup();
605 $org_id = $user->org_id;
607 $period = new Period(INTERVAL_THIS_WEEK, $date);
608 $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
609 " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
610 " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
611 $res = $mdb2->query($sql);
612 if (!is_a($res, 'PEAR_Error')) {
613 $val = $res->fetchRow();
614 return ttTimeHelper::minutesToDuration($val['sm'] / 60);
619 // getTimeForMonth - gets total time for a user for a given month.
620 static function getTimeForMonth($date) {
623 $mdb2 = getConnection();
625 $user_id = $user->getUser();
626 $group_id = $user->getGroup();
627 $org_id = $user->org_id;
629 $period = new Period(INTERVAL_THIS_MONTH, $date);
630 $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
631 " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
632 " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
633 $res = $mdb2->query($sql);
634 if (!is_a($res, 'PEAR_Error')) {
635 $val = $res->fetchRow();
636 return ttTimeHelper::minutesToDuration($val['sm'] / 60);
641 // getUncompleted - retrieves an uncompleted record for user, if one exists.
642 static function getUncompleted($user_id) {
643 $mdb2 = getConnection();
645 $sql = "select id, start from tt_log
646 where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
647 $res = $mdb2->query($sql);
648 if (!is_a($res, 'PEAR_Error')) {
649 if (!$res->numRows()) {
652 if ($val = $res->fetchRow()) {
659 // overlaps - determines if a record overlaps with an already existing record.
662 // $user_id - user id for whom to determine overlap
664 // $start - new record start time
665 // $finish - new record finish time, may be null
666 // $record_id - optional record id we may be editing, excluded from overlap set
667 static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
668 // Do not bother checking if we allow overlaps.
670 if ($user->allow_overlap) return false;
672 $mdb2 = getConnection();
674 $start = ttTimeHelper::to24HourFormat($start);
676 $finish = ttTimeHelper::to24HourFormat($finish);
677 if ('00:00' == $finish) $finish = '24:00';
679 // Handle these 3 overlap situations:
680 // - start time in existing record
681 // - end time in existing record
682 // - record fully encloses existing record
683 $sql = "select id from tt_log
684 where user_id = $user_id and date = ".$mdb2->quote($date)."
685 and start is not null and duration is not null and status = 1 and (
686 (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
688 $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
689 or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
693 $sql .= " and id <> $record_id";
695 $res = $mdb2->query($sql);
696 if (!is_a($res, 'PEAR_Error')) {
697 if (!$res->numRows()) {
700 if ($val = $res->fetchRow()) {
707 // getRecord - retrieves a time record identified by its id.
708 static function getRecord($id) {
711 $user_id = $user->getUser();
712 $group_id = $user->getGroup();
713 $org_id = $user->org_id;
715 $sql_time_format = "'%k:%i'"; // 24 hour format.
716 if ('%I:%M %p' == $user->time_format)
717 $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
719 $mdb2 = getConnection();
721 $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
722 " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
723 " TIME_FORMAT(l.duration, '%k:%i') as duration,".
724 " p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id,".
725 " l.timesheet_id, l.invoice_id, l.billable, l.approved, l.paid, l.date from tt_log l".
726 " left join tt_projects p on (p.id = l.project_id)".
727 " left join tt_tasks t on (t.id = l.task_id)".
728 " where l.id = $id and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
729 $res = $mdb2->query($sql);
730 if (!is_a($res, 'PEAR_Error')) {
731 if (!$res->numRows()) {
734 if ($val = $res->fetchRow()) {
741 // getRecordForFileView - retrieves a time record identified by its id for
742 // attachment view operation.
744 // It is different from getRecord, as we want users with appropriate rights
745 // to be able to see other users files, without changing "on behalf" user.
746 // For example, viewing reports for all users and their attached files
747 // from report links.
748 static function getRecordForFileView($id) {
749 // There are several possible situations:
751 // Record is ours. Check "view_own_reports" or "view_all_reports".
752 // Record is for the current on behalf user. Check "view_reports" or "view_all_reports".
753 // Record is for someone else. Check "view_reports" or "view_all_reports" and rank.
755 // It looks like the best way is to use 2 queries, obtain user_id first, then check rank.
759 $group_id = $user->getGroup();
760 $org_id = $user->org_id;
762 $mdb2 = getConnection();
764 // Obtain user_id for the time record.
765 $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved from tt_log l ".
766 " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
767 $res = $mdb2->query($sql);
768 if (is_a($res, 'PEAR_Error')) return false;
769 if (!$res->numRows()) return false;
771 $val = $res->fetchRow();
772 $user_id = $val['user_id'];
774 // If record is ours.
775 if ($user_id == $user->id) {
776 if ($user->can('view_own_reports') || $user->can('view_all_reports')) {
777 $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
780 return false; // No rights.
783 // If record belongs to a user we impersonate.
784 if ($user->behalfUser && $user_id == $user->behalfUser->id) {
785 if ($user->can('view_reports') || $user->can('view_all_reports')) {
786 $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
789 return false; // No rights.
792 // Record belongs to someone else. We need to check user rank.
793 if (!($user->can('view_reports') || $user->can('view_all_reports'))) return false;
794 $max_rank = $user->can('view_all_reports') ? MAX_RANK : $user->getMaxRankForGroup($group_id);
796 $left_joins = ' left join tt_users u on (l.user_id = u.id)';
797 $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
799 $where_part = " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
800 $where_part .= " and r.rank <= $max_rank";
802 $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved".
803 " from tt_log l $left_joins $where_part";
804 $res = $mdb2->query($sql);
805 if (!is_a($res, 'PEAR_Error')) {
806 if (!$res->numRows()) {
809 if ($val = $res->fetchRow()) {
810 $val['can_edit'] = false;
817 // getAllRecords - returns all time records for a certain user.
818 static function getAllRecords($user_id) {
821 $mdb2 = getConnection();
823 $sql = "select l.id, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
824 TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
825 TIME_FORMAT(l.duration, '%k:%i') as duration,
826 l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.paid, l.status
827 from tt_log l where l.user_id = $user_id order by l.id";
828 $res = $mdb2->query($sql);
829 if (!is_a($res, 'PEAR_Error')) {
830 while ($val = $res->fetchRow()) {
838 // getRecords - returns time records for a user for a given date.
839 static function getRecords($date, $includeFiles = false) {
841 $mdb2 = getConnection();
843 $user_id = $user->getUser();
844 $group_id = $user->getGroup();
845 $org_id = $user->org_id;
847 $sql_time_format = "'%k:%i'"; // 24 hour format.
848 if ('%I:%M %p' == $user->getTimeFormat())
849 $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
851 $client_field = null;
852 if ($user->isPluginEnabled('cl'))
853 $client_field = ", c.name as client";
855 $include_cf_1 = $user->isPluginEnabled('cf');
857 $custom_fields = new CustomFields();
858 $cf_1_type = $custom_fields->fields[0]['type'];
859 if ($cf_1_type == CustomFields::TYPE_TEXT) {
860 $custom_field = ", cfl.value as cf_1";
861 } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
862 $custom_field = ", cfo.value as cf_1";
867 $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
868 $fileJoin = " left join (select distinct entity_id from tt_files".
869 " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
870 " on (l.id = Sub1.entity_id)";
873 $left_joins = " left join tt_projects p on (l.project_id = p.id)".
874 " left join tt_tasks t on (l.task_id = t.id)";
875 if ($user->isPluginEnabled('cl'))
876 $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
878 if ($cf_1_type == CustomFields::TYPE_TEXT)
879 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
880 elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
881 $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
882 " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
885 $left_joins .= $fileJoin;
888 $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
889 " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
890 " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
891 " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field $filePart from tt_log l $left_joins".
892 " where l.date = '$date' and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
893 " order by l.start, l.id";
894 $res = $mdb2->query($sql);
895 if (!is_a($res, 'PEAR_Error')) {
896 while ($val = $res->fetchRow()) {
897 if($val['duration']=='0:00')
906 // canAdd determines if we can add a record in case there is a limit.
907 static function canAdd() {
908 $mdb2 = getConnection();
909 $sql = "select param_value from tt_site_config where param_name = 'exp_date'";
910 $res = $mdb2->query($sql);
911 $val = $res->fetchRow();
912 if (!$val) return true; // No expiration date.
914 if (strtotime($val['param_value']) > time())
915 return true; // Expiration date exists but not reached.