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('form.TextField');
34 import('ttUserHelper');
35 import('ttTeamHelper');
36 import('ttWeekViewHelper');
37 import('ttClientHelper');
38 import('ttTimeHelper');
39 import('DateAndTime');
42 if (!ttAccessCheck(right_data_entry)) {
43 header('Location: access_denied.php');
47 // Initialize and store date in session.
48 $cl_date = $request->getParameter('date', @$_SESSION['date']);
49 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
50 if($selected_date->isError())
51 $selected_date = new DateAndTime(DB_DATEFORMAT);
53 $cl_date = $selected_date->toString(DB_DATEFORMAT);
54 $_SESSION['date'] = $cl_date;
56 // Determine selected week start and end dates.
57 $weekStartDay = $user->week_start;
58 $t_arr = localtime($selected_date->getTimestamp());
59 $t_arr[5] = $t_arr[5] + 1900;
60 if ($t_arr[6] < $weekStartDay)
61 $startWeekBias = $weekStartDay - 7;
63 $startWeekBias = $weekStartDay;
64 $startDate = new DateAndTime();
65 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
66 $endDate = new DateAndTime();
67 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
68 // The above is needed to set date range (timestring) in page title.
70 // Use custom fields plugin if it is enabled.
71 if ($user->isPluginEnabled('cf')) {
72 require_once('plugins/CustomFields.class.php');
73 $custom_fields = new CustomFields($user->team_id);
74 $smarty->assign('custom_fields', $custom_fields);
77 // Use Monthly Quotas plugin, if applicable.
78 if ($user->isPluginEnabled('mq')){
79 require_once('plugins/MonthlyQuota.class.php');
80 $quota = new MonthlyQuota();
81 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
82 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
83 $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
85 $smarty->assign('month_total', $month_total);
86 $smarty->assign('over_quota', $minutes_left < 0);
87 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
90 // Initialize variables.
92 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
93 $_SESSION['cf_1'] = $cl_cf_1;
95 if ($user->isPluginEnabled('iv')) {
96 if ($request->isPost()) {
97 $cl_billable = $request->getParameter('billable');
98 $_SESSION['billable'] = (int) $cl_billable;
100 if (isset($_SESSION['billable']))
101 $cl_billable = $_SESSION['billable'];
103 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
104 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
105 $_SESSION['client'] = $cl_client;
106 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
107 $_SESSION['project'] = $cl_project;
108 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
109 $_SESSION['task'] = $cl_task;
111 // Get the data we need to display week view.
112 // Get column headers, which are day numbers in month.
113 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
114 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
115 // Get already existing records.
116 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
117 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
119 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
121 $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
123 // Build day totals (total durations for each day in week).
124 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
126 // Define rendering class for a label field to the left of durations.
127 class LabelCellRenderer extends DefaultCellRenderer {
128 function render(&$table, $value, $row, $column, $selected = false) {
129 $this->setOptions(array('width'=>200,'valign'=>'middle'));
130 // Special handling for row 0, which represents a new week entry.
132 $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
133 } else if (0 != $row % 2) {
134 $this->setOptions(array('style'=>'text-align: right;'));
136 // Special handling for not billable entries.
137 if ($row > 1 && 0 == $row % 2) {
138 $row_id = $table->getValueAtName($row,'row_id');
139 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
141 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
144 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
145 return $this->toString();
149 // Define rendering class for a single cell for a time or a comment entry in week view table.
150 class WeekViewCellRenderer extends DefaultCellRenderer {
151 function render(&$table, $value, $row, $column, $selected = false) {
152 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
153 $field = new TextField($field_name);
154 // Disable control if the date is locked.
156 if ($lockedDays[$column-1])
157 $field->setEnabled(false);
158 $field->setFormName($table->getFormName());
159 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
161 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
163 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
164 $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to help view the entire comment.
166 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
167 // because we can't supply start and finish times in week view - there are no fields for them.
169 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
170 $field->setEnabled(false);
172 $this->setValue($field->getHtml());
173 return $this->toString();
177 // Elements of weekTimeForm.
178 $form = new Form('weekTimeForm');
180 if ($user->canManageTeam()) {
181 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
182 if (count($user_list) > 1) {
183 $form->addInput(array('type'=>'combobox',
184 'onchange'=>'this.form.submit();',
185 'name'=>'onBehalfUser',
186 'style'=>'width: 250px;',
187 'value'=>$on_behalf_id,
189 'datakeys'=>array('id','name')));
190 $smarty->assign('on_behalf_control', 1);
194 // Create week_durations table.
195 $table = new Table('week_durations', 'week_view_table');
196 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
197 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
198 $table->setData($dataArray);
199 // Add columns to table.
200 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
201 for ($i = 0; $i < 7; $i++) {
202 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
204 $table->setInteractive(false);
205 $form->addInputElement($table);
207 // Dropdown for clients in MODE_TIME. Use all active clients.
208 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
209 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
210 $form->addInput(array('type'=>'combobox',
211 'onchange'=>'fillProjectDropdown(this.value);',
213 'style'=>'width: 250px;',
215 'data'=>$active_clients,
216 'datakeys'=>array('id', 'name'),
217 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
218 // Note: in other modes the client list is filtered to relevant clients only. See below.
221 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
222 // Dropdown for projects assigned to user.
223 $project_list = $user->getAssignedProjects();
224 $form->addInput(array('type'=>'combobox',
225 'onchange'=>'fillTaskDropdown(this.value);',
227 'style'=>'width: 250px;',
228 'value'=>$cl_project,
229 'data'=>$project_list,
230 'datakeys'=>array('id','name'),
231 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
233 // Dropdown for clients if the clients plugin is enabled.
234 if ($user->isPluginEnabled('cl')) {
235 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
236 // We need an array of assigned project ids to do some trimming.
237 foreach($project_list as $project)
238 $projects_assigned_to_user[] = $project['id'];
240 // Build a client list out of active clients. Use only clients that are relevant to user.
241 // Also trim their associated project list to only assigned projects (to user).
242 foreach($active_clients as $client) {
243 $projects_assigned_to_client = explode(',', $client['projects']);
244 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
245 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
247 $client['projects'] = implode(',', $intersection);
248 $client_list[] = $client;
251 $form->addInput(array('type'=>'combobox',
252 'onchange'=>'fillProjectDropdown(this.value);',
254 'style'=>'width: 250px;',
256 'data'=>$client_list,
257 'datakeys'=>array('id', 'name'),
258 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
262 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
263 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
264 $form->addInput(array('type'=>'combobox',
266 'style'=>'width: 250px;',
269 'datakeys'=>array('id','name'),
270 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
273 // Add other controls.
274 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
275 if ($user->isPluginEnabled('iv'))
276 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
277 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
278 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
280 // If we have custom fields - add controls for them.
281 if ($custom_fields && $custom_fields->fields[0]) {
282 // Only one custom field is supported at this time.
283 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
284 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
285 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
286 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
287 'style'=>'width: 250px;',
289 'data'=>$custom_fields->options,
290 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
295 if ($request->isPost()) {
296 if ($request->getParameter('btn_submit')) {
297 // Validate user input for row 0.
298 // Determine if a new entry was posted.
299 $newEntryPosted = false;
300 foreach($dayHeaders as $dayHeader) {
301 $control_id = '0_'.$dayHeader;
302 if ($request->getParameter($control_id)) {
303 $newEntryPosted = true;
307 if ($newEntryPosted) {
308 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
309 $err->add($i18n->getKey('error.client'));
310 if ($custom_fields) {
311 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
313 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
314 if (!$cl_project) $err->add($i18n->getKey('error.project'));
316 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
317 if (!$cl_task) $err->add($i18n->getKey('error.task'));
321 // Process the table of values.
324 // Obtain values. Iterate through posted parameters one by one,
325 // see if value changed, apply one change at a time until we see an error.
328 // Iterate through existing rows.
329 foreach ($dataArray as $row) {
330 // Iterate through days.
331 foreach ($dayHeaders as $key => $dayHeader) {
332 // Do not process locked days.
333 if ($lockedDays[$key]) continue;
334 // Make control id for the cell.
335 $control_id = $rowNumber.'_'.$dayHeader;
337 // Handle durations and comments in separate blocks of code.
338 if (0 == $rowNumber % 2) {
339 // Handle durations row here.
341 // Obtain existing and posted durations.
342 $postedDuration = $request->getParameter($control_id);
343 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
344 // If posted value is not null, check and normalize it.
345 if ($postedDuration) {
346 if (ttTimeHelper::isValidDuration($postedDuration)) {
347 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
349 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
350 $result = false; break; // Break out. Stop any further processing.
353 // Do not process if value has not changed.
354 if ($postedDuration == $existingDuration)
356 // Posted value is different.
357 if ($existingDuration == null) {
358 // Skip inserting 0 duration values.
359 if (0 == ttTimeHelper::toMinutes($postedDuration))
361 // Insert a new record.
363 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
364 if (!$fields['row_id']) {
365 // Special handling for row 0, a new entry. Need to construct new row_id.
367 $record['client_id'] = $cl_client;
368 $record['billable'] = $cl_billable ? '1' : '0';
369 $record['project_id'] = $cl_project;
370 $record['task_id'] = $cl_task;
371 $record['cf_1_value'] = $cl_cf_1;
372 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
373 // Note: no need to check for a possible conflict with an already existing row
374 // because we are doing an insert that does not affect already existing data.
376 $fields['day_header'] = $dayHeader;
377 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
378 $fields['duration'] = $postedDuration;
379 $fields['browser_today'] = $request->getParameter('browser_today', null);
380 // Take note value from the control below duration.
381 $noteRowNumber = $rowNumber + 1;
382 $note_control_id = $noteRowNumber.'_'.$dayHeader;
383 $fields['note'] = $request->getParameter($note_control_id);
384 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
385 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
386 // Delete an already existing record here.
387 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
390 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
391 $fields['duration'] = $postedDuration;
392 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
394 if (!$result) break; // Break out of the loop in case of first error.
397 // Handle commments row here.
399 // Obtain existing and posted comments.
400 $postedComment = $request->getParameter($control_id);
401 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
402 // If posted value is not null, check it.
403 if ($postedComment && !ttValidString($postedComment, true)) {
404 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
405 $result = false; break; // Break out. Stop any further processing.
407 // Do not process if value has not changed.
408 if ($postedComment == $existingComment)
411 // Posted value is different.
412 // TODO: handle new entries separately in the durations block above.
414 // Here, only update the comment on an already existing record.
416 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
417 if ($fields['tt_log_id']) {
418 $fields['comment'] = $postedComment;
419 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
421 if (!$result) break; // Break out of the loop in case of first error.
424 if (!$result) break; // Break out of the loop in case of first error.
428 header('Location: week.php'); // Normal exit.
433 elseif ($request->getParameter('onBehalfUser')) {
434 if($user->canManageTeam()) {
435 unset($_SESSION['behalf_id']);
436 unset($_SESSION['behalf_name']);
438 if($on_behalf_id != $user->id) {
439 $_SESSION['behalf_id'] = $on_behalf_id;
440 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
442 header('Location: week.php');
448 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
450 $smarty->assign('selected_date', $selected_date);
451 $smarty->assign('week_total', $week_total);
453 $smarty->assign('client_list', $client_list);
454 $smarty->assign('project_list', $project_list);
455 $smarty->assign('task_list', $task_list);
456 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
457 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
458 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
459 $smarty->assign('time_records', $records);
461 $smarty->assign('title', $i18n->getKey('title.time'));
462 $smarty->assign('content_page_name', 'week.tpl');
463 $smarty->display('index.tpl');