Added a field for note value in week view to apply to new entries.
[timetracker.git] / WEB-INF / lib / ttTimeHelper.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 import('DateAndTime');
30
31 // The ttTimeHelper is a class to help with time-related values.
32 class ttTimeHelper {
33
34   // isWeekend determines if $date falls on weekend.
35   static function isWeekend($date) {
36     $weekDay = date('w', strtotime($date));
37     return ($weekDay == WEEKEND_START_DAY || $weekDay == (WEEKEND_START_DAY + 1) % 7);
38   }
39
40   // isHoliday determines if $date falls on a holiday.
41   static function isHoliday($date) {
42     global $i18n;
43     // $date is expected as string in DB_DATEFORMAT.
44     $month = date('m', strtotime($date));
45     $day = date('d', strtotime($date));
46     if (in_array($month.'/'.$day, $i18n->holidays))
47       return true;
48
49     return false;
50   }
51
52   // isValidTime validates a value as a time string.
53   static function isValidTime($value) {
54     if (strlen($value)==0 || !isset($value)) return false;
55
56     // 24 hour patterns.
57     if ($value == '24:00' || $value == '2400') return true;
58
59     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
60       return true;
61     }
62     if (preg_match('/^([0-1]{0,1}[0-9]|[2][0-4])$/', $value )) { // 0 - 24
63       return true;
64     }
65
66     // 12 hour patterns
67     if (preg_match('/^[1-9]\s?(am|AM|pm|PM)$/', $value)) { // 1 - 9 am
68       return true;
69     }
70     if (preg_match('/^(0[1-9]|1[0-2])\s?(am|AM|pm|PM)$/', $value)) { // 01 - 12 am
71       return true;
72     }
73     if (preg_match('/^[1-9]:?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 1:00 - 9:59 am, 100 - 959 am
74       return true;
75     }
76     if (preg_match('/^(0[1-9]|1[0-2]):?[0-5][0-9]\s?(am|AM|pm|PM)$/', $value)) { // 01:00 - 12:59 am, 0100 - 1259 am
77       return true;
78     }
79
80     return false;
81   }
82
83   // isValidDuration validates a value as a time duration string (in hours and minutes).
84   static function isValidDuration($value) {
85     if (strlen($value)==0 || !isset($value)) return false;
86
87     if ($value == '24:00' || $value == '2400') return true;
88
89     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-3]):?[0-5][0-9]$/', $value )) { // 0:00 - 23:59, 000 - 2359
90       return true;
91     }
92     if (preg_match('/^([0-1]{0,1}[0-9]|2[0-4])h?$/', $value )) { // 0, 1 ... 24
93       return true;
94     }
95
96     global $user;
97     $localizedPattern = '/^([0-1]{0,1}[0-9]|2[0-3])?['.$user->decimal_mark.'][0-9]{1,4}h?$/';
98     if (preg_match($localizedPattern, $value )) { // decimal values like 0.5, 1.25h, ... .. 23.9999h (or with comma)
99       return true;
100     }
101
102     return false;
103   }
104
105   // normalizeDuration - converts a valid time duration string to format 00:00.
106   static function normalizeDuration($value, $leadingZero = true) {
107     $time_value = $value;
108
109     // If we have a decimal format - convert to time format 00:00.
110     global $user;
111     if ($user->decimal_mark == ',')
112       $time_value = str_replace (',', '.', $time_value);
113
114     if((strpos($time_value, '.') !== false) || (strpos($time_value, 'h') !== false)) {
115       $val = floatval($time_value);
116       $mins = round($val * 60);
117       $hours = (string)((int)($mins / 60));
118       $mins = (string)($mins % 60);
119       if ($leadingZero && strlen($hours) == 1)
120         $hours = '0'.$hours;
121       if (strlen($mins) == 1)
122         $mins = '0' . $mins;
123       return $hours.':'.$mins;
124     }
125
126     $time_a = explode(':', $time_value);
127     $res = '';
128
129     // 0-99
130     if ((strlen($time_value) >= 1) && (strlen($time_value) <= 2) && !isset($time_a[1])) {
131       $hours = $time_a[0];
132       if ($leadingZero && strlen($hours) == 1)
133         $hours = '0'.$hours;
134        return $hours.':00';
135     }
136
137     // 000-2359 (2400)
138     if ((strlen($time_value) >= 3) && (strlen($time_value) <= 4) && !isset($time_a[1])) {
139       if (strlen($time_value)==3) $time_value = '0'.$time_value;
140       $hours = substr($time_value,0,2);
141       if ($leadingZero && strlen($hours) == 1)
142         $hours = '0'.$hours;
143       return $hours.':'.substr($time_value,2,2);
144     }
145
146     // 0:00-23:59 (24:00)
147     if ((strlen($time_value) >= 4) && (strlen($time_value) <= 5) && isset($time_a[1])) {
148       $hours = $time_a[0];
149       if ($leadingZero && strlen($hours) == 1)
150         $hours = '0'.$hours;
151       return $hours.':'.$time_a[1];
152     }
153
154     return $res;
155   }
156
157   // toMinutes - converts a time string in format 00:00 to a number of minutes.
158   static function toMinutes($value) {
159     $time_a = explode(':', $value);
160     return (int)@$time_a[1] + ((int)@$time_a[0]) * 60;
161   }
162
163   // toAbsDuration - converts a number of minutes to format 0:00
164   // even if $minutes is negative.
165   static function toAbsDuration($minutes){
166     $hours = (string)((int)abs($minutes / 60));
167     $mins = (string)(abs($minutes % 60));
168     if (strlen($mins) == 1)
169       $mins = '0' . $mins;
170     return $hours.':'.$mins;
171   }
172
173   // toDuration - calculates duration between start and finish times in 00:00 format.
174   static function toDuration($start, $finish) {
175     $duration_minutes = ttTimeHelper::toMinutes($finish) - ttTimeHelper::toMinutes($start);
176     if ($duration_minutes <= 0) return false;
177
178     return ttTimeHelper::toAbsDuration($duration_minutes);
179   }
180
181   // The to12HourFormat function converts a 24-hour time value (such as 15:23) to 12 hour format (03:23 PM).
182   static function to12HourFormat($value) {
183     if ('24:00' == $value) return '12:00 AM';
184
185     $time_a = explode(':', $value);
186     if ($time_a[0] > 12)
187       $res = (string)((int)$time_a[0] - 12).':'.$time_a[1].' PM';
188     elseif ($time_a[0] == 12)
189       $res = $value.' PM';
190     elseif ($time_a[0] == 0)
191       $res = '12:'.$time_a[1].' AM';
192     else
193       $res = $value.' AM';
194     return $res;
195   }
196
197   // The to24HourFormat function attempts to convert a string value (human readable notation of time of day)
198   // to a 24-hour time format HH:MM.
199   static function to24HourFormat($value) {
200     $res = null;
201
202     // Algorithm: use regular expressions to find a matching pattern, starting with most popular patterns first.
203     $tmp_val = trim($value);
204
205     // 24 hour patterns.
206     if (preg_match('/^([01][0-9]|2[0-3]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 23:59
207       // We already have a 24-hour format. Just return it.
208       $res = $tmp_val;
209       return $res;
210     }
211     if (preg_match('/^[0-9]:[0-5][0-9]$/', $tmp_val)) { // 0:00 - 9:59
212       // This is a 24-hour format without a leading zero. Add 0 and return.
213       $res = '0'.$tmp_val;
214       return $res;
215     }
216     if (preg_match('/^[0-9]$/', $tmp_val)) { // 0 - 9
217       // Single digit. Assuming hour number.
218       $res = '0'.$tmp_val.':00';
219       return $res;
220     }
221     if (preg_match('/^([01][0-9]|2[0-4])$/', $tmp_val)) { // 00 - 24
222       // Two digit hour number.
223       $res = $tmp_val.':00';
224       return $res;
225     }
226     if (preg_match('/^[0-9][0-5][0-9]$/', $tmp_val)) { // 000 - 959
227       // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
228       $tmp_arr = str_split($tmp_val);
229       $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
230       return $res;
231     }
232     if (preg_match('/^([01][0-9]|2[0-3])[0-5][0-9]$/', $tmp_val)) { // 0000 - 2359
233       // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
234       $tmp_arr = str_split($tmp_val);
235       $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
236       return $res;
237     }
238     // Special handling for midnight.
239     if ($tmp_val == '24:00' || $tmp_val == '2400')
240       return '24:00';
241
242     // 12 hour AM patterns.
243     if (preg_match('/.(am|AM)$/', $tmp_val)) {
244
245       // The $value ends in am or AM. Strip it.
246       $tmp_val = rtrim(substr($tmp_val, 0, -2));
247
248       // Special case to handle 12, 12:MM, and 12MM AM.
249       if (preg_match('/^12:?([0-5][0-9])?$/', $tmp_val))
250         $tmp_val = '00'.substr($tmp_val, 2);
251
252       // We are ready to convert AM time.
253       if (preg_match('/^(0[0-9]|1[0-1]):[0-5][0-9]$/', $tmp_val)) { // 00:00 - 11:59
254         // We already have a 24-hour format. Just return it.
255         $res = $tmp_val;
256         return $res;
257       }
258       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
259         // This is a 24-hour format without a leading zero. Add 0 and return.
260         $res = '0'.$tmp_val;
261         return $res;
262       }
263       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
264         // Single digit. Assuming hour number.
265         $res = '0'.$tmp_val.':00';
266         return $res;
267       }
268       if (preg_match('/^(0[0-9]|1[0-1])$/', $tmp_val)) { // 00 - 11
269         // Two digit hour number.
270         $res = $tmp_val.':00';
271         return $res;
272       }
273       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
274         // Missing colon. Assume the first digit is the hour, the rest is minutes.
275         $tmp_arr = str_split($tmp_val);
276         $res = '0'.$tmp_arr[0].':'.$tmp_arr[1].$tmp_arr[2];
277         return $res;
278       }
279       if (preg_match('/^(0[0-9]|1[0-1])[0-5][0-9]$/', $tmp_val)) { // 0000 - 1159
280         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
281         $tmp_arr = str_split($tmp_val);
282         $res = $tmp_arr[0].$tmp_arr[1].':'.$tmp_arr[2].$tmp_arr[3];
283         return $res;
284       }
285     } // AM cases handling.
286
287     // 12 hour PM patterns.
288     if (preg_match('/.(pm|PM)$/', $tmp_val)) {
289
290       // The $value ends in pm or PM. Strip it.
291       $tmp_val = rtrim(substr($tmp_val, 0, -2));
292
293       if (preg_match('/^[1-9]$/', $tmp_val)) { // 1 - 9
294         // Single digit. Assuming hour number.
295         $hour = (string)(12 + (int)$tmp_val);
296         $res = $hour.':00';
297         return $res;
298       }
299       if (preg_match('/^((0[1-9])|(1[0-2]))$/', $tmp_val)) { // 01 - 12
300         // Double digit hour.
301         if ('12' != $tmp_val)
302           $tmp_val = (string)(12 + (int)$tmp_val);
303         $res = $tmp_val.':00';
304         return $res;
305       }
306       if (preg_match('/^[1-9][0-5][0-9]$/', $tmp_val)) { // 100 - 959
307         // Missing colon. We'll assume the first digit is the hour, the rest is minutes.
308         $tmp_arr = str_split($tmp_val);
309         $hour = (string)(12 + (int)$tmp_arr[0]);
310         $res = $hour.':'.$tmp_arr[1].$tmp_arr[2];
311         return $res;
312       }
313       if (preg_match('/^(0[1-9]|1[0-2])[0-5][0-9]$/', $tmp_val)) { // 0100 - 1259
314         // Missing colon. We'll assume the first 2 digits are the hour, the rest is minutes.
315         $hour = substr($tmp_val, 0, -2);
316         $min = substr($tmp_val, 2);
317         if ('12' != $hour)
318           $hour = (string)(12 + (int)$hour);
319         $res = $hour.':'.$min;
320         return $res;
321       }
322       if (preg_match('/^[1-9]:[0-5][0-9]$/', $tmp_val)) { // 1:00 - 9:59
323         $hour = substr($tmp_val, 0, -3);
324         $min = substr($tmp_val, 2);
325         $hour = (string)(12 + (int)$hour);
326         $res = $hour.':'.$min;
327         return $res;
328       }
329       if (preg_match('/^(0[1-9]|1[0-2]):[0-5][0-9]$/', $tmp_val)) { // 01:00 - 12:59
330         $hour = substr($tmp_val, 0, -3);
331         $min = substr($tmp_val, 3);
332         if ('12' != $hour)
333           $hour = (string)(12 + (int)$hour);
334         $res = $hour.':'.$min;
335         return $res;
336       }
337     } // PM cases handling.
338
339     return $res;
340   }
341
342   // isValidInterval - checks if finish time is greater than start time.
343   static function isValidInterval($start, $finish) {
344     $start = ttTimeHelper::to24HourFormat($start);
345     $finish = ttTimeHelper::to24HourFormat($finish);
346     if ('00:00' == $finish) $finish = '24:00';
347
348     $minutesStart = ttTimeHelper::toMinutes($start);
349     $minutesFinish = ttTimeHelper::toMinutes($finish);
350     if ($minutesFinish > $minutesStart)
351       return true;
352
353     return false;
354   }
355
356   // insert - inserts a time record into log table. Does not deal with custom fields.
357   static function insert($fields)
358   {
359     $mdb2 = getConnection();
360
361     $timestamp = isset($fields['timestamp']) ? $fields['timestamp'] : '';
362     $user_id = $fields['user_id'];
363     $date = $fields['date'];
364     $start = $fields['start'];
365     $finish = $fields['finish'];
366     $duration = $fields['duration'];
367     $client = $fields['client'];
368     $project = $fields['project'];
369     $task = $fields['task'];
370     $invoice = $fields['invoice'];
371     $note = $fields['note'];
372     $billable = $fields['billable'];
373     if (array_key_exists('status', $fields)) { // Key exists and may be NULL during migration of data.
374       $status_f = ', status';
375       $status_v = ', '.$mdb2->quote($fields['status']);
376     }
377
378     $start = ttTimeHelper::to24HourFormat($start);
379     if ($finish) {
380       $finish = ttTimeHelper::to24HourFormat($finish);
381       if ('00:00' == $finish) $finish = '24:00';
382     }
383     $duration = ttTimeHelper::normalizeDuration($duration);
384
385     if (!$timestamp) {
386       $timestamp = date('YmdHis'); //yyyymmddhhmmss
387       // TODO: this timestamp could be illegal if we hit inside DST switch deadzone, such as '2016-03-13 02:30:00'
388       // Anything between 2am and 3am on DST introduction date will not work if we run on a system with DST on.
389       // We need to address this properly to avoid potential complications.
390     }
391
392     if (!$billable) $billable = 0;
393
394     if ($duration) {
395       $sql = "insert into tt_log (timestamp, user_id, date, duration, client_id, project_id, task_id, invoice_id, comment, billable $status_f) ".
396         "values ('$timestamp', $user_id, ".$mdb2->quote($date).", '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable $status_v)";
397       $affected = $mdb2->exec($sql);
398       if (is_a($affected, 'PEAR_Error'))
399         return false;
400     } else {
401       $duration = ttTimeHelper::toDuration($start, $finish);
402       if ($duration === false) $duration = 0;
403       if (!$duration && ttTimeHelper::getUncompleted($user_id)) return false;
404
405       $sql = "insert into tt_log (timestamp, user_id, date, start, duration, client_id, project_id, task_id, invoice_id, comment, billable $status_f) ".
406         "values ('$timestamp', $user_id, ".$mdb2->quote($date).", '$start', '$duration', ".$mdb2->quote($client).", ".$mdb2->quote($project).", ".$mdb2->quote($task).", ".$mdb2->quote($invoice).", ".$mdb2->quote($note).", $billable $status_v)";
407       $affected = $mdb2->exec($sql);
408       if (is_a($affected, 'PEAR_Error'))
409         return false;
410     }
411
412     $id = $mdb2->lastInsertID('tt_log', 'id');
413     return $id;
414   }
415
416   // update - updates a record in log table. Does not update its custom fields.
417   static function update($fields)
418   {
419     $mdb2 = getConnection();
420
421     $id = $fields['id'];
422     $date = $fields['date'];
423     $user_id = $fields['user_id'];
424     $client = $fields['client'];
425     $project = $fields['project'];
426     $task = $fields['task'];
427     $start = $fields['start'];
428     $finish = $fields['finish'];
429     $duration = $fields['duration'];
430     $note = $fields['note'];
431     $billable = $fields['billable'];
432
433     $start = ttTimeHelper::to24HourFormat($start);
434     $finish = ttTimeHelper::to24HourFormat($finish);
435     if ('00:00' == $finish) $finish = '24:00';
436     $duration = ttTimeHelper::normalizeDuration($duration);
437
438     if (!$billable) $billable = 0;
439     if ($start) $duration = '';
440
441     if ($duration) {
442       $sql = "UPDATE tt_log set start = NULL, duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
443         "comment = ".$mdb2->quote($note).", billable = $billable, date = '$date' WHERE id = $id";
444       $affected = $mdb2->exec($sql);
445       if (is_a($affected, 'PEAR_Error'))
446         return false;
447     } else {
448       $duration = ttTimeHelper::toDuration($start, $finish);
449       if ($duration === false)
450         $duration = 0;
451       $uncompleted = ttTimeHelper::getUncompleted($user_id);
452       if (!$duration && $uncompleted && ($uncompleted['id'] != $id))
453         return false;
454
455       $sql = "UPDATE tt_log SET start = '$start', duration = '$duration', client_id = ".$mdb2->quote($client).", project_id = ".$mdb2->quote($project).", task_id = ".$mdb2->quote($task).", ".
456         "comment = ".$mdb2->quote($note).", billable = $billable, date = '$date' WHERE id = $id";
457       $affected = $mdb2->exec($sql);
458       if (is_a($affected, 'PEAR_Error'))
459         return false;
460     }
461     return true;
462   }
463
464   // delete - deletes a record from tt_log table and its associated custom field values.
465   static function delete($id, $user_id) {
466     $mdb2 = getConnection();
467
468     $sql = "update tt_log set status = NULL where id = $id and user_id = $user_id";
469     $affected = $mdb2->exec($sql);
470     if (is_a($affected, 'PEAR_Error'))
471       return false;
472
473     $sql = "update tt_custom_field_log set status = NULL where log_id = $id";
474     $affected = $mdb2->exec($sql);
475     if (is_a($affected, 'PEAR_Error'))
476       return false;
477
478     return true;
479   }
480
481   // getTimeForDay - gets total time for a user for a specific date.
482   static function getTimeForDay($user_id, $date) {
483     $mdb2 = getConnection();
484
485     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date = '$date' and status = 1";
486     $res = $mdb2->query($sql);
487     if (!is_a($res, 'PEAR_Error')) {
488       $val = $res->fetchRow();
489       return sec_to_time_fmt_hm($val['sm']);
490     }
491     return false;
492   }
493
494   // getTimeForWeek - gets total time for a user for a given week.
495   static function getTimeForWeek($user_id, $date) {
496     import('Period');
497     $mdb2 = getConnection();
498
499     $period = new Period(INTERVAL_THIS_WEEK, $date);
500     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
501     $res = $mdb2->query($sql);
502     if (!is_a($res, 'PEAR_Error')) {
503       $val = $res->fetchRow();
504       return sec_to_time_fmt_hm($val['sm']);
505     }
506     return 0;
507   }
508
509   // getTimeForMonth - gets total time for a user for a given month.
510   static function getTimeForMonth($user_id, $date){
511     import('Period');
512     $mdb2 = getConnection();
513
514     $period = new Period(INTERVAL_THIS_MONTH, $date);
515     $sql = "select sum(time_to_sec(duration)) as sm from tt_log where user_id = $user_id and date >= '".$period->getStartDate(DB_DATEFORMAT)."' and date <= '".$period->getEndDate(DB_DATEFORMAT)."' and status = 1";
516     $res = $mdb2->query($sql);
517     if (!is_a($res, 'PEAR_Error')) {
518       $val = $res->fetchRow();
519       return sec_to_time_fmt_hm($val['sm']);
520     }
521     return 0;
522   }
523
524   // getUncompleted - retrieves an uncompleted record for user, if one exists.
525   static function getUncompleted($user_id) {
526     $mdb2 = getConnection();
527
528     $sql = "select id, start from tt_log  
529       where user_id = $user_id and start is not null and time_to_sec(duration) = 0 and status = 1";
530     $res = $mdb2->query($sql);
531     if (!is_a($res, 'PEAR_Error')) {
532       if (!$res->numRows()) {
533         return false;
534       }
535       if ($val = $res->fetchRow()) {
536         return $val;
537       }
538     }
539     return false;
540   }
541
542   // overlaps - determines if a record overlaps with an already existing record.
543   //
544   // Parameters:
545   //   $user_id - user id for whom to determine overlap
546   //   $date - date
547   //   $start - new record start time
548   //   $finish - new record finish time, may be null
549   //   $record_id - optional record id we may be editing, excluded from overlap set
550   static function overlaps($user_id, $date, $start, $finish, $record_id = null) {
551     // Do not bother checking if we allow overlaps.
552     if (defined('ALLOW_OVERLAP') && ALLOW_OVERLAP == true)
553       return false;
554
555     $mdb2 = getConnection();
556
557     $start = ttTimeHelper::to24HourFormat($start);
558     if ($finish) {
559       $finish = ttTimeHelper::to24HourFormat($finish);
560       if ('00:00' == $finish) $finish = '24:00';
561     }
562     // Handle these 3 overlap situations:
563     // - start time in existing record
564     // - end time in existing record
565     // - record fully encloses existing record
566     $sql = "select id from tt_log  
567       where user_id = $user_id and date = ".$mdb2->quote($date)."
568       and start is not null and duration is not null and status = 1 and (
569       (cast(".$mdb2->quote($start)." as time) >= start and cast(".$mdb2->quote($start)." as time) < addtime(start, duration))";
570     if ($finish) {
571       $sql .= " or (cast(".$mdb2->quote($finish)." as time) <= addtime(start, duration) and cast(".$mdb2->quote($finish)." as time) > start)
572       or (cast(".$mdb2->quote($start)." as time) < start and cast(".$mdb2->quote($finish)." as time) > addtime(start, duration))";
573     }
574     $sql .= ")";
575     if ($record_id) {
576       $sql .= " and id <> $record_id";
577     }
578     $res = $mdb2->query($sql);
579     if (!is_a($res, 'PEAR_Error')) {
580       if (!$res->numRows()) {
581         return false;
582       }
583       if ($val = $res->fetchRow()) {
584         return $val;
585       }
586     }
587     return false;
588   }
589
590   // wvCanModify (weekViewCanModify) - determines if an  already existing tt_log record
591   // can be modified with a new user-provided duration.
592   static function wvCanModify($tt_log_id, $new_duration, $err) {
593     global $i18n;
594     $mdb2 = getConnection();
595
596     // Determine if we have start time in record, as further checking does not makes sense otherwise.
597     $sql = "select user_id, date, start, duration from tt_log  where id = $tt_log_id";
598     $res = $mdb2->query($sql);
599     if (!is_a($res, 'PEAR_Error')) {
600       if (!$res->numRows()) {
601         $err->add($i18n->getKey('error.db')); // This is not expected.
602         return false;
603       }
604       $val = $res->fetchRow();
605       $oldDuration = $val['duration'];
606       if (!$val['start'])
607         return true; // There is no start time in the record, therefore safe to modify.
608     }
609
610     // We do have start time.
611     // Quick test if new duration is less then already existing.
612     $newMinutes = ttTimeHelper::toMinutes($new_duration);
613     $oldMinutes = ttTimeHelper::toMinutes($oldDuration);
614     if ($newMinutes < $oldMinutes)
615       return true; // Safe to modify.
616
617     // Does the new duration put the record beyond 24:00 boundary?
618     $startMinutes = ttTimeHelper::toMinutes($val['start']);
619     $newEndMinutes = $startMinutes + $newMinutes;
620     if ($newEndMinutes > 1440) {
621       // Invalid duration, as new duration puts the record beyond current day.
622       $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
623       return false;
624     }
625
626     // Does the new duration causes the record to overlap with others?
627     $user_id = $val['user_id'];
628     $date = $val['date'];
629     $startMinutes = ttTimeHelper::toMinutes($val['start']);
630     $start = ttTimeHelper::toAbsDuration($startMinutes);
631     $finish = ttTimeHelper::toAbsDuration($newEndMinutes);
632     if (ttTimeHelper::overlaps($user_id, $date, $start, $finish, $tt_log_id)) {
633       $err->add($i18n->getKey('error.overlap'));
634       return false;
635     }
636
637     return true; // There are no conflicts, safe to modify.
638   }
639
640   // getRecord - retrieves a time record identified by its id.
641   static function getRecord($id, $user_id) {
642     global $user;
643     $sql_time_format = "'%k:%i'"; //  24 hour format.
644     if ('%I:%M %p' == $user->time_format)
645       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
646
647     $mdb2 = getConnection();
648
649     $sql = "select l.id as id, l.timestamp as timestamp, TIME_FORMAT(l.start, $sql_time_format) as start,
650       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
651       TIME_FORMAT(l.duration, '%k:%i') as duration,
652       p.name as project_name, t.name as task_name, l.comment, l.client_id, l.project_id, l.task_id, l.invoice_id, l.billable, l.date
653       from tt_log l
654       left join tt_projects p on (p.id = l.project_id)
655       left join tt_tasks t on (t.id = l.task_id)
656       where l.id = $id and l.user_id = $user_id and l.status = 1";
657     $res = $mdb2->query($sql);
658     if (!is_a($res, 'PEAR_Error')) {
659       if (!$res->numRows()) {
660         return false;
661       }
662       if ($val = $res->fetchRow()) {
663         return $val;
664       }
665     }
666     return false;
667   }
668
669   // getAllRecords - returns all time records for a certain user.
670   static function getAllRecords($user_id) {
671     $result = array();
672
673     $mdb2 = getConnection();
674
675     $sql = "select l.id, l.timestamp, l.user_id, l.date, TIME_FORMAT(l.start, '%k:%i') as start,
676       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), '%k:%i') as finish,
677       TIME_FORMAT(l.duration, '%k:%i') as duration,
678       l.client_id, l.project_id, l.task_id, l.invoice_id, l.comment, l.billable, l.status
679       from tt_log l where l.user_id = $user_id order by l.id";
680     $res = $mdb2->query($sql);
681     if (!is_a($res, 'PEAR_Error')) {
682       while ($val = $res->fetchRow()) {
683         $result[] = $val;
684       }
685     } else return false;
686
687     return $result;
688   }
689
690   // getRecords - returns time records for a user for a given date.
691   static function getRecords($user_id, $date) {
692     global $user;
693     $sql_time_format = "'%k:%i'"; //  24 hour format.
694     if ('%I:%M %p' == $user->time_format)
695       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
696
697     $result = array();
698     $mdb2 = getConnection();
699
700     $client_field = null;
701     if ($user->isPluginEnabled('cl'))
702       $client_field = ", c.name as client";
703
704     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
705       " left join tt_tasks t on (l.task_id = t.id)";
706     if ($user->isPluginEnabled('cl'))
707       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
708
709     $sql = "select l.id as id, TIME_FORMAT(l.start, $sql_time_format) as start,
710       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
711       TIME_FORMAT(l.duration, '%k:%i') as duration, p.name as project, t.name as task, l.comment, l.billable, l.invoice_id $client_field
712       from tt_log l
713       $left_joins
714       where l.date = '$date' and l.user_id = $user_id and l.status = 1
715       order by l.start, l.id";
716     $res = $mdb2->query($sql);
717     if (!is_a($res, 'PEAR_Error')) {
718       while ($val = $res->fetchRow()) {
719         if($val['duration']=='0:00')
720           $val['finish'] = '';
721         $result[] = $val;
722       }
723     } else return false;
724
725     return $result;
726   }
727
728   // getRecordsForInterval - returns time records for a user for a given interval of dates.
729   static function getRecordsForInterval($user_id, $start_date, $end_date) {
730     global $user;
731     $sql_time_format = "'%k:%i'"; //  24 hour format.
732     if ('%I:%M %p' == $user->time_format)
733       $sql_time_format = "'%h:%i %p'"; // 12 hour format for MySQL TIME_FORMAT function.
734
735     $result = array();
736     $mdb2 = getConnection();
737
738     $client_field = null;
739     if ($user->isPluginEnabled('cl'))
740       $client_field = ', c.id as client_id, c.name as client';
741
742     $custom_field_1 = null;
743     if ($user->isPluginEnabled('cf')) {
744       $custom_fields = new CustomFields($user->team_id);
745       $cf_1_type = $custom_fields->fields[0]['type'];
746       if ($cf_1_type == CustomFields::TYPE_TEXT) {
747         $custom_field_1 = ', cfl.value as cf_1_value';
748       } elseif ($cf_1_type == CustomFields::TYPE_DROPDOWN) {
749         $custom_field_1 = ', cfo.id as cf_1_id, cfo.value as cf_1_value';
750       }
751     }
752
753     $left_joins = " left join tt_projects p on (l.project_id = p.id)".
754       " left join tt_tasks t on (l.task_id = t.id)";
755     if ($user->isPluginEnabled('cl'))
756       $left_joins .= " left join tt_clients c on (l.client_id = c.id)";
757     if ($user->isPluginEnabled('cf')) {
758       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
759         $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) ';
760       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
761         $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) ';
762     }
763
764     $sql = "select l.id as id, l.date as date, TIME_FORMAT(l.start, $sql_time_format) as start,
765       TIME_FORMAT(sec_to_time(time_to_sec(l.start) + time_to_sec(l.duration)), $sql_time_format) as finish,
766       TIME_FORMAT(l.duration, '%k:%i') as duration, p.id as project_id, p.name as project,
767       t.id as task_id, t.name as task, l.comment, l.billable, l.invoice_id $client_field $custom_field_1
768       from tt_log l
769       $left_joins
770       where l.date >= '$start_date' and l.date <= '$end_date' and l.user_id = $user_id and l.status = 1
771       order by p.name, t.name, l.date, l.start, l.id";
772     $res = $mdb2->query($sql);
773     if (!is_a($res, 'PEAR_Error')) {
774       while ($val = $res->fetchRow()) {
775         if($val['duration']=='0:00')
776           $val['finish'] = '';
777         $result[] = $val;
778       }
779     } else return false;
780
781     return $result;
782   }
783
784   // getDataForWeekView - builds an array to render a table of durations for week view.
785   // In a week view we want one row representing the same attributes to have 7 values for each day of week.
786   // We identify simlar records by a combination of client, billable, project, task, and custom field values.
787   // This will allow us to extend the feature when more custom fields are added.
788   //
789   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:example text"
790   // The above means client 546, billable, project 23456, task 27464, custom field text "example text".
791   //
792   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:7623"
793   // The above means client 546, not billable, project 23456, task 27464, custom field option id 7623.
794   //
795   // Description of $dataArray format that the function returns.
796   // $dataArray = array(
797   //   array( // Row 0. This is a special, one-off row for a new week entry with empty values.
798   //     'row_id' => null', // Row identifier. Null for a new entry.
799   //     'label' => 'New entry', // Human readable label for the row describing what this time entry is for.
800   //     'day_0' => array('control_id' => '0_day_0', 'tt_log_id' => null, 'duration' => null), // control_id is row_id plus day header for column.
801   //     'day_1' => array('control_id' => '0_day_1', 'tt_log_id' => null, 'duration' => null),
802   //     'day_2' => array('control_id' => '0_day_2', 'tt_log_id' => null, 'duration' => null),
803   //     'day_3' => array('control_id' => '0_day_3', 'tt_log_id' => null, 'duration' => null),
804   //     'day_4' => array('control_id' => '0_day_4', 'tt_log_id' => null, 'duration' => null),
805   //     'day_5' => array('control_id' => '0_day_5', 'tt_log_id' => null, 'duration' => null),
806   //     'day_6' => array('control_id' => '0_day_6', 'tt_log_id' => null, 'duration' => null)
807   //   ),
808   //   array( // Row 1.
809   //     'row_id' => 'cl:546,bl:1,pr:23456,ts:27464,cf_1:7623_0', // Row identifier. See ttTimeHelper::makeRecordIdentifier().
810   //     'label' => 'Anuko - Time Tracker - Coding',              // Human readable label for the row describing what this time entry is for.
811   //     '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.
812   //     'day_1' => array('control_id' => '1_day_1', 'tt_log_id' => 12346, 'duration' => '01:00'),
813   //     'day_2' => array('control_id' => '1_day_2', 'tt_log_id' => 12347, 'duration' => '02:00'),
814   //     'day_3' => array('control_id' => '1_day_3', 'tt_log_id' => null, 'duration' => null),
815   //     'day_4' => array('control_id' => '1_day_4', 'tt_log_id' => 12348, 'duration' => '04:00'),
816   //     'day_5' => array('control_id' => '1_day_5', 'tt_log_id' => 12349, 'duration' => '04:00'),
817   //     'day_6' => array('control_id' => '1_day_6', 'tt_log_id' => null, 'duration' => null)
818   //   ),
819   //   array( // Row 2.
820   //     'row_id' => 'bl:0_0',
821   //     'label' => '', // In this case the label is empty as we don't have anything to put into it, as we only have billable flag.
822   //     'day_0' => array('control_id' => '2_day_0', 'tt_log_id' => null, 'duration' => null),
823   //     'day_1' => array('control_id' => '2_day_1', 'tt_log_id' => 12350, 'duration' => '01:30'),
824   //     'day_2' => array('control_id' => '2_day_2', 'tt_log_id' => null, 'duration' => null),
825   //     'day_3' => array('control_id' => '2_day_3', 'tt_log_id' => 12351,'duration' => '02:30'),
826   //     'day_4' => array('control_id' => '2_day_4', 'tt_log_id' => 12352, 'duration' => '04:00'),
827   //     'day_5' => array('control_id' => '2_day_5', 'tt_log_id' => null, 'duration' => null),
828   //     'day_6' => array('control_id' => '2_day_6', 'tt_log_id' => null, 'duration' => null)
829   //   )
830   // );
831   static function getDataForWeekView($user_id, $start_date, $end_date, $dayHeaders) {
832     global $i18n;
833
834     // Start by obtaining all records in interval.
835     $records = ttTimeHelper::getRecordsForInterval($user_id, $start_date, $end_date);
836
837     $dataArray = array();
838
839     // Construct the first row for a brand new entry.
840     $dataArray[] = array('row_id' => null,'label' => $i18n->getKey('form.week.new_entry')); // Insert row.
841     // Insert empty cells with proper control ids.
842     for ($i = 0; $i < 7; $i++) {
843       $control_id = '0_'. $dayHeaders[$i];
844       $dataArray[0][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
845     }
846
847     // Iterate through records and build $dataArray cell by cell.
848     foreach ($records as $record) {
849       // Create record id without suffix.
850       $record_id_no_suffix = ttTimeHelper::makeRecordIdentifier($record);
851       // Handle potential multiple records with the same attributes by using a numerical suffix.
852       $suffix = 0;
853       $record_id = $record_id_no_suffix.'_'.$suffix;
854       $day_header = substr($record['date'], 8); // Day number in month.
855       while (ttTimeHelper::cellExists($record_id, $day_header, $dataArray)) {
856         $suffix++;
857         $record_id = $record_id_no_suffix.'_'.$suffix;
858       }
859       // Find row.
860       $pos = ttTimeHelper::findRow($record_id, $dataArray);
861       if ($pos < 0) {
862         $dataArray[] = array('row_id' => $record_id,'label' => ttTimeHelper::makeRecordLabel($record)); // Insert row.
863         $pos = ttTimeHelper::findRow($record_id, $dataArray);
864         // Insert empty cells with proper control ids.
865         for ($i = 0; $i < 7; $i++) {
866           $control_id = $pos.'_'. $dayHeaders[$i];
867           $dataArray[$pos][$dayHeaders[$i]] = array('control_id' => $control_id, 'tt_log_id' => null,'duration' => null);
868         }
869       }
870       // Insert actual cell data from $record (one cell only).
871       $dataArray[$pos][$day_header] = array('control_id' => $pos.'_'. $day_header, 'tt_log_id' => $record['id'],'duration' => $record['duration']);
872     }
873     return $dataArray;
874   }
875
876   // cellExists is a helper function for getDataForWeekView() to see if a cell with a given label
877   // and a day header already exists.
878   static function cellExists($row_id, $day_header, $dataArray) {
879     foreach($dataArray as $row) {
880       if ($row['row_id'] == $row_id && !empty($row[$day_header]['duration']))
881         return true;
882     }
883     return false;
884   }
885
886   // findRow returns an existing row position in $dataArray, -1 otherwise.
887   static function findRow($row_id, $dataArray) {
888     $pos = 0; // Row position in array.
889     foreach($dataArray as $row) {
890       if ($row['row_id'] == $row_id)
891         return $pos;
892       $pos++; // Increment for search.
893     }
894     return -1; // Row not found.
895   }
896
897   // makeRecordIdentifier - builds a string identifying a record for a grouped display (such as a week view).
898   // For example:
899   // "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
900   // "cl:546,bl:1,pr:23456,ts:27464,cf_1:7623"
901   // See comment for getGroupedRecordsForInterval.
902   static function makeRecordIdentifier($record) {
903     global $user;
904     // Start with client.
905     if ($user->isPluginEnabled('cl'))
906       $record_identifier = $record['client_id'] ? 'cl:'.$record['client_id'] : '';
907     // Add billable flag.
908     if (!empty($record_identifier)) $record_identifier .= ',';
909     $record_identifier .= 'bl:'.$record['billable'];
910     // Add project.
911     $record_identifier .= $record['project_id'] ? ',pr:'.$record['project_id'] : '';
912     // Add task.
913     $record_identifier .= $record['task_id'] ? ',ts:'.$record['task_id'] : '';
914     // Add custom field 1. This requires modifying the query to get the data we need.
915     if ($user->isPluginEnabled('cf')) {
916       if ($record['cf_1_id'])
917         $record_identifier .= ',cf_1:'.$record['cf_1_id'];
918       else if ($record['cf_1_value'])
919         $record_identifier .= ',cf_1:'.$record['cf_1_value'];
920     }
921
922     return $record_identifier;
923   }
924
925   // parseFromWeekViewRow - obtains field value encoded in row identifier.
926   // For example, for a row id like "cl:546,bl:0,pr:23456,ts:27464,cf_1:example text"
927   // requesting a client "cl" should return 546.
928   static function parseFromWeekViewRow($row_id, $field_label) {
929     // Find beginning of label.
930     $pos = strpos($row_id, $field_label);
931     if ($pos === false) return null; // Not found.
932
933     // Strip suffix from row id.
934     $suffixPos = strrpos($row_id, '_');
935     if ($suffixPos)
936       $remaninder = substr($row_id, 0, $suffixPos);
937
938     // Find beginning of value.
939     $posBegin = 1 + strpos($remaninder, ':', $pos);
940     // Find end of value.
941     $posEnd = strpos($remaninder, ',', $posBegin);
942     if ($posEnd === false) $posEnd = strlen($remaninder);
943     // Return value.
944     return substr($remaninder, $posBegin, $posEnd - $posBegin);
945   }
946
947   // makeRecordLabel - builds a human readable label for a row in week view,
948   // which is a combination ot record properties.
949   // Client - Project - Task - Custom field 1.
950   // Note that billable property is not part of the label. Instead, we intend to
951   // identify such records with a different color in week view.
952   static function makeRecordLabel($record) {
953     global $user;
954     // Start with client.
955     if ($user->isPluginEnabled('cl'))
956       $label = $record['client'];
957
958     // Add project.
959     if (!empty($label) && !empty($record['project'])) $label .= ' - ';
960     $label .= $record['project'];
961
962     // Add task.
963     if (!empty($label) && !empty($record['task'])) $label .= ' - ';
964     $label .= $record['task'];
965
966     // Add custom field 1.
967     if ($user->isPluginEnabled('cf')) {
968       if (!empty($label) && !empty($record['cf_1_value'])) $label .= ' - ';
969       $label .= $record['cf_1_value'];
970     }
971
972     return $label;
973   }
974
975   // getDayHeadersForWeek - obtains day column headers for week view, which are simply day numbers in month.
976   static function getDayHeadersForWeek($start_date) {
977     $dayHeaders = array();
978     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
979     $dayHeaders[] = (string) $objDate->getDate(); // It returns an int on first call.
980     if (strlen($dayHeaders[0]) == 1)              // Which is an implementation detail of DateAndTime class.
981       $dayHeaders[0] = '0'.$dayHeaders[0];        // Add a 0 for single digit day.
982     $objDate->incDay();
983     $dayHeaders[] = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
984     $objDate->incDay();
985     $dayHeaders[] = $objDate->getDate();
986     $objDate->incDay();
987     $dayHeaders[] = $objDate->getDate();
988     $objDate->incDay();
989     $dayHeaders[] = $objDate->getDate();
990     $objDate->incDay();
991     $dayHeaders[] = $objDate->getDate();
992     $objDate->incDay();
993     $dayHeaders[] = $objDate->getDate();
994     unset($objDate);
995     return $dayHeaders;
996   }
997
998     // getLockedDaysForWeek - builds an array of locked days in week.
999   static function getLockedDaysForWeek($start_date) {
1000     global $user;
1001     $lockedDays = array();
1002     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
1003     for ($i = 0; $i < 7; $i++) {
1004       $lockedDays[] = $user->isDateLocked($objDate);
1005       $objDate->incDay();
1006     }
1007     unset($objDate);
1008     return $lockedDays;
1009   }
1010
1011   // getDayTotals calculates total durations for each day from the existing data in $dataArray.
1012   static function getDayTotals($dataArray, $dayHeaders) {
1013     $dayTotals = array();
1014
1015     // Insert label.
1016     global $i18n;
1017     $dayTotals['label'] = $i18n->getKey('label.total');
1018
1019     foreach ($dataArray as $row) {
1020       foreach($dayHeaders as $dayHeader) {
1021         if (array_key_exists($dayHeader, $row)) {
1022           $minutes = ttTimeHelper::toMinutes($row[$dayHeader]['duration']);
1023           $dayTotals[$dayHeader] += $minutes;
1024         }
1025       }
1026     }
1027     // Convert minutes to hh:mm for display.
1028     foreach($dayHeaders as $dayHeader) {
1029       $dayTotals[$dayHeader] = ttTimeHelper::toAbsDuration($dayTotals[$dayHeader]);
1030     }
1031     return $dayTotals;
1032   }
1033
1034   // dateFromDayHeader calculates date from start date and day header in week view.
1035   static function dateFromDayHeader($start_date, $day_header) {
1036     $objDate = new DateAndTime(DB_DATEFORMAT, $start_date);
1037     $currentDayHeader = (string) $objDate->getDate(); // It returns an int on first call.
1038     if (strlen($currentDayHeader) == 1)               // Which is an implementation detail of DateAndTime class.
1039       $currentDayHeader = '0'.$currentDayHeader;      // Add a 0 for single digit day.
1040     $i = 1;
1041     while ($currentDayHeader != $day_header && $i < 7) {
1042       // Iterate through remaining days to find a match.
1043       $objDate->incDay();
1044       $currentDayHeader = $objDate->getDate(); // After incDay it returns a string with leading 0, when necessary.
1045       $i++;
1046     }
1047     return $objDate->toString(DB_DATEFORMAT);
1048   }
1049
1050   // insertDurationFromWeekView - inserts a new record in log tables from a week view post.
1051   static function insertDurationFromWeekView($fields, $custom_fields, $err) {
1052     global $i18n;
1053     global $user;
1054
1055     // Determine date for a new entry.
1056     $entry_date = ttTimeHelper::dateFromDayHeader($fields['start_date'], $fields['day_header']);
1057     $objEntryDate = new DateAndTime(DB_DATEFORMAT, $entry_date);
1058
1059     // Prohibit creating entries in future.
1060     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES) && $fields['browser_today']) {
1061       $objBrowserToday = new DateAndTime(DB_DATEFORMAT, $fields['browser_today']);
1062       if ($objEntryDate->after($objBrowserToday)) {
1063         $err->add($i18n->getKey('error.future_date'));
1064         return false;
1065       }
1066     }
1067
1068     // Prepare an array of fields for regular insert function.
1069     $fields4insert = array();
1070     $fields4insert['user_id'] = $user->getActiveUser();
1071     $fields4insert['date'] = $entry_date;
1072     $fields4insert['duration'] = $fields['duration'];
1073     $fields4insert['client'] = ttTimeHelper::parseFromWeekViewRow($fields['row_id'], 'cl');
1074     $fields4insert['billable'] = ttTimeHelper::parseFromWeekViewRow($fields['row_id'], 'bl');
1075     $fields4insert['project'] = ttTimeHelper::parseFromWeekViewRow($fields['row_id'], 'pr');
1076     $fields4insert['task'] = ttTimeHelper::parseFromWeekViewRow($fields['row_id'], 'ts');
1077     $fields4insert['note'] = $fields['note'];
1078
1079     // Try to insert a record.
1080     $id = ttTimeHelper::insert($fields4insert);
1081     if (!$id) return false; // Something failed.
1082
1083     // Insert custom field if we have it.
1084     $result = true;
1085     $cf_1 = ttTimeHelper::parseFromWeekViewRow($fields['row_id'], 'cf_1');
1086     if ($custom_fields && $cf_1) {
1087       if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
1088         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cf_1);
1089       elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
1090         $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cf_1, null);
1091     }
1092
1093     return $result;
1094   }
1095
1096
1097   // modifyFromWeekView - modifies a duration of an existing record from a week view post.
1098   static function modifyDurationFromWeekView($fields, $err) {
1099     global $i18n;
1100     global $user;
1101
1102     // Possible errors: 1) Overlap if the existing record has start time. 2) Going beyond 24 hour boundary.
1103     // TODO: rename this function.
1104     // Handle different errors with specific error messages.
1105     if (!ttTimeHelper::wvCanModify($fields['tt_log_id'], $fields['duration'], $err)) {
1106       // $err->add($i18n->getKey('error.overlap'));
1107       return false;
1108     }
1109
1110     $mdb2 = getConnection();
1111     $duration = $fields['duration'];
1112     $tt_log_id = $fields['tt_log_id'];
1113     $user_id = $user->getActiveUser();
1114     $sql = "update tt_log set duration = '$duration' where id = $tt_log_id and user_id = $user_id";
1115     $affected = $mdb2->exec($sql);
1116     if (is_a($affected, 'PEAR_Error'))
1117       return false;
1118
1119     return true;
1120   }
1121 }
1122