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