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.
59 // Initialize and store date in session.
60 $cl_date = $request->getParameter('date', @$_SESSION['date']);
61 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
62 if($selected_date->isError())
63 $selected_date = new DateAndTime(DB_DATEFORMAT);
65 $cl_date = $selected_date->toString(DB_DATEFORMAT);
66 $_SESSION['date'] = $cl_date;
68 // Determine selected week start and end dates.
69 $weekStartDay = $user->week_start;
70 $t_arr = localtime($selected_date->getTimestamp());
71 $t_arr[5] = $t_arr[5] + 1900;
72 if ($t_arr[6] < $weekStartDay)
73 $startWeekBias = $weekStartDay - 7;
75 $startWeekBias = $weekStartDay;
76 $startDate = new DateAndTime();
77 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
78 $endDate = new DateAndTime();
79 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
80 // The above is needed to set date range (timestring) in page title.
82 // Use custom fields plugin if it is enabled.
83 if ($user->isPluginEnabled('cf')) {
84 require_once('plugins/CustomFields.class.php');
85 $custom_fields = new CustomFields($user->team_id);
86 $smarty->assign('custom_fields', $custom_fields);
89 // Use Monthly Quotas plugin, if applicable.
90 if ($user->isPluginEnabled('mq')){
91 require_once('plugins/MonthlyQuota.class.php');
92 $quota = new MonthlyQuota();
93 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
94 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
95 $minutes_left = round(60*$month_quota) - ttTimeHelper::toMinutes($month_total);
97 $smarty->assign('month_total', $month_total);
98 $smarty->assign('over_quota', $minutes_left < 0);
99 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
102 // Initialize variables.
104 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
105 $_SESSION['cf_1'] = $cl_cf_1;
107 if ($user->isPluginEnabled('iv')) {
108 if ($request->isPost()) {
109 $cl_billable = $request->getParameter('billable');
110 $_SESSION['billable'] = (int) $cl_billable;
112 if (isset($_SESSION['billable']))
113 $cl_billable = $_SESSION['billable'];
115 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
116 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
117 $_SESSION['client'] = $cl_client;
118 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
119 $_SESSION['project'] = $cl_project;
120 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
121 $_SESSION['task'] = $cl_task;
122 $cl_note = $request->getParameter('note', ($request->isPost() ? null : @$_SESSION['note']));
123 $_SESSION['note'] = $cl_note;
125 // Get the data we need to display week view.
126 // Get column headers, which are day numbers in month.
127 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
128 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
129 // Get already existing records.
130 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
131 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
133 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
135 $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
137 // Build day totals (total durations for each day in week).
138 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
140 // Define rendering class for a label field to the left of durations.
141 class LabelCellRenderer extends DefaultCellRenderer {
142 function render(&$table, $value, $row, $column, $selected = false) {
145 $this->setOptions(array('width'=>200,'valign'=>'middle'));
147 // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
149 $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
150 } else if ($user->isPluginEnabled('wvns') && (1 == $row)) {
151 $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
152 } else if ($user->isPluginEnabled('wvns') && (0 != $row % 2)) {
153 $this->setOptions(array('style'=>'text-align: right;'));
155 // Special handling for not billable entries.
156 $ignoreRow = $user->isPluginEnabled('wvns') ? 1 : 0;
157 if ($row > $ignoreRow) {
158 $row_id = $table->getValueAtName($row,'row_id');
159 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
161 if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
162 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
166 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
167 return $this->toString();
171 // Define rendering class for a single cell for a time or a comment entry in week view table.
172 class WeekViewCellRenderer extends DefaultCellRenderer {
173 function render(&$table, $value, $row, $column, $selected = false) {
176 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
177 $field = new TextField($field_name);
178 // Disable control if the date is locked.
180 if ($lockedDays[$column-1])
181 $field->setEnabled(false);
182 $field->setFormName($table->getFormName());
183 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
184 // Provide visual separation for new entry row.
185 $rowToSeparate = $user->isPluginEnabled('wvns') ? 1 : 0;
186 if ($rowToSeparate == $row) {
187 $field->setStyle('width: 60px; margin-bottom: 40px');
189 if ($user->isPluginEnabled('wvns')) {
191 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
193 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
194 $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to help view the entire comment.
197 $field->setValue($table->getValueAt($row,$column)['duration']);
198 // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
200 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
201 // because we can't supply start and finish times in week view - there are no fields for them.
202 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
203 $field->setEnabled(false);
205 $this->setValue($field->getHtml());
206 return $this->toString();
210 // Elements of weekTimeForm.
211 $form = new Form('weekTimeForm');
213 if ($user->can('track_time')) {
214 if ($user->can('track_own_time'))
215 $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1,'include_self'=>true,'self_first'=>true);
217 $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1);
218 $user_list = $user->getUsers($options);
219 if (count($user_list) >= 1) {
220 $form->addInput(array('type'=>'combobox',
221 'onchange'=>'this.form.submit();',
222 'name'=>'onBehalfUser',
223 'style'=>'width: 250px;',
224 'value'=>$on_behalf_id,
226 'datakeys'=>array('id','name')));
227 $smarty->assign('on_behalf_control', 1);
231 // Create week_durations table.
232 $table = new Table('week_durations', 'week_view_table');
233 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
234 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
235 $table->setData($dataArray);
236 // Add columns to table.
237 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
238 for ($i = 0; $i < 7; $i++) {
239 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
241 $table->setInteractive(false);
242 $form->addInputElement($table);
244 // Dropdown for clients in MODE_TIME. Use all active clients.
245 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
246 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
247 $form->addInput(array('type'=>'combobox',
248 'onchange'=>'fillProjectDropdown(this.value);',
250 'style'=>'width: 250px;',
252 'data'=>$active_clients,
253 'datakeys'=>array('id', 'name'),
254 'empty'=>array(''=>$i18n->get('dropdown.select'))));
255 // Note: in other modes the client list is filtered to relevant clients only. See below.
258 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
259 // Dropdown for projects assigned to user.
260 $project_list = $user->getAssignedProjects();
261 $form->addInput(array('type'=>'combobox',
262 'onchange'=>'fillTaskDropdown(this.value);',
264 'style'=>'width: 250px;',
265 'value'=>$cl_project,
266 'data'=>$project_list,
267 'datakeys'=>array('id','name'),
268 'empty'=>array(''=>$i18n->get('dropdown.select'))));
270 // Dropdown for clients if the clients plugin is enabled.
271 if ($user->isPluginEnabled('cl')) {
272 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
273 // We need an array of assigned project ids to do some trimming.
274 foreach($project_list as $project)
275 $projects_assigned_to_user[] = $project['id'];
277 // Build a client list out of active clients. Use only clients that are relevant to user.
278 // Also trim their associated project list to only assigned projects (to user).
279 foreach($active_clients as $client) {
280 $projects_assigned_to_client = explode(',', $client['projects']);
281 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
282 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
284 $client['projects'] = implode(',', $intersection);
285 $client_list[] = $client;
288 $form->addInput(array('type'=>'combobox',
289 'onchange'=>'fillProjectDropdown(this.value);',
291 'style'=>'width: 250px;',
293 'data'=>$client_list,
294 'datakeys'=>array('id', 'name'),
295 'empty'=>array(''=>$i18n->get('dropdown.select'))));
299 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
300 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
301 $form->addInput(array('type'=>'combobox',
303 'style'=>'width: 250px;',
306 'datakeys'=>array('id','name'),
307 'empty'=>array(''=>$i18n->get('dropdown.select'))));
309 if (!defined('NOTE_INPUT_HEIGHT'))
310 define('NOTE_INPUT_HEIGHT', 40);
311 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
313 // Add other controls.
314 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
315 if ($user->isPluginEnabled('iv'))
316 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
317 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
318 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
320 // If we have custom fields - add controls for them.
321 if ($custom_fields && $custom_fields->fields[0]) {
322 // Only one custom field is supported at this time.
323 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
324 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
325 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
326 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
327 'style'=>'width: 250px;',
329 'data'=>$custom_fields->options,
330 'empty'=>array(''=>$i18n->get('dropdown.select'))));
335 if ($request->isPost()) {
336 if ($request->getParameter('btn_submit')) {
337 // Validate user input for row 0.
338 // Determine if a new entry was posted.
339 $newEntryPosted = false;
340 foreach($dayHeaders as $dayHeader) {
341 $control_id = '0_'.$dayHeader;
342 if ($request->getParameter($control_id)) {
343 $newEntryPosted = true;
347 if ($newEntryPosted) {
348 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
349 $err->add($i18n->get('error.client'));
350 if ($custom_fields) {
351 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
353 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
354 if (!$cl_project) $err->add($i18n->get('error.project'));
356 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
357 if (!$cl_task) $err->add($i18n->get('error.task'));
360 // Finished validating user input for row 0.
362 // Process the table of values.
365 // Obtain values. Iterate through posted parameters one by one,
366 // see if value changed, apply one change at a time until we see an error.
369 // Iterate through existing rows.
370 foreach ($dataArray as $row) {
371 // Iterate through days.
372 foreach ($dayHeaders as $key => $dayHeader) {
373 // Do not process locked days.
374 if ($lockedDays[$key]) continue;
375 // Make control id for the cell.
376 $control_id = $rowNumber.'_'.$dayHeader;
378 // Handle durations and comments in separate blocks of code.
379 if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
380 // Handle durations row here.
382 // Obtain existing and posted durations.
383 $postedDuration = $request->getParameter($control_id);
384 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
385 // If posted value is not null, check and normalize it.
386 if ($postedDuration) {
387 if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
388 $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
389 $result = false; break; // Break out. Stop any further processing.
391 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
392 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
395 // Do not process if value has not changed.
396 if ($postedDuration == $existingDuration)
398 // Posted value is different.
399 if ($existingDuration == null) {
400 // Skip inserting 0 duration values.
401 if (0 == ttTimeHelper::toMinutes($postedDuration))
403 // Insert a new record.
405 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
406 if (!$fields['row_id']) {
407 // Special handling for row 0, a new entry. Need to construct new row_id.
409 $record['client_id'] = $cl_client;
410 $record['billable'] = $cl_billable ? '1' : '0';
411 $record['project_id'] = $cl_project;
412 $record['task_id'] = $cl_task;
413 $record['cf_1_value'] = $cl_cf_1;
414 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
415 // Note: no need to check for a possible conflict with an already existing row
416 // because we are doing an insert that does not affect already existing data.
418 if ($user->isPluginEnabled('wvn')) {
419 $fields['note'] = $request->getParameter('note');
422 $fields['day_header'] = $dayHeader;
423 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
424 $fields['duration'] = $postedDuration;
425 $fields['browser_today'] = $request->getParameter('browser_today', null);
426 if ($user->isPluginEnabled('wvns')) {
427 // Take note value from the control below duration.
428 $noteRowNumber = $rowNumber + 1;
429 $note_control_id = $noteRowNumber.'_'.$dayHeader;
430 $fields['note'] = $request->getParameter($note_control_id);
432 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
433 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
434 // Delete an already existing record here.
435 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
438 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
439 $fields['duration'] = $postedDuration;
440 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
442 if (!$result) break; // Break out of the loop in case of first error.
444 } else if ($user->isPluginEnabled('wvns')) {
445 // Handle commments row here.
447 // Obtain existing and posted comments.
448 $postedComment = $request->getParameter($control_id);
449 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
450 // If posted value is not null, check it.
451 if ($postedComment && !ttValidString($postedComment, true)) {
452 $err->add($i18n->get('error.field'), $i18n->get('label.note'));
453 $result = false; break; // Break out. Stop any further processing.
455 // Do not process if value has not changed.
456 if ($postedComment == $existingComment)
459 // Posted value is different.
460 // TODO: handle new entries separately in the durations block above.
462 // Here, only update the comment on an already existing record.
464 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
465 if ($fields['tt_log_id']) {
466 $fields['comment'] = $postedComment;
467 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
469 if (!$result) break; // Break out of the loop in case of first error.
472 if (!$result) break; // Break out of the loop in case of first error.
476 header('Location: week.php'); // Normal exit.
481 elseif ($request->getParameter('onBehalfUser')) {
482 if($user->can('track_time')) {
483 unset($_SESSION['behalf_id']);
484 unset($_SESSION['behalf_name']);
486 if($on_behalf_id != $user->id) {
487 $_SESSION['behalf_id'] = $on_behalf_id;
488 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
490 header('Location: week.php');
496 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
498 $smarty->assign('selected_date', $selected_date);
499 $smarty->assign('week_total', $week_total);
501 $smarty->assign('client_list', $client_list);
502 $smarty->assign('project_list', $project_list);
503 $smarty->assign('task_list', $task_list);
504 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
505 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
506 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
507 $smarty->assign('time_records', $records);
509 $smarty->assign('title', $i18n->get('title.time'));
510 $smarty->assign('content_page_name', 'week.tpl');
511 $smarty->display('index.tpl');