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->getMethod()=='POST'? 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->getMethod()=='POST'? null : @$_SESSION['client']));
105 $_SESSION['client'] = $cl_client;
106 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
107 $_SESSION['project'] = $cl_project;
108 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? 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 the function.
118 $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
119 // Build day totals (total durations for each day in week).
120 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
122 // Define rendering class for a label field to the left of durations.
123 class LabelCellRenderer extends DefaultCellRenderer {
124 function render(&$table, $value, $row, $column, $selected = false) {
125 $this->setOptions(array('width'=>200,'valign'=>'middle'));
126 // Special handling for row 0, which represents a new week entry.
128 $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
129 } else if (0 != $row % 2) {
130 $this->setOptions(array('style'=>'text-align: right;'));
132 // Special handling for not billable entries.
133 if ($row > 1 && 0 == $row % 2) {
134 $row_id = $table->getValueAtName($row,'row_id');
135 $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
137 $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
140 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
141 return $this->toString();
145 // Define rendering class for a single cell for a time or a comment entry in week view table.
146 class WeekViewCellRenderer extends DefaultCellRenderer {
147 function render(&$table, $value, $row, $column, $selected = false) {
148 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
149 $field = new TextField($field_name);
150 // Disable control if the date is locked.
152 if ($lockedDays[$column-1])
153 $field->setEnabled(false);
154 $field->setFormName($table->getFormName());
155 $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
157 $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
159 $field->setValue($table->getValueAt($row,$column)['note']); // Comment for odd rows.
160 $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to help view the entire comment.
162 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
163 // because we can't supply start and finish times in week view - there are no fields for them.
165 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
166 $field->setEnabled(false);
168 $this->setValue($field->getHtml());
169 return $this->toString();
173 // Elements of weekTimeForm.
174 $form = new Form('weekTimeForm');
176 if ($user->canManageTeam()) {
177 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
178 if (count($user_list) > 1) {
179 $form->addInput(array('type'=>'combobox',
180 'onchange'=>'this.form.submit();',
181 'name'=>'onBehalfUser',
182 'style'=>'width: 250px;',
183 'value'=>$on_behalf_id,
185 'datakeys'=>array('id','name')));
186 $smarty->assign('on_behalf_control', 1);
190 // Create week_durations table.
191 $table = new Table('week_durations', 'week_view_table');
192 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
193 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
194 $table->setData($dataArray);
195 // Add columns to table.
196 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
197 for ($i = 0; $i < 7; $i++) {
198 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
200 $table->setInteractive(false);
201 $form->addInputElement($table);
203 // Dropdown for clients in MODE_TIME. Use all active clients.
204 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
205 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
206 $form->addInput(array('type'=>'combobox',
207 'onchange'=>'fillProjectDropdown(this.value);',
209 'style'=>'width: 250px;',
211 'data'=>$active_clients,
212 'datakeys'=>array('id', 'name'),
213 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
214 // Note: in other modes the client list is filtered to relevant clients only. See below.
217 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
218 // Dropdown for projects assigned to user.
219 $project_list = $user->getAssignedProjects();
220 $form->addInput(array('type'=>'combobox',
221 'onchange'=>'fillTaskDropdown(this.value);',
223 'style'=>'width: 250px;',
224 'value'=>$cl_project,
225 'data'=>$project_list,
226 'datakeys'=>array('id','name'),
227 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
229 // Dropdown for clients if the clients plugin is enabled.
230 if ($user->isPluginEnabled('cl')) {
231 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
232 // We need an array of assigned project ids to do some trimming.
233 foreach($project_list as $project)
234 $projects_assigned_to_user[] = $project['id'];
236 // Build a client list out of active clients. Use only clients that are relevant to user.
237 // Also trim their associated project list to only assigned projects (to user).
238 foreach($active_clients as $client) {
239 $projects_assigned_to_client = explode(',', $client['projects']);
240 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
241 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
243 $client['projects'] = implode(',', $intersection);
244 $client_list[] = $client;
247 $form->addInput(array('type'=>'combobox',
248 'onchange'=>'fillProjectDropdown(this.value);',
250 'style'=>'width: 250px;',
252 'data'=>$client_list,
253 'datakeys'=>array('id', 'name'),
254 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
258 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
259 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
260 $form->addInput(array('type'=>'combobox',
262 'style'=>'width: 250px;',
265 'datakeys'=>array('id','name'),
266 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
269 // Add other controls.
270 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
271 if ($user->isPluginEnabled('iv'))
272 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
273 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
274 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
276 // If we have custom fields - add controls for them.
277 if ($custom_fields && $custom_fields->fields[0]) {
278 // Only one custom field is supported at this time.
279 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
280 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
281 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
282 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
283 'style'=>'width: 250px;',
285 'data'=>$custom_fields->options,
286 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
291 if ($request->isPost()) {
292 if ($request->getParameter('btn_submit')) {
293 // Validate user input for row 0.
294 // Determine if a new entry was posted.
295 $newEntryPosted = false;
296 foreach($dayHeaders as $dayHeader) {
297 $control_id = '0_'.$dayHeader;
298 if ($request->getParameter($control_id)) {
299 $newEntryPosted = true;
303 if ($newEntryPosted) {
304 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
305 $err->add($i18n->getKey('error.client'));
306 if ($custom_fields) {
307 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
309 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
310 if (!$cl_project) $err->add($i18n->getKey('error.project'));
312 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
313 if (!$cl_task) $err->add($i18n->getKey('error.task'));
317 // Process the table of values.
320 // Obtain values. Iterate through posted parameters one by one,
321 // see if value changed, apply one change at a time until we see an error.
324 // Iterate through existing rows.
325 foreach ($dataArray as $row) {
326 // Iterate through days.
327 foreach ($dayHeaders as $key => $dayHeader) {
328 // Do not process locked days.
329 if ($lockedDays[$key]) continue;
330 // Make control id for the cell.
331 $control_id = $rowNumber.'_'.$dayHeader;
333 // Handle durations and comments in separate blocks of code.
334 if (0 == $rowNumber % 2) {
335 // Handle durations row here.
337 // Obtain existing and posted durations.
338 $postedDuration = $request->getParameter($control_id);
339 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
340 // If posted value is not null, check and normalize it.
341 if ($postedDuration) {
342 if (ttTimeHelper::isValidDuration($postedDuration)) {
343 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
345 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
346 $result = false; break; // Break out. Stop any further processing.
349 // Do not process if value has not changed.
350 if ($postedDuration == $existingDuration)
352 // Posted value is different.
353 if ($existingDuration == null) {
354 // Skip inserting 0 duration values.
355 if (0 == ttTimeHelper::toMinutes($postedDuration))
357 // Insert a new record.
359 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
360 if (!$fields['row_id']) {
361 // Special handling for row 0, a new entry. Need to construct new row_id.
363 $record['client_id'] = $cl_client;
364 $record['billable'] = $cl_billable ? '1' : '0';
365 $record['project_id'] = $cl_project;
366 $record['task_id'] = $cl_task;
367 $record['cf_1_value'] = $cl_cf_1;
368 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
369 // Note: no need to check for a possible conflict with an already existing row
370 // because we are doing an insert that does not affect already existing data.
372 $fields['day_header'] = $dayHeader;
373 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
374 $fields['duration'] = $postedDuration;
375 $fields['browser_today'] = $request->getParameter('browser_today', null);
376 // Take note value from the control below duration.
377 $noteRowNumber = $rowNumber + 1;
378 $note_control_id = $noteRowNumber.'_'.$dayHeader;
379 $fields['note'] = $request->getParameter($note_control_id);
380 $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
381 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
382 // Delete an already existing record here.
383 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
386 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
387 $fields['duration'] = $postedDuration;
388 $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
390 if (!$result) break; // Break out of the loop in case of first error.
393 // Handle commments row here.
395 // Obtain existing and posted comments.
396 $postedComment = $request->getParameter($control_id);
397 $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
398 // If posted value is not null, check it.
399 if ($postedComment && !ttValidString($postedComment, true)) {
400 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
401 $result = false; break; // Break out. Stop any further processing.
403 // Do not process if value has not changed.
404 if ($postedComment == $existingComment)
407 // Posted value is different.
408 // TODO: handle new entries separately in the durations block above.
410 // Here, only update the comment on an already existing record.
412 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
413 if ($fields['tt_log_id']) {
414 $fields['comment'] = $postedComment;
415 $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
417 if (!$result) break; // Break out of the loop in case of first error.
420 if (!$result) break; // Break out of the loop in case of first error.
424 header('Location: week.php'); // Normal exit.
429 elseif ($request->getParameter('onBehalfUser')) {
430 if($user->canManageTeam()) {
431 unset($_SESSION['behalf_id']);
432 unset($_SESSION['behalf_name']);
434 if($on_behalf_id != $user->id) {
435 $_SESSION['behalf_id'] = $on_behalf_id;
436 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
438 header('Location: week.php');
444 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
446 $smarty->assign('selected_date', $selected_date);
447 $smarty->assign('week_total', $week_total);
449 $smarty->assign('client_list', $client_list);
450 $smarty->assign('project_list', $project_list);
451 $smarty->assign('task_list', $task_list);
452 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
453 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
454 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
455 $smarty->assign('time_records', $records);
457 $smarty->assign('title', $i18n->getKey('title.time'));
458 $smarty->assign('content_page_name', 'week.tpl');
459 $smarty->display('index.tpl');