More refactoring of rights checks (#61)
[timetracker.git] / time.php
1 <?php
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.
10 // |
11 // | There are only two ways to violate the license:
12 // |
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).
16 // |
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).
20 // |
21 // | This license applies to this document only, not any other software
22 // | that it may be combined with.
23 // |
24 // +----------------------------------------------------------------------+
25 // | Contributors:
26 // | https://www.anuko.com/time_tracker/credits.htm
27 // +----------------------------------------------------------------------+
28
29 require_once('initialize.php');
30 import('form.Form');
31 import('ttUserHelper');
32 import('ttTeamHelper');
33 import('ttClientHelper');
34 import('ttTimeHelper');
35 import('DateAndTime');
36
37 // Access checks.
38 if (!(ttAccessAllowed('track_own_time') || ttAccessAllowed('track_time'))) {
39   header('Location: access_denied.php');
40   exit();
41 }
42 if ($user->behalf_id && (!$user->can('track_time') || !$user->checkBehalfId())) {
43   header('Location: access_denied.php'); // Trying on behalf, but no right or wrong user.
44   exit();
45 }
46 if (!$user->behalf_id && !$user->can('track_own_time') && !$user->adjustBehalfId()) {
47   header('Location: access_denied.php'); // Trying as self, but no right for self, and noone to work on behalf.
48   exit();
49 }
50 // End of access checks.
51
52 // Initialize and store date in session.
53 $cl_date = $request->getParameter('date', @$_SESSION['date']);
54 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
55 if($selected_date->isError())
56   $selected_date = new DateAndTime(DB_DATEFORMAT);
57 if(!$cl_date)
58   $cl_date = $selected_date->toString(DB_DATEFORMAT);
59 $_SESSION['date'] = $cl_date;
60
61 // Use custom fields plugin if it is enabled.
62 if ($user->isPluginEnabled('cf')) {
63   require_once('plugins/CustomFields.class.php');
64   $custom_fields = new CustomFields($user->group_id);
65   $smarty->assign('custom_fields', $custom_fields);
66 }
67
68 if ($user->isPluginEnabled('mq')){
69   require_once('plugins/MonthlyQuota.class.php');
70   $quota = new MonthlyQuota();
71   $month_quota_minutes = $quota->get($selected_date->mYear, $selected_date->mMonth);
72   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
73   $minutes_left = $month_quota_minutes - ttTimeHelper::toMinutes($month_total);
74   
75   $smarty->assign('month_total', $month_total);
76   $smarty->assign('over_quota', $minutes_left < 0);
77   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
78 }
79
80 // Initialize variables.
81 $cl_start = trim($request->getParameter('start'));
82 $cl_finish = trim($request->getParameter('finish'));
83 $cl_duration = trim($request->getParameter('duration'));
84 $cl_note = trim($request->getParameter('note'));
85 // Custom field.
86 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
87 $_SESSION['cf_1'] = $cl_cf_1;
88 $cl_billable = 1;
89 if ($user->isPluginEnabled('iv')) {
90   if ($request->isPost()) {
91     $cl_billable = $request->getParameter('billable');
92     $_SESSION['billable'] = (int) $cl_billable;
93   } else
94     if (isset($_SESSION['billable']))
95       $cl_billable = $_SESSION['billable'];
96 }
97 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
98 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
99 $_SESSION['client'] = $cl_client;
100 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
101 $_SESSION['project'] = $cl_project;
102 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
103 $_SESSION['task'] = $cl_task;
104
105 // Elements of timeRecordForm.
106 $form = new Form('timeRecordForm');
107
108 if ($user->can('track_time')) {
109   if ($user->can('track_own_time'))
110     $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1,'include_self'=>true,'self_first'=>true);
111   else
112     $options = array('status'=>ACTIVE,'max_rank'=>$user->rank-1);
113   $user_list = $user->getUsers($options);
114   if (count($user_list) >= 1) {
115     $form->addInput(array('type'=>'combobox',
116       'onchange'=>'this.form.submit();',
117       'name'=>'onBehalfUser',
118       'style'=>'width: 250px;',
119       'value'=>$on_behalf_id,
120       'data'=>$user_list,
121       'datakeys'=>array('id','name')));
122     $smarty->assign('on_behalf_control', 1);
123   }
124 }
125
126 // Dropdown for clients in MODE_TIME. Use all active clients.
127 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
128   $active_clients = ttTeamHelper::getActiveClients($user->group_id, true);
129   $form->addInput(array('type'=>'combobox',
130     'onchange'=>'fillProjectDropdown(this.value);',
131     'name'=>'client',
132     'style'=>'width: 250px;',
133     'value'=>$cl_client,
134     'data'=>$active_clients,
135     'datakeys'=>array('id', 'name'),
136     'empty'=>array(''=>$i18n->get('dropdown.select'))));
137   // Note: in other modes the client list is filtered to relevant clients only. See below.
138 }
139
140 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
141   // Dropdown for projects assigned to user.
142   $project_list = $user->getAssignedProjects();
143   $form->addInput(array('type'=>'combobox',
144     'onchange'=>'fillTaskDropdown(this.value);',
145     'name'=>'project',
146     'style'=>'width: 250px;',
147     'value'=>$cl_project,
148     'data'=>$project_list,
149     'datakeys'=>array('id','name'),
150     'empty'=>array(''=>$i18n->get('dropdown.select'))));
151
152   // Dropdown for clients if the clients plugin is enabled.
153   if ($user->isPluginEnabled('cl')) {
154     $active_clients = ttTeamHelper::getActiveClients($user->group_id, true);
155     // We need an array of assigned project ids to do some trimming.
156     foreach($project_list as $project)
157       $projects_assigned_to_user[] = $project['id'];
158
159     // Build a client list out of active clients. Use only clients that are relevant to user.
160     // Also trim their associated project list to only assigned projects (to user).
161     foreach($active_clients as $client) {
162       $projects_assigned_to_client = explode(',', $client['projects']);
163       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
164         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
165       if ($intersection) {
166         $client['projects'] = implode(',', $intersection);
167         $client_list[] = $client;
168       }
169     }
170     $form->addInput(array('type'=>'combobox',
171       'onchange'=>'fillProjectDropdown(this.value);',
172       'name'=>'client',
173       'style'=>'width: 250px;',
174       'value'=>$cl_client,
175       'data'=>$client_list,
176       'datakeys'=>array('id', 'name'),
177       'empty'=>array(''=>$i18n->get('dropdown.select'))));
178   }
179 }
180
181 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
182   $task_list = ttTeamHelper::getActiveTasks($user->group_id);
183   $form->addInput(array('type'=>'combobox',
184     'name'=>'task',
185     'style'=>'width: 250px;',
186     'value'=>$cl_task,
187     'data'=>$task_list,
188     'datakeys'=>array('id','name'),
189     'empty'=>array(''=>$i18n->get('dropdown.select'))));
190 }
191
192 // Add other controls.
193 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
194   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
195   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
196   if ($user->punch_mode && !$user->canOverridePunchMode()) {
197     // Make the start and finish fields read-only.
198     $form->getElement('start')->setEnabled(false);
199     $form->getElement('finish')->setEnabled(false);
200   }
201 }
202 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
203   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
204 if (!defined('NOTE_INPUT_HEIGHT'))
205   define('NOTE_INPUT_HEIGHT', 40);
206 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
207 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
208 if ($user->isPluginEnabled('iv'))
209   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
210 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
211 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
212
213 // If we have custom fields - add controls for them.
214 if ($custom_fields && $custom_fields->fields[0]) {
215   // Only one custom field is supported at this time.
216   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
217     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
218   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
219     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
220       'style'=>'width: 250px;',
221       'value'=>$cl_cf_1,
222       'data'=>$custom_fields->options,
223       'empty'=>array(''=>$i18n->get('dropdown.select'))));
224   }
225 }
226
227 // Submit.
228 if ($request->isPost()) {
229   if ($request->getParameter('btn_submit')) {
230
231     // Validate user input.
232     if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
233       $err->add($i18n->get('error.client'));
234     if ($custom_fields) {
235       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
236     }
237     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
238       if (!$cl_project) $err->add($i18n->get('error.project'));
239     }
240     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
241       if (!$cl_task) $err->add($i18n->get('error.task'));
242     }
243     if (strlen($cl_duration) == 0) {
244       if ($cl_start || $cl_finish) {
245         if (!ttTimeHelper::isValidTime($cl_start))
246           $err->add($i18n->get('error.field'), $i18n->get('label.start'));
247         if ($cl_finish) {
248           if (!ttTimeHelper::isValidTime($cl_finish))
249             $err->add($i18n->get('error.field'), $i18n->get('label.finish'));
250           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
251             $err->add($i18n->get('error.interval'), $i18n->get('label.finish'), $i18n->get('label.start'));
252         }
253       } else {
254         if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
255           $err->add($i18n->get('error.empty'), $i18n->get('label.start'));
256           $err->add($i18n->get('error.empty'), $i18n->get('label.finish'));
257         }
258         if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
259           $err->add($i18n->get('error.empty'), $i18n->get('label.duration'));
260       }
261     } else {
262       if (false === ttTimeHelper::postedDurationToMinutes($cl_duration))
263         $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
264     }
265     if (!ttValidString($cl_note, true)) $err->add($i18n->get('error.field'), $i18n->get('label.note'));
266     // Finished validating user input.
267
268     // Prohibit creating entries in future.
269     if (!$user->future_entries) {
270       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
271       if ($selected_date->after($browser_today))
272         $err->add($i18n->get('error.future_date'));
273     }
274
275     // Prohibit creating entries in locked range.
276     if ($user->isDateLocked($selected_date))
277       $err->add($i18n->get('error.range_locked'));
278
279     // Prohibit creating another uncompleted record.
280     if ($err->no()) {
281       if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
282         $err->add($i18n->get('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->get('error.goto_uncompleted')."</a>");
283     }
284
285     // Prohibit creating an overlapping record.
286     if ($err->no()) {
287       if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
288         $err->add($i18n->get('error.overlap'));
289     }
290
291     // Insert record.
292     if ($err->no()) {
293       $id = ttTimeHelper::insert(array(
294         'date' => $cl_date,
295         'user_id' => $user->getActiveUser(),
296         'client' => $cl_client,
297         'project' => $cl_project,
298         'task' => $cl_task,
299         'start' => $cl_start,
300         'finish' => $cl_finish,
301         'duration' => $cl_duration,
302         'note' => $cl_note,
303         'billable' => $cl_billable));
304
305       // Insert a custom field if we have it.
306       $result = true;
307       if ($id && $custom_fields && $cl_cf_1) {
308         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
309           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
310         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
311           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
312       }
313       if ($id && $result) {
314         header('Location: time.php');
315         exit();
316       }
317       $err->add($i18n->get('error.db'));
318     }
319   } elseif ($request->getParameter('btn_stop')) {
320     // Stop button pressed to finish an uncompleted record.
321     $record_id = $request->getParameter('record_id');
322     $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
323     $browser_date = $request->getParameter('browser_date');
324     $browser_time = $request->getParameter('browser_time');
325
326     // Can we complete this record?
327     if ($record['date'] == $browser_date                                // closing today's record
328       && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
329       && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
330       $res = ttTimeHelper::update(array(
331           'id'=>$record['id'],
332           'date'=>$record['date'],
333           'user_id'=>$user->getActiveUser(),
334           'client'=>$record['client_id'],
335           'project'=>$record['project_id'],
336           'task'=>$record['task_id'],
337           'start'=>$record['start'],
338           'finish'=>$browser_time,
339           'note'=>$record['comment'],
340           'billable'=>$record['billable']));
341       if (!$res)
342         $err->add($i18n->get('error.db'));
343     } else {
344       // Cannot complete, redirect for manual edit.
345       header('Location: time_edit.php?id='.$record_id);
346       exit();
347     }
348   }
349   elseif ($request->getParameter('onBehalfUser')) {
350     if($user->can('track_time')) {
351       unset($_SESSION['behalf_id']);
352       unset($_SESSION['behalf_name']);
353
354       if($on_behalf_id != $user->id) {
355         $_SESSION['behalf_id'] = $on_behalf_id;
356         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
357       }
358       header('Location: time.php');
359       exit();
360     }
361   }
362 } // isPost
363
364 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
365
366 $smarty->assign('selected_date', $selected_date);
367 $smarty->assign('week_total', $week_total);
368 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($user->getActiveUser(), $cl_date));
369 $smarty->assign('time_records', ttTimeHelper::getRecords($user->getActiveUser(), $cl_date));
370 $smarty->assign('client_list', $client_list);
371 $smarty->assign('project_list', $project_list);
372 $smarty->assign('task_list', $task_list);
373 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
374 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
375 $smarty->assign('timestring', $selected_date->toString($user->date_format));
376 $smarty->assign('title', $i18n->get('title.time'));
377 $smarty->assign('content_page_name', 'time.tpl');
378 $smarty->display('index.tpl');