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