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('ttUserHelper');
34 import('ttTeamHelper');
35 import('ttClientHelper');
36 import('ttTimeHelper');
37 import('DateAndTime');
40 if (!ttAccessCheck(right_data_entry)) {
41 header('Location: access_denied.php');
45 // Initialize and store date in session.
46 $cl_date = $request->getParameter('date', @$_SESSION['date']);
47 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
48 if($selected_date->isError())
49 $selected_date = new DateAndTime(DB_DATEFORMAT);
51 $cl_date = $selected_date->toString(DB_DATEFORMAT);
52 $_SESSION['date'] = $cl_date;
54 // Determine selected week start and end dates.
55 $weekStartDay = $user->week_start;
56 $t_arr = localtime($selected_date->getTimestamp());
57 $t_arr[5] = $t_arr[5] + 1900;
58 if ($t_arr[6] < $weekStartDay)
59 $startWeekBias = $weekStartDay - 7;
61 $startWeekBias = $weekStartDay;
62 $startDate = new DateAndTime();
63 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
64 $endDate = new DateAndTime();
65 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
66 // The above is needed to set date range (timestring) in page title.
68 // Use custom fields plugin if it is enabled.
69 if ($user->isPluginEnabled('cf')) {
70 require_once('plugins/CustomFields.class.php');
71 $custom_fields = new CustomFields($user->team_id);
72 $smarty->assign('custom_fields', $custom_fields);
75 // TODO: how is this plugin supposed to work for week view?
76 if ($user->isPluginEnabled('mq')){
77 require_once('plugins/MonthlyQuota.class.php');
78 $quota = new MonthlyQuota();
79 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
80 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
81 $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
83 $smarty->assign('month_total', $month_total);
84 $smarty->assign('over_quota', $minutes_left < 0);
85 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
88 // Initialize variables.
90 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
91 $_SESSION['cf_1'] = $cl_cf_1;
93 if ($user->isPluginEnabled('iv')) {
94 if ($request->isPost()) {
95 $cl_billable = $request->getParameter('billable');
96 $_SESSION['billable'] = (int) $cl_billable;
98 if (isset($_SESSION['billable']))
99 $cl_billable = $_SESSION['billable'];
101 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
102 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
103 $_SESSION['client'] = $cl_client;
104 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
105 $_SESSION['project'] = $cl_project;
106 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
107 $_SESSION['task'] = $cl_task;
109 // Get the data we need to display week view.
110 // Get column headers, which are day numbers in month.
111 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
112 $lockedDays = ttTimeHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
113 // Build data array for the table. Format is described in the function..
114 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT), $dayHeaders);
115 // Build day totals (total durations for each day in week).
116 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
118 // TODO: refactoring ongoing down from here.
120 // 1) Handle editable - not editable records properly meaning that UI should reflect this.
121 // 2) Start coding modification of existing records.
122 // 3) Then adding new records for existing rows.
123 // 4) Then add code and UI for adding a new row.
125 // Actually this is work in progress at this point, even documenting the array, as we still miss control IDs, and
126 // editing entries is not yet implemented. When this is done, we will have to re-document the above.
128 // Define rendering class for a label field to the left of durations.
129 class LabelCellRenderer extends DefaultCellRenderer {
130 function render(&$table, $value, $row, $column, $selected = false) {
131 $this->setOptions(array('width'=>200,'valign'=>'middle'));
132 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
133 return $this->toString();
137 // Define rendering class for a single cell for time entry in week view table.
138 class TimeCellRenderer extends DefaultCellRenderer {
139 function render(&$table, $value, $row, $column, $selected = false) {
140 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
141 $field = new TextField($field_name);
142 // Disable control if the date is locked.
144 if ($lockedDays[$column-1])
145 $field->setEnabled(false);
146 $field->setFormName($table->getFormName());
148 $field->setValue($table->getValueAt($row,$column)['duration']);
149 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
150 // because we can't supply start and finish times in week view - there are no fields for them.
152 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
153 $field->setEnabled(false);
155 $this->setValue($field->getHtml());
156 return $this->toString();
160 // Elements of weekTimeForm.
161 $form = new Form('weekTimeForm');
163 if ($user->canManageTeam()) {
164 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
165 if (count($user_list) > 1) {
166 $form->addInput(array('type'=>'combobox',
167 'onchange'=>'this.form.submit();',
168 'name'=>'onBehalfUser',
169 'style'=>'width: 250px;',
170 'value'=>$on_behalf_id,
172 'datakeys'=>array('id','name')));
173 $smarty->assign('on_behalf_control', 1);
177 // Create week_durations table.
178 $table = new Table('week_durations');
179 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
180 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
181 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
182 $table->setData($dataArray);
183 // Add columns to table.
184 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
185 for ($i = 0; $i < 7; $i++) {
186 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
188 $table->setInteractive(false);
189 $form->addInputElement($table);
191 // Dropdown for clients in MODE_TIME. Use all active clients.
192 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
193 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
194 $form->addInput(array('type'=>'combobox',
195 'onchange'=>'fillProjectDropdown(this.value);',
197 'style'=>'width: 250px;',
199 'data'=>$active_clients,
200 'datakeys'=>array('id', 'name'),
201 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
202 // Note: in other modes the client list is filtered to relevant clients only. See below.
205 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
206 // Dropdown for projects assigned to user.
207 $project_list = $user->getAssignedProjects();
208 $form->addInput(array('type'=>'combobox',
209 'onchange'=>'fillTaskDropdown(this.value);',
211 'style'=>'width: 250px;',
212 'value'=>$cl_project,
213 'data'=>$project_list,
214 'datakeys'=>array('id','name'),
215 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
217 // Dropdown for clients if the clients plugin is enabled.
218 if ($user->isPluginEnabled('cl')) {
219 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
220 // We need an array of assigned project ids to do some trimming.
221 foreach($project_list as $project)
222 $projects_assigned_to_user[] = $project['id'];
224 // Build a client list out of active clients. Use only clients that are relevant to user.
225 // Also trim their associated project list to only assigned projects (to user).
226 foreach($active_clients as $client) {
227 $projects_assigned_to_client = explode(',', $client['projects']);
228 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
229 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
231 $client['projects'] = implode(',', $intersection);
232 $client_list[] = $client;
235 $form->addInput(array('type'=>'combobox',
236 'onchange'=>'fillProjectDropdown(this.value);',
238 'style'=>'width: 250px;',
240 'data'=>$client_list,
241 'datakeys'=>array('id', 'name'),
242 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
246 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
247 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
248 $form->addInput(array('type'=>'combobox',
250 'style'=>'width: 250px;',
253 'datakeys'=>array('id','name'),
254 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
257 // Add other controls.
258 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
259 $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
260 $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
261 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
262 // Make the start and finish fields read-only.
263 $form->getElement('start')->setEnabled(false);
264 $form->getElement('finish')->setEnabled(false);
267 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
268 $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
269 if (!defined('NOTE_INPUT_HEIGHT'))
270 define('NOTE_INPUT_HEIGHT', 40);
271 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
272 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
273 if ($user->isPluginEnabled('iv'))
274 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
275 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
276 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
278 // If we have custom fields - add controls for them.
279 if ($custom_fields && $custom_fields->fields[0]) {
280 // Only one custom field is supported at this time.
281 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
282 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
283 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
284 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
285 'style'=>'width: 250px;',
287 'data'=>$custom_fields->options,
288 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
291 // TODO: the above needs to be refactored for week view.
296 if ($request->isPost()) {
297 if ($request->getParameter('btn_submit')) {
299 // Validate user input.
300 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
301 $err->add($i18n->getKey('error.client'));
302 if ($custom_fields) {
303 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
305 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
306 if (!$cl_project) $err->add($i18n->getKey('error.project'));
308 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
309 if (!$cl_task) $err->add($i18n->getKey('error.task'));
311 if (strlen($cl_duration) == 0) {
312 if ($cl_start || $cl_finish) {
313 if (!ttTimeHelper::isValidTime($cl_start))
314 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
316 if (!ttTimeHelper::isValidTime($cl_finish))
317 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
318 if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
319 $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
322 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
323 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
324 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
326 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
327 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
330 if (!ttTimeHelper::isValidDuration($cl_duration))
331 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
333 if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
334 // Finished validating user input.
336 // Prohibit creating entries in future.
337 if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
338 $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
339 if ($selected_date->after($browser_today))
340 $err->add($i18n->getKey('error.future_date'));
343 // Prohibit creating entries in locked range.
344 if ($user->isDateLocked($selected_date))
345 $err->add($i18n->getKey('error.range_locked'));
347 // Prohibit creating another uncompleted record.
349 if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
350 $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
353 // Prohibit creating an overlapping record.
355 if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
356 $err->add($i18n->getKey('error.overlap'));
358 // TODO: refactor the above.
360 // Obtain values. Perhaps, it's best to iterate throigh posted parameters one by one,
361 // see if anything changed, and apply one change at a time until we see an error.
362 // TODO: check for locked days just in case.
365 // Iterate through existing rows.
366 foreach ($dataArray as $row) {
367 // Iterate through days.
368 foreach ($dayHeaders as $key => $dayHeader) {
369 // Do not process locked days.
370 if ($lockedDays[$key]) continue;
371 // Make control id for the cell.
372 $control_id = $rowNumber.'_'.$dayHeader;
373 // Optain existing and posted durations.
374 $postedDuration = $request->getParameter($control_id);
375 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
376 // If posted value is not null, check and normalize it.
377 if ($postedDuration) {
378 if (ttTimeHelper::isValidDuration($postedDuration)) {
379 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
381 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
382 $result = false; break; // Break out. Stop any further processing.
385 // Do not process if value has not changed.
386 if ($postedDuration == $existingDuration)
388 // Posted value is different.
389 if ($existingDuration == null) {
390 // Insert a new record here.
392 $result = ttTimeHelper::insertDurationFromWeekView($fields, $err);
393 //$dataArray[$rowNumber]['row_id'],
396 //$startDate->toString(DB_DATEFORMAT));
397 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
398 // Delete an already existing record here.
399 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
402 $result = ttTimeHelper::modifyDurationFromWeekView($fields, $err);
403 //$result = ttTimeHelper::modifyDurationFromWeekView($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $postedDuration, $user->getActiveUser());
405 if (!$result) break; // Break out of the loop in case of first error.
407 if (!$result) break; // Break out of the loop in case of first error.
411 header('Location: week.php'); // Normal exit.
414 $err->add($i18n->getKey('error.db'));
421 $id = ttTimeHelper::insert(array(
423 'user_id' => $user->getActiveUser(),
424 'client' => $cl_client,
425 'project' => $cl_project,
427 'start' => $cl_start,
428 'finish' => $cl_finish,
429 'duration' => $cl_duration,
431 'billable' => $cl_billable));
433 // Insert a custom field if we have it.
435 if ($id && $custom_fields && $cl_cf_1) {
436 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
437 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
438 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
439 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
441 if ($id && $result) {
442 header('Location: time.php');
445 $err->add($i18n->getKey('error.db'));
447 } elseif ($request->getParameter('btn_stop')) {
448 // Stop button pressed to finish an uncompleted record.
449 $record_id = $request->getParameter('record_id');
450 $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
451 $browser_date = $request->getParameter('browser_date');
452 $browser_time = $request->getParameter('browser_time');
454 // Can we complete this record?
455 if ($record['date'] == $browser_date // closing today's record
456 && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
457 && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
458 $res = ttTimeHelper::update(array(
460 'date'=>$record['date'],
461 'user_id'=>$user->getActiveUser(),
462 'client'=>$record['client_id'],
463 'project'=>$record['project_id'],
464 'task'=>$record['task_id'],
465 'start'=>$record['start'],
466 'finish'=>$browser_time,
467 'note'=>$record['comment'],
468 'billable'=>$record['billable']));
470 $err->add($i18n->getKey('error.db'));
472 // Cannot complete, redirect for manual edit.
473 header('Location: time_edit.php?id='.$record_id);
477 elseif ($request->getParameter('onBehalfUser')) {
478 if($user->canManageTeam()) {
479 unset($_SESSION['behalf_id']);
480 unset($_SESSION['behalf_name']);
482 if($on_behalf_id != $user->id) {
483 $_SESSION['behalf_id'] = $on_behalf_id;
484 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
486 header('Location: week.php');
492 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
494 $smarty->assign('selected_date', $selected_date);
495 $smarty->assign('week_total', $week_total);
497 $smarty->assign('client_list', $client_list);
498 $smarty->assign('project_list', $project_list);
499 $smarty->assign('task_list', $task_list);
500 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
501 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
502 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
504 $smarty->assign('title', $i18n->getKey('title.time'));
505 $smarty->assign('content_page_name', 'week.tpl');
506 $smarty->display('index.tpl');