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');
51 // Initialize and store date in session.
52 $cl_date = $request->getParameter('date', @$_SESSION['date']);
53 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
54 if($selected_date->isError())
55 $selected_date = new DateAndTime(DB_DATEFORMAT);
57 $cl_date = $selected_date->toString(DB_DATEFORMAT);
58 $_SESSION['date'] = $cl_date;
60 // Determine selected week start and end dates.
61 $weekStartDay = $user->week_start;
62 $t_arr = localtime($selected_date->getTimestamp());
63 $t_arr[5] = $t_arr[5] + 1900;
64 if ($t_arr[6] < $weekStartDay)
65 $startWeekBias = $weekStartDay - 7;
67 $startWeekBias = $weekStartDay;
68 $startDate = new DateAndTime();
69 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
70 $endDate = new DateAndTime();
71 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
72 // The above is needed to set date range (timestring) in page title.
74 // Use custom fields plugin if it is enabled.
75 if ($user->isPluginEnabled('cf')) {
76 require_once('plugins/CustomFields.class.php');
77 $custom_fields = new CustomFields($user->team_id);
78 $smarty->assign('custom_fields', $custom_fields);
81 // Use Monthly Quotas plugin, if applicable.
82 if ($user->isPluginEnabled('mq')){
83 require_once('plugins/MonthlyQuota.class.php');
84 $quota = new MonthlyQuota();
85 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
86 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
87 $minutes_left = round(60*$month_quota) - ttTimeHelper::toMinutes($month_total);
89 $smarty->assign('month_total', $month_total);
90 $smarty->assign('over_quota', $minutes_left < 0);
91 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
94 // Initialize variables.
96 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
97 $_SESSION['cf_1'] = $cl_cf_1;
99 if ($user->isPluginEnabled('iv')) {
100 if ($request->isPost()) {
101 $cl_billable = $request->getParameter('billable');
102 $_SESSION['billable'] = (int) $cl_billable;
104 if (isset($_SESSION['billable']))
105 $cl_billable = $_SESSION['billable'];
107 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
108 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
109 $_SESSION['client'] = $cl_client;
110 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
111 $_SESSION['project'] = $cl_project;
112 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
113 $_SESSION['task'] = $cl_task;
114 $cl_note = $request->getParameter('note', ($request->isPost() ? null : @$_SESSION['note']));
115 $_SESSION['note'] = $cl_note;
117 // Get the data we need to display week view.
118 // Get column headers, which are day numbers in month.
119 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
120 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
121 // Get already existing records.
122 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
123 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
125 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
127 $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
129 // Build day totals (total durations for each day in week).
130 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
132 // Define rendering class for a label field to the left of durations.
133 class LabelCellRenderer extends DefaultCellRenderer {
134 function render(&$table, $value, $row, $column, $selected = false) {
137 $this->setOptions(array('width'=>200,'valign'=>'middle'));
139 // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
141 $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
142 } else if ($user->isPluginEnabled('wvns') && (1 == $row)) {
143 $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
144 } else if ($user->isPluginEnabled('wvns') && (0 != $row % 2)) {
145 $this->setOptions(array('style'=>'text-align: right;'));
147 // Special handling for not billable entries.
148 $ignoreRow = $user->isPluginEnabled('wvns') ? 1 : 0;
149 if ($row > $ignoreRow) {
150 $row_id = $table->getValueAtName($row,'row_id');
151 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
153 if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
154 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
158 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
159 return $this->toString();
163 // Define rendering class for a single cell for a time or a comment entry in week view table.
164 class WeekViewCellRenderer extends DefaultCellRenderer {
165 function render(&$table, $value, $row, $column, $selected = false) {
168 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
169 $field = new TextField($field_name);
170 // Disable control if the date is locked.
172 if ($lockedDays[$column-1])
173 $field->setEnabled(false);
174 $field->setFormName($table->getFormName());
175 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
176 // Provide visual separation for new entry row.
177 $rowToSeparate = $user->isPluginEnabled('wvns') ? 1 : 0;
178 if ($rowToSeparate == $row) {
179 $field->setStyle('width: 60px; margin-bottom: 40px');
181 if ($user->isPluginEnabled('wvns')) {
183 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
185 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
186 $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to help view the entire comment.
189 $field->setValue($table->getValueAt($row,$column)['duration']);
190 // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
192 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
193 // because we can't supply start and finish times in week view - there are no fields for them.
194 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
195 $field->setEnabled(false);
197 $this->setValue($field->getHtml());
198 return $this->toString();
202 // Elements of weekTimeForm.
203 $form = new Form('weekTimeForm');
205 if ($user->can('track_time')) {
206 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
207 if (count($user_list) > 1) {
208 $form->addInput(array('type'=>'combobox',
209 'onchange'=>'this.form.submit();',
210 'name'=>'onBehalfUser',
211 'style'=>'width: 250px;',
212 'value'=>$on_behalf_id,
214 'datakeys'=>array('id','name')));
215 $smarty->assign('on_behalf_control', 1);
219 // Create week_durations table.
220 $table = new Table('week_durations', 'week_view_table');
221 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
222 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
223 $table->setData($dataArray);
224 // Add columns to table.
225 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
226 for ($i = 0; $i < 7; $i++) {
227 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
229 $table->setInteractive(false);
230 $form->addInputElement($table);
232 // Dropdown for clients in MODE_TIME. Use all active clients.
233 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
234 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
235 $form->addInput(array('type'=>'combobox',
236 'onchange'=>'fillProjectDropdown(this.value);',
238 'style'=>'width: 250px;',
240 'data'=>$active_clients,
241 'datakeys'=>array('id', 'name'),
242 'empty'=>array(''=>$i18n->get('dropdown.select'))));
243 // Note: in other modes the client list is filtered to relevant clients only. See below.
246 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
247 // Dropdown for projects assigned to user.
248 $project_list = $user->getAssignedProjects();
249 $form->addInput(array('type'=>'combobox',
250 'onchange'=>'fillTaskDropdown(this.value);',
252 'style'=>'width: 250px;',
253 'value'=>$cl_project,
254 'data'=>$project_list,
255 'datakeys'=>array('id','name'),
256 'empty'=>array(''=>$i18n->get('dropdown.select'))));
258 // Dropdown for clients if the clients plugin is enabled.
259 if ($user->isPluginEnabled('cl')) {
260 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
261 // We need an array of assigned project ids to do some trimming.
262 foreach($project_list as $project)
263 $projects_assigned_to_user[] = $project['id'];
265 // Build a client list out of active clients. Use only clients that are relevant to user.
266 // Also trim their associated project list to only assigned projects (to user).
267 foreach($active_clients as $client) {
268 $projects_assigned_to_client = explode(',', $client['projects']);
269 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
270 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
272 $client['projects'] = implode(',', $intersection);
273 $client_list[] = $client;
276 $form->addInput(array('type'=>'combobox',
277 'onchange'=>'fillProjectDropdown(this.value);',
279 'style'=>'width: 250px;',
281 'data'=>$client_list,
282 'datakeys'=>array('id', 'name'),
283 'empty'=>array(''=>$i18n->get('dropdown.select'))));
287 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
288 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
289 $form->addInput(array('type'=>'combobox',
291 'style'=>'width: 250px;',
294 'datakeys'=>array('id','name'),
295 'empty'=>array(''=>$i18n->get('dropdown.select'))));
297 if (!defined('NOTE_INPUT_HEIGHT'))
298 define('NOTE_INPUT_HEIGHT', 40);
299 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
301 // Add other controls.
302 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
303 if ($user->isPluginEnabled('iv'))
304 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
305 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
306 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
308 // If we have custom fields - add controls for them.
309 if ($custom_fields && $custom_fields->fields[0]) {
310 // Only one custom field is supported at this time.
311 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
312 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
313 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
314 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
315 'style'=>'width: 250px;',
317 'data'=>$custom_fields->options,
318 'empty'=>array(''=>$i18n->get('dropdown.select'))));
323 if ($request->isPost()) {
324 if ($request->getParameter('btn_submit')) {
325 // Validate user input for row 0.
326 // Determine if a new entry was posted.
327 $newEntryPosted = false;
328 foreach($dayHeaders as $dayHeader) {
329 $control_id = '0_'.$dayHeader;
330 if ($request->getParameter($control_id)) {
331 $newEntryPosted = true;
335 if ($newEntryPosted) {
336 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
337 $err->add($i18n->get('error.client'));
338 if ($custom_fields) {
339 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
341 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
342 if (!$cl_project) $err->add($i18n->get('error.project'));
344 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
345 if (!$cl_task) $err->add($i18n->get('error.task'));
348 // Finished validating user input for row 0.
350 // Process the table of values.
353 // Obtain values. Iterate through posted parameters one by one,
354 // see if value changed, apply one change at a time until we see an error.
357 // Iterate through existing rows.
358 foreach ($dataArray as $row) {
359 // Iterate through days.
360 foreach ($dayHeaders as $key => $dayHeader) {
361 // Do not process locked days.
362 if ($lockedDays[$key]) continue;
363 // Make control id for the cell.
364 $control_id = $rowNumber.'_'.$dayHeader;
366 // Handle durations and comments in separate blocks of code.
367 if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
368 // Handle durations row here.
370 // Obtain existing and posted durations.
371 $postedDuration = $request->getParameter($control_id);
372 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
373 // If posted value is not null, check and normalize it.
374 if ($postedDuration) {
375 if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
376 $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
377 $result = false; break; // Break out. Stop any further processing.
379 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
380 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
383 // Do not process if value has not changed.
384 if ($postedDuration == $existingDuration)
386 // Posted value is different.
387 if ($existingDuration == null) {
388 // Skip inserting 0 duration values.
389 if (0 == ttTimeHelper::toMinutes($postedDuration))
391 // Insert a new record.
393 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
394 if (!$fields['row_id']) {
395 // Special handling for row 0, a new entry. Need to construct new row_id.
397 $record['client_id'] = $cl_client;
398 $record['billable'] = $cl_billable ? '1' : '0';
399 $record['project_id'] = $cl_project;
400 $record['task_id'] = $cl_task;
401 $record['cf_1_value'] = $cl_cf_1;
402 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
403 // Note: no need to check for a possible conflict with an already existing row
404 // because we are doing an insert that does not affect already existing data.
406 if ($user->isPluginEnabled('wvn')) {
407 $fields['note'] = $request->getParameter('note');
410 $fields['day_header'] = $dayHeader;
411 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
412 $fields['duration'] = $postedDuration;
413 $fields['browser_today'] = $request->getParameter('browser_today', null);
414 if ($user->isPluginEnabled('wvns')) {
415 // Take note value from the control below duration.
416 $noteRowNumber = $rowNumber + 1;
417 $note_control_id = $noteRowNumber.'_'.$dayHeader;
418 $fields['note'] = $request->getParameter($note_control_id);
420 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
421 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
422 // Delete an already existing record here.
423 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
426 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
427 $fields['duration'] = $postedDuration;
428 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
430 if (!$result) break; // Break out of the loop in case of first error.
432 } else if ($user->isPluginEnabled('wvns')) {
433 // Handle commments row here.
435 // Obtain existing and posted comments.
436 $postedComment = $request->getParameter($control_id);
437 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
438 // If posted value is not null, check it.
439 if ($postedComment && !ttValidString($postedComment, true)) {
440 $err->add($i18n->get('error.field'), $i18n->get('label.note'));
441 $result = false; break; // Break out. Stop any further processing.
443 // Do not process if value has not changed.
444 if ($postedComment == $existingComment)
447 // Posted value is different.
448 // TODO: handle new entries separately in the durations block above.
450 // Here, only update the comment on an already existing record.
452 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
453 if ($fields['tt_log_id']) {
454 $fields['comment'] = $postedComment;
455 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
457 if (!$result) break; // Break out of the loop in case of first error.
460 if (!$result) break; // Break out of the loop in case of first error.
464 header('Location: week.php'); // Normal exit.
469 elseif ($request->getParameter('onBehalfUser')) {
470 if($user->can('track_time')) {
471 unset($_SESSION['behalf_id']);
472 unset($_SESSION['behalf_name']);
474 if($on_behalf_id != $user->id) {
475 $_SESSION['behalf_id'] = $on_behalf_id;
476 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
478 header('Location: week.php');
484 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
486 $smarty->assign('selected_date', $selected_date);
487 $smarty->assign('week_total', $week_total);
489 $smarty->assign('client_list', $client_list);
490 $smarty->assign('project_list', $project_list);
491 $smarty->assign('task_list', $task_list);
492 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
493 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
494 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
495 $smarty->assign('time_records', $records);
497 $smarty->assign('title', $i18n->get('title.time'));
498 $smarty->assign('content_page_name', 'week.tpl');
499 $smarty->display('index.tpl');