Added prepopulation fueature for a week view.
[timetracker.git] / WEB-INF / lib / ttWeekViewHelper.class.php
1 <?php
2 // +----------------------------------------------------------------------+
3 // | Anuko Time Tracker
4 // +----------------------------------------------------------------------+
5 // | Copyright (c) Anuko International Ltd. (https://www.anuko.com)
6 // +----------------------------------------------------------------------+
7 // | LIBERAL FREEWARE LICENSE: This source code document may be used
8 // | by anyone for any purpose, and freely redistributed alone or in
9 // | combination with other software, provided that the license is obeyed.
10 // |
11 // | There are only two ways to violate the license:
12 // |
13 // | 1. To redistribute this code in source form, with the copyright
14 // |    notice or license removed or altered. (Distributing in compiled
15 // |    forms without embedded copyright notices is permitted).
16 // |
17 // | 2. To redistribute modified versions of this code in *any* form
18 // |    that bears insufficient indications that the modifications are
19 // |    not the work of the original author(s).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 // ttWeekViewHelper class groups together functions used in week view.
30 class ttWeekViewHelper {
31
32   // getRecordsForInterval - returns time records for a user for a given interval of dates.
33   static function getRecordsForInterval($user_id, $start_date, $end_date) {
34     global $user;
35     $sql_time_format = "'%k:%i'"; //  24 hour format.
36     if ('%I:%M %p' == $user->time_format)
37       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
38
39     $result = array();
40     $mdb2 = getConnection();
41
42     $client_field = null;
43     if ($user->isPluginEnabled('cl'))
44       $client_field = ', c.id as client_id, c.name as client';
45
46     $custom_field_1 = null;
47     if ($user->isPluginEnabled('cf')) {
48       $custom_fields = new CustomFields($user->team_id);
49       $cf_1_type = $custom_fields->fields[0]['type'];
50       if ($cf_1_type == CustomFields::TYPE_TEXT) {
51         $custom_field_1 = ', cfl.value as cf_1_value';
52       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
53         $custom_field_1 = ', cfo.id as cf_1_id, cfo.value as cf_1_value';
54       }
55     }
56
57     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
58       " left join tt_tasks t on (l.task_id = t.id)";
59     if ($user->isPluginEnabled('cl'))
60       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
61     if ($user->isPluginEnabled('cf')) {
62       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
63         $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) ';
64       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
65         $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) ';
66     }
67
68     $sql = "select l.id as id, l.date as date, TIME_FORMAT(l.start, $sql_time_format) as start,
69       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
70       TIME_FORMAT(l.duration, '%k:%i') as duration, p.id as project_id, p.name as project,
71       t.id as task_id, t.name as task, l.comment, l.billable, l.invoice_id $client_field $custom_field_1
72       from tt_log l
73       $left_joins
74       where l.date >= '$start_date' and l.date <= '$end_date' and l.user_id = $user_id and l.status = 1
75       order by l.date, p.name, t.name, l.start, l.id";
76     $res = $mdb2->query($sql);
77     if (!is_a($res, 'PEAR_Error')) {
78       while ($val = $res->fetchRow()) {
79         if($val['duration']=='0:00')
80           $val['finish'] = '';
81         $result[] = $val;
82       }
83     } else return false;
84
85     return $result;
86   }
87
88   // getDataForWeekView - builds an array to render a table of durations and comments for week view.
89   // In a week view we want one row representing the same attributes to have 7 values for each day of week.
90   // We identify simlar records by a combination of client, billable, project, task, and custom field values.
91   // This will allow us to extend the feature when more custom fields are added.
92   //
93   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:example text"
94   // The above means client 546, billable, project 23456, task 27464, custom field text "example text".
95   //
96   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:7623"
97   // The above means client 546, not billable, project 23456, task 27464, custom field option id 7623.
98   //
99   // Daily comments are implemented as alternate rows following week durations.
100   // For example: row_0 - new entry durations, row_1 - new entry daily comments,
101   //              row_2 - existing entry durations, row_3 - existing entry comments, etc.
102   //
103   // Description of $dataArray format that the function returns.
104   // $dataArray = array(
105   //   array( // Row 0. This is a special, one-off row for a new week entry with empty values.
106   //     'row_id' => null, // Row identifier. Null for a new entry.
107   //     'label' => 'New entry', // Human readable label for the row describing what this time entry is for.
108   //     'day_0' => array('control_id' => '0_day_0', 'tt_log_id' => null, 'duration' => null), // control_id is row_id plus day header for column.
109   //     'day_1' => array('control_id' => '0_day_1', 'tt_log_id' => null, 'duration' => null),
110   //     'day_2' => array('control_id' => '0_day_2', 'tt_log_id' => null, 'duration' => null),
111   //     'day_3' => array('control_id' => '0_day_3', 'tt_log_id' => null, 'duration' => null),
112   //     'day_4' => array('control_id' => '0_day_4', 'tt_log_id' => null, 'duration' => null),
113   //     'day_5' => array('control_id' => '0_day_5', 'tt_log_id' => null, 'duration' => null),
114   //     'day_6' => array('control_id' => '0_day_6', 'tt_log_id' => null, 'duration' => null)
115   //   ),
116   //
117   //   TODO: work in progress re-documenting the array for improved week view. Trying to implement this now.
118   //   array( // Row 1. This row represents daily comments for a new entry in row above (row 0).
119   //     'row_id' => null, // Row identifier. See ttWeekViewHelper::makeRowIdentifier().
120   //     'label' => 'Notes', // Human readable label.
121   //     'day_0' => array('control_id' => '1_day_0', 'tt_log_id' => null, 'note' => null),
122   //     'day_1' => array('control_id' => '1_day_1', 'tt_log_id' => null, 'note' => null),
123   //     'day_2' => array('control_id' => '1_day_2', 'tt_log_id' => null, 'note' => null),
124   //     'day_3' => array('control_id' => '1_day_3', 'tt_log_id' => null, 'note' => null),
125   //     'day_4' => array('control_id' => '1_day_4', 'tt_log_id' => null, 'note' => null),
126   //     'day_5' => array('control_id' => '1_day_5', 'tt_log_id' => null, 'note' => null),
127   //     'day_6' => array('control_id' => '1_day_6', 'tt_log_id' => null, 'note' => null)
128   //   ),
129   //   TODO: work in progress...
130   //
131   //   array( // Row 1.
132   //     'row_id' => 'cl:546,bl:1,pr:23456,ts:27464,cf_1:7623_0', // Row identifier. See ttWeekViewHelper::makeRowIdentifier().
133   //     'label' => 'Anuko - Time Tracker - Coding',              // Human readable label for the row describing what this time entry is for.
134   //     'day_0' => array('control_id' => '1_day_0', 'tt_log_id' => 12345, 'duration' => '00:00'), // control_id is row_id plus day header for column.
135   //     'day_1' => array('control_id' => '1_day_1', 'tt_log_id' => 12346, 'duration' => '01:00'),
136   //     'day_2' => array('control_id' => '1_day_2', 'tt_log_id' => 12347, 'duration' => '02:00'),
137   //     'day_3' => array('control_id' => '1_day_3', 'tt_log_id' => null, 'duration' => null),
138   //     'day_4' => array('control_id' => '1_day_4', 'tt_log_id' => 12348, 'duration' => '04:00'),
139   //     'day_5' => array('control_id' => '1_day_5', 'tt_log_id' => 12349, 'duration' => '04:00'),
140   //     'day_6' => array('control_id' => '1_day_6', 'tt_log_id' => null, 'duration' => null)
141   //   ),
142   //   array( // Row 2.
143   //     'row_id' => 'bl:0_0',
144   //     'label' => '', // In this case the label is empty as we don't have anything to put into it, as we only have billable flag.
145   //     'day_0' => array('control_id' => '2_day_0', 'tt_log_id' => null, 'duration' => null),
146   //     'day_1' => array('control_id' => '2_day_1', 'tt_log_id' => 12350, 'duration' => '01:30'),
147   //     'day_2' => array('control_id' => '2_day_2', 'tt_log_id' => null, 'duration' => null),
148   //     'day_3' => array('control_id' => '2_day_3', 'tt_log_id' => 12351,'duration' => '02:30'),
149   //     'day_4' => array('control_id' => '2_day_4', 'tt_log_id' => 12352, 'duration' => '04:00'),
150   //     'day_5' => array('control_id' => '2_day_5', 'tt_log_id' => null, 'duration' => null),
151   //     'day_6' => array('control_id' => '2_day_6', 'tt_log_id' => null, 'duration' => null)
152   //   )
153   // );
154   static function getDataForWeekView($records, $dayHeaders) {
155     global $i18n;
156
157     $dataArray = array();
158
159     // Construct the first row for a brand new entry.
160     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('form.week.new_entry').':'); // Insert row.
161     // Insert empty cells with proper control ids.
162     for ($i = 0; $i < 7; $i++) {
163       $control_id = '0_'. $dayHeaders[$i];
164       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
165     }
166     // Construct the second row for daily comments for a brand new entry.
167     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('label.notes').':'); // Insert row.
168     // Insert empty cells with proper control ids.
169     for ($i = 0; $i < 7; $i++) {
170       $control_id = '1_'. $dayHeaders[$i];
171       $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
172     }
173
174     // Iterate through records and build $dataArray cell by cell.
175     foreach ($records as $record) {
176       // Create row id without suffix.
177       $row_id_no_suffix = ttWeekViewHelper::makeRowIdentifier($record);
178       // Handle potential multiple records with the same attributes by using a numerical suffix.
179       $suffix = 0;
180       $row_id = $row_id_no_suffix.'_'.$suffix;
181       $day_header = substr($record['date'], 8); // Day number in month.
182       while (ttWeekViewHelper::cellExists($row_id, $day_header, $dataArray)) {
183         $suffix++;
184         $row_id = $row_id_no_suffix.'_'.$suffix;
185       }
186       // Find row.
187       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
188       if ($pos < 0) {
189         // Insert row for durations.
190         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
191         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
192         // Insert empty cells with proper control ids.
193         for ($i = 0; $i < 7; $i++) {
194           $control_id = $pos.'_'. $dayHeaders[$i];
195           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
196         }
197         // Insert row for comments.
198         $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->getKey('label.notes').':');
199         $pos++;
200         // Insert empty cells with proper control ids.
201         for ($i = 0; $i < 7; $i++) {
202           $control_id = $pos.'_'. $dayHeaders[$i];
203           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
204         }
205         $pos--;
206       }
207       // Insert actual cell data from $record (one cell only).
208       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'duration' => $record['duration']);
209       // Insert existing comment from $record into the duration cell.
210       $pos++;
211       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'note' => $record['comment']);
212     }
213     return $dataArray;
214   }
215
216   // prePopulateFromPastWeeks - is a complementary function to getDataForWeekView.
217   // It build an "empty" $dataArray with only labels present. Labels are taken from
218   // the most recent past week, up to 5 weeks back from this week.
219   // This is a data entry acceleration feature to help users quickly populate their
220   // regular entry list for a new week, even after a long vacation.
221   static function prePopulateFromPastWeeks($startDate, $dayHeaders) {
222     global $user;
223     global $i18n;
224
225     // First, determine past week start and end dates.
226     $objDate = new DateAndTime(DB_DATEFORMAT, $startDate);
227     $objDate->decDay(7);
228     $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
229     $objDate->incDay(6);
230     $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
231     unset($objDate);
232
233     // Obtain past week(s) records.
234     $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $pastWeekStartDate, $pastWeekEndDate);
235     // Handle potential situation of no records by re-trying for up to 4 more previous weeks (after a long vacation, etc.).
236     if (!$records) {
237       for ($i = 0; $i < 4; $i++) {
238         $objDate = new DateAndTime(DB_DATEFORMAT, $pastWeekStartDate);
239         $objDate->decDay(7);
240         $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
241         $objDate->incDay(6);
242         $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
243         unset($objDate);
244
245         $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $pastWeekStartDate, $pastWeekEndDate);
246         // Break out of the loop if we found something.
247         if ($records) break;
248       }
249     }
250
251     // TODO: consider refactoring, this block of code is used 2 times.
252     // Construct the first row for a brand new entry.
253     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('form.week.new_entry').':'); // Insert row.
254     // Insert empty cells with proper control ids.
255     for ($i = 0; $i < 7; $i++) {
256       $control_id = '0_'. $dayHeaders[$i];
257       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
258     }
259     // Construct the second row for daily comments for a brand new entry.
260     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('label.notes').':'); // Insert row.
261     // Insert empty cells with proper control ids.
262     for ($i = 0; $i < 7; $i++) {
263       $control_id = '1_'. $dayHeaders[$i];
264       $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
265     }
266
267     // Iterate through records and build an "empty" $dataArray.
268     foreach ($records as $record) {
269       // Create row id with 0 suffix. In prepopulated view, we only need one row for similar records.
270       $row_id = ttWeekViewHelper::makeRowIdentifier($record).'_0';
271       // Find row.
272       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
273       if ($pos < 0) {
274         // Insert row for durations.
275         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
276         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
277         // Insert empty cells with proper control ids.
278         for ($i = 0; $i < 7; $i++) {
279           $control_id = $pos.'_'. $dayHeaders[$i];
280           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
281         }
282         // Insert row for comments.
283         $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->getKey('label.notes').':');
284         $pos++;
285         // Insert empty cells with proper control ids.
286         for ($i = 0; $i < 7; $i++) {
287           $control_id = $pos.'_'. $dayHeaders[$i];
288           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
289         }
290         $pos--;
291       }
292     }
293
294     return $dataArray;
295   }
296
297   // cellExists is a helper function for getDataForWeekView() to see if a cell with a given label
298   // and a day header already exists.
299   static function cellExists($row_id, $day_header, $dataArray) {
300     foreach($dataArray as $row) {
301       if ($row['row_id'] == $row_id && !empty($row[$day_header]['duration']))
302         return true;
303     }
304     return false;
305   }
306
307   // findRow returns an existing row position in $dataArray, -1 otherwise.
308   static function findRow($row_id, $dataArray) {
309     $pos = 0; // Row position in array.
310     foreach($dataArray as $row) {
311       if ($row['row_id'] == $row_id)
312         return $pos;
313       $pos++; // Increment for search.
314     }
315     return -1; // Row not found.
316   }
317
318   // getDayTotals calculates total durations for each day from the existing data in $dataArray.
319   static function getDayTotals($dataArray, $dayHeaders) {
320     $dayTotals = array();
321
322     // Insert label.
323     global $i18n;
324     $dayTotals['label'] = $i18n->getKey('label.day_total').':';
325
326     foreach ($dataArray as $row) {
327       foreach($dayHeaders as $dayHeader) {
328         if (array_key_exists($dayHeader, $row)) {
329           $minutes = ttTimeHelper::toMinutes($row[$dayHeader]['duration']);
330           $dayTotals[$dayHeader] += $minutes;
331         }
332       }
333     }
334     // Convert minutes to hh:mm for display.
335     foreach($dayHeaders as $dayHeader) {
336       $dayTotals[$dayHeader] = ttTimeHelper::toAbsDuration($dayTotals[$dayHeader]);
337     }
338     return $dayTotals;
339   }
340
341   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
342   static function getDayHeadersForWeek($start_date) {
343     $dayHeaders = array();
344     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
345     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
346     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
347       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
348     $objDate->incDay();
349     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
350     $objDate->incDay();
351     $dayHeaders[] = $objDate->getDate();
352     $objDate->incDay();
353     $dayHeaders[] = $objDate->getDate();
354     $objDate->incDay();
355     $dayHeaders[] = $objDate->getDate();
356     $objDate->incDay();
357     $dayHeaders[] = $objDate->getDate();
358     $objDate->incDay();
359     $dayHeaders[] = $objDate->getDate();
360     unset($objDate);
361     return $dayHeaders;
362   }
363
364   // getLockedDaysForWeek - builds an array of locked days in week.
365   static function getLockedDaysForWeek($start_date) {
366     global $user;
367     $lockedDays = array();
368     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
369     for ($i = 0; $i < 7; $i++) {
370       $lockedDays[] = $user->isDateLocked($objDate);
371       $objDate->incDay();
372     }
373     unset($objDate);
374     return $lockedDays;
375   }
376
377   // makeRowIdentifier - builds a string identifying a row for a week view from a single record properties.
378   //                     Note that the return value is without a suffix.
379   // For example:
380   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
381   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:7623"
382   static function makeRowIdentifier($record) {
383     global $user;
384     // Start with client.
385     if ($user->isPluginEnabled('cl'))
386       $row_identifier = $record['client_id'] ? 'cl:'.$record['client_id'] : '';
387     // Add billable flag.
388     if (!empty($row_identifier)) $row_identifier .= ',';
389     $row_identifier .= 'bl:'.$record['billable'];
390     // Add project.
391     $row_identifier .= $record['project_id'] ? ',pr:'.$record['project_id'] : '';
392     // Add task.
393     $row_identifier .= $record['task_id'] ? ',ts:'.$record['task_id'] : '';
394     // Add custom field 1.
395     if ($user->isPluginEnabled('cf')) {
396       if ($record['cf_1_id'])
397         $row_identifier .= ',cf_1:'.$record['cf_1_id'];
398       else if ($record['cf_1_value'])
399         $row_identifier .= ',cf_1:'.$record['cf_1_value'];
400     }
401
402     return $row_identifier;
403   }
404
405   // makeRowLabel - builds a human readable label for a row in week view,
406   // which is a combination ot record properties.
407   // Client - Project - Task - Custom field 1.
408   // Note that billable property is not part of the label. Instead,
409   // we identify such records with a different color in week view.
410   static function makeRowLabel($record) {
411     global $user;
412     // Start with client.
413     if ($user->isPluginEnabled('cl'))
414       $label = $record['client'];
415
416     // Add project.
417     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
418     $label .= $record['project'];
419
420     // Add task.
421     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
422     $label .= $record['task'];
423
424     // Add custom field 1.
425     if ($user->isPluginEnabled('cf')) {
426       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
427       $label .= $record['cf_1_value'];
428     }
429
430     return $label;
431   }
432
433   // parseFromWeekViewRow - obtains field value encoded in row identifier.
434   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
435   // requesting a client "cl" should return 546.
436   static function parseFromWeekViewRow($row_id, $field_label) {
437     // Find beginning of label.
438     $pos = strpos($row_id, $field_label);
439     if ($pos === false) return null; // Not found.
440
441     // Strip suffix from row id.
442     $suffixPos = strrpos($row_id, '_');
443     if ($suffixPos)
444       $remaninder = substr($row_id, 0, $suffixPos);
445
446     // Find beginning of value.
447     $posBegin = 1 + strpos($remaninder, ':', $pos);
448     // Find end of value.
449     $posEnd = strpos($remaninder, ',', $posBegin);
450     if ($posEnd === false) $posEnd = strlen($remaninder);
451     // Return value.
452     return substr($remaninder, $posBegin, $posEnd - $posBegin);
453   }
454
455   // dateFromDayHeader calculates date from start date and day header in week view.
456   static function dateFromDayHeader($start_date, $day_header) {
457     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
458     $currentDayHeader = (string) $objDate->getDate(); // It returns an int on first call.
459     if (strlen($currentDayHeader) == 1)               // Which is an implementation detail of DateAndTime class.
460       $currentDayHeader = '0'.$currentDayHeader;      // Add a 0 for single digit day.
461     $i = 1;
462     while ($currentDayHeader != $day_header && $i < 7) {
463       // Iterate through remaining days to find a match.
464       $objDate->incDay();
465       $currentDayHeader = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
466       $i++;
467     }
468     return $objDate->toString(DB_DATEFORMAT);
469   }
470
471   // insertDurationFromWeekView - inserts a new record in log tables from a week view post.
472   static function insertDurationFromWeekView($fields, $custom_fields, $err) {
473     global $i18n;
474     global $user;
475
476     // Determine date for a new entry.
477     $entry_date = ttWeekViewHelper::dateFromDayHeader($fields['start_date'], $fields['day_header']);
478     $objEntryDate = new DateAndTime(DB_DATEFORMAT, $entry_date);
479
480     // Prohibit creating entries in future.
481     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES) && $fields['browser_today']) {
482       $objBrowserToday = new DateAndTime(DB_DATEFORMAT, $fields['browser_today']);
483       if ($objEntryDate->after($objBrowserToday)) {
484         $err->add($i18n->getKey('error.future_date'));
485         return false;
486       }
487     }
488
489     // Prepare an array of fields for regular insert function.
490     $fields4insert = array();
491     $fields4insert['user_id'] = $user->getActiveUser();
492     $fields4insert['date'] = $entry_date;
493     $fields4insert['duration'] = $fields['duration'];
494     $fields4insert['client'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cl');
495     $fields4insert['billable'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'bl');
496     $fields4insert['project'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'pr');
497     $fields4insert['task'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'ts');
498     $fields4insert['note'] = $fields['note'];
499
500     // Try to insert a record.
501     $id = ttTimeHelper::insert($fields4insert);
502     if (!$id) return false; // Something failed.
503
504     // Insert custom field if we have it.
505     $result = true;
506     $cf_1 = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cf_1');
507     if ($custom_fields && $cf_1) {
508       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
509         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cf_1);
510       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
511         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cf_1, null);
512     }
513
514     return $result;
515   }
516
517   // modifyDurationFromWeekView - modifies a duration of an existing record from a week view post.
518   static function modifyDurationFromWeekView($fields, $err) {
519     global $i18n;
520     global $user;
521
522     // Possible errors: 1) Overlap if the existing record has start time. 2) Going beyond 24 hour boundary.
523     if (!ttWeekViewHelper::canModify($fields['tt_log_id'], $fields['duration'], $err))
524       return false;
525
526     $mdb2 = getConnection();
527     $duration = $fields['duration'];
528     $tt_log_id = $fields['tt_log_id'];
529     $user_id = $user->getActiveUser();
530     $sql = "update tt_log set duration = '$duration' where id = $tt_log_id and user_id = $user_id";
531     $affected = $mdb2->exec($sql);
532     if (is_a($affected, 'PEAR_Error'))
533       return false;
534
535     return true;
536   }
537
538   // canModify - determines if an  already existing tt_log record
539   // can be modified with a new user-provided duration.
540   static function canModify($tt_log_id, $new_duration, $err) {
541     global $i18n;
542     $mdb2 = getConnection();
543
544     // Determine if we have start time in record, as further checking does not makes sense otherwise.
545     $sql = "select user_id, date, start, duration from tt_log  where id = $tt_log_id";
546     $res = $mdb2->query($sql);
547     if (!is_a($res, 'PEAR_Error')) {
548       if (!$res->numRows()) {
549         $err->add($i18n->getKey('error.db')); // This is not expected.
550         return false;
551       }
552       $val = $res->fetchRow();
553       $oldDuration = $val['duration'];
554       if (!$val['start'])
555         return true; // There is no start time in the record, therefore safe to modify.
556     }
557
558     // We do have start time.
559     // Quick test if new duration is less then already existing.
560     $newMinutes = ttTimeHelper::toMinutes($new_duration);
561     $oldMinutes = ttTimeHelper::toMinutes($oldDuration);
562     if ($newMinutes < $oldMinutes)
563       return true; // Safe to modify.
564
565     // Does the new duration put the record beyond 24:00 boundary?
566     $startMinutes = ttTimeHelper::toMinutes($val['start']);
567     $newEndMinutes = $startMinutes + $newMinutes;
568     if ($newEndMinutes > 1440) {
569       // Invalid duration, as new duration puts the record beyond current day.
570       $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
571       return false;
572     }
573
574     // Does the new duration causes the record to overlap with others?
575     $user_id = $val['user_id'];
576     $date = $val['date'];
577     $startMinutes = ttTimeHelper::toMinutes($val['start']);
578     $start = ttTimeHelper::toAbsDuration($startMinutes);
579     $finish = ttTimeHelper::toAbsDuration($newEndMinutes);
580     if (ttTimeHelper::overlaps($user_id, $date, $start, $finish, $tt_log_id)) {
581       $err->add($i18n->getKey('error.overlap'));
582       return false;
583     }
584
585     return true; // There are no conflicts, safe to modify.
586   }
587
588   // modifyCommentFromWeekView - modifies a comment in an existing record from a week view post.
589   static function modifyCommentFromWeekView($fields) {
590     global $user;
591
592     $mdb2 = getConnection();
593     $tt_log_id = $fields['tt_log_id'];
594     $comment = $fields['comment'];
595     $user_id = $user->getActiveUser();
596     $sql = "update tt_log set comment = ".$mdb2->quote($fields['comment'])." where id = $tt_log_id and user_id = $user_id";
597     $affected = $mdb2->exec($sql);
598     if (is_a($affected, 'PEAR_Error'))
599       return false;
600
601     return true;
602   }
603 }