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) {
 
  45     if (!$user->show_holidays) return false;
 
  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))
 
  56   // isValidTime validates a value as a time string.
 
  57   static function isValidTime($value) {
 
  58     if (strlen($value)==0 || !isset($value)) return false;
 
  61     if ($value == '24:00' || $value == '2400') return true;
 
  63     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
 
  66     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
 
  71     if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
 
  74     if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
 
  77     if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
 
  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
 
  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;
 
  91     if ($value == '24:00' || $value == '2400') return true;
 
  93     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
 
  96     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
 
 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)
 
 109   // postedDurationToMinutes - converts a value representing a duration
 
 110   // (usually enetered in a form by a user) to an integer number of minutes.
 
 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.
 
 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.
 
 125   //   2) A duration of a monthly quota, with max value of 31*24*60 minutes.
 
 127   // This function is generic to be used for both types.
 
 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.
 
 135     // We allow negative durations, similar to negative expenses (installments).
 
 136     $signMultiplier = ttStartsWith($duration, '-') ? -1 : 1;
 
 137     if ($signMultiplier == -1) $duration = ltrim($duration, '-');
 
 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;
 
 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;
 
 152     // Handle localized fractional hours.
 
 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);
 
 159         $minutes = (int)round(60 * floatval($duration));
 
 160         return $minutes > $max ? false : $signMultiplier * $minutes;
 
 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;
 
 169     // Everything else is not a valid duration.
 
 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);
 
 179     $hours = (string) (int)($minutes / 60);
 
 180     $mins = (string) round(fmod($minutes, 60));
 
 181     if (strlen($mins) == 1)
 
 183     if ($abbreviate && $mins == '00')
 
 186     return $sign.$hours.':'.$mins;
 
 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, '-');
 
 194     $time_a = explode(':', $value);
 
 195     return $signMultiplier * ((int)@$time_a[1] + ((int)@$time_a[0]) * 60);
 
 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)
 
 205     if ($abbreviate && $mins == '00')
 
 208     return $hours.':'.$mins;
 
 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;
 
 216     return ttTimeHelper::toAbsDuration($duration_minutes);
 
 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';
 
 223     $time_a = explode(':', $value);
 
 225       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
 
 226     elseif ($time_a[0] == 12)
 
 228     elseif ($time_a[0] == 0)
 
 229       $res = '12:'.$time_a[1].' AM';
 
 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) {
 
 240     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
 
 241     $tmp_val = trim($value);
 
 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.
 
 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.
 
 254     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
 
 255       // Single digit. Assuming hour number.
 
 256       $res = '0'.$tmp_val.':00';
 
 259     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
 
 260       // Two digit hour number.
 
 261       $res = $tmp_val.':00';
 
 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];
 
 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];
 
 276     // Special handling for midnight.
 
 277     if ($tmp_val == '24:00' || $tmp_val == '2400')
 
 280     // 12 hour AM patterns.
 
 281     if (preg_match('/.(am|AM)$/', $tmp_val)) {
 
 283       // The $value ends in am or AM. Strip it.
 
 284       $tmp_val = rtrim(substr($tmp_val, 0, -2));
 
 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);
 
 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.
 
 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.
 
 301       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
 
 302         // Single digit. Assuming hour number.
 
 303         $res = '0'.$tmp_val.':00';
 
 306       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
 
 307         // Two digit hour number.
 
 308         $res = $tmp_val.':00';
 
 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];
 
 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];
 
 323     } // AM cases handling.
 
 325     // 12 hour PM patterns.
 
 326     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
 
 328       // The $value ends in pm or PM. Strip it.
 
 329       $tmp_val = rtrim(substr($tmp_val, 0, -2));
 
 331       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
 
 332         // Single digit. Assuming hour number.
 
 333         $hour = (string)(12 + (int)$tmp_val);
 
 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';
 
 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];
 
 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);
 
 356           $hour = (string)(12 + (int)$hour);
 
 357         $res = $hour.':'.$min;
 
 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;
 
 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);
 
 371           $hour = (string)(12 + (int)$hour);
 
 372         $res = $hour.':'.$min;
 
 375     } // PM cases handling.
 
 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';
 
 386     $minutesStart = ttTimeHelper::toMinutes($start);
 
 387     $minutesFinish = ttTimeHelper::toMinutes($finish);
 
 388     if ($minutesFinish > $minutesStart)
 
 394   // insert - inserts a time record into tt_log table. Does not deal with custom fields.
 
 395   static function insert($fields)
 
 398     $mdb2 = getConnection();
 
 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'];
 
 408       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
 
 409       $duration = ttTimeHelper::minutesToDuration($minutes);
 
 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']);
 
 423     $start = ttTimeHelper::to24HourFormat($start);
 
 425       $finish = ttTimeHelper::to24HourFormat($finish);
 
 426       if ('00:00' == $finish) $finish = '24:00';
 
 429     $created_v = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
 
 431     if (!$billable) $billable = 0;
 
 432     if (!$paid) $paid = 0;
 
 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'))
 
 441       $duration = ttTimeHelper::toDuration($start, $finish);
 
 442       if ($duration === false) $duration = 0;
 
 443       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
 
 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'))
 
 452     $id = $mdb2->lastInsertID('tt_log', 'id');
 
 456   // update - updates a record in log table. Does not update its custom fields.
 
 457   static function update($fields)
 
 460     $mdb2 = getConnection();
 
 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'];
 
 472       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
 
 473       $duration = ttTimeHelper::minutesToDuration($minutes);
 
 475     $note = $fields['note'];
 
 478     if ($user->isPluginEnabled('iv')) {
 
 479       $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
 
 482     if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
 
 483       $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
 
 485     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
 
 487     $start = ttTimeHelper::to24HourFormat($start);
 
 488     $finish = ttTimeHelper::to24HourFormat($finish);
 
 489     if ('00:00' == $finish) $finish = '24:00';
 
 491     if ($start) $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'))
 
 500       $duration = ttTimeHelper::toDuration($start, $finish);
 
 501       if ($duration === false)
 
 503       $uncompleted = ttTimeHelper::getUncompleted($user_id);
 
 504       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
 
 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'))
 
 516   // delete - deletes a record from tt_log table and its associated custom field values.
 
 517   static function delete($id) {
 
 519     $mdb2 = getConnection();
 
 521     // Delete associated files.
 
 522     if ($user->isPluginEnabled('at')) {
 
 523       import('ttFileHelper');
 
 525       $fileHelper = new ttFileHelper($err);
 
 526       if (!$fileHelper->deleteEntityFiles($id, 'time'))
 
 530     $user_id = $user->getUser();
 
 531     $group_id = $user->getGroup();
 
 532     $org_id = $user->org_id;
 
 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'))
 
 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'))
 
 549   // getTimeForDay - gets total time for a user for a specific date.
 
 550   static function getTimeForDay($date) {
 
 552     $mdb2 = getConnection();
 
 554     $user_id = $user->getUser();
 
 555     $group_id = $user->getGroup();
 
 556     $org_id = $user->org_id;
 
 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);
 
 568   // getTimeForWeek - gets total time for a user for a given week.
 
 569   static function getTimeForWeek($date) {
 
 572     $mdb2 = getConnection();
 
 574     $user_id = $user->getUser();
 
 575     $group_id = $user->getGroup();
 
 576     $org_id = $user->org_id;
 
 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);
 
 590   // getTimeForMonth - gets total time for a user for a given month.
 
 591   static function getTimeForMonth($date) {
 
 594     $mdb2 = getConnection();
 
 596     $user_id = $user->getUser();
 
 597     $group_id = $user->getGroup();
 
 598     $org_id = $user->org_id;
 
 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);
 
 612   // getUncompleted - retrieves an uncompleted record for user, if one exists.
 
 613   static function getUncompleted($user_id) {
 
 614     $mdb2 = getConnection();
 
 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()) {
 
 623       if ($val = $res->fetchRow()) {
 
 630   // overlaps - determines if a record overlaps with an already existing record.
 
 633   //   $user_id - user id for whom to determine overlap
 
 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.
 
 641     if ($user->allow_overlap) return false;
 
 643     $mdb2 = getConnection();
 
 645     $start = ttTimeHelper::to24HourFormat($start);
 
 647       $finish = ttTimeHelper::to24HourFormat($finish);
 
 648       if ('00:00' == $finish) $finish = '24:00';
 
 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))";
 
 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))";
 
 664       $sql .= " and id <> $record_id";
 
 666     $res = $mdb2->query($sql);
 
 667     if (!is_a($res, 'PEAR_Error')) {
 
 668       if (!$res->numRows()) {
 
 671       if ($val = $res->fetchRow()) {
 
 678   // getRecord - retrieves a time record identified by its id.
 
 679   static function getRecord($id) {
 
 682     $user_id = $user->getUser();
 
 683     $group_id = $user->getGroup();
 
 684     $org_id = $user->org_id;
 
 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.
 
 690     $mdb2 = getConnection();
 
 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()) {
 
 705       if ($val = $res->fetchRow()) {
 
 712   // getRecordForFileView - retrieves a time record identified by its id for
 
 713   // attachment view operation.
 
 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:
 
 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.
 
 726     // It looks like the best way is to use 2 queries, obtain user_id first, then check rank.
 
 730     $group_id = $user->getGroup();
 
 731     $org_id = $user->org_id;
 
 733     $mdb2 = getConnection();
 
 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;
 
 742     $val = $res->fetchRow();
 
 743     $user_id = $val['user_id'];
 
 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']);
 
 751       return false; // No rights.
 
 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']);
 
 760       return false; // No rights.
 
 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);
 
 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)';
 
 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";
 
 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()) {
 
 780       if ($val = $res->fetchRow()) {
 
 781         $val['can_edit'] = false;
 
 788   // getAllRecords - returns all time records for a certain user.
 
 789   static function getAllRecords($user_id) {
 
 792     $mdb2 = getConnection();
 
 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()) {
 
 809   // getRecords - returns time records for a user for a given date.
 
 810   static function getRecords($date, $includeFiles = false) {
 
 812     $mdb2 = getConnection();
 
 814     $user_id = $user->getUser();
 
 815     $group_id = $user->getGroup();
 
 816     $org_id = $user->org_id;
 
 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.
 
 822     $client_field = null;
 
 823     if ($user->isPluginEnabled('cl'))
 
 824       $client_field = ", c.name as client";
 
 826     $include_cf_1 = $user->isPluginEnabled('cf');
 
 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";
 
 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)";
 
 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)";
 
 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)";
 
 856     $left_joins .= $fileJoin;
 
 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')
 
 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.
 
 885     if (strtotime($val['param_value']) > time())
 
 886       return true; // Expiration date exists but not reached.