Replaced getKey() with get() calls.
[timetracker.git] / week.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 require_once('initialize.php');
30 import('form.Form');
31 import('form.DefaultCellRenderer');
32 import('form.Table');
33 import('form.TextField');
34 import('ttUserHelper');
35 import('ttTeamHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
40
41 // Access check.
42 if (!ttAccessAllowed('track_own_time') || !$user->isPluginEnabled('wv')) {
43   header('Location: access_denied.php');
44   exit();
45 }
46
47 // Initialize and store date in session.
48 $cl_date = $request->getParameter('date', @$_SESSION['date']);
49 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
50 if($selected_date->isError())
51   $selected_date = new DateAndTime(DB_DATEFORMAT);
52 if(!$cl_date)
53   $cl_date = $selected_date->toString(DB_DATEFORMAT);
54 $_SESSION['date'] = $cl_date;
55
56 // Determine selected week start and end dates.
57 $weekStartDay = $user->week_start;
58 $t_arr = localtime($selected_date->getTimestamp());
59 $t_arr[5] = $t_arr[5] + 1900;
60 if ($t_arr[6] < $weekStartDay)
61   $startWeekBias = $weekStartDay - 7;
62 else
63   $startWeekBias = $weekStartDay;
64 $startDate = new DateAndTime();
65 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
66 $endDate = new DateAndTime();
67 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
68 // The above is needed to set date range (timestring) in page title.
69
70 // Use custom fields plugin if it is enabled.
71 if ($user->isPluginEnabled('cf')) {
72   require_once('plugins/CustomFields.class.php');
73   $custom_fields = new CustomFields($user->team_id);
74   $smarty->assign('custom_fields', $custom_fields);
75 }
76
77 // Use Monthly Quotas plugin, if applicable.
78 if ($user->isPluginEnabled('mq')){
79   require_once('plugins/MonthlyQuota.class.php');
80   $quota = new MonthlyQuota();
81   $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
82   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
83   $minutes_left = round(60*$month_quota) - ttTimeHelper::toMinutes($month_total);
84
85   $smarty->assign('month_total', $month_total);
86   $smarty->assign('over_quota', $minutes_left < 0);
87   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
88 }
89
90 // Initialize variables.
91 // Custom field.
92 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
93 $_SESSION['cf_1'] = $cl_cf_1;
94 $cl_billable = 1;
95 if ($user->isPluginEnabled('iv')) {
96   if ($request->isPost()) {
97     $cl_billable = $request->getParameter('billable');
98     $_SESSION['billable'] = (int) $cl_billable;
99   } else
100     if (isset($_SESSION['billable']))
101       $cl_billable = $_SESSION['billable'];
102 }
103 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
104 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
105 $_SESSION['client'] = $cl_client;
106 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
107 $_SESSION['project'] = $cl_project;
108 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
109 $_SESSION['task'] = $cl_task;
110 $cl_note = $request->getParameter('note', ($request->isPost() ? null : @$_SESSION['note']));
111 $_SESSION['note'] = $cl_note;
112
113 // Get the data we need to display week view.
114 // Get column headers, which are day numbers in month.
115 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
116 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
117 // Get already existing records.
118 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
119 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
120 if ($records)
121   $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
122 else
123   $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
124
125 // Build day totals (total durations for each day in week).
126 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
127
128 // Define rendering class for a label field to the left of durations.
129 class LabelCellRenderer extends DefaultCellRenderer {
130   function render(&$table, $value, $row, $column, $selected = false) {
131     global $user;
132
133     $this->setOptions(array('width'=>200,'valign'=>'middle'));
134
135     // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
136     if (0 == $row) {
137       $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
138     } else if ($user->isPluginEnabled('wvns') && (1 == $row)) {
139       $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
140     } else if ($user->isPluginEnabled('wvns') && (0 != $row % 2)) {
141       $this->setOptions(array('style'=>'text-align: right;'));
142     }
143     // Special handling for not billable entries.
144     $ignoreRow = $user->isPluginEnabled('wvns') ? 1 : 0; 
145     if ($row > $ignoreRow) {
146       $row_id = $table->getValueAtName($row,'row_id');
147       $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
148       if (!$billable) {
149         if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
150           $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
151         }
152       }
153     }
154     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
155     return $this->toString();
156   }
157 }
158
159 // Define rendering class for a single cell for a time or a comment entry in week view table.
160 class WeekViewCellRenderer extends DefaultCellRenderer {
161   function render(&$table, $value, $row, $column, $selected = false) {
162     global $user;
163
164     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
165     $field = new TextField($field_name);
166     // Disable control if the date is locked.
167     global $lockedDays;
168     if ($lockedDays[$column-1])
169       $field->setEnabled(false);
170     $field->setFormName($table->getFormName());
171     $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
172     // Provide visual separation for new entry row.
173     $rowToSeparate = $user->isPluginEnabled('wvns') ? 1 : 0;
174     if ($rowToSeparate == $row) {
175       $field->setStyle('width: 60px; margin-bottom: 40px');
176     }
177     if ($user->isPluginEnabled('wvns')) {
178       if (0 == $row % 2) {
179         $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
180       } else {
181         $field->setValue($table->getValueAt($row,$column)['note']);     // Comment for odd rows.
182         $field->setTitle($table->getValueAt($row,$column)['note']);     // Tooltip to help view the entire comment.
183       }
184     } else {
185       $field->setValue($table->getValueAt($row,$column)['duration']);
186       // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
187     }
188     // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
189     // because we can't supply start and finish times in week view - there are no fields for them.
190     if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
191         $field->setEnabled(false);
192     }
193     $this->setValue($field->getHtml());
194     return $this->toString();
195   }
196 }
197
198 // Elements of weekTimeForm.
199 $form = new Form('weekTimeForm');
200
201 if ($user->can('track_time')) {
202   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
203   if (count($user_list) > 1) {
204     $form->addInput(array('type'=>'combobox',
205       'onchange'=>'this.form.submit();',
206       'name'=>'onBehalfUser',
207       'style'=>'width: 250px;',
208       'value'=>$on_behalf_id,
209       'data'=>$user_list,
210       'datakeys'=>array('id','name')));
211     $smarty->assign('on_behalf_control', 1);
212   }
213 }
214
215 // Create week_durations table.
216 $table = new Table('week_durations', 'week_view_table');
217 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
218 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
219 $table->setData($dataArray);
220 // Add columns to table.
221 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
222 for ($i = 0; $i < 7; $i++) {
223   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
224 }
225 $table->setInteractive(false);
226 $form->addInputElement($table);
227
228 // Dropdown for clients in MODE_TIME. Use all active clients.
229 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
230   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
231   $form->addInput(array('type'=>'combobox',
232     'onchange'=>'fillProjectDropdown(this.value);',
233     'name'=>'client',
234     'style'=>'width: 250px;',
235     'value'=>$cl_client,
236     'data'=>$active_clients,
237     'datakeys'=>array('id', 'name'),
238     'empty'=>array(''=>$i18n->get('dropdown.select'))));
239   // Note: in other modes the client list is filtered to relevant clients only. See below.
240 }
241
242 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
243   // Dropdown for projects assigned to user.
244   $project_list = $user->getAssignedProjects();
245   $form->addInput(array('type'=>'combobox',
246     'onchange'=>'fillTaskDropdown(this.value);',
247     'name'=>'project',
248     'style'=>'width: 250px;',
249     'value'=>$cl_project,
250     'data'=>$project_list,
251     'datakeys'=>array('id','name'),
252     'empty'=>array(''=>$i18n->get('dropdown.select'))));
253
254   // Dropdown for clients if the clients plugin is enabled.
255   if ($user->isPluginEnabled('cl')) {
256     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
257     // We need an array of assigned project ids to do some trimming.
258     foreach($project_list as $project)
259       $projects_assigned_to_user[] = $project['id'];
260
261     // Build a client list out of active clients. Use only clients that are relevant to user.
262     // Also trim their associated project list to only assigned projects (to user).
263     foreach($active_clients as $client) {
264       $projects_assigned_to_client = explode(',', $client['projects']);
265       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
266         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
267       if ($intersection) {
268         $client['projects'] = implode(',', $intersection);
269         $client_list[] = $client;
270       }
271     }
272     $form->addInput(array('type'=>'combobox',
273       'onchange'=>'fillProjectDropdown(this.value);',
274       'name'=>'client',
275       'style'=>'width: 250px;',
276       'value'=>$cl_client,
277       'data'=>$client_list,
278       'datakeys'=>array('id', 'name'),
279       'empty'=>array(''=>$i18n->get('dropdown.select'))));
280   }
281 }
282
283 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
284   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
285   $form->addInput(array('type'=>'combobox',
286     'name'=>'task',
287     'style'=>'width: 250px;',
288     'value'=>$cl_task,
289     'data'=>$task_list,
290     'datakeys'=>array('id','name'),
291     'empty'=>array(''=>$i18n->get('dropdown.select'))));
292 }
293 if (!defined('NOTE_INPUT_HEIGHT'))
294   define('NOTE_INPUT_HEIGHT', 40);
295 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
296
297 // Add other controls.
298 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
299 if ($user->isPluginEnabled('iv'))
300   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
301 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
302 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
303
304 // If we have custom fields - add controls for them.
305 if ($custom_fields && $custom_fields->fields[0]) {
306   // Only one custom field is supported at this time.
307   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
308     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
309   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
310     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
311       'style'=>'width: 250px;',
312       'value'=>$cl_cf_1,
313       'data'=>$custom_fields->options,
314       'empty'=>array(''=>$i18n->get('dropdown.select'))));
315   }
316 }
317
318 // Submit.
319 if ($request->isPost()) {
320   if ($request->getParameter('btn_submit')) {
321     // Validate user input for row 0.
322     // Determine if a new entry was posted.
323     $newEntryPosted = false;
324     foreach($dayHeaders as $dayHeader) {
325       $control_id = '0_'.$dayHeader;
326       if ($request->getParameter($control_id)) {
327         $newEntryPosted = true;
328         break;
329       }
330     }
331     if ($newEntryPosted) {
332       if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
333         $err->add($i18n->get('error.client'));
334       if ($custom_fields) {
335         if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
336       }
337       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
338         if (!$cl_project) $err->add($i18n->get('error.project'));
339       }
340       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
341         if (!$cl_task) $err->add($i18n->get('error.task'));
342       }
343     }
344     // Finished validating user input for row 0.
345
346     // Process the table of values.
347     if ($err->no()) {
348
349       // Obtain values. Iterate through posted parameters one by one,
350       // see if value changed, apply one change at a time until we see an error.
351       $result = true;
352       $rowNumber = 0;
353       // Iterate through existing rows.
354       foreach ($dataArray as $row) {
355         // Iterate through days.
356         foreach ($dayHeaders as $key => $dayHeader) {
357           // Do not process locked days.
358           if ($lockedDays[$key]) continue;
359           // Make control id for the cell.
360           $control_id = $rowNumber.'_'.$dayHeader;
361
362           // Handle durations and comments in separate blocks of code.
363           if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
364             // Handle durations row here.
365
366             // Obtain existing and posted durations.
367             $postedDuration = $request->getParameter($control_id);
368             $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
369             // If posted value is not null, check and normalize it.
370             if ($postedDuration) {
371               if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
372                 $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
373                 $result = false; break; // Break out. Stop any further processing.
374               } else {
375                 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
376                 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
377               }
378             }
379             // Do not process if value has not changed.
380             if ($postedDuration == $existingDuration)
381               continue;
382             // Posted value is different.
383             if ($existingDuration == null) {
384               // Skip inserting 0 duration values.
385               if (0 == ttTimeHelper::toMinutes($postedDuration))
386                 continue;
387               // Insert a new record.
388               $fields = array();
389               $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
390               if (!$fields['row_id']) {
391                 // Special handling for row 0, a new entry. Need to construct new row_id.
392                 $record = array();
393                 $record['client_id'] = $cl_client;
394                 $record['billable'] = $cl_billable ? '1' : '0';
395                 $record['project_id'] = $cl_project;
396                 $record['task_id'] = $cl_task;
397                 $record['cf_1_value'] = $cl_cf_1;
398                 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
399                 // Note: no need to check for a possible conflict with an already existing row
400                 // because we are doing an insert that does not affect already existing data.
401
402                 if ($user->isPluginEnabled('wvn')) {
403                   $fields['note'] = $request->getParameter('note');
404                 }
405               }
406               $fields['day_header'] = $dayHeader;
407               $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
408               $fields['duration'] = $postedDuration;
409               $fields['browser_today'] = $request->getParameter('browser_today', null);
410               if ($user->isPluginEnabled('wvns')) {
411                 // Take note value from the control below duration.
412                 $noteRowNumber = $rowNumber + 1;
413                 $note_control_id =  $noteRowNumber.'_'.$dayHeader;
414                 $fields['note'] = $request->getParameter($note_control_id);
415               }
416               $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
417             } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
418               // Delete an already existing record here.
419               $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
420             } else {
421               $fields = array();
422               $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
423               $fields['duration'] = $postedDuration;
424               $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
425             }
426             if (!$result) break; // Break out of the loop in case of first error.
427
428           } else if ($user->isPluginEnabled('wvns')) {
429             // Handle commments row here.
430
431             // Obtain existing and posted comments.
432             $postedComment = $request->getParameter($control_id);
433             $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
434             // If posted value is not null, check it.
435             if ($postedComment && !ttValidString($postedComment, true)) {
436               $err->add($i18n->get('error.field'), $i18n->get('label.note'));
437               $result = false; break; // Break out. Stop any further processing.
438             }
439             // Do not process if value has not changed.
440             if ($postedComment == $existingComment)
441               continue;
442
443             // Posted value is different.
444             // TODO: handle new entries separately in the durations block above.
445
446             // Here, only update the comment on an already existing record.
447             $fields = array();
448             $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
449             if ($fields['tt_log_id']) {
450               $fields['comment'] = $postedComment;
451               $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
452             }
453             if (!$result) break; // Break out of the loop in case of first error.
454           }
455         }
456         if (!$result) break; // Break out of the loop in case of first error.
457         $rowNumber++;
458       }
459       if ($result) {
460         header('Location: week.php'); // Normal exit.
461         exit();
462       }
463     }
464   }
465   elseif ($request->getParameter('onBehalfUser')) {
466     if($user->can('track_time')) {
467       unset($_SESSION['behalf_id']);
468       unset($_SESSION['behalf_name']);
469
470       if($on_behalf_id != $user->id) {
471         $_SESSION['behalf_id'] = $on_behalf_id;
472         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
473       }
474       header('Location: week.php');
475       exit();
476     }
477   }
478 } // isPost
479
480 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
481
482 $smarty->assign('selected_date', $selected_date);
483 $smarty->assign('week_total', $week_total);
484
485 $smarty->assign('client_list', $client_list);
486 $smarty->assign('project_list', $project_list);
487 $smarty->assign('task_list', $task_list);
488 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
489 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
490 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
491 $smarty->assign('time_records', $records);
492
493 $smarty->assign('title', $i18n->get('title.time'));
494 $smarty->assign('content_page_name', 'week.tpl');
495 $smarty->display('index.tpl');