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 // ttWeekViewHelper class groups together functions used in week view.
 
  30 class ttWeekViewHelper {
 
  32   // getRecordsForInterval - returns time records for a user for a given interval of dates.
 
  33   static function getRecordsForInterval($start_date, $end_date, $includeFiles = false) {
 
  36     $user_id = $user->getUser();
 
  37     $group_id = $user->getGroup();
 
  38     $org_id = $user->org_id;
 
  40     $sql_time_format = "'%k:%i'"; //  24 hour format.
 
  41     if ('%I:%M %p' == $user->time_format)
 
  42       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
 
  45     $mdb2 = getConnection();
 
  48     if ($user->isPluginEnabled('cl'))
 
  49       $client_field = ', c.id as client_id, c.name as client';
 
  51     $custom_field_1 = null;
 
  52     if ($user->isPluginEnabled('cf')) {
 
  53       $custom_fields = new CustomFields();
 
  54       $cf_1_type = $custom_fields->fields[0]['type'];
 
  55       if ($cf_1_type == CustomFields::TYPE_TEXT) {
 
  56         $custom_field_1 = ', cfl.value as cf_1_value';
 
  57       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
 
  58         $custom_field_1 = ', cfo.id as cf_1_id, cfo.value as cf_1_value';
 
  63       $filePart = ', if(Sub1.entity_id is null, 0, 1) as has_files';
 
  64       $fileJoin =  " left join (select distinct entity_id from tt_files".
 
  65       " where entity_type = 'time' and group_id = $group_id and org_id = $org_id and status = 1) Sub1".
 
  66       " on (l.id = Sub1.entity_id)";
 
  69     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
 
  70       " left join tt_tasks t on (l.task_id = t.id)";
 
  71     if ($user->isPluginEnabled('cl'))
 
  72       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
 
  73     if ($user->isPluginEnabled('cf')) {
 
  74       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
  75         $left_joins .= 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.value = cfo.id) ';
 
  76       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
  77         $left_joins .= 'left join tt_custom_field_log cfl on (l.id = cfl.log_id and cfl.status = 1) left join tt_custom_field_options cfo on (cfl.option_id = cfo.id) ';
 
  79     $left_joins .= $fileJoin;
 
  81     $sql = "select l.id as id, l.date as date, TIME_FORMAT(l.start, $sql_time_format) as start,".
 
  82       " TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,".
 
  83       " TIME_FORMAT(l.duration, '%k:%i') as duration, p.id as project_id, p.name as project,".
 
  84       " t.id as task_id, t.name as task, l.comment, l.billable, l.invoice_id $client_field $custom_field_1 $filePart".
 
  85       " from tt_log l $left_joins".
 
  86       " where l.date >= '$start_date' and l.date <= '$end_date'".
 
  87       " and l.user_id = $user_id and l.group_id = $group_id and l.org_id = $org_id and l.status = 1".
 
  88       " order by l.date, p.name, t.name, l.start, l.id";
 
  89     $res = $mdb2->query($sql);
 
  90     if (!is_a($res, 'PEAR_Error')) {
 
  91       while ($val = $res->fetchRow()) {
 
  92         if($val['duration']=='0:00')
 
 101   // getDataForWeekView - builds an array to render a table of durations and comments for a week view.
 
 102   // In a week view we want one row representing the same attributes to have 7 values for each day of week.
 
 103   // We identify similar records by a combination of client, billable, project, task, and custom field values.
 
 104   // This will allow us to extend the feature when more custom fields are added.
 
 106   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:example text"
 
 107   // The above means client 546, billable, project 23456, task 27464, custom field text "example text".
 
 109   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:7623"
 
 110   // The above means client 546, not billable, project 23456, task 27464, custom field option id 7623.
 
 112   // Daily comments are implemented as alternate rows following week durations (when enabled).
 
 113   // For example: row_0 - new entry durations, row_1 - new entry daily comments,
 
 114   //              row_2 - existing entry durations, row_3 - existing entry comments, etc.
 
 116   // Description of $dataArray format that the function returns.
 
 117   // $dataArray = array(
 
 118   //   array( // Row 0. This is a special, one-off row for a new week entry with empty values.
 
 119   //     'row_id' => null, // Row identifier. Null for a new entry.
 
 120   //     'label' => 'New entry:', // Human readable label for the row describing what this time entry is for.
 
 121   //     'day_0' => array('control_id' => '0_day_0', 'tt_log_id' => null, 'duration' => null), // control_id is row_id plus day header for column.
 
 122   //     'day_1' => array('control_id' => '0_day_1', 'tt_log_id' => null, 'duration' => null),
 
 123   //     'day_2' => array('control_id' => '0_day_2', 'tt_log_id' => null, 'duration' => null),
 
 124   //     'day_3' => array('control_id' => '0_day_3', 'tt_log_id' => null, 'duration' => null),
 
 125   //     'day_4' => array('control_id' => '0_day_4', 'tt_log_id' => null, 'duration' => null),
 
 126   //     'day_5' => array('control_id' => '0_day_5', 'tt_log_id' => null, 'duration' => null),
 
 127   //     'day_6' => array('control_id' => '0_day_6', 'tt_log_id' => null, 'duration' => null)
 
 130   //   array( // Row 1. This row represents daily comments for a new entry in row above (row 0).
 
 132   //     'label' => 'Notes:',
 
 133   //     'day_0' => array('control_id' => '1_day_0', 'tt_log_id' => null, 'note' => null),
 
 134   //     'day_1' => array('control_id' => '1_day_1', 'tt_log_id' => null, 'note' => null),
 
 135   //     'day_2' => array('control_id' => '1_day_2', 'tt_log_id' => null, 'note' => null),
 
 136   //     'day_3' => array('control_id' => '1_day_3', 'tt_log_id' => null, 'note' => null),
 
 137   //     'day_4' => array('control_id' => '1_day_4', 'tt_log_id' => null, 'note' => null),
 
 138   //     'day_5' => array('control_id' => '1_day_5', 'tt_log_id' => null, 'note' => null),
 
 139   //     'day_6' => array('control_id' => '1_day_6', 'tt_log_id' => null, 'note' => null)
 
 143   //     'row_id' => 'cl:546,bl:1,pr:23456,ts:27464,cf_1:7623_0',
 
 144   //     'label' => 'Anuko - Time Tracker - Coding - Option 2',
 
 145   //     'day_0' => array('control_id' => '2_day_0', 'tt_log_id' => 12345, 'duration' => '00:00'),
 
 146   //     'day_1' => array('control_id' => '2_day_1', 'tt_log_id' => 12346, 'duration' => '01:00'),
 
 147   //     'day_2' => array('control_id' => '2_day_2', 'tt_log_id' => 12347, 'duration' => '02:00'),
 
 148   //     'day_3' => array('control_id' => '2_day_3', 'tt_log_id' => null, 'duration' => null),
 
 149   //     'day_4' => array('control_id' => '2_day_4', 'tt_log_id' => 12348, 'duration' => '04:00'),
 
 150   //     'day_5' => array('control_id' => '2_day_5', 'tt_log_id' => 12349, 'duration' => '04:00'),
 
 151   //     'day_6' => array('control_id' => '2_day_6', 'tt_log_id' => null, 'duration' => null)
 
 154   //     'row_id' => 'cl:546,bl:1,pr:23456,ts:27464,cf_1:7623_0_notes',
 
 155   //     'label' => 'Notes:',
 
 156   //     'day_0' => array('control_id' => '3_day_0', 'tt_log_id' => 12345, 'note' => 'Comment one'),
 
 157   //     'day_1' => array('control_id' => '3_day_1', 'tt_log_id' => 12346, 'note' => 'Comment two'),
 
 158   //     'day_2' => array('control_id' => '3_day_2', 'tt_log_id' => 12347, 'note' => 'Comment three'),
 
 159   //     'day_3' => array('control_id' => '3_day_3', 'tt_log_id' => null, 'note' => null),
 
 160   //     'day_4' => array('control_id' => '3_day_4', 'tt_log_id' => 12348, 'note' => 'Comment four'),
 
 161   //     'day_5' => array('control_id' => '3_day_5', 'tt_log_id' => 12349, 'note' => 'Comment five'),
 
 162   //     'day_6' => array('control_id' => '3_day_6', 'tt_log_id' => null, 'note' => null)
 
 165   static function getDataForWeekView($records, $dayHeaders) {
 
 169     $dataArray = array();
 
 171     // Construct the first row for a brand new entry.
 
 172     $dataArray[] = array('row_id' => null,'label' => $i18n->get('form.week.new_entry').':'); // Insert row.
 
 173     // Insert empty cells with proper control ids.
 
 174     for ($i = 0; $i < 7; $i++) {
 
 175       $control_id = '0_'. $dayHeaders[$i];
 
 176       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
 
 178     if ($user->isPluginEnabled('wvns')) {
 
 179       // Construct the second row for daily comments for a brand new entry.
 
 180       $dataArray[] = array('row_id' => null,'label' => $i18n->get('label.notes').':'); // Insert row.
 
 181       // Insert empty cells with proper control ids.
 
 182       for ($i = 0; $i < 7; $i++) {
 
 183         $control_id = '1_'. $dayHeaders[$i];
 
 184         $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
 
 188     // Iterate through records and build $dataArray cell by cell.
 
 189     foreach ($records as $record) {
 
 190       // Create row id without suffix.
 
 191       $row_id_no_suffix = ttWeekViewHelper::makeRowIdentifier($record);
 
 192       // Handle potential multiple records with the same attributes by using a numerical suffix.
 
 194       $row_id = $row_id_no_suffix.'_'.$suffix;
 
 195       $day_header = substr($record['date'], 8); // Day number in month.
 
 196       while (ttWeekViewHelper::cellExists($row_id, $day_header, $dataArray)) {
 
 198         $row_id = $row_id_no_suffix.'_'.$suffix;
 
 201       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
 
 203         // Insert row for durations.
 
 204         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
 
 205         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
 
 206         // Insert empty cells with proper control ids.
 
 207         for ($i = 0; $i < 7; $i++) {
 
 208           $control_id = $pos.'_'. $dayHeaders[$i];
 
 209           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
 
 211         // Insert row for comments.
 
 212         if ($user->isPluginEnabled('wvns')) {
 
 213           $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->get('label.notes').':');
 
 215           // Insert empty cells with proper control ids.
 
 216           for ($i = 0; $i < 7; $i++) {
 
 217             $control_id = $pos.'_'. $dayHeaders[$i];
 
 218             $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
 
 223       // Insert actual cell data from $record (one cell only).
 
 224       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'duration' => $record['duration']);
 
 225       // Insert existing comment from $record into the comment cell.
 
 226       if ($user->isPluginEnabled('wvns')) {
 
 228         $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'note' => $record['comment']);
 
 234   // prePopulateFromPastWeeks - is a complementary function to getDataForWeekView.
 
 235   // It builds an "empty" $dataArray with only labels present. Labels are taken from
 
 236   // the most recent active past week, up to 5 weeks back from now.
 
 237   // This is a data entry acceleration feature to help users quickly populate their
 
 238   // regular entry list for a new week, even after a long vacation.
 
 239   static function prePopulateFromPastWeeks($startDate, $dayHeaders) {
 
 243     // First, determine past week start and end dates.
 
 244     $objDate = new DateAndTime(DB_DATEFORMAT, $startDate);
 
 246     $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
 
 248     $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
 
 251     // Obtain past week(s) records.
 
 252     $records = ttWeekViewHelper::getRecordsForInterval($pastWeekStartDate, $pastWeekEndDate);
 
 253     // Handle potential situation of no records by re-trying for up to 4 more previous weeks (after a long vacation, etc.).
 
 255       for ($i = 0; $i < 4; $i++) {
 
 256         $objDate = new DateAndTime(DB_DATEFORMAT, $pastWeekStartDate);
 
 258         $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
 
 260         $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
 
 263         $records = ttWeekViewHelper::getRecordsForInterval($pastWeekStartDate, $pastWeekEndDate);
 
 264         // Break out of the loop if we found something.
 
 269     // Construct the first row for a brand new entry.
 
 270     $dataArray[] = array('row_id' => null,'label' => $i18n->get('form.week.new_entry').':'); // Insert row.
 
 271     // Insert empty cells with proper control ids.
 
 272     for ($i = 0; $i < 7; $i++) {
 
 273       $control_id = '0_'. $dayHeaders[$i];
 
 274       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
 
 276     if ($user->isPluginEnabled('wvns')) {
 
 277       // Construct the second row for daily comments for a brand new entry.
 
 278       $dataArray[] = array('row_id' => null,'label' => $i18n->get('label.notes').':'); // Insert row.
 
 279       // Insert empty cells with proper control ids.
 
 280       for ($i = 0; $i < 7; $i++) {
 
 281         $control_id = '1_'. $dayHeaders[$i];
 
 282         $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
 
 286     // Iterate through records and build an "empty" $dataArray.
 
 287     foreach ($records as $record) {
 
 288       // Create row id with 0 suffix. In prepopulated view, we only need one row for similar records.
 
 289       $row_id = ttWeekViewHelper::makeRowIdentifier($record).'_0';
 
 291       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
 
 293         // Insert row for durations.
 
 294         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
 
 295         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
 
 296         // Insert empty cells with proper control ids.
 
 297         for ($i = 0; $i < 7; $i++) {
 
 298           $control_id = $pos.'_'. $dayHeaders[$i];
 
 299           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
 
 301         // Insert row for comments.
 
 302         if ($user->isPluginEnabled('wvns')) {
 
 303           $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->get('label.notes').':');
 
 305           // Insert empty cells with proper control ids.
 
 306           for ($i = 0; $i < 7; $i++) {
 
 307             $control_id = $pos.'_'. $dayHeaders[$i];
 
 308             $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
 
 318   // cellExists is a helper function for getDataForWeekView() to see if a cell with a given label
 
 319   // and a day header already exists.
 
 320   static function cellExists($row_id, $day_header, $dataArray) {
 
 321     foreach($dataArray as $row) {
 
 322       if ($row['row_id'] == $row_id && !empty($row[$day_header]['duration']))
 
 328   // findRow returns an existing row position in $dataArray, -1 otherwise.
 
 329   static function findRow($row_id, $dataArray) {
 
 330     $pos = 0; // Row position in array.
 
 331     foreach($dataArray as $row) {
 
 332       if ($row['row_id'] == $row_id)
 
 334       $pos++; // Increment for search.
 
 336     return -1; // Row not found.
 
 339   // getDayTotals calculates total durations for each day from the existing data in $dataArray.
 
 340   static function getDayTotals($dataArray, $dayHeaders) {
 
 341     $dayTotals = array();
 
 345     $dayTotals['label'] = $i18n->get('label.day_total').':';
 
 347     foreach ($dataArray as $row) {
 
 348       foreach($dayHeaders as $dayHeader) {
 
 349         if (array_key_exists($dayHeader, $row)) {
 
 350           $minutes = ttTimeHelper::toMinutes($row[$dayHeader]['duration']);
 
 351           $dayTotals[$dayHeader] += $minutes;
 
 355     // Convert minutes to hh:mm for display.
 
 356     foreach($dayHeaders as $dayHeader) {
 
 357       $dayTotals[$dayHeader] = ttTimeHelper::minutesToDuration($dayTotals[$dayHeader]);
 
 362   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
 
 363   static function getDayHeadersForWeek($start_date) {
 
 364     $dayHeaders = array();
 
 365     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
 
 366     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
 
 367     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
 
 368       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
 
 370     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
 
 372     $dayHeaders[] = $objDate->getDate();
 
 374     $dayHeaders[] = $objDate->getDate();
 
 376     $dayHeaders[] = $objDate->getDate();
 
 378     $dayHeaders[] = $objDate->getDate();
 
 380     $dayHeaders[] = $objDate->getDate();
 
 385   // getLockedDaysForWeek - builds an array of locked days in week.
 
 386   static function getLockedDaysForWeek($start_date) {
 
 388     $lockedDays = array();
 
 389     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
 
 390     for ($i = 0; $i < 7; $i++) {
 
 391       $lockedDays[] = $user->isDateLocked($objDate);
 
 398   // makeRowIdentifier - builds a string identifying a row for a week view from a single record properties.
 
 399   //                     Note that the return value is without a suffix.
 
 401   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
 
 402   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:7623"
 
 403   static function makeRowIdentifier($record) {
 
 405     // Start with client.
 
 406     if ($user->isPluginEnabled('cl'))
 
 407       $row_identifier = $record['client_id'] ? 'cl:'.$record['client_id'] : '';
 
 408     // Add billable flag.
 
 409     if (!empty($row_identifier)) $row_identifier .= ',';
 
 410     $row_identifier .= 'bl:'.$record['billable'];
 
 412     $row_identifier .= $record['project_id'] ? ',pr:'.$record['project_id'] : '';
 
 414     $row_identifier .= $record['task_id'] ? ',ts:'.$record['task_id'] : '';
 
 415     // Add custom field 1.
 
 416     if ($user->isPluginEnabled('cf')) {
 
 417       if ($record['cf_1_id'])
 
 418         $row_identifier .= ',cf_1:'.$record['cf_1_id'];
 
 419       else if ($record['cf_1_value'])
 
 420         $row_identifier .= ',cf_1:'.$record['cf_1_value'];
 
 423     return $row_identifier;
 
 426   // makeRowLabel - builds a human readable label for a row in week view,
 
 427   // which is a combination ot record properties.
 
 428   // Client - Project - Task - Custom field 1.
 
 429   // Note that billable property is not part of the label. Instead,
 
 430   // we identify such records with a different color in week view.
 
 431   static function makeRowLabel($record) {
 
 433     // Start with client.
 
 434     if ($user->isPluginEnabled('cl'))
 
 435       $label = $record['client'];
 
 438     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
 
 439     $label .= $record['project'];
 
 442     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
 
 443     $label .= $record['task'];
 
 445     // Add custom field 1.
 
 446     if ($user->isPluginEnabled('cf')) {
 
 447       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
 
 448       $label .= $record['cf_1_value'];
 
 454   // parseFromWeekViewRow - obtains field value encoded in row identifier.
 
 455   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
 
 456   // requesting a client "cl" should return 546.
 
 457   static function parseFromWeekViewRow($row_id, $field_label) {
 
 458     // Find beginning of label.
 
 459     $pos = strpos($row_id, $field_label);
 
 460     if ($pos === false) return null; // Not found.
 
 462     // Strip suffix from row id.
 
 463     $suffixPos = strrpos($row_id, '_');
 
 465       $remaninder = substr($row_id, 0, $suffixPos);
 
 467     // Find beginning of value.
 
 468     $posBegin = 1 + strpos($remaninder, ':', $pos);
 
 469     // Find end of value.
 
 470     $posEnd = strpos($remaninder, ',', $posBegin);
 
 471     if ($posEnd === false) $posEnd = strlen($remaninder);
 
 473     return substr($remaninder, $posBegin, $posEnd - $posBegin);
 
 476   // dateFromDayHeader calculates date from start date and day header in week view.
 
 477   static function dateFromDayHeader($start_date, $day_header) {
 
 478     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
 
 479     $currentDayHeader = (string) $objDate->getDate(); // It returns an int on first call.
 
 480     if (strlen($currentDayHeader) == 1)               // Which is an implementation detail of DateAndTime class.
 
 481       $currentDayHeader = '0'.$currentDayHeader;      // Add a 0 for single digit day.
 
 483     while ($currentDayHeader != $day_header && $i < 7) {
 
 484       // Iterate through remaining days to find a match.
 
 486       $currentDayHeader = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
 
 489     return $objDate->toString(DB_DATEFORMAT);
 
 492   // insertDurationFromWeekView - inserts a new record in log tables from a week view post.
 
 493   static function insertDurationFromWeekView($fields, $custom_fields, $err) {
 
 497     // Determine date for a new entry.
 
 498     $entry_date = ttWeekViewHelper::dateFromDayHeader($fields['start_date'], $fields['day_header']);
 
 499     $objEntryDate = new DateAndTime(DB_DATEFORMAT, $entry_date);
 
 501     // Prohibit creating entries in future.
 
 502     if (!$user->future_entries && $fields['browser_today']) {
 
 503       $objBrowserToday = new DateAndTime(DB_DATEFORMAT, $fields['browser_today']);
 
 504       if ($objEntryDate->after($objBrowserToday)) {
 
 505         $err->add($i18n->get('error.future_date'));
 
 510     // Prepare an array of fields for regular insert function.
 
 511     $fields4insert = array();
 
 512     $fields4insert['user_id'] = $user->getUser();
 
 513     $fields4insert['group_id'] = $user->getGroup();
 
 514     $fields4insert['org_id'] = $user->org_id;
 
 515     $fields4insert['date'] = $entry_date;
 
 516     $fields4insert['duration'] = $fields['duration'];
 
 517     $fields4insert['client'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cl');
 
 518     $fields4insert['billable'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'bl');
 
 519     $fields4insert['project'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'pr');
 
 520     $fields4insert['task'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'ts');
 
 521     $fields4insert['note'] = $fields['note'];
 
 523     // Try to insert a record.
 
 524     $id = ttTimeHelper::insert($fields4insert);
 
 525     if (!$id) return false; // Something failed.
 
 527     // Insert custom field if we have it.
 
 529     $cf_1 = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cf_1');
 
 530     if ($custom_fields && $cf_1) {
 
 531       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
 
 532         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cf_1);
 
 533       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
 
 534         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cf_1, null);
 
 540   // modifyDurationFromWeekView - modifies a duration of an existing record from a week view post.
 
 541   static function modifyDurationFromWeekView($fields, $err) {
 
 545     // Possible errors: 1) Overlap if the existing record has start time. 2) Going beyond 24 hour boundary.
 
 546     if (!ttWeekViewHelper::canModify($fields['tt_log_id'], $fields['duration'], $err))
 
 549     $mdb2 = getConnection();
 
 550     $duration = $fields['duration'];
 
 551     $tt_log_id = $fields['tt_log_id'];
 
 552     $user_id = $user->getUser();
 
 553     $sql = "update tt_log set duration = '$duration' where id = $tt_log_id and user_id = $user_id";
 
 554     $affected = $mdb2->exec($sql);
 
 555     if (is_a($affected, 'PEAR_Error'))
 
 561   // canModify - determines if an  already existing tt_log record
 
 562   // can be modified with a new user-provided duration.
 
 563   static function canModify($tt_log_id, $new_duration, $err) {
 
 565     $mdb2 = getConnection();
 
 567     // Determine if we have start time in record, as further checking does not makes sense otherwise.
 
 568     $sql = "select user_id, date, start, duration from tt_log  where id = $tt_log_id";
 
 569     $res = $mdb2->query($sql);
 
 570     if (!is_a($res, 'PEAR_Error')) {
 
 571       if (!$res->numRows()) {
 
 572         $err->add($i18n->get('error.db')); // This is not expected.
 
 575       $val = $res->fetchRow();
 
 576       $oldDuration = $val['duration'];
 
 578         return true; // There is no start time in the record, therefore safe to modify.
 
 581     // We do have start time.
 
 582     $newMinutes = ttTimeHelper::toMinutes($new_duration);
 
 583     if ($newMinutes < 0) {
 
 584       // Negative durations are not supported when start time is defined.
 
 585       $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
 
 589     // Quick test if new duration is less than already existing.
 
 590     $oldMinutes = ttTimeHelper::toMinutes($oldDuration);
 
 591     if ($newMinutes < $oldMinutes)
 
 592       return true; // Safe to modify.
 
 594     // Does the new duration put the record beyond 24:00 boundary?
 
 595     $startMinutes = ttTimeHelper::toMinutes($val['start']);
 
 596     $newEndMinutes = $startMinutes + $newMinutes;
 
 597     if ($newEndMinutes > 1440) {
 
 598       // Invalid duration, as new duration puts the record beyond current day.
 
 599       $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
 
 603     // Does the new duration causes the record to overlap with others?
 
 604     $user_id = $val['user_id'];
 
 605     $date = $val['date'];
 
 606     $startMinutes = ttTimeHelper::toMinutes($val['start']);
 
 607     $start = ttTimeHelper::toAbsDuration($startMinutes);
 
 608     $finish = ttTimeHelper::toAbsDuration($newEndMinutes);
 
 609     if (ttTimeHelper::overlaps($user_id, $date, $start, $finish, $tt_log_id)) {
 
 610       $err->add($i18n->get('error.overlap'));
 
 614     return true; // There are no conflicts, safe to modify.
 
 617   // modifyCommentFromWeekView - modifies a comment in an existing record from a week view post.
 
 618   static function modifyCommentFromWeekView($fields) {
 
 621     $mdb2 = getConnection();
 
 622     $tt_log_id = $fields['tt_log_id'];
 
 623     $comment = $fields['comment'];
 
 624     $user_id = $user->getUser();
 
 625     $sql = "update tt_log set comment = ".$mdb2->quote($fields['comment'])." where id = $tt_log_id and user_id = $user_id";
 
 626     $affected = $mdb2->exec($sql);
 
 627     if (is_a($affected, 'PEAR_Error'))