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