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     $time_a = explode(':', $value);
 
 192     return (int)@$time_a[1] + ((int)@$time_a[0]) * 60;
 
 195   // toAbsDuration - converts a number of minutes to format 0:00
 
 196   // even if $minutes is negative.
 
 197   static function toAbsDuration($minutes, $abbreviate = false){
 
 198     $hours = (string)((int)abs($minutes / 60));
 
 199     $mins = (string) round(abs(fmod($minutes, 60)));
 
 200     if (strlen($mins) == 1)
 
 202     if ($abbreviate && $mins == '00')
 
 205     return $hours.':'.$mins;
 
 208   // toDuration - calculates duration between start and finish times in 00:00 format.
 
 209   static function toDuration($start, $finish) {
 
 210     $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
 
 211     if ($duration_minutes <= 0) return false;
 
 213     return ttTimeHelper::toAbsDuration($duration_minutes);
 
 216   // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
 
 217   static function to12HourFormat($value) {
 
 218     if ('24:00' == $value) return '12:00 AM';
 
 220     $time_a = explode(':', $value);
 
 222       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
 
 223     elseif ($time_a[0] == 12)
 
 225     elseif ($time_a[0] == 0)
 
 226       $res = '12:'.$time_a[1].' AM';
 
 232   // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
 
 233   // to a 24-hour time format HH:MM.
 
 234   static function to24HourFormat($value) {
 
 237     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
 
 238     $tmp_val = trim($value);
 
 241     if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
 
 242       // We already have a 24-hour format. Just return it.
 
 246     if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
 
 247       // This is a 24-hour format without a leading zero. Add 0 and return.
 
 251     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
 
 252       // Single digit. Assuming hour number.
 
 253       $res = '0'.$tmp_val.':00';
 
 256     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
 
 257       // Two digit hour number.
 
 258       $res = $tmp_val.':00';
 
 261     if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
 
 262       // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
 
 263       $tmp_arr = str_split($tmp_val);
 
 264       $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
 
 267     if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
 
 268       // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
 
 269       $tmp_arr = str_split($tmp_val);
 
 270       $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
 
 273     // Special handling for midnight.
 
 274     if ($tmp_val == '24:00' || $tmp_val == '2400')
 
 277     // 12 hour AM patterns.
 
 278     if (preg_match('/.(am|AM)$/', $tmp_val)) {
 
 280       // The $value ends in am or AM. Strip it.
 
 281       $tmp_val = rtrim(substr($tmp_val, 0, -2));
 
 283       // Special case to handle 12, 12:MM, and 12MM AM.
 
 284       if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
 
 285         $tmp_val = '00'.substr($tmp_val, 2);
 
 287       // We are ready to convert AM time.
 
 288       if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
 
 289         // We already have a 24-hour format. Just return it.
 
 293       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
 
 294         // This is a 24-hour format without a leading zero. Add 0 and return.
 
 298       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
 
 299         // Single digit. Assuming hour number.
 
 300         $res = '0'.$tmp_val.':00';
 
 303       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
 
 304         // Two digit hour number.
 
 305         $res = $tmp_val.':00';
 
 308       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
 
 309         // Missing colon. Assume the first digit is the hour, the rest is minutes.
 
 310         $tmp_arr = str_split($tmp_val);
 
 311         $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
 
 314       if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
 
 315         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
 
 316         $tmp_arr = str_split($tmp_val);
 
 317         $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
 
 320     } // AM cases handling.
 
 322     // 12 hour PM patterns.
 
 323     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
 
 325       // The $value ends in pm or PM. Strip it.
 
 326       $tmp_val = rtrim(substr($tmp_val, 0, -2));
 
 328       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
 
 329         // Single digit. Assuming hour number.
 
 330         $hour = (string)(12 + (int)$tmp_val);
 
 334       if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
 
 335         // Double digit hour.
 
 336         if ('12' != $tmp_val)
 
 337           $tmp_val = (string)(12 + (int)$tmp_val);
 
 338         $res = $tmp_val.':00';
 
 341       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
 
 342         // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
 
 343         $tmp_arr = str_split($tmp_val);
 
 344         $hour = (string)(12 + (int)$tmp_arr[0]);
 
 345         $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
 
 348       if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
 
 349         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
 
 350         $hour = substr($tmp_val, 0, -2);
 
 351         $min = substr($tmp_val, 2);
 
 353           $hour = (string)(12 + (int)$hour);
 
 354         $res = $hour.':'.$min;
 
 357       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
 
 358         $hour = substr($tmp_val, 0, -3);
 
 359         $min = substr($tmp_val, 2);
 
 360         $hour = (string)(12 + (int)$hour);
 
 361         $res = $hour.':'.$min;
 
 364       if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
 
 365         $hour = substr($tmp_val, 0, -3);
 
 366         $min = substr($tmp_val, 3);
 
 368           $hour = (string)(12 + (int)$hour);
 
 369         $res = $hour.':'.$min;
 
 372     } // PM cases handling.
 
 377   // isValidInterval - checks if finish time is greater than start time.
 
 378   static function isValidInterval($start, $finish) {
 
 379     $start = ttTimeHelper::to24HourFormat($start);
 
 380     $finish = ttTimeHelper::to24HourFormat($finish);
 
 381     if ('00:00' == $finish) $finish = '24:00';
 
 383     $minutesStart = ttTimeHelper::toMinutes($start);
 
 384     $minutesFinish = ttTimeHelper::toMinutes($finish);
 
 385     if ($minutesFinish > $minutesStart)
 
 391   // insert - inserts a time record into tt_log table. Does not deal with custom fields.
 
 392   static function insert($fields)
 
 395     $mdb2 = getConnection();
 
 397     $user_id = (int) $fields['user_id'];
 
 398     $group_id = (int) $fields['group_id'];
 
 399     $org_id = (int) $fields['org_id'];
 
 400     $date = $fields['date'];
 
 401     $start = $fields['start'];
 
 402     $finish = $fields['finish'];
 
 403     $duration = $fields['duration'];
 
 405       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
 
 406       $duration = ttTimeHelper::minutesToDuration($minutes);
 
 408     $client = $fields['client'];
 
 409     $project = $fields['project'];
 
 410     $task = $fields['task'];
 
 411     $invoice = $fields['invoice'];
 
 412     $note = $fields['note'];
 
 413     $billable = $fields['billable'];
 
 414     $paid = $fields['paid'];
 
 415     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
 
 416       $status_f = ', status';
 
 417       $status_v = ', '.$mdb2->quote($fields['status']);
 
 420     $start = ttTimeHelper::to24HourFormat($start);
 
 422       $finish = ttTimeHelper::to24HourFormat($finish);
 
 423       if ('00:00' == $finish) $finish = '24:00';
 
 426     $created_v = ', now(), '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', '.$user->id;
 
 428     if (!$billable) $billable = 0;
 
 429     if (!$paid) $paid = 0;
 
 432       $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) ".
 
 433         "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)";
 
 434       $affected = $mdb2->exec($sql);
 
 435       if (is_a($affected, 'PEAR_Error'))
 
 438       $duration = ttTimeHelper::toDuration($start, $finish);
 
 439       if ($duration === false) $duration = 0;
 
 440       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
 
 442       $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) ".
 
 443         "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)";
 
 444       $affected = $mdb2->exec($sql);
 
 445       if (is_a($affected, 'PEAR_Error'))
 
 449     $id = $mdb2->lastInsertID('tt_log', 'id');
 
 453   // update - updates a record in log table. Does not update its custom fields.
 
 454   static function update($fields)
 
 457     $mdb2 = getConnection();
 
 460     $date = $fields['date'];
 
 461     $user_id = $fields['user_id'];
 
 462     $client = $fields['client'];
 
 463     $project = $fields['project'];
 
 464     $task = $fields['task'];
 
 465     $start = $fields['start'];
 
 466     $finish = $fields['finish'];
 
 467     $duration = $fields['duration'];
 
 469       $minutes = ttTimeHelper::postedDurationToMinutes($duration);
 
 470       $duration = ttTimeHelper::minutesToDuration($minutes);
 
 472     $note = $fields['note'];
 
 475     if ($user->isPluginEnabled('iv')) {
 
 476       $billable_part = $fields['billable'] ? ', billable = 1' : ', billable = 0';
 
 479     if ($user->can('manage_invoices') && $user->isPluginEnabled('ps')) {
 
 480       $paid_part = $fields['paid'] ? ', paid = 1' : ', paid = 0';
 
 482     $modified_part = ', modified = now(), modified_ip = '.$mdb2->quote($_SERVER['REMOTE_ADDR']).', modified_by = '.$user->id;
 
 484     $start = ttTimeHelper::to24HourFormat($start);
 
 485     $finish = ttTimeHelper::to24HourFormat($finish);
 
 486     if ('00:00' == $finish) $finish = '24:00';
 
 488     if ($start) $duration = '';
 
 491       $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
 
 492         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
 
 493       $affected = $mdb2->exec($sql);
 
 494       if (is_a($affected, 'PEAR_Error'))
 
 497       $duration = ttTimeHelper::toDuration($start, $finish);
 
 498       if ($duration === false)
 
 500       $uncompleted = ttTimeHelper::getUncompleted($user_id);
 
 501       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
 
 504       $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
 
 505         "comment = ".$mdb2->quote($note)."$billable_part $paid_part $modified_part, date = '$date' WHERE id = $id";
 
 506       $affected = $mdb2->exec($sql);
 
 507       if (is_a($affected, 'PEAR_Error'))
 
 513   // delete - deletes a record from tt_log table and its associated custom field values.
 
 514   static function delete($id) {
 
 516     $mdb2 = getConnection();
 
 518     // Delete associated files.
 
 519     if ($user->isPluginEnabled('at')) {
 
 520       import('ttFileHelper');
 
 522       $fileHelper = new ttFileHelper($err);
 
 523       if (!$fileHelper->deleteEntityFiles($id, 'time'))
 
 527     $user_id = $user->getUser();
 
 528     $group_id = $user->getGroup();
 
 529     $org_id = $user->org_id;
 
 531     $sql = "update tt_log set status = null".
 
 532       " where id = $id and user_id = $user_id and group_id = $group_id and org_id = $org_id";
 
 533     $affected = $mdb2->exec($sql);
 
 534     if (is_a($affected, 'PEAR_Error'))
 
 537     $sql = "update tt_custom_field_log set status = null".
 
 538       " where log_id = $id and group_id = $group_id and org_id = $org_id";
 
 539     $affected = $mdb2->exec($sql);
 
 540     if (is_a($affected, 'PEAR_Error'))
 
 546   // getTimeForDay - gets total time for a user for a specific date.
 
 547   static function getTimeForDay($date) {
 
 549     $mdb2 = getConnection();
 
 551     $user_id = $user->getUser();
 
 552     $group_id = $user->getGroup();
 
 553     $org_id = $user->org_id;
 
 555     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
 
 556       " where user_id = $user_id and group_id = $group_id and org_id = $org_id and date = '$date' and status = 1";
 
 557     $res = $mdb2->query($sql);
 
 558     if (!is_a($res, 'PEAR_Error')) {
 
 559       $val = $res->fetchRow();
 
 560       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
 
 565   // getTimeForWeek - gets total time for a user for a given week.
 
 566   static function getTimeForWeek($date) {
 
 569     $mdb2 = getConnection();
 
 571     $user_id = $user->getUser();
 
 572     $group_id = $user->getGroup();
 
 573     $org_id = $user->org_id;
 
 575     $period = new Period(INTERVAL_THIS_WEEK, $date);
 
 576     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
 
 577       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
 
 578       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
 
 579     $res = $mdb2->query($sql);
 
 580     if (!is_a($res, 'PEAR_Error')) {
 
 581       $val = $res->fetchRow();
 
 582       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
 
 587   // getTimeForMonth - gets total time for a user for a given month.
 
 588   static function getTimeForMonth($date) {
 
 591     $mdb2 = getConnection();
 
 593     $user_id = $user->getUser();
 
 594     $group_id = $user->getGroup();
 
 595     $org_id = $user->org_id;
 
 597     $period = new Period(INTERVAL_THIS_MONTH, $date);
 
 598     $sql = "select sum(time_to_sec(duration)) as sm from tt_log".
 
 599       " where user_id = $user_id and group_id = $group_id and org_id = $org_id".
 
 600       " and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
 
 601     $res = $mdb2->query($sql);
 
 602     if (!is_a($res, 'PEAR_Error')) {
 
 603       $val = $res->fetchRow();
 
 604       return ttTimeHelper::minutesToDuration($val['sm'] / 60);
 
 609   // getUncompleted - retrieves an uncompleted record for user, if one exists.
 
 610   static function getUncompleted($user_id) {
 
 611     $mdb2 = getConnection();
 
 613     $sql = "select id, start from tt_log  
 
 614       where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
 
 615     $res = $mdb2->query($sql);
 
 616     if (!is_a($res, 'PEAR_Error')) {
 
 617       if (!$res->numRows()) {
 
 620       if ($val = $res->fetchRow()) {
 
 627   // overlaps - determines if a record overlaps with an already existing record.
 
 630   //   $user_id - user id for whom to determine overlap
 
 632   //   $start - new record start time
 
 633   //   $finish - new record finish time, may be null
 
 634   //   $record_id - optional record id we may be editing, excluded from overlap set
 
 635   static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
 
 636     // Do not bother checking if we allow overlaps.
 
 638     if ($user->allow_overlap) return false;
 
 640     $mdb2 = getConnection();
 
 642     $start = ttTimeHelper::to24HourFormat($start);
 
 644       $finish = ttTimeHelper::to24HourFormat($finish);
 
 645       if ('00:00' == $finish) $finish = '24:00';
 
 647     // Handle these 3 overlap situations:
 
 648     // - start time in existing record
 
 649     // - end time in existing record
 
 650     // - record fully encloses existing record
 
 651     $sql = "select id from tt_log  
 
 652       where user_id = $user_id and date = ".$mdb2->quote($date)."
 
 653       and start is not null and duration is not null and status = 1 and (
 
 654       (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
 
 656       $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
 
 657       or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
 
 661       $sql .= " and id <> $record_id";
 
 663     $res = $mdb2->query($sql);
 
 664     if (!is_a($res, 'PEAR_Error')) {
 
 665       if (!$res->numRows()) {
 
 668       if ($val = $res->fetchRow()) {
 
 675   // getRecord - retrieves a time record identified by its id.
 
 676   static function getRecord($id) {
 
 679     $user_id = $user->getUser();
 
 680     $group_id = $user->getGroup();
 
 681     $org_id = $user->org_id;
 
 683     $sql_time_format = "'%k:%i'"; //  24 hour format.
 
 684     if ('%I:%M %p' == $user->time_format)
 
 685       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
 
 687     $mdb2 = getConnection();
 
 689     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
 
 690       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
 
 691       " TIME_FORMAT(l.duration, '%k:%i') as duration,".
 
 692       " p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id,".
 
 693       " l.timesheet_id, l.invoice_id, l.billable, l.approved, l.paid, l.date from tt_log l".
 
 694       " left join tt_projects p on (p.id = l.project_id)".
 
 695       " left join tt_tasks t on (t.id = l.task_id)".
 
 696       " 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";
 
 697     $res = $mdb2->query($sql);
 
 698     if (!is_a($res, 'PEAR_Error')) {
 
 699       if (!$res->numRows()) {
 
 702       if ($val = $res->fetchRow()) {
 
 709   // getRecordForFileView - retrieves a time record identified by its id for
 
 710   // attachment view operation.
 
 712   // It is different from getRecord, as we want users with appropriate rights
 
 713   // to be able to see other users files, without changing "on behalf" user.
 
 714   // For example, viewing reports for all users and their attached files
 
 715   // from report links.
 
 716   static function getRecordForFileView($id) {
 
 717     // There are several possible situations:
 
 719     // Record is ours. Check "view_own_reports" or "view_all_reports".
 
 720     // Record is for the current on behalf user. Check "view_reports" or "view_all_reports".
 
 721     // Record is for someone else. Check "view_reports" or "view_all_reports" and rank.
 
 723     // It looks like the best way is to use 2 queries, obtain user_id first, then check rank.
 
 727     $group_id = $user->getGroup();
 
 728     $org_id = $user->org_id;
 
 730     $mdb2 = getConnection();
 
 732     // Obtain user_id for the time record.
 
 733     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved from tt_log l ".
 
 734       " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1";
 
 735     $res = $mdb2->query($sql);
 
 736     if (is_a($res, 'PEAR_Error')) return false;
 
 737     if (!$res->numRows()) return false;
 
 739     $val = $res->fetchRow();
 
 740     $user_id = $val['user_id'];
 
 742     // If record is ours.
 
 743     if ($user_id == $user->id) {
 
 744       if ($user->can('view_own_reports') || $user->can('view_all_reports')) {
 
 745         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
 
 748       return false; // No rights.
 
 751     // If record belongs to a user we impersonate.
 
 752     if ($user->behalfUser && $user_id == $user->behalfUser->id) {
 
 753       if ($user->can('view_reports') || $user->can('view_all_reports')) {
 
 754         $val['can_edit'] = !($val['timesheet_id'] || $val['invoice_id'] || $val['approved']);
 
 757       return false; // No rights.
 
 760     // Record belongs to someone else. We need to check user rank.
 
 761     if (!($user->can('view_reports') || $user->can('view_all_reports'))) return false;
 
 762     $max_rank = $user->can('view_all_reports') ? MAX_RANK : $user->getMaxRankForGroup($group_id);
 
 764     $left_joins = ' left join tt_users u on (l.user_id = u.id)';
 
 765     $left_joins .= ' left join tt_roles r on (u.role_id = r.id)';
 
 767     $where_part = " where l.id = $id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
 
 768     $where_part .= " and r.rank <= $max_rank";
 
 770     $sql = "select l.id, l.user_id, l.timesheet_id, l.invoice_id, l.approved".
 
 771       " from tt_log l $left_joins $where_part";
 
 772     $res = $mdb2->query($sql);
 
 773     if (!is_a($res, 'PEAR_Error')) {
 
 774       if (!$res->numRows()) {
 
 777       if ($val = $res->fetchRow()) {
 
 778         $val['can_edit'] = false;
 
 785   // getAllRecords - returns all time records for a certain user.
 
 786   static function getAllRecords($user_id) {
 
 789     $mdb2 = getConnection();
 
 791     $sql = "select l.id, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
 
 792       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
 
 793       TIME_FORMAT(l.duration, '%k:%i') as duration,
 
 794       l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.paid, l.status
 
 795       from tt_log l where l.user_id = $user_id order by l.id";
 
 796     $res = $mdb2->query($sql);
 
 797     if (!is_a($res, 'PEAR_Error')) {
 
 798       while ($val = $res->fetchRow()) {
 
 806   // getRecords - returns time records for a user for a given date.
 
 807   static function getRecords($user_id, $date) {
 
 808     // TODO: merge getRecords and getRecordsWithFiles into one function.
 
 810     $mdb2 = getConnection();
 
 812     $group_id = $user->getGroup();
 
 813     $org_id = $user->org_id;
 
 815     $sql_time_format = "'%k:%i'"; //  24 hour format.
 
 816     if ('%I:%M %p' == $user->getTimeFormat())
 
 817       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
 
 819     $client_field = null;
 
 820     if ($user->isPluginEnabled('cl'))
 
 821       $client_field = ", c.name as client";
 
 823     $include_cf_1 = $user->isPluginEnabled('cf');
 
 825       $custom_fields = new CustomFields();
 
 826       $cf_1_type = $custom_fields->fields[0]['type'];
 
 827       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 828         $custom_field = ", cfl.value as cf_1";
 
 829       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 830         $custom_field = ", cfo.value as cf_1";
 
 834     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
 
 835       " left join tt_tasks t on (l.task_id = t.id)";
 
 836     if ($user->isPluginEnabled('cl'))
 
 837       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
 
 839       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 840         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 841       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 842         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 843           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 848     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
 
 849       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
 
 850       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
 
 851       " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field from tt_log l $left_joins".
 
 852       " 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".
 
 853       " order by l.start, l.id";
 
 854     $res = $mdb2->query($sql);
 
 855     if (!is_a($res, 'PEAR_Error')) {
 
 856       while ($val = $res->fetchRow()) {
 
 857         if($val['duration']=='0:00')
 
 866   // getRecordsWithFiles - returns time records for a user for a given date
 
 867   // with information whether they have attached files (has_files property).
 
 868   // A separate fiunction from getRecords because sql here is more complex.
 
 869   static function getRecordsWithFiles($user_id, $date) {
 
 871     $mdb2 = getConnection();
 
 873     $group_id = $user->getGroup();
 
 874     $org_id = $user->org_id;
 
 876     $sql_time_format = "'%k:%i'"; //  24 hour format.
 
 877     if ('%I:%M %p' == $user->getTimeFormat())
 
 878       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
 
 880     $client_field = null;
 
 881     if ($user->isPluginEnabled('cl'))
 
 882       $client_field = ", c.name as client";
 
 884     $include_cf_1 = $user->isPluginEnabled('cf');
 
 886       $custom_fields = new CustomFields();
 
 887       $cf_1_type = $custom_fields->fields[0]['type'];
 
 888       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
 889         $custom_field = ", cfl.value as cf_1";
 
 890       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 891         $custom_field = ", cfo.value as cf_1";
 
 895     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
 
 896       " left join tt_tasks t on (l.task_id = t.id)";
 
 897     if ($user->isPluginEnabled('cl'))
 
 898       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
 
 900       if ($cf_1_type == CustomFields::TYPE_TEXT)
 
 901         $left_joins .= " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)";
 
 902       elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
 903         $left_joins .=  " left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1)".
 
 904           " left join tt_custom_field_options cfo on (cfl.option_id = cfo.id)";
 
 908     $left_joins .= " left join (select distinct entity_id from tt_files".
 
 909       " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
 
 910       " on (l.id = Sub1.entity_id)";
 
 913     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,".
 
 914       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
 
 915       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment,".
 
 916       " if(Sub1.entity_id is null, 0, 1) as has_files,".
 
 917       " l.billable, l.approved, l.timesheet_id, l.invoice_id $client_field $custom_field from tt_log l $left_joins".
 
 918       " 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".
 
 919       " order by l.start, l.id";
 
 920     $res = $mdb2->query($sql);
 
 921     if (!is_a($res, 'PEAR_Error')) {
 
 922       while ($val = $res->fetchRow()) {
 
 923         if($val['duration']=='0:00')
 
 932   // canAdd determines if we can add a record in case there is a limit.
 
 933   static function canAdd() {
 
 934     $mdb2 = getConnection();
 
 935     $sql = "select param_value from tt_site_config where param_name = 'exp_date'";
 
 936     $res = $mdb2->query($sql);
 
 937     $val = $res->fetchRow();
 
 938     if (!$val) return true; // No expiration date.
 
 940     if (strtotime($val['param_value']) > time())
 
 941       return true; // Expiration date exists but not reached.