Refactoring. Moved week_menu config option to plugin config.
[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($start_date, $end_date, $includeFiles = false) {
34     global $user;
35
36     $user_id = $user->getUser();
37     $group_id = $user->getGroup();
38     $org_id = $user->org_id;
39
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.
43
44     $result = array();
45     $mdb2 = getConnection();
46
47     $client_field = null;
48     if ($user->isPluginEnabled('cl'))
49       $client_field = ', c.id as client_id, c.name as client';
50
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';
59       }
60     }
61
62     if ($includeFiles) {
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)";
67     }
68
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) ';
78     }
79     $left_joins .= $fileJoin;
80
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')
93           $val['finish'] = '';
94         $result[] = $val;
95       }
96     } else return false;
97
98     return $result;
99   }
100
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.
105   //
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".
108   //
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.
111   //
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.
115   //
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)
128   //   ),
129   //
130   //   array( // Row 1. This row represents daily comments for a new entry in row above (row 0).
131   //     'row_id' => null,
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)
140   //   ),
141   //
142   //   array( // Row 2.
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)
152   //   ),
153   //   array( // Row 3.
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)
163   //   )
164   // );
165   static function getDataForWeekView($records, $dayHeaders) {
166     global $user;
167     global $i18n;
168
169     $dataArray = array();
170     $includeNotes = $user->isOptionEnabled('week_notes');
171
172     // Construct the first row for a brand new entry.
173     $dataArray[] = array('row_id' => null,'label' => $i18n->get('form.week.new_entry').':'); // Insert row.
174     // Insert empty cells with proper control ids.
175     for ($i = 0; $i < 7; $i++) {
176       $control_id = '0_'. $dayHeaders[$i];
177       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
178     }
179     if ($includeNotes) {
180       // Construct the second row for daily comments for a brand new entry.
181       $dataArray[] = array('row_id' => null,'label' => $i18n->get('label.notes').':'); // Insert row.
182       // Insert empty cells with proper control ids.
183       for ($i = 0; $i < 7; $i++) {
184         $control_id = '1_'. $dayHeaders[$i];
185         $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
186       }
187     }
188
189     // Iterate through records and build $dataArray cell by cell.
190     foreach ($records as $record) {
191       // Create row id without suffix.
192       $row_id_no_suffix = ttWeekViewHelper::makeRowIdentifier($record);
193       // Handle potential multiple records with the same attributes by using a numerical suffix.
194       $suffix = 0;
195       $row_id = $row_id_no_suffix.'_'.$suffix;
196       $day_header = substr($record['date'], 8); // Day number in month.
197       while (ttWeekViewHelper::cellExists($row_id, $day_header, $dataArray)) {
198         $suffix++;
199         $row_id = $row_id_no_suffix.'_'.$suffix;
200       }
201       // Find row.
202       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
203       if ($pos < 0) {
204         // Insert row for durations.
205         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
206         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
207         // Insert empty cells with proper control ids.
208         for ($i = 0; $i < 7; $i++) {
209           $control_id = $pos.'_'. $dayHeaders[$i];
210           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
211         }
212         // Insert row for comments.
213         if ($includeNotes) {
214           $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->get('label.notes').':');
215           $pos++;
216           // Insert empty cells with proper control ids.
217           for ($i = 0; $i < 7; $i++) {
218             $control_id = $pos.'_'. $dayHeaders[$i];
219             $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
220           }
221           $pos--;
222         }
223       }
224       // Insert actual cell data from $record (one cell only).
225       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'duration' => $record['duration']);
226       // Insert existing comment from $record into the comment cell.
227       if ($includeNotes) {
228         $pos++;
229         $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'note' => $record['comment']);
230       }
231     }
232     return $dataArray;
233   }
234
235   // prePopulateFromPastWeeks - is a complementary function to getDataForWeekView.
236   // It builds an "empty" $dataArray with only labels present. Labels are taken from
237   // the most recent active past week, up to 5 weeks back from now.
238   // This is a data entry acceleration feature to help users quickly populate their
239   // regular entry list for a new week, even after a long vacation.
240   static function prePopulateFromPastWeeks($startDate, $dayHeaders) {
241     global $user;
242     global $i18n;
243
244     // First, determine past week start and end dates.
245     $objDate = new DateAndTime(DB_DATEFORMAT, $startDate);
246     $objDate->decDay(7);
247     $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
248     $objDate->incDay(6);
249     $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
250     unset($objDate);
251
252     // Obtain past week(s) records.
253     $records = ttWeekViewHelper::getRecordsForInterval($pastWeekStartDate, $pastWeekEndDate);
254     // Handle potential situation of no records by re-trying for up to 4 more previous weeks (after a long vacation, etc.).
255     if (!$records) {
256       for ($i = 0; $i < 4; $i++) {
257         $objDate = new DateAndTime(DB_DATEFORMAT, $pastWeekStartDate);
258         $objDate->decDay(7);
259         $pastWeekStartDate = $objDate->toString(DB_DATEFORMAT);
260         $objDate->incDay(6);
261         $pastWeekEndDate = $objDate->toString(DB_DATEFORMAT);
262         unset($objDate);
263
264         $records = ttWeekViewHelper::getRecordsForInterval($pastWeekStartDate, $pastWeekEndDate);
265         // Break out of the loop if we found something.
266         if ($records) break;
267       }
268     }
269
270     // Construct the first row for a brand new entry.
271     $dataArray[] = array('row_id' => null,'label' => $i18n->get('form.week.new_entry').':'); // Insert row.
272     // Insert empty cells with proper control ids.
273     for ($i = 0; $i < 7; $i++) {
274       $control_id = '0_'. $dayHeaders[$i];
275       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
276     }
277     $includeNotes = $user->isOptionEnabled('week_notes');
278     if ($includeNotes) {
279       // Construct the second row for daily comments for a brand new entry.
280       $dataArray[] = array('row_id' => null,'label' => $i18n->get('label.notes').':'); // Insert row.
281       // Insert empty cells with proper control ids.
282       for ($i = 0; $i < 7; $i++) {
283         $control_id = '1_'. $dayHeaders[$i];
284         $dataArray[1][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
285       }
286     }
287
288     // Iterate through records and build an "empty" $dataArray.
289     foreach ($records as $record) {
290       // Create row id with 0 suffix. In prepopulated view, we only need one row for similar records.
291       $row_id = ttWeekViewHelper::makeRowIdentifier($record).'_0';
292       // Find row.
293       $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
294       if ($pos < 0) {
295         // Insert row for durations.
296         $dataArray[] = array('row_id' => $row_id,'label' => ttWeekViewHelper::makeRowLabel($record));
297         $pos = ttWeekViewHelper::findRow($row_id, $dataArray);
298         // Insert empty cells with proper control ids.
299         for ($i = 0; $i < 7; $i++) {
300           $control_id = $pos.'_'. $dayHeaders[$i];
301           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
302         }
303         // Insert row for comments.
304         if ($includeNotes) {
305           $dataArray[] = array('row_id' => $row_id.'_notes','label' => $i18n->get('label.notes').':');
306           $pos++;
307           // Insert empty cells with proper control ids.
308           for ($i = 0; $i < 7; $i++) {
309             $control_id = $pos.'_'. $dayHeaders[$i];
310             $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'note' => null);
311           }
312           $pos--;
313         }
314       }
315     }
316
317     return $dataArray;
318   }
319
320   // cellExists is a helper function for getDataForWeekView() to see if a cell with a given label
321   // and a day header already exists.
322   static function cellExists($row_id, $day_header, $dataArray) {
323     foreach($dataArray as $row) {
324       if ($row['row_id'] == $row_id && !empty($row[$day_header]['duration']))
325         return true;
326     }
327     return false;
328   }
329
330   // findRow returns an existing row position in $dataArray, -1 otherwise.
331   static function findRow($row_id, $dataArray) {
332     $pos = 0; // Row position in array.
333     foreach($dataArray as $row) {
334       if ($row['row_id'] == $row_id)
335         return $pos;
336       $pos++; // Increment for search.
337     }
338     return -1; // Row not found.
339   }
340
341   // getDayTotals calculates total durations for each day from the existing data in $dataArray.
342   static function getDayTotals($dataArray, $dayHeaders) {
343     $dayTotals = array();
344
345     // Insert label.
346     global $i18n;
347     $dayTotals['label'] = $i18n->get('label.day_total').':';
348
349     foreach ($dataArray as $row) {
350       foreach($dayHeaders as $dayHeader) {
351         if (array_key_exists($dayHeader, $row)) {
352           $minutes = ttTimeHelper::toMinutes($row[$dayHeader]['duration']);
353           $dayTotals[$dayHeader] += $minutes;
354         }
355       }
356     }
357     // Convert minutes to hh:mm for display.
358     foreach($dayHeaders as $dayHeader) {
359       $dayTotals[$dayHeader] = ttTimeHelper::minutesToDuration($dayTotals[$dayHeader]);
360     }
361     return $dayTotals;
362   }
363
364   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
365   static function getDayHeadersForWeek($start_date) {
366     $dayHeaders = array();
367     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
368     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
369     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
370       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
371     $objDate->incDay();
372     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
373     $objDate->incDay();
374     $dayHeaders[] = $objDate->getDate();
375     $objDate->incDay();
376     $dayHeaders[] = $objDate->getDate();
377     $objDate->incDay();
378     $dayHeaders[] = $objDate->getDate();
379     $objDate->incDay();
380     $dayHeaders[] = $objDate->getDate();
381     $objDate->incDay();
382     $dayHeaders[] = $objDate->getDate();
383     unset($objDate);
384     return $dayHeaders;
385   }
386
387   // getLockedDaysForWeek - builds an array of locked days in week.
388   static function getLockedDaysForWeek($start_date) {
389     global $user;
390     $lockedDays = array();
391     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
392     for ($i = 0; $i < 7; $i++) {
393       $lockedDays[] = $user->isDateLocked($objDate);
394       $objDate->incDay();
395     }
396     unset($objDate);
397     return $lockedDays;
398   }
399
400   // makeRowIdentifier - builds a string identifying a row for a week view from a single record properties.
401   //                     Note that the return value is without a suffix.
402   // For example:
403   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
404   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:7623"
405   static function makeRowIdentifier($record) {
406     global $user;
407     // Start with client.
408     if ($user->isPluginEnabled('cl'))
409       $row_identifier = $record['client_id'] ? 'cl:'.$record['client_id'] : '';
410     // Add billable flag.
411     if (!empty($row_identifier)) $row_identifier .= ',';
412     $row_identifier .= 'bl:'.$record['billable'];
413     // Add project.
414     $row_identifier .= $record['project_id'] ? ',pr:'.$record['project_id'] : '';
415     // Add task.
416     $row_identifier .= $record['task_id'] ? ',ts:'.$record['task_id'] : '';
417     // Add custom field 1.
418     if ($user->isPluginEnabled('cf')) {
419       if ($record['cf_1_id'])
420         $row_identifier .= ',cf_1:'.$record['cf_1_id'];
421       else if ($record['cf_1_value'])
422         $row_identifier .= ',cf_1:'.$record['cf_1_value'];
423     }
424
425     return $row_identifier;
426   }
427
428   // makeRowLabel - builds a human readable label for a row in week view,
429   // which is a combination ot record properties.
430   // Client - Project - Task - Custom field 1.
431   // Note that billable property is not part of the label. Instead,
432   // we identify such records with a different color in week view.
433   static function makeRowLabel($record) {
434     global $user;
435     // Start with client.
436     if ($user->isPluginEnabled('cl'))
437       $label = $record['client'];
438
439     // Add project.
440     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
441     $label .= $record['project'];
442
443     // Add task.
444     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
445     $label .= $record['task'];
446
447     // Add custom field 1.
448     if ($user->isPluginEnabled('cf')) {
449       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
450       $label .= $record['cf_1_value'];
451     }
452
453     return $label;
454   }
455
456   // parseFromWeekViewRow - obtains field value encoded in row identifier.
457   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
458   // requesting a client "cl" should return 546.
459   static function parseFromWeekViewRow($row_id, $field_label) {
460     // Find beginning of label.
461     $pos = strpos($row_id, $field_label);
462     if ($pos === false) return null; // Not found.
463
464     // Strip suffix from row id.
465     $suffixPos = strrpos($row_id, '_');
466     if ($suffixPos)
467       $remaninder = substr($row_id, 0, $suffixPos);
468
469     // Find beginning of value.
470     $posBegin = 1 + strpos($remaninder, ':', $pos);
471     // Find end of value.
472     $posEnd = strpos($remaninder, ',', $posBegin);
473     if ($posEnd === false) $posEnd = strlen($remaninder);
474     // Return value.
475     return substr($remaninder, $posBegin, $posEnd - $posBegin);
476   }
477
478   // dateFromDayHeader calculates date from start date and day header in week view.
479   static function dateFromDayHeader($start_date, $day_header) {
480     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
481     $currentDayHeader = (string) $objDate->getDate(); // It returns an int on first call.
482     if (strlen($currentDayHeader) == 1)               // Which is an implementation detail of DateAndTime class.
483       $currentDayHeader = '0'.$currentDayHeader;      // Add a 0 for single digit day.
484     $i = 1;
485     while ($currentDayHeader != $day_header && $i < 7) {
486       // Iterate through remaining days to find a match.
487       $objDate->incDay();
488       $currentDayHeader = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
489       $i++;
490     }
491     return $objDate->toString(DB_DATEFORMAT);
492   }
493
494   // insertDurationFromWeekView - inserts a new record in log tables from a week view post.
495   static function insertDurationFromWeekView($fields, $custom_fields, $err) {
496     global $i18n;
497     global $user;
498
499     // Determine date for a new entry.
500     $entry_date = ttWeekViewHelper::dateFromDayHeader($fields['start_date'], $fields['day_header']);
501     $objEntryDate = new DateAndTime(DB_DATEFORMAT, $entry_date);
502
503     // Prohibit creating entries in future.
504     if (!$user->future_entries && $fields['browser_today']) {
505       $objBrowserToday = new DateAndTime(DB_DATEFORMAT, $fields['browser_today']);
506       if ($objEntryDate->after($objBrowserToday)) {
507         $err->add($i18n->get('error.future_date'));
508         return false;
509       }
510     }
511
512     // Prepare an array of fields for regular insert function.
513     $fields4insert = array();
514     $fields4insert['user_id'] = $user->getUser();
515     $fields4insert['group_id'] = $user->getGroup();
516     $fields4insert['org_id'] = $user->org_id;
517     $fields4insert['date'] = $entry_date;
518     $fields4insert['duration'] = $fields['duration'];
519     $fields4insert['client'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cl');
520     $fields4insert['billable'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'bl');
521     $fields4insert['project'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'pr');
522     $fields4insert['task'] = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'ts');
523     $fields4insert['note'] = $fields['note'];
524
525     // Try to insert a record.
526     $id = ttTimeHelper::insert($fields4insert);
527     if (!$id) return false; // Something failed.
528
529     // Insert custom field if we have it.
530     $result = true;
531     $cf_1 = ttWeekViewHelper::parseFromWeekViewRow($fields['row_id'], 'cf_1');
532     if ($custom_fields && $cf_1) {
533       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
534         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cf_1);
535       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
536         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cf_1, null);
537     }
538
539     return $result;
540   }
541
542   // modifyDurationFromWeekView - modifies a duration of an existing record from a week view post.
543   static function modifyDurationFromWeekView($fields, $err) {
544     global $i18n;
545     global $user;
546
547     // Possible errors: 1) Overlap if the existing record has start time. 2) Going beyond 24 hour boundary.
548     if (!ttWeekViewHelper::canModify($fields['tt_log_id'], $fields['duration'], $err))
549       return false;
550
551     $mdb2 = getConnection();
552     $duration = $fields['duration'];
553     $tt_log_id = $fields['tt_log_id'];
554     $user_id = $user->getUser();
555     $sql = "update tt_log set duration = '$duration' where id = $tt_log_id and user_id = $user_id";
556     $affected = $mdb2->exec($sql);
557     if (is_a($affected, 'PEAR_Error'))
558       return false;
559
560     return true;
561   }
562
563   // canModify - determines if an  already existing tt_log record
564   // can be modified with a new user-provided duration.
565   static function canModify($tt_log_id, $new_duration, $err) {
566     global $i18n;
567     $mdb2 = getConnection();
568
569     // Determine if we have start time in record, as further checking does not makes sense otherwise.
570     $sql = "select user_id, date, start, duration from tt_log  where id = $tt_log_id";
571     $res = $mdb2->query($sql);
572     if (!is_a($res, 'PEAR_Error')) {
573       if (!$res->numRows()) {
574         $err->add($i18n->get('error.db')); // This is not expected.
575         return false;
576       }
577       $val = $res->fetchRow();
578       $oldDuration = $val['duration'];
579       if (!$val['start'])
580         return true; // There is no start time in the record, therefore safe to modify.
581     }
582
583     // We do have start time.
584     $newMinutes = ttTimeHelper::toMinutes($new_duration);
585     if ($newMinutes < 0) {
586       // Negative durations are not supported when start time is defined.
587       $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
588       return false;
589     }
590
591     // Quick test if new duration is less than already existing.
592     $oldMinutes = ttTimeHelper::toMinutes($oldDuration);
593     if ($newMinutes < $oldMinutes)
594       return true; // Safe to modify.
595
596     // Does the new duration put the record beyond 24:00 boundary?
597     $startMinutes = ttTimeHelper::toMinutes($val['start']);
598     $newEndMinutes = $startMinutes + $newMinutes;
599     if ($newEndMinutes > 1440) {
600       // Invalid duration, as new duration puts the record beyond current day.
601       $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
602       return false;
603     }
604
605     // Does the new duration causes the record to overlap with others?
606     $user_id = $val['user_id'];
607     $date = $val['date'];
608     $startMinutes = ttTimeHelper::toMinutes($val['start']);
609     $start = ttTimeHelper::toAbsDuration($startMinutes);
610     $finish = ttTimeHelper::toAbsDuration($newEndMinutes);
611     if (ttTimeHelper::overlaps($user_id, $date, $start, $finish, $tt_log_id)) {
612       $err->add($i18n->get('error.overlap'));
613       return false;
614     }
615
616     return true; // There are no conflicts, safe to modify.
617   }
618
619   // modifyCommentFromWeekView - modifies a comment in an existing record from a week view post.
620   static function modifyCommentFromWeekView($fields) {
621     global $user;
622
623     $mdb2 = getConnection();
624     $tt_log_id = $fields['tt_log_id'];
625     $comment = $fields['comment'];
626     $user_id = $user->getUser();
627     $sql = "update tt_log set comment = ".$mdb2->quote($fields['comment'])." where id = $tt_log_id and user_id = $user_id";
628     $affected = $mdb2->exec($sql);
629     if (is_a($affected, 'PEAR_Error'))
630       return false;
631
632     return true;
633   }
634 }