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 // Get column headers.
69 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
71 // TODO: replace these two sample arrays with real data.
72 $durations_with_labels = array(
74 'id' => 'something goes here too', // Row identifier.
75 'label' => 'This is a label for row 0',
76 'day_0' => array('id' => '0_0', 'duration' => '00:00'),
77 'day_1' => array('id' => '0_1', 'duration' => '01:00'),
78 'day_2' => array('id' => '0_2', 'duration' => '02:00'),
79 'day_3' => array('id' => '0_3', 'duration' => null),
80 'day_4' => array('id' => '0_4', 'duration' => '04:00')
83 'label' => 'This is a label for row 1',
84 'day_0' => array('id' => '1_0', 'duration' => '00:30'),
85 'day_1' => array('id' => '1_1', 'duration' => '01:30'),
86 'day_2' => array('id' => '1_2', 'duration' => '02:30'),
101 // Define rendering class for a label field to the left of durations.
102 class LabelCellRenderer extends DefaultCellRenderer {
103 function render(&$table, $value, $row, $column, $selected = false) {
104 $this->setOptions(array('width'=>200,'valign'=>'middle'));
105 $this->setValue(htmlspecialchars($value));
106 return $this->toString();
110 // Define rendering class for a single cell for time entry in week view table.
111 class TimeCellRenderer extends DefaultCellRenderer {
112 function render(&$table, $value, $row, $column, $selected = false) {
113 $field_name = $table->getValueAtName($row,$column)['id']; // Our text field names (and ids) are like x_y (row_column).
114 $field = new TextField($field_name);
115 $field->setFormName($table->getFormName());
117 $field->setValue($table->getValueAt($row,$column)['duration']);
118 $this->setValue($field->getHtml());
119 return $this->toString();
128 //$durations = ttTimeHelper::getDurationsForWeek($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
132 $groupedRecords = ttTimeHelper::getGroupedRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
138 $dayTotals = ttTimeHelper::getGroupedRecordsTotals($groupedRecords);
140 // Use custom fields plugin if it is enabled.
141 if ($user->isPluginEnabled('cf')) {
142 require_once('plugins/CustomFields.class.php');
143 $custom_fields = new CustomFields($user->team_id);
144 $smarty->assign('custom_fields', $custom_fields);
147 // TODO: how is this plugin supposed to work for week view?
148 if ($user->isPluginEnabled('mq')){
149 require_once('plugins/MonthlyQuota.class.php');
150 $quota = new MonthlyQuota();
151 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
152 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
153 $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
155 $smarty->assign('month_total', $month_total);
156 $smarty->assign('over_quota', $minutes_left < 0);
157 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
160 // Initialize variables.
161 $cl_start = trim($request->getParameter('start'));
162 $cl_finish = trim($request->getParameter('finish'));
163 $cl_duration = trim($request->getParameter('duration'));
164 $cl_note = trim($request->getParameter('note'));
166 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
167 $_SESSION['cf_1'] = $cl_cf_1;
169 if ($user->isPluginEnabled('iv')) {
170 if ($request->isPost()) {
171 $cl_billable = $request->getParameter('billable');
172 $_SESSION['billable'] = (int) $cl_billable;
174 if (isset($_SESSION['billable']))
175 $cl_billable = $_SESSION['billable'];
177 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
178 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
179 $_SESSION['client'] = $cl_client;
180 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
181 $_SESSION['project'] = $cl_project;
182 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
183 $_SESSION['task'] = $cl_task;
185 // Elements of weekTimeForm.
186 $form = new Form('weekTimeForm');
188 if ($user->canManageTeam()) {
189 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
190 if (count($user_list) > 1) {
191 $form->addInput(array('type'=>'combobox',
192 'onchange'=>'this.form.submit();',
193 'name'=>'onBehalfUser',
194 'style'=>'width: 250px;',
195 'value'=>$on_behalf_id,
197 'datakeys'=>array('id','name')));
198 $smarty->assign('on_behalf_control', 1);
202 // Create week_durations table.
203 $table = new Table('week_durations');
204 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
205 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
206 $table->setRowOptions(array('valign'=>'top','class'=>'tableHeader'));
207 $table->setData($durations_with_labels);
208 // Add columns to table.
209 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $totals['label']));
210 $table->addColumn(new TableColumn('day_0', $dayHeaders['day_header_0'], new TimeCellRenderer(), $totals['day_0']));
211 $table->addColumn(new TableColumn('day_1', $dayHeaders['day_header_1'], new TimeCellRenderer(), $totals['day_1']));
212 $table->addColumn(new TableColumn('day_2', $dayHeaders['day_header_2'], new TimeCellRenderer(), $totals['day_2']));
213 $table->addColumn(new TableColumn('day_3', $dayHeaders['day_header_3'], new TimeCellRenderer(), $totals['day_3']));
214 $table->addColumn(new TableColumn('day_4', $dayHeaders['day_header_4'], new TimeCellRenderer(), $totals['day_4']));
215 $table->addColumn(new TableColumn('day_5', $dayHeaders['day_header_5'], new TimeCellRenderer()));
216 $table->addColumn(new TableColumn('day_6', $dayHeaders['day_header_6'], new TimeCellRenderer()));
217 $table->setInteractive(false);
218 $form->addInputElement($table);
221 // Dropdown for clients in MODE_TIME. Use all active clients.
222 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
223 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
224 $form->addInput(array('type'=>'combobox',
225 'onchange'=>'fillProjectDropdown(this.value);',
227 'style'=>'width: 250px;',
229 'data'=>$active_clients,
230 'datakeys'=>array('id', 'name'),
231 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
232 // Note: in other modes the client list is filtered to relevant clients only. See below.
235 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
236 // Dropdown for projects assigned to user.
237 $project_list = $user->getAssignedProjects();
238 $form->addInput(array('type'=>'combobox',
239 'onchange'=>'fillTaskDropdown(this.value);',
241 'style'=>'width: 250px;',
242 'value'=>$cl_project,
243 'data'=>$project_list,
244 'datakeys'=>array('id','name'),
245 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
247 // Dropdown for clients if the clients plugin is enabled.
248 if ($user->isPluginEnabled('cl')) {
249 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
250 // We need an array of assigned project ids to do some trimming.
251 foreach($project_list as $project)
252 $projects_assigned_to_user[] = $project['id'];
254 // Build a client list out of active clients. Use only clients that are relevant to user.
255 // Also trim their associated project list to only assigned projects (to user).
256 foreach($active_clients as $client) {
257 $projects_assigned_to_client = explode(',', $client['projects']);
258 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
259 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
261 $client['projects'] = implode(',', $intersection);
262 $client_list[] = $client;
265 $form->addInput(array('type'=>'combobox',
266 'onchange'=>'fillProjectDropdown(this.value);',
268 'style'=>'width: 250px;',
270 'data'=>$client_list,
271 'datakeys'=>array('id', 'name'),
272 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
276 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
277 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
278 $form->addInput(array('type'=>'combobox',
280 'style'=>'width: 250px;',
283 'datakeys'=>array('id','name'),
284 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
287 // Add other controls.
288 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
289 $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
290 $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
291 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
292 // Make the start and finish fields read-only.
293 $form->getElement('start')->setEnabled(false);
294 $form->getElement('finish')->setEnabled(false);
297 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
298 $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
299 if (!defined('NOTE_INPUT_HEIGHT'))
300 define('NOTE_INPUT_HEIGHT', 40);
301 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
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'=>'')); // 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->getKey('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->getKey('dropdown.select'))));
323 if ($request->isPost()) {
324 if ($request->getParameter('btn_submit')) {
326 // Validate user input.
327 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
328 $err->add($i18n->getKey('error.client'));
329 if ($custom_fields) {
330 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
332 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
333 if (!$cl_project) $err->add($i18n->getKey('error.project'));
335 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
336 if (!$cl_task) $err->add($i18n->getKey('error.task'));
338 if (strlen($cl_duration) == 0) {
339 if ($cl_start || $cl_finish) {
340 if (!ttTimeHelper::isValidTime($cl_start))
341 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
343 if (!ttTimeHelper::isValidTime($cl_finish))
344 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
345 if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
346 $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
349 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
350 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
351 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
353 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
354 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
357 if (!ttTimeHelper::isValidDuration($cl_duration))
358 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
360 if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
361 // Finished validating user input.
363 // Prohibit creating entries in future.
364 if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
365 $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
366 if ($selected_date->after($browser_today))
367 $err->add($i18n->getKey('error.future_date'));
370 // Prohibit creating entries in locked range.
371 if ($user->isDateLocked($selected_date))
372 $err->add($i18n->getKey('error.range_locked'));
374 // Prohibit creating another uncompleted record.
376 if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
377 $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
380 // Prohibit creating an overlapping record.
382 if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
383 $err->add($i18n->getKey('error.overlap'));
388 $id = ttTimeHelper::insert(array(
390 'user_id' => $user->getActiveUser(),
391 'client' => $cl_client,
392 'project' => $cl_project,
394 'start' => $cl_start,
395 'finish' => $cl_finish,
396 'duration' => $cl_duration,
398 'billable' => $cl_billable));
400 // Insert a custom field if we have it.
402 if ($id && $custom_fields && $cl_cf_1) {
403 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
404 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
405 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
406 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
408 if ($id && $result) {
409 header('Location: time.php');
412 $err->add($i18n->getKey('error.db'));
414 } elseif ($request->getParameter('btn_stop')) {
415 // Stop button pressed to finish an uncompleted record.
416 $record_id = $request->getParameter('record_id');
417 $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
418 $browser_date = $request->getParameter('browser_date');
419 $browser_time = $request->getParameter('browser_time');
421 // Can we complete this record?
422 if ($record['date'] == $browser_date // closing today's record
423 && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
424 && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
425 $res = ttTimeHelper::update(array(
427 'date'=>$record['date'],
428 'user_id'=>$user->getActiveUser(),
429 'client'=>$record['client_id'],
430 'project'=>$record['project_id'],
431 'task'=>$record['task_id'],
432 'start'=>$record['start'],
433 'finish'=>$browser_time,
434 'note'=>$record['comment'],
435 'billable'=>$record['billable']));
437 $err->add($i18n->getKey('error.db'));
439 // Cannot complete, redirect for manual edit.
440 header('Location: time_edit.php?id='.$record_id);
444 elseif ($request->getParameter('onBehalfUser')) {
445 if($user->canManageTeam()) {
446 unset($_SESSION['behalf_id']);
447 unset($_SESSION['behalf_name']);
449 if($on_behalf_id != $user->id) {
450 $_SESSION['behalf_id'] = $on_behalf_id;
451 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
453 header('Location: week.php');
459 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
463 $smarty->assign('selected_date', $selected_date);
464 $smarty->assign('week_total', $week_total);
465 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($user->getActiveUser(), $cl_date));
466 //$groupedRecords = ttTimeHelper::getGroupedRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
467 $smarty->assign('grouped_records', $groupedRecords);
468 $smarty->assign('grouped_records_totals', ttTimeHelper::getGroupedRecordsTotals($groupedRecords));
470 $smarty->assign('client_list', $client_list);
471 $smarty->assign('project_list', $project_list);
472 $smarty->assign('task_list', $task_list);
473 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
474 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
475 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
477 // Prepare and assign date headers. Note how startDate moves to the end of the week, so it no longer holds correct start week value.
478 $smarty->assign('date_0', $startDate->toString(DB_DATEFORMAT));
479 $smarty->assign('day_header_0', $startDate->getDate());
480 $startDate->incDay();
481 $smarty->assign('date_1', $startDate->toString(DB_DATEFORMAT));
482 $smarty->assign('day_header_1', $startDate->getDate());
483 $startDate->incDay();
484 $smarty->assign('date_2', $startDate->toString(DB_DATEFORMAT));
485 $smarty->assign('day_header_2', $startDate->getDate());
486 $startDate->incDay();
487 $smarty->assign('date_3', $startDate->toString(DB_DATEFORMAT));
488 $smarty->assign('day_header_3', $startDate->getDate());
489 $startDate->incDay();
490 $smarty->assign('date_4', $startDate->toString(DB_DATEFORMAT));
491 $smarty->assign('day_header_4', $startDate->getDate());
492 $startDate->incDay();
493 $smarty->assign('date_5', $startDate->toString(DB_DATEFORMAT));
494 $smarty->assign('day_header_5', $startDate->getDate());
495 $startDate->incDay();
496 $smarty->assign('date_6', $startDate->toString(DB_DATEFORMAT));
497 $smarty->assign('day_header_6', $startDate->getDate());
499 $smarty->assign('title', $i18n->getKey('title.time'));
500 $smarty->assign('content_page_name', 'week.tpl');
501 $smarty->display('index.tpl');