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->setHeaderOptions(array('align'=>'center')); // TODO: use a class and CSS instead, perhaps a separate class for footer.
213 $table->setRowOptions(array('valign'=>'top','class'=>'tableHeader'));
214 $table->setData($dataArray); // $durations_with_labels);
215 // Add columns to table.
216 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
217 $table->addColumn(new TableColumn($dayHeaders['day_header_0'], $dayHeaders['day_header_0'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_0']]));
218 $table->addColumn(new TableColumn($dayHeaders['day_header_1'], $dayHeaders['day_header_1'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_1']]));
219 $table->addColumn(new TableColumn($dayHeaders['day_header_2'], $dayHeaders['day_header_2'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_2']]));
220 $table->addColumn(new TableColumn($dayHeaders['day_header_3'], $dayHeaders['day_header_3'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_3']]));
221 $table->addColumn(new TableColumn($dayHeaders['day_header_4'], $dayHeaders['day_header_4'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_4']]));
222 $table->addColumn(new TableColumn($dayHeaders['day_header_5'], $dayHeaders['day_header_5'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_5']]));
223 $table->addColumn(new TableColumn($dayHeaders['day_header_6'], $dayHeaders['day_header_6'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_6']]));
224 $table->setInteractive(false);
225 $form->addInputElement($table);
228 // Dropdown for clients in MODE_TIME. Use all active clients.
229 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
230 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
231 $form->addInput(array('type'=>'combobox',
232 'onchange'=>'fillProjectDropdown(this.value);',
234 'style'=>'width: 250px;',
236 'data'=>$active_clients,
237 'datakeys'=>array('id', 'name'),
238 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
239 // Note: in other modes the client list is filtered to relevant clients only. See below.
242 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
243 // Dropdown for projects assigned to user.
244 $project_list = $user->getAssignedProjects();
245 $form->addInput(array('type'=>'combobox',
246 'onchange'=>'fillTaskDropdown(this.value);',
248 'style'=>'width: 250px;',
249 'value'=>$cl_project,
250 'data'=>$project_list,
251 'datakeys'=>array('id','name'),
252 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
254 // Dropdown for clients if the clients plugin is enabled.
255 if ($user->isPluginEnabled('cl')) {
256 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
257 // We need an array of assigned project ids to do some trimming.
258 foreach($project_list as $project)
259 $projects_assigned_to_user[] = $project['id'];
261 // Build a client list out of active clients. Use only clients that are relevant to user.
262 // Also trim their associated project list to only assigned projects (to user).
263 foreach($active_clients as $client) {
264 $projects_assigned_to_client = explode(',', $client['projects']);
265 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
266 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
268 $client['projects'] = implode(',', $intersection);
269 $client_list[] = $client;
272 $form->addInput(array('type'=>'combobox',
273 'onchange'=>'fillProjectDropdown(this.value);',
275 'style'=>'width: 250px;',
277 'data'=>$client_list,
278 'datakeys'=>array('id', 'name'),
279 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
283 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
284 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
285 $form->addInput(array('type'=>'combobox',
287 'style'=>'width: 250px;',
290 'datakeys'=>array('id','name'),
291 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
294 // Add other controls.
295 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
296 $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
297 $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
298 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
299 // Make the start and finish fields read-only.
300 $form->getElement('start')->setEnabled(false);
301 $form->getElement('finish')->setEnabled(false);
304 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
305 $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
306 if (!defined('NOTE_INPUT_HEIGHT'))
307 define('NOTE_INPUT_HEIGHT', 40);
308 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
309 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
310 if ($user->isPluginEnabled('iv'))
311 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
312 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
313 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
315 // If we have custom fields - add controls for them.
316 if ($custom_fields && $custom_fields->fields[0]) {
317 // Only one custom field is supported at this time.
318 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
319 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
320 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
321 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
322 'style'=>'width: 250px;',
324 'data'=>$custom_fields->options,
325 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
330 if ($request->isPost()) {
331 if ($request->getParameter('btn_submit')) {
333 // Validate user input.
334 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
335 $err->add($i18n->getKey('error.client'));
336 if ($custom_fields) {
337 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
339 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
340 if (!$cl_project) $err->add($i18n->getKey('error.project'));
342 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
343 if (!$cl_task) $err->add($i18n->getKey('error.task'));
345 if (strlen($cl_duration) == 0) {
346 if ($cl_start || $cl_finish) {
347 if (!ttTimeHelper::isValidTime($cl_start))
348 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
350 if (!ttTimeHelper::isValidTime($cl_finish))
351 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
352 if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
353 $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
356 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
357 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
358 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
360 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
361 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
364 if (!ttTimeHelper::isValidDuration($cl_duration))
365 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
367 if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
368 // Finished validating user input.
370 // Prohibit creating entries in future.
371 if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
372 $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
373 if ($selected_date->after($browser_today))
374 $err->add($i18n->getKey('error.future_date'));
377 // Prohibit creating entries in locked range.
378 if ($user->isDateLocked($selected_date))
379 $err->add($i18n->getKey('error.range_locked'));
381 // Prohibit creating another uncompleted record.
383 if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
384 $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
387 // Prohibit creating an overlapping record.
389 if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
390 $err->add($i18n->getKey('error.overlap'));
395 $id = ttTimeHelper::insert(array(
397 'user_id' => $user->getActiveUser(),
398 'client' => $cl_client,
399 'project' => $cl_project,
401 'start' => $cl_start,
402 'finish' => $cl_finish,
403 'duration' => $cl_duration,
405 'billable' => $cl_billable));
407 // Insert a custom field if we have it.
409 if ($id && $custom_fields && $cl_cf_1) {
410 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
411 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
412 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
413 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
415 if ($id && $result) {
416 header('Location: time.php');
419 $err->add($i18n->getKey('error.db'));
421 } elseif ($request->getParameter('btn_stop')) {
422 // Stop button pressed to finish an uncompleted record.
423 $record_id = $request->getParameter('record_id');
424 $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
425 $browser_date = $request->getParameter('browser_date');
426 $browser_time = $request->getParameter('browser_time');
428 // Can we complete this record?
429 if ($record['date'] == $browser_date // closing today's record
430 && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
431 && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
432 $res = ttTimeHelper::update(array(
434 'date'=>$record['date'],
435 'user_id'=>$user->getActiveUser(),
436 'client'=>$record['client_id'],
437 'project'=>$record['project_id'],
438 'task'=>$record['task_id'],
439 'start'=>$record['start'],
440 'finish'=>$browser_time,
441 'note'=>$record['comment'],
442 'billable'=>$record['billable']));
444 $err->add($i18n->getKey('error.db'));
446 // Cannot complete, redirect for manual edit.
447 header('Location: time_edit.php?id='.$record_id);
451 elseif ($request->getParameter('onBehalfUser')) {
452 if($user->canManageTeam()) {
453 unset($_SESSION['behalf_id']);
454 unset($_SESSION['behalf_name']);
456 if($on_behalf_id != $user->id) {
457 $_SESSION['behalf_id'] = $on_behalf_id;
458 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
460 header('Location: week.php');
466 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
470 $smarty->assign('selected_date', $selected_date);
471 $smarty->assign('week_total', $week_total);
472 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($user->getActiveUser(), $cl_date));
473 //$groupedRecords = ttTimeHelper::getGroupedRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
474 //$smarty->assign('grouped_records', $groupedRecords);
475 //$smarty->assign('grouped_records_totals', ttTimeHelper::getGroupedRecordsTotals($groupedRecords));
477 $smarty->assign('client_list', $client_list);
478 $smarty->assign('project_list', $project_list);
479 $smarty->assign('task_list', $task_list);
480 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
481 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
482 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
484 // Prepare and assign date headers. Note how startDate moves to the end of the week, so it no longer holds correct start week value.
485 $smarty->assign('date_0', $startDate->toString(DB_DATEFORMAT));
486 $smarty->assign('day_header_0', $startDate->getDate());
487 $startDate->incDay();
488 $smarty->assign('date_1', $startDate->toString(DB_DATEFORMAT));
489 $smarty->assign('day_header_1', $startDate->getDate());
490 $startDate->incDay();
491 $smarty->assign('date_2', $startDate->toString(DB_DATEFORMAT));
492 $smarty->assign('day_header_2', $startDate->getDate());
493 $startDate->incDay();
494 $smarty->assign('date_3', $startDate->toString(DB_DATEFORMAT));
495 $smarty->assign('day_header_3', $startDate->getDate());
496 $startDate->incDay();
497 $smarty->assign('date_4', $startDate->toString(DB_DATEFORMAT));
498 $smarty->assign('day_header_4', $startDate->getDate());
499 $startDate->incDay();
500 $smarty->assign('date_5', $startDate->toString(DB_DATEFORMAT));
501 $smarty->assign('day_header_5', $startDate->getDate());
502 $startDate->incDay();
503 $smarty->assign('date_6', $startDate->toString(DB_DATEFORMAT));
504 $smarty->assign('day_header_6', $startDate->getDate());
506 $smarty->assign('title', $i18n->getKey('title.time'));
507 $smarty->assign('content_page_name', 'week.tpl');
508 $smarty->display('index.tpl');