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 // Build data array for the table. Format is described in the function..
113 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
114 // Build day totals (total durations for each day in week).
115 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
117 // TODO: refactoring ongoing down from here.
119 // Actually this is work in progress at this point, even documenting the array, as we still miss control IDs, and
120 // editing entries is not yet implemented. When this is done, we will have to re-document the above.
123 // 1) make sure we have IDs for cells, which are now missing.
125 // Define rendering class for a label field to the left of durations.
126 class LabelCellRenderer extends DefaultCellRenderer {
127 function render(&$table, $value, $row, $column, $selected = false) {
128 $this->setOptions(array('width'=>200,'valign'=>'middle'));
129 $this->setValue(htmlspecialchars($value));
130 return $this->toString();
134 // Define rendering class for a single cell for time entry in week view table.
135 class TimeCellRenderer extends DefaultCellRenderer {
136 function render(&$table, $value, $row, $column, $selected = false) {
137 $field_name = $table->getValueAt($row,$column)['id']; // Our text field names (and ids) are like x_y (row_column).
138 $field = new TextField($field_name);
139 $field->setFormName($table->getFormName());
141 $field->setValue($table->getValueAt($row,$column)['duration']);
142 $this->setValue($field->getHtml());
143 return $this->toString();
147 // Elements of weekTimeForm.
148 $form = new Form('weekTimeForm');
150 if ($user->canManageTeam()) {
151 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
152 if (count($user_list) > 1) {
153 $form->addInput(array('type'=>'combobox',
154 'onchange'=>'this.form.submit();',
155 'name'=>'onBehalfUser',
156 'style'=>'width: 250px;',
157 'value'=>$on_behalf_id,
159 'datakeys'=>array('id','name')));
160 $smarty->assign('on_behalf_control', 1);
164 // Create week_durations table.
165 $table = new Table('week_durations');
166 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
167 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
168 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
169 $table->setData($dataArray);
170 // Add columns to table.
171 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
172 $table->addColumn(new TableColumn($dayHeaders['day_header_0'], $dayHeaders['day_header_0'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_0']]));
173 $table->addColumn(new TableColumn($dayHeaders['day_header_1'], $dayHeaders['day_header_1'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_1']]));
174 $table->addColumn(new TableColumn($dayHeaders['day_header_2'], $dayHeaders['day_header_2'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_2']]));
175 $table->addColumn(new TableColumn($dayHeaders['day_header_3'], $dayHeaders['day_header_3'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_3']]));
176 $table->addColumn(new TableColumn($dayHeaders['day_header_4'], $dayHeaders['day_header_4'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_4']]));
177 $table->addColumn(new TableColumn($dayHeaders['day_header_5'], $dayHeaders['day_header_5'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_5']]));
178 $table->addColumn(new TableColumn($dayHeaders['day_header_6'], $dayHeaders['day_header_6'], new TimeCellRenderer(), $dayTotals[$dayHeaders['day_header_6']]));
179 $table->setInteractive(false);
180 $form->addInputElement($table);
182 // Dropdown for clients in MODE_TIME. Use all active clients.
183 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
184 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
185 $form->addInput(array('type'=>'combobox',
186 'onchange'=>'fillProjectDropdown(this.value);',
188 'style'=>'width: 250px;',
190 'data'=>$active_clients,
191 'datakeys'=>array('id', 'name'),
192 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
193 // Note: in other modes the client list is filtered to relevant clients only. See below.
196 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
197 // Dropdown for projects assigned to user.
198 $project_list = $user->getAssignedProjects();
199 $form->addInput(array('type'=>'combobox',
200 'onchange'=>'fillTaskDropdown(this.value);',
202 'style'=>'width: 250px;',
203 'value'=>$cl_project,
204 'data'=>$project_list,
205 'datakeys'=>array('id','name'),
206 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
208 // Dropdown for clients if the clients plugin is enabled.
209 if ($user->isPluginEnabled('cl')) {
210 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
211 // We need an array of assigned project ids to do some trimming.
212 foreach($project_list as $project)
213 $projects_assigned_to_user[] = $project['id'];
215 // Build a client list out of active clients. Use only clients that are relevant to user.
216 // Also trim their associated project list to only assigned projects (to user).
217 foreach($active_clients as $client) {
218 $projects_assigned_to_client = explode(',', $client['projects']);
219 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
220 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
222 $client['projects'] = implode(',', $intersection);
223 $client_list[] = $client;
226 $form->addInput(array('type'=>'combobox',
227 'onchange'=>'fillProjectDropdown(this.value);',
229 'style'=>'width: 250px;',
231 'data'=>$client_list,
232 'datakeys'=>array('id', 'name'),
233 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
237 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
238 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
239 $form->addInput(array('type'=>'combobox',
241 'style'=>'width: 250px;',
244 'datakeys'=>array('id','name'),
245 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
248 // Add other controls.
249 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
250 $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
251 $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
252 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
253 // Make the start and finish fields read-only.
254 $form->getElement('start')->setEnabled(false);
255 $form->getElement('finish')->setEnabled(false);
258 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
259 $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
260 if (!defined('NOTE_INPUT_HEIGHT'))
261 define('NOTE_INPUT_HEIGHT', 40);
262 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
263 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
264 if ($user->isPluginEnabled('iv'))
265 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
266 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
267 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
269 // If we have custom fields - add controls for them.
270 if ($custom_fields && $custom_fields->fields[0]) {
271 // Only one custom field is supported at this time.
272 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
273 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
274 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
275 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
276 'style'=>'width: 250px;',
278 'data'=>$custom_fields->options,
279 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
284 if ($request->isPost()) {
285 if ($request->getParameter('btn_submit')) {
287 // Validate user input.
288 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
289 $err->add($i18n->getKey('error.client'));
290 if ($custom_fields) {
291 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
293 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
294 if (!$cl_project) $err->add($i18n->getKey('error.project'));
296 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
297 if (!$cl_task) $err->add($i18n->getKey('error.task'));
299 if (strlen($cl_duration) == 0) {
300 if ($cl_start || $cl_finish) {
301 if (!ttTimeHelper::isValidTime($cl_start))
302 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
304 if (!ttTimeHelper::isValidTime($cl_finish))
305 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
306 if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
307 $err->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
310 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
311 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
312 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
314 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
315 $err->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
318 if (!ttTimeHelper::isValidDuration($cl_duration))
319 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
321 if (!ttValidString($cl_note, true)) $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
322 // Finished validating user input.
324 // Prohibit creating entries in future.
325 if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
326 $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
327 if ($selected_date->after($browser_today))
328 $err->add($i18n->getKey('error.future_date'));
331 // Prohibit creating entries in locked range.
332 if ($user->isDateLocked($selected_date))
333 $err->add($i18n->getKey('error.range_locked'));
335 // Prohibit creating another uncompleted record.
337 if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
338 $err->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
341 // Prohibit creating an overlapping record.
343 if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
344 $err->add($i18n->getKey('error.overlap'));
349 $id = ttTimeHelper::insert(array(
351 'user_id' => $user->getActiveUser(),
352 'client' => $cl_client,
353 'project' => $cl_project,
355 'start' => $cl_start,
356 'finish' => $cl_finish,
357 'duration' => $cl_duration,
359 'billable' => $cl_billable));
361 // Insert a custom field if we have it.
363 if ($id && $custom_fields && $cl_cf_1) {
364 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
365 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
366 elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
367 $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
369 if ($id && $result) {
370 header('Location: time.php');
373 $err->add($i18n->getKey('error.db'));
375 } elseif ($request->getParameter('btn_stop')) {
376 // Stop button pressed to finish an uncompleted record.
377 $record_id = $request->getParameter('record_id');
378 $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
379 $browser_date = $request->getParameter('browser_date');
380 $browser_time = $request->getParameter('browser_time');
382 // Can we complete this record?
383 if ($record['date'] == $browser_date // closing today's record
384 && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
385 && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
386 $res = ttTimeHelper::update(array(
388 'date'=>$record['date'],
389 'user_id'=>$user->getActiveUser(),
390 'client'=>$record['client_id'],
391 'project'=>$record['project_id'],
392 'task'=>$record['task_id'],
393 'start'=>$record['start'],
394 'finish'=>$browser_time,
395 'note'=>$record['comment'],
396 'billable'=>$record['billable']));
398 $err->add($i18n->getKey('error.db'));
400 // Cannot complete, redirect for manual edit.
401 header('Location: time_edit.php?id='.$record_id);
405 elseif ($request->getParameter('onBehalfUser')) {
406 if($user->canManageTeam()) {
407 unset($_SESSION['behalf_id']);
408 unset($_SESSION['behalf_name']);
410 if($on_behalf_id != $user->id) {
411 $_SESSION['behalf_id'] = $on_behalf_id;
412 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
414 header('Location: week.php');
420 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
422 $smarty->assign('selected_date', $selected_date);
423 $smarty->assign('week_total', $week_total);
425 $smarty->assign('client_list', $client_list);
426 $smarty->assign('project_list', $project_list);
427 $smarty->assign('task_list', $task_list);
428 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
429 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
430 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
432 $smarty->assign('title', $i18n->getKey('title.time'));
433 $smarty->assign('content_page_name', 'week.tpl');
434 $smarty->display('index.tpl');