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;
120 // Get column headers.
121 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
122 // Build data array for the table.
123 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
125 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
127 // TODO: replace these two sample arrays with real data.
128 $durations_with_labels = array(
130 'id' => 'something goes here too', // Row identifier.
131 'label' => 'This is a label for row 0',
132 'day_0' => array('id' => '0_0', 'duration' => '00:00'),
133 'day_1' => array('id' => '0_1', 'duration' => '01:00'),
134 'day_2' => array('id' => '0_2', 'duration' => '02:00'),
135 'day_3' => array('id' => '0_3', 'duration' => null),
136 'day_4' => array('id' => '0_4', 'duration' => '04:00')
139 'label' => 'This is a label for row 1',
140 'day_0' => array('id' => '1_0', 'duration' => '00:30'),
141 'day_1' => array('id' => '1_1', 'duration' => '01:30'),
142 'day_2' => array('id' => '1_2', 'duration' => '02:30'),
157 // Define rendering class for a label field to the left of durations.
158 class LabelCellRenderer extends DefaultCellRenderer {
159 function render(&$table, $value, $row, $column, $selected = false) {
160 $this->setOptions(array('width'=>200,'valign'=>'middle'));
161 $this->setValue(htmlspecialchars($value));
162 return $this->toString();
166 // Define rendering class for a single cell for time entry in week view table.
167 class TimeCellRenderer extends DefaultCellRenderer {
168 function render(&$table, $value, $row, $column, $selected = false) {
169 $field_name = $table->getValueAtName($row,$column)['id']; // Our text field names (and ids) are like x_y (row_column).
170 $field = new TextField($field_name);
171 $field->setFormName($table->getFormName());
173 $field->setValue($table->getValueAt($row,$column)['duration']);
174 $this->setValue($field->getHtml());
175 return $this->toString();
179 //$durations = ttTimeHelper::getDurationsForWeek($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
183 //$groupedRecords = ttTimeHelper::getGroupedRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
184 //$dayTotals = ttTimeHelper::getGroupedRecordsTotals($groupedRecords);
191 // Elements of weekTimeForm.
192 $form = new Form('weekTimeForm');
194 if ($user->canManageTeam()) {
195 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
196 if (count($user_list) > 1) {
197 $form->addInput(array('type'=>'combobox',
198 'onchange'=>'this.form.submit();',
199 'name'=>'onBehalfUser',
200 'style'=>'width: 250px;',
201 'value'=>$on_behalf_id,
203 'datakeys'=>array('id','name')));
204 $smarty->assign('on_behalf_control', 1);
208 // Create week_durations table.
209 $table = new Table('week_durations');
210 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
211 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
212 $table->setRowOptions(array('valign'=>'top','class'=>'tableHeader'));
213 $table->setData($dataArray); // $durations_with_labels);
214 // Add columns to table.
215 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
216 $table->addColumn(new TableColumn($dayHeaders['day_header_0'], $dayHeaders['day_header_0'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_0']]));
217 $table->addColumn(new TableColumn($dayHeaders['day_header_1'], $dayHeaders['day_header_1'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_1']]));
218 $table->addColumn(new TableColumn($dayHeaders['day_header_2'], $dayHeaders['day_header_2'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_2']]));
219 $table->addColumn(new TableColumn($dayHeaders['day_header_3'], $dayHeaders['day_header_3'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_3']]));
220 $table->addColumn(new TableColumn($dayHeaders['day_header_4'], $dayHeaders['day_header_4'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_4']]));
221 $table->addColumn(new TableColumn($dayHeaders['day_header_5'], $dayHeaders['day_header_5'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_5']]));
222 $table->addColumn(new TableColumn($dayHeaders['day_header_6'], $dayHeaders['day_header_6'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_6']]));
223 $table->setInteractive(false);
224 $form->addInputElement($table);
227 // Dropdown for clients in MODE_TIME. Use all active clients.
228 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
229 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
230 $form->addInput(array('type'=>'combobox',
231 'onchange'=>'fillProjectDropdown(this.value);',
233 'style'=>'width: 250px;',
235 'data'=>$active_clients,
236 'datakeys'=>array('id', 'name'),
237 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
238 // Note: in other modes the client list is filtered to relevant clients only. See below.
241 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
242 // Dropdown for projects assigned to user.
243 $project_list = $user->getAssignedProjects();
244 $form->addInput(array('type'=>'combobox',
245 'onchange'=>'fillTaskDropdown(this.value);',
247 'style'=>'width: 250px;',
248 'value'=>$cl_project,
249 'data'=>$project_list,
250 'datakeys'=>array('id','name'),
251 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
253 // Dropdown for clients if the clients plugin is enabled.
254 if ($user->isPluginEnabled('cl')) {
255 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
256 // We need an array of assigned project ids to do some trimming.
257 foreach($project_list as $project)
258 $projects_assigned_to_user[] = $project['id'];
260 // Build a client list out of active clients. Use only clients that are relevant to user.
261 // Also trim their associated project list to only assigned projects (to user).
262 foreach($active_clients as $client) {
263 $projects_assigned_to_client = explode(',', $client['projects']);
264 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
265 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
267 $client['projects'] = implode(',', $intersection);
268 $client_list[] = $client;
271 $form->addInput(array('type'=>'combobox',
272 'onchange'=>'fillProjectDropdown(this.value);',
274 'style'=>'width: 250px;',
276 'data'=>$client_list,
277 'datakeys'=>array('id', 'name'),
278 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
282 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
283 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
284 $form->addInput(array('type'=>'combobox',
286 'style'=>'width: 250px;',
289 'datakeys'=>array('id','name'),
290 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
293 // Add other controls.
294 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
295 $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
296 $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
297 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
298 // Make the start and finish fields read-only.
299 $form->getElement('start')->setEnabled(false);
300 $form->getElement('finish')->setEnabled(false);
303 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
304 $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
305 if (!defined('NOTE_INPUT_HEIGHT'))
306 define('NOTE_INPUT_HEIGHT', 40);
307 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
308 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
309 if ($user->isPluginEnabled('iv'))
310 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
311 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
312 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
314 // If we have custom fields - add controls for them.
315 if ($custom_fields && $custom_fields->fields[0]) {
316 // Only one custom field is supported at this time.
317 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
318 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
319 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
320 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
321 'style'=>'width: 250px;',
323 'data'=>$custom_fields->options,
324 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
329 if ($request->isPost()) {
330 if ($request->getParameter('btn_submit')) {
332 // Validate user input.
333 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
334 $err->add($i18n->getKey('error.client'));
335 if ($custom_fields) {
336 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
338 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
339 if (!$cl_project) $err->add($i18n->getKey('error.project'));
341 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
342 if (!$cl_task) $err->add($i18n->getKey('error.task'));
344 if (strlen($cl_duration) == 0) {
345 if ($cl_start || $cl_finish) {
346 if (!ttTimeHelper::isValidTime($cl_start))
347 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
349 if (!ttTimeHelper::isValidTime($cl_finish))
350 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
351 if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
352 $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
355 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
356 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
357 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
359 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
360 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
363 if (!ttTimeHelper::isValidDuration($cl_duration))
364 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
366 if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
367 // Finished validating user input.
369 // Prohibit creating entries in future.
370 if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
371 $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
372 if ($selected_date->after($browser_today))
373 $err->add($i18n->getKey('error.future_date'));
376 // Prohibit creating entries in locked range.
377 if ($user->isDateLocked($selected_date))
378 $err->add($i18n->getKey('error.range_locked'));
380 // Prohibit creating another uncompleted record.
382 if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
383 $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
386 // Prohibit creating an overlapping record.
388 if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
389 $err->add($i18n->getKey('error.overlap'));
394 $id = ttTimeHelper::insert(array(
396 'user_id' => $user->getActiveUser(),
397 'client' => $cl_client,
398 'project' => $cl_project,
400 'start' => $cl_start,
401 'finish' => $cl_finish,
402 'duration' => $cl_duration,
404 'billable' => $cl_billable));
406 // Insert a custom field if we have it.
408 if ($id && $custom_fields && $cl_cf_1) {
409 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
410 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
411 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
412 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
414 if ($id && $result) {
415 header('Location: time.php');
418 $err->add($i18n->getKey('error.db'));
420 } elseif ($request->getParameter('btn_stop')) {
421 // Stop button pressed to finish an uncompleted record.
422 $record_id = $request->getParameter('record_id');
423 $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
424 $browser_date = $request->getParameter('browser_date');
425 $browser_time = $request->getParameter('browser_time');
427 // Can we complete this record?
428 if ($record['date'] == $browser_date // closing today's record
429 && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
430 && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
431 $res = ttTimeHelper::update(array(
433 'date'=>$record['date'],
434 'user_id'=>$user->getActiveUser(),
435 'client'=>$record['client_id'],
436 'project'=>$record['project_id'],
437 'task'=>$record['task_id'],
438 'start'=>$record['start'],
439 'finish'=>$browser_time,
440 'note'=>$record['comment'],
441 'billable'=>$record['billable']));
443 $err->add($i18n->getKey('error.db'));
445 // Cannot complete, redirect for manual edit.
446 header('Location: time_edit.php?id='.$record_id);
450 elseif ($request->getParameter('onBehalfUser')) {
451 if($user->canManageTeam()) {
452 unset($_SESSION['behalf_id']);
453 unset($_SESSION['behalf_name']);
455 if($on_behalf_id != $user->id) {
456 $_SESSION['behalf_id'] = $on_behalf_id;
457 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
459 header('Location: week.php');
465 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
469 $smarty->assign('selected_date', $selected_date);
470 $smarty->assign('week_total', $week_total);
471 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($user->getActiveUser(), $cl_date));
472 //$groupedRecords = ttTimeHelper::getGroupedRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
473 //$smarty->assign('grouped_records', $groupedRecords);
474 //$smarty->assign('grouped_records_totals', ttTimeHelper::getGroupedRecordsTotals($groupedRecords));
476 $smarty->assign('client_list', $client_list);
477 $smarty->assign('project_list', $project_list);
478 $smarty->assign('task_list', $task_list);
479 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
480 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
481 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
483 // Prepare and assign date headers. Note how startDate moves to the end of the week, so it no longer holds correct start week value.
484 $smarty->assign('date_0', $startDate->toString(DB_DATEFORMAT));
485 $smarty->assign('day_header_0', $startDate->getDate());
486 $startDate->incDay();
487 $smarty->assign('date_1', $startDate->toString(DB_DATEFORMAT));
488 $smarty->assign('day_header_1', $startDate->getDate());
489 $startDate->incDay();
490 $smarty->assign('date_2', $startDate->toString(DB_DATEFORMAT));
491 $smarty->assign('day_header_2', $startDate->getDate());
492 $startDate->incDay();
493 $smarty->assign('date_3', $startDate->toString(DB_DATEFORMAT));
494 $smarty->assign('day_header_3', $startDate->getDate());
495 $startDate->incDay();
496 $smarty->assign('date_4', $startDate->toString(DB_DATEFORMAT));
497 $smarty->assign('day_header_4', $startDate->getDate());
498 $startDate->incDay();
499 $smarty->assign('date_5', $startDate->toString(DB_DATEFORMAT));
500 $smarty->assign('day_header_5', $startDate->getDate());
501 $startDate->incDay();
502 $smarty->assign('date_6', $startDate->toString(DB_DATEFORMAT));
503 $smarty->assign('day_header_6', $startDate->getDate());
505 $smarty->assign('title', $i18n->getKey('title.time'));
506 $smarty->assign('content_page_name', 'week.tpl');
507 $smarty->display('index.tpl');