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);
146 $showWeekNote = $user->isOptionEnabled('week_note');
147 $showWeekNotes = $user->isOptionEnabled('week_notes');
150 // Define rendering class for a label field to the left of durations.
151 class LabelCellRenderer extends DefaultCellRenderer {
152 function render(&$table, $value, $row, $column, $selected = false) {
154 $showNotes = $user->isOptionEnabled('week_notes');
156 $this->setOptions(array('width'=>200,'valign'=>'middle'));
158 // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
160 $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
161 } else if ($showNotes && (1 == $row)) {
162 $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
163 } else if ($showNotes && (0 != $row % 2)) {
164 $this->setOptions(array('style'=>'text-align: right;'));
166 // Special handling for not billable entries.
167 $ignoreRow = $showNotes ? 1 : 0;
168 if ($row > $ignoreRow) {
169 $row_id = $table->getValueAtName($row,'row_id');
170 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
172 if (($showNotes && (0 == $row % 2)) || !$showNotes) {
173 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
177 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
178 return $this->toString();
182 // Define rendering class for a single cell for a time or a comment entry in week view table.
183 class WeekViewCellRenderer extends DefaultCellRenderer {
184 function render(&$table, $value, $row, $column, $selected = false) {
186 $showNotes = $user->isOptionEnabled('week_notes');
188 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
189 $field = new TextField($field_name);
190 // Disable control if the date is locked.
192 if ($lockedDays[$column-1])
193 $field->setEnabled(false);
194 $field->setFormName($table->getFormName());
195 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
196 // Provide visual separation for new entry row.
197 $rowToSeparate = $showNotes ? 1 : 0;
198 if ($rowToSeparate == $row) {
199 $field->setStyle('width: 60px; margin-bottom: 40px');
203 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
205 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
206 $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to help view the entire comment.
209 $field->setValue($table->getValueAt($row,$column)['duration']);
210 // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
212 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
213 // because we can't supply start and finish times in week view - there are no fields for them.
214 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
215 $field->setEnabled(false);
217 $this->setValue($field->getHtml());
218 return $this->toString();
222 // Elements of weekTimeForm.
223 $form = new Form('weekTimeForm');
225 if ($user->can('track_time')) {
226 if ($user->can('track_own_time'))
227 $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1,'include_self'=>true,'self_first'=>true);
229 $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1);
230 $user_list = $user->getUsers($options);
231 if (count($user_list) >= 1) {
232 $form->addInput(array('type'=>'combobox',
233 'onchange'=>'this.form.submit();',
234 'name'=>'onBehalfUser',
235 'style'=>'width: 250px;',
236 'value'=>$on_behalf_id,
238 'datakeys'=>array('id','name')));
239 $smarty->assign('on_behalf_control', 1);
243 // Create week_durations table.
244 $table = new Table('week_durations', 'week_view_table');
245 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
246 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
247 $table->setData($dataArray);
248 // Add columns to table.
249 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
250 for ($i = 0; $i < 7; $i++) {
251 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
253 $table->setInteractive(false);
254 $form->addInputElement($table);
256 // Dropdown for clients in MODE_TIME. Use all active clients.
257 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
258 $active_clients = ttGroupHelper::getActiveClients(true);
259 $form->addInput(array('type'=>'combobox',
260 'onchange'=>'fillProjectDropdown(this.value);',
262 'style'=>'width: 250px;',
264 'data'=>$active_clients,
265 'datakeys'=>array('id', 'name'),
266 'empty'=>array(''=>$i18n->get('dropdown.select'))));
267 // Note: in other modes the client list is filtered to relevant clients only. See below.
270 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
271 // Dropdown for projects assigned to user.
272 $project_list = $user->getAssignedProjects();
273 $form->addInput(array('type'=>'combobox',
274 'onchange'=>'fillTaskDropdown(this.value);',
276 'style'=>'width: 250px;',
277 'value'=>$cl_project,
278 'data'=>$project_list,
279 'datakeys'=>array('id','name'),
280 'empty'=>array(''=>$i18n->get('dropdown.select'))));
282 // Dropdown for clients if the clients plugin is enabled.
283 if ($user->isPluginEnabled('cl')) {
284 $active_clients = ttGroupHelper::getActiveClients(true);
285 // We need an array of assigned project ids to do some trimming.
286 foreach($project_list as $project)
287 $projects_assigned_to_user[] = $project['id'];
289 // Build a client list out of active clients. Use only clients that are relevant to user.
290 // Also trim their associated project list to only assigned projects (to user).
291 foreach($active_clients as $client) {
292 $projects_assigned_to_client = explode(',', $client['projects']);
293 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
294 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
296 $client['projects'] = implode(',', $intersection);
297 $client_list[] = $client;
300 $form->addInput(array('type'=>'combobox',
301 'onchange'=>'fillProjectDropdown(this.value);',
303 'style'=>'width: 250px;',
305 'data'=>$client_list,
306 'datakeys'=>array('id', 'name'),
307 'empty'=>array(''=>$i18n->get('dropdown.select'))));
311 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
312 $task_list = ttGroupHelper::getActiveTasks();
313 $form->addInput(array('type'=>'combobox',
315 'style'=>'width: 250px;',
318 'datakeys'=>array('id','name'),
319 'empty'=>array(''=>$i18n->get('dropdown.select'))));
321 if (!defined('NOTE_INPUT_HEIGHT'))
322 define('NOTE_INPUT_HEIGHT', 40);
323 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
325 // Add other controls.
326 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
327 if ($user->isPluginEnabled('iv'))
328 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
329 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
330 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
332 // If we have custom fields - add controls for them.
333 if ($custom_fields && $custom_fields->fields[0]) {
334 // Only one custom field is supported at this time.
335 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
336 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
337 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
338 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
339 'style'=>'width: 250px;',
341 'data'=>$custom_fields->options,
342 'empty'=>array(''=>$i18n->get('dropdown.select'))));
347 if ($request->isPost()) {
348 if ($request->getParameter('btn_submit')) {
349 // Validate user input for row 0.
350 // Determine if a new entry was posted.
351 $newEntryPosted = false;
352 foreach($dayHeaders as $dayHeader) {
353 $control_id = '0_'.$dayHeader;
354 if ($request->getParameter($control_id)) {
355 $newEntryPosted = true;
359 if ($newEntryPosted) {
360 if ($user->isPluginEnabled('cl') && $user->isOptionEnabled('client_required') && !$cl_client)
361 $err->add($i18n->get('error.client'));
362 if ($custom_fields) {
363 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
365 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
366 if (!$cl_project) $err->add($i18n->get('error.project'));
368 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
369 if (!$cl_task) $err->add($i18n->get('error.task'));
372 // Finished validating user input for row 0.
374 // Process the table of values.
377 // Obtain values. Iterate through posted parameters one by one,
378 // see if value changed, apply one change at a time until we see an error.
381 // Iterate through existing rows.
382 foreach ($dataArray as $row) {
383 // Iterate through days.
384 foreach ($dayHeaders as $key => $dayHeader) {
385 // Do not process locked days.
386 if ($lockedDays[$key]) continue;
387 // Make control id for the cell.
388 $control_id = $rowNumber.'_'.$dayHeader;
390 // Handle durations and comments in separate blocks of code.
391 if (!$showWeekNotes || (0 == $rowNumber % 2)) {
392 // Handle durations row here.
394 // Obtain existing and posted durations.
395 $postedDuration = $request->getParameter($control_id);
396 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
397 // If posted value is not null, check and normalize it.
398 if ($postedDuration) {
399 if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
400 $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
401 $result = false; break; // Break out. Stop any further processing.
403 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
404 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
407 // Do not process if value has not changed.
408 if ($postedDuration == $existingDuration)
410 // Posted value is different.
411 if ($existingDuration == null) {
412 // Skip inserting 0 duration values.
413 if (0 == ttTimeHelper::toMinutes($postedDuration))
415 // Insert a new record.
417 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
418 if (!$fields['row_id']) {
419 // Special handling for row 0, a new entry. Need to construct new row_id.
421 $record['client_id'] = $cl_client;
422 $record['billable'] = $cl_billable ? '1' : '0';
423 $record['project_id'] = $cl_project;
424 $record['task_id'] = $cl_task;
425 $record['cf_1_value'] = $cl_cf_1;
426 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
427 // Note: no need to check for a possible conflict with an already existing row
428 // because we are doing an insert that does not affect already existing data.
431 $fields['note'] = $request->getParameter('note');
434 $fields['day_header'] = $dayHeader;
435 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
436 $fields['duration'] = $postedDuration;
437 $fields['browser_today'] = $request->getParameter('browser_today', null);
438 if ($showWeekNotes) {
439 // Take note value from the control below duration.
440 $noteRowNumber = $rowNumber + 1;
441 $note_control_id = $noteRowNumber.'_'.$dayHeader;
442 $fields['note'] = $request->getParameter($note_control_id);
444 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
445 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
446 // Delete an already existing record here.
447 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getUser());
450 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
451 $fields['duration'] = $postedDuration;
452 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
454 if (!$result) break; // Break out of the loop in case of first error.
456 } else if ($showWeekNotes) {
457 // Handle commments row here.
459 // Obtain existing and posted comments.
460 $postedComment = $request->getParameter($control_id);
461 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
462 // If posted value is not null, check it.
463 if ($postedComment && !ttValidString($postedComment, true)) {
464 $err->add($i18n->get('error.field'), $i18n->get('label.note'));
465 $result = false; break; // Break out. Stop any further processing.
467 // Do not process if value has not changed.
468 if ($postedComment == $existingComment)
471 // Posted value is different.
472 // TODO: handle new entries separately in the durations block above.
474 // Here, only update the comment on an already existing record.
476 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
477 if ($fields['tt_log_id']) {
478 $fields['comment'] = $postedComment;
479 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
481 if (!$result) break; // Break out of the loop in case of first error.
484 if (!$result) break; // Break out of the loop in case of first error.
488 header('Location: week.php'); // Normal exit.
493 elseif ($request->getParameter('onBehalfUser')) {
494 if($user->can('track_time')) {
495 unset($_SESSION['behalf_id']);
496 unset($_SESSION['behalf_name']);
498 if($on_behalf_id != $user->id) {
499 $_SESSION['behalf_id'] = $on_behalf_id;
500 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
502 header('Location: week.php');
508 $week_total = ttTimeHelper::getTimeForWeek($selected_date);
510 $smarty->assign('selected_date', $selected_date);
511 $smarty->assign('week_total', $week_total);
513 $smarty->assign('client_list', $client_list);
514 $smarty->assign('project_list', $project_list);
515 $smarty->assign('task_list', $task_list);
516 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
517 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
518 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
519 $smarty->assign('time_records', $records);
520 $smarty->assign('show_navigation', !$user->isOptionEnabled('week_menu'));
521 $smarty->assign('show_client', $showClient);
522 $smarty->assign('show_project', $showProject);
523 $smarty->assign('show_task', $showTask);
524 $smarty->assign('show_week_note', $showWeekNote);
525 $smarty->assign('show_week_list', $user->isOptionEnabled('week_list'));
526 $smarty->assign('show_files', $showFiles);
527 $smarty->assign('title', $i18n->get('menu.week'));
528 $smarty->assign('content_page_name', 'week.tpl');
529 $smarty->display('index.tpl');