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.
11 // | There are only two ways to violate the license:
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).
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).
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
24 // +----------------------------------------------------------------------+
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
29 require_once('initialize.php');
31 import('form.DefaultCellRenderer');
33 import('form.TextField');
34 import('ttUserHelper');
35 import('ttTeamHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
42 if (!(ttAccessAllowed('track_own_time') || ttAccessAllowed('track_time'))) {
43 header('Location: access_denied.php');
46 if (!$user->isPluginEnabled('wv')) {
47 header('Location: feature_disabled.php');
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.
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.
58 // End of access checks.
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);
66 $cl_date = $selected_date->toString(DB_DATEFORMAT);
67 $_SESSION['date'] = $cl_date;
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;
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.
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($user->team_id);
87 $smarty->assign('custom_fields', $custom_fields);
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 = $quota->get($selected_date->mYear, $selected_date->mMonth);
95 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
96 $minutes_left = round(60*$month_quota) - ttTimeHelper::toMinutes($month_total);
98 $smarty->assign('month_total', $month_total);
99 $smarty->assign('over_quota', $minutes_left < 0);
100 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
103 // Initialize variables.
105 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
106 $_SESSION['cf_1'] = $cl_cf_1;
108 if ($user->isPluginEnabled('iv')) {
109 if ($request->isPost()) {
110 $cl_billable = $request->getParameter('billable');
111 $_SESSION['billable'] = (int) $cl_billable;
113 if (isset($_SESSION['billable']))
114 $cl_billable = $_SESSION['billable'];
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;
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->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
132 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
134 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
136 $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
138 // Build day totals (total durations for each day in week).
139 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
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) {
146 $this->setOptions(array('width'=>200,'valign'=>'middle'));
148 // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
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;'));
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');
162 if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
163 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
167 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
168 return $this->toString();
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) {
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.
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');
190 if ($user->isPluginEnabled('wvns')) {
192 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
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.
198 $field->setValue($table->getValueAt($row,$column)['duration']);
199 // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
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);
206 $this->setValue($field->getHtml());
207 return $this->toString();
211 // Elements of weekTimeForm.
212 $form = new Form('weekTimeForm');
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);
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,
227 'datakeys'=>array('id','name')));
228 $smarty->assign('on_behalf_control', 1);
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]]));
242 $table->setInteractive(false);
243 $form->addInputElement($table);
245 // Dropdown for clients in MODE_TIME. Use all active clients.
246 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
247 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
248 $form->addInput(array('type'=>'combobox',
249 'onchange'=>'fillProjectDropdown(this.value);',
251 'style'=>'width: 250px;',
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.
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);',
265 'style'=>'width: 250px;',
266 'value'=>$cl_project,
267 'data'=>$project_list,
268 'datakeys'=>array('id','name'),
269 'empty'=>array(''=>$i18n->get('dropdown.select'))));
271 // Dropdown for clients if the clients plugin is enabled.
272 if ($user->isPluginEnabled('cl')) {
273 $active_clients = ttTeamHelper::getActiveClients($user->team_id, 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'];
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);
285 $client['projects'] = implode(',', $intersection);
286 $client_list[] = $client;
289 $form->addInput(array('type'=>'combobox',
290 'onchange'=>'fillProjectDropdown(this.value);',
292 'style'=>'width: 250px;',
294 'data'=>$client_list,
295 'datakeys'=>array('id', 'name'),
296 'empty'=>array(''=>$i18n->get('dropdown.select'))));
300 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
301 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
302 $form->addInput(array('type'=>'combobox',
304 'style'=>'width: 250px;',
307 'datakeys'=>array('id','name'),
308 'empty'=>array(''=>$i18n->get('dropdown.select'))));
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));
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')));
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;',
330 'data'=>$custom_fields->options,
331 'empty'=>array(''=>$i18n->get('dropdown.select'))));
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;
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']);
354 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
355 if (!$cl_project) $err->add($i18n->get('error.project'));
357 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
358 if (!$cl_task) $err->add($i18n->get('error.task'));
361 // Finished validating user input for row 0.
363 // Process the table of values.
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.
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;
379 // Handle durations and comments in separate blocks of code.
380 if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
381 // Handle durations row here.
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.
392 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
393 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
396 // Do not process if value has not changed.
397 if ($postedDuration == $existingDuration)
399 // Posted value is different.
400 if ($existingDuration == null) {
401 // Skip inserting 0 duration values.
402 if (0 == ttTimeHelper::toMinutes($postedDuration))
404 // Insert a new record.
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.
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.
419 if ($user->isPluginEnabled('wvn')) {
420 $fields['note'] = $request->getParameter('note');
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);
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->getActiveUser());
439 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
440 $fields['duration'] = $postedDuration;
441 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
443 if (!$result) break; // Break out of the loop in case of first error.
445 } else if ($user->isPluginEnabled('wvns')) {
446 // Handle commments row here.
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.
456 // Do not process if value has not changed.
457 if ($postedComment == $existingComment)
460 // Posted value is different.
461 // TODO: handle new entries separately in the durations block above.
463 // Here, only update the comment on an already existing record.
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);
470 if (!$result) break; // Break out of the loop in case of first error.
473 if (!$result) break; // Break out of the loop in case of first error.
477 header('Location: week.php'); // Normal exit.
482 elseif ($request->getParameter('onBehalfUser')) {
483 if($user->can('track_time')) {
484 unset($_SESSION['behalf_id']);
485 unset($_SESSION['behalf_name']);
487 if($on_behalf_id != $user->id) {
488 $_SESSION['behalf_id'] = $on_behalf_id;
489 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
491 header('Location: week.php');
497 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
499 $smarty->assign('selected_date', $selected_date);
500 $smarty->assign('week_total', $week_total);
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);
510 $smarty->assign('title', $i18n->get('title.time'));
511 $smarty->assign('content_page_name', 'week.tpl');
512 $smarty->display('index.tpl');