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('ttClientHelper');
37 import('ttTimeHelper');
38 import('DateAndTime');
41 if (!ttAccessCheck(right_data_entry)) {
42 header('Location: access_denied.php');
46 // Initialize and store date in session.
47 $cl_date = $request->getParameter('date', @$_SESSION['date']);
48 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
49 if($selected_date->isError())
50 $selected_date = new DateAndTime(DB_DATEFORMAT);
52 $cl_date = $selected_date->toString(DB_DATEFORMAT);
53 $_SESSION['date'] = $cl_date;
55 // Determine selected week start and end dates.
56 $weekStartDay = $user->week_start;
57 $t_arr = localtime($selected_date->getTimestamp());
58 $t_arr[5] = $t_arr[5] + 1900;
59 if ($t_arr[6] < $weekStartDay)
60 $startWeekBias = $weekStartDay - 7;
62 $startWeekBias = $weekStartDay;
63 $startDate = new DateAndTime();
64 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
65 $endDate = new DateAndTime();
66 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
67 // The above is needed to set date range (timestring) in page title.
69 // Use custom fields plugin if it is enabled.
70 if ($user->isPluginEnabled('cf')) {
71 require_once('plugins/CustomFields.class.php');
72 $custom_fields = new CustomFields($user->team_id);
73 $smarty->assign('custom_fields', $custom_fields);
76 // TODO: how is this plugin supposed to work for week view?
77 if ($user->isPluginEnabled('mq')){
78 require_once('plugins/MonthlyQuota.class.php');
79 $quota = new MonthlyQuota();
80 $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
81 $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
82 $minutes_left = ttTimeHelper::toMinutes($month_quota) - ttTimeHelper::toMinutes($month_total);
84 $smarty->assign('month_total', $month_total);
85 $smarty->assign('over_quota', $minutes_left < 0);
86 $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
89 // Initialize variables.
91 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
92 $_SESSION['cf_1'] = $cl_cf_1;
94 if ($user->isPluginEnabled('iv')) {
95 if ($request->isPost()) {
96 $cl_billable = $request->getParameter('billable');
97 $_SESSION['billable'] = (int) $cl_billable;
99 if (isset($_SESSION['billable']))
100 $cl_billable = $_SESSION['billable'];
102 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
103 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
104 $_SESSION['client'] = $cl_client;
105 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
106 $_SESSION['project'] = $cl_project;
107 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
108 $_SESSION['task'] = $cl_task;
110 // Get the data we need to display week view.
111 // Get column headers, which are day numbers in month.
112 $dayHeaders = ttTimeHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
113 $lockedDays = ttTimeHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
114 // Build data array for the table. Format is described in the function..
115 $dataArray = ttTimeHelper::getDataForWeekView($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT), $dayHeaders);
116 // Build day totals (total durations for each day in week).
117 $dayTotals = ttTimeHelper::getDayTotals($dataArray, $dayHeaders);
119 // Define rendering class for a label field to the left of durations.
120 class LabelCellRenderer extends DefaultCellRenderer {
121 function render(&$table, $value, $row, $column, $selected = false) {
122 $this->setOptions(array('width'=>200,'valign'=>'middle'));
123 // Special handling for row 0, which represents a new week entry.
125 $this->setOptions(array('style'=>'text-align: center; font-weight: bold;'));
127 // Special handling for not billable entries.
128 /* // TODO: this does not work and should be coded properly.
130 $row_id = $table->getValueAt($row,1+$column)['row_id'];
131 $billable = ttTimeHelper::parseFromWeekViewRow($row_id, 'bl');
133 $this->setOptions(array('class'=>'not_billable')); // TODO: Should not we add options instead? How does it work exactly?
136 $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
137 return $this->toString();
141 // Define rendering class for a single cell for time entry in week view table.
142 class TimeCellRenderer extends DefaultCellRenderer {
143 function render(&$table, $value, $row, $column, $selected = false) {
144 $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
145 $field = new TextField($field_name);
146 // Disable control if the date is locked.
148 if ($lockedDays[$column-1])
149 $field->setEnabled(false);
150 $field->setFormName($table->getFormName());
152 $field->setValue($table->getValueAt($row,$column)['duration']);
153 // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
154 // because we can't supply start and finish times in week view - there are no fields for them.
156 if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
157 $field->setEnabled(false);
159 $this->setValue($field->getHtml());
160 return $this->toString();
164 // Elements of weekTimeForm.
165 $form = new Form('weekTimeForm');
167 if ($user->canManageTeam()) {
168 $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
169 if (count($user_list) > 1) {
170 $form->addInput(array('type'=>'combobox',
171 'onchange'=>'this.form.submit();',
172 'name'=>'onBehalfUser',
173 'style'=>'width: 250px;',
174 'value'=>$on_behalf_id,
176 'datakeys'=>array('id','name')));
177 $smarty->assign('on_behalf_control', 1);
181 // Create week_durations table.
182 $table = new Table('week_durations');
183 // $table->setIAScript('markModified'); // TODO: write a script to mark table or particular cells as modified.
184 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
185 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
186 $table->setData($dataArray);
187 // Add columns to table.
188 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
189 for ($i = 0; $i < 7; $i++) {
190 $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new TimeCellRenderer(), $dayTotals[$dayHeaders[$i]]));
192 $table->setInteractive(false);
193 $form->addInputElement($table);
195 // Dropdown for clients in MODE_TIME. Use all active clients.
196 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
197 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
198 $form->addInput(array('type'=>'combobox',
199 'onchange'=>'fillProjectDropdown(this.value);',
201 'style'=>'width: 250px;',
203 'data'=>$active_clients,
204 'datakeys'=>array('id', 'name'),
205 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
206 // Note: in other modes the client list is filtered to relevant clients only. See below.
209 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
210 // Dropdown for projects assigned to user.
211 $project_list = $user->getAssignedProjects();
212 $form->addInput(array('type'=>'combobox',
213 'onchange'=>'fillTaskDropdown(this.value);',
215 'style'=>'width: 250px;',
216 'value'=>$cl_project,
217 'data'=>$project_list,
218 'datakeys'=>array('id','name'),
219 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
221 // Dropdown for clients if the clients plugin is enabled.
222 if ($user->isPluginEnabled('cl')) {
223 $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
224 // We need an array of assigned project ids to do some trimming.
225 foreach($project_list as $project)
226 $projects_assigned_to_user[] = $project['id'];
228 // Build a client list out of active clients. Use only clients that are relevant to user.
229 // Also trim their associated project list to only assigned projects (to user).
230 foreach($active_clients as $client) {
231 $projects_assigned_to_client = explode(',', $client['projects']);
232 if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
233 $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
235 $client['projects'] = implode(',', $intersection);
236 $client_list[] = $client;
239 $form->addInput(array('type'=>'combobox',
240 'onchange'=>'fillProjectDropdown(this.value);',
242 'style'=>'width: 250px;',
244 'data'=>$client_list,
245 'datakeys'=>array('id', 'name'),
246 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
250 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
251 $task_list = ttTeamHelper::getActiveTasks($user->team_id);
252 $form->addInput(array('type'=>'combobox',
254 'style'=>'width: 250px;',
257 'datakeys'=>array('id','name'),
258 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
261 // Add other controls.
262 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
263 if ($user->isPluginEnabled('iv'))
264 $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
265 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
266 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
268 // If we have custom fields - add controls for them.
269 if ($custom_fields && $custom_fields->fields[0]) {
270 // Only one custom field is supported at this time.
271 if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
272 $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
273 } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
274 $form->addInput(array('type'=>'combobox','name'=>'cf_1',
275 'style'=>'width: 250px;',
277 'data'=>$custom_fields->options,
278 'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
283 if ($request->isPost()) {
284 if ($request->getParameter('btn_submit')) {
285 // Validate user input for row 0.
286 // Determine if a new entry was posted.
287 $newEntryPosted = false;
288 foreach($dayHeaders as $dayHeader) {
289 $control_id = '0_'.$dayHeader;
290 if ($request->getParameter($control_id)) {
291 $newEntryPosted = true;
295 if ($newEntryPosted) {
296 if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
297 $err->add($i18n->getKey('error.client'));
298 if ($custom_fields) {
299 if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
301 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
302 if (!$cl_project) $err->add($i18n->getKey('error.project'));
304 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
305 if (!$cl_task) $err->add($i18n->getKey('error.task'));
309 // Process the table of values.
312 // Obtain values. Perhaps, it's best to iterate throigh posted parameters one by one,
313 // see if anything changed, and apply one change at a time until we see an error.
316 // Iterate through existing rows.
317 foreach ($dataArray as $row) {
318 // Iterate through days.
319 foreach ($dayHeaders as $key => $dayHeader) {
320 // Do not process locked days.
321 if ($lockedDays[$key]) continue;
322 // Make control id for the cell.
323 $control_id = $rowNumber.'_'.$dayHeader;
324 // Optain existing and posted durations.
325 $postedDuration = $request->getParameter($control_id);
326 $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
327 // If posted value is not null, check and normalize it.
328 if ($postedDuration) {
329 if (ttTimeHelper::isValidDuration($postedDuration)) {
330 $postedDuration = ttTimeHelper::normalizeDuration($postedDuration, false); // No leading zero.
332 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
333 $result = false; break; // Break out. Stop any further processing.
336 // Do not process if value has not changed.
337 if ($postedDuration == $existingDuration)
339 // Posted value is different.
340 if ($existingDuration == null) {
341 // Insert a new record here.
343 $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
344 if (!$fields['row_id']) {
345 // Special handling for row 0, a new entry. Need to construct row_id.
347 $record['client_id'] = $cl_client;
348 $record['billable'] = $cl_billable ? '1' : '0';
349 $record['project_id'] = $cl_project;
350 $record['task_id'] = $cl_task;
351 $record['cf_1_value'] = $cl_cf_1;
352 $fields['row_id'] = ttTimeHelper::makeRecordIdentifier($record).'_0';
354 $fields['day_header'] = $dayHeader;
355 $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
356 $fields['duration'] = $postedDuration;
357 $fields['browser_today'] = $request->getParameter('browser_today', null);
358 $result = ttTimeHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
359 } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
360 // Delete an already existing record here.
361 $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
364 $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
365 $fields['duration'] = $postedDuration;
366 $result = ttTimeHelper::modifyDurationFromWeekView($fields, $err);
368 if (!$result) break; // Break out of the loop in case of first error.
370 if (!$result) break; // Break out of the loop in case of first error.
374 header('Location: week.php'); // Normal exit.
379 elseif ($request->getParameter('onBehalfUser')) {
380 if($user->canManageTeam()) {
381 unset($_SESSION['behalf_id']);
382 unset($_SESSION['behalf_name']);
384 if($on_behalf_id != $user->id) {
385 $_SESSION['behalf_id'] = $on_behalf_id;
386 $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
388 header('Location: week.php');
394 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
396 $smarty->assign('selected_date', $selected_date);
397 $smarty->assign('week_total', $week_total);
399 $smarty->assign('client_list', $client_list);
400 $smarty->assign('project_list', $project_list);
401 $smarty->assign('task_list', $task_list);
402 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
403 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
404 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
406 $smarty->assign('title', $i18n->getKey('title.time'));
407 $smarty->assign('content_page_name', 'week.tpl');
408 $smarty->display('index.tpl');