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