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