Removed PHP closing tag in more files
[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 // This is a now removed check whether user browser supports cookies.
38 // if (!isset($_COOKIE['tt_PHPSESSID'])) {
39   // This test gives a false-positive if user goes directly to this page
40   // as from a desktop shortcut (on first request only).
41   // die ("Your browser's cookie functionality is turned off. Please turn it on.");
42 // }
43
44 // Access check.
45 if (!ttAccessCheck(right_data_entry)) {
46   header('Location: access_denied.php');
47   exit();
48 }
49
50 // Initialize and store date in session.
51 $cl_date = $request->getParameter('date', @$_SESSION['date']);
52 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
53 if($selected_date->isError())
54   $selected_date = new DateAndTime(DB_DATEFORMAT);
55 if(!$cl_date)
56   $cl_date = $selected_date->toString(DB_DATEFORMAT);
57 $_SESSION['date'] = $cl_date;
58
59 // Use custom fields plugin if it is enabled.
60 if (in_array('cf', explode(',', $user->plugins))) {
61   require_once('plugins/CustomFields.class.php');
62   $custom_fields = new CustomFields($user->team_id);
63   $smarty->assign('custom_fields', $custom_fields);
64 }
65
66 // Initialize variables.
67 $cl_start = trim($request->getParameter('start'));
68 $cl_finish = trim($request->getParameter('finish'));
69 $cl_duration = trim($request->getParameter('duration'));
70 $cl_note = trim($request->getParameter('note'));
71 // Custom field.
72 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->getMethod()=='POST'? null : @$_SESSION['cf_1'])));
73 $_SESSION['cf_1'] = $cl_cf_1;
74 $cl_billable = 1;
75 if (in_array('iv', explode(',', $user->plugins))) {
76   if ($request->getMethod() == 'POST') {
77     $cl_billable = $request->getParameter('billable');
78     $_SESSION['billable'] = (int) $cl_billable;
79   } else 
80     if (isset($_SESSION['billable']))
81       $cl_billable = $_SESSION['billable'];
82 }
83 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
84 $cl_client = $request->getParameter('client', ($request->getMethod()=='POST'? null : @$_SESSION['client']));
85 $_SESSION['client'] = $cl_client;
86 $cl_project = $request->getParameter('project', ($request->getMethod()=='POST'? null : @$_SESSION['project']));
87 $_SESSION['project'] = $cl_project;
88 $cl_task = $request->getParameter('task', ($request->getMethod()=='POST'? null : @$_SESSION['task']));
89 $_SESSION['task'] = $cl_task;
90
91 // Elements of timeRecordForm.
92 $form = new Form('timeRecordForm');
93
94 if ($user->canManageTeam()) {
95   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
96   if (count($user_list) > 1) {
97     $form->addInput(array('type'=>'combobox',
98       'onchange'=>'this.form.submit();',
99       'name'=>'onBehalfUser',
100       'style'=>'width: 250px;',
101       'value'=>$on_behalf_id,
102       'data'=>$user_list,
103       'datakeys'=>array('id','name'),
104     ));
105     $smarty->assign('on_behalf_control', 1);
106   }
107 }
108
109 // Dropdown for clients in MODE_TIME. Use all active clients.
110 if (MODE_TIME == $user->tracking_mode && in_array('cl', explode(',', $user->plugins))) {
111     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
112     $form->addInput(array('type'=>'combobox',
113       'onchange'=>'fillProjectDropdown(this.value);',
114       'name'=>'client',
115       'style'=>'width: 250px;',
116       'value'=>$cl_client,
117       'data'=>$active_clients,
118       'datakeys'=>array('id', 'name'),
119       'empty'=>array(''=>$i18n->getKey('dropdown.select'))
120     ));
121   // Note: in other modes the client list is filtered to relevant clients only. See below.
122 }
123
124 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
125   // Dropdown for projects assigned to user.
126   $project_list = $user->getAssignedProjects();
127   $form->addInput(array('type'=>'combobox',
128     'onchange'=>'fillTaskDropdown(this.value);',
129     'name'=>'project',
130     'style'=>'width: 250px;',
131     'value'=>$cl_project,
132     'data'=>$project_list,
133     'datakeys'=>array('id','name'),
134     'empty'=>array(''=>$i18n->getKey('dropdown.select'))
135   ));
136
137   // Dropdown for clients if the clients plugin is enabled.
138   if (in_array('cl', explode(',', $user->plugins))) {
139     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
140     // We need an array of assigned project ids to do some trimming. 
141     foreach($project_list as $project)
142       $projects_assigned_to_user[] = $project['id'];
143
144     // Build a client list out of active clients. Use only clients that are relevant to user.
145     // Also trim their associated project list to only assigned projects (to user).
146     foreach($active_clients as $client) {
147       $projects_assigned_to_client = explode(',', $client['projects']);
148           $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
149           if ($intersection) {
150             $client['projects'] = implode(',', $intersection);
151             $client_list[] = $client;
152           }
153     }
154     $form->addInput(array('type'=>'combobox',
155       'onchange'=>'fillProjectDropdown(this.value);',
156       'name'=>'client',
157       'style'=>'width: 250px;',
158       'value'=>$cl_client,
159       'data'=>$client_list,
160       'datakeys'=>array('id', 'name'),
161       'empty'=>array(''=>$i18n->getKey('dropdown.select'))
162     ));
163   }
164 }
165
166 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
167   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
168   $form->addInput(array('type'=>'combobox',
169     'name'=>'task',
170     'style'=>'width: 250px;',
171     'value'=>$cl_task,
172     'data'=>$task_list,
173     'datakeys'=>array('id','name'),
174     'empty'=>array(''=>$i18n->getKey('dropdown.select'))
175   ));
176 }
177
178 // Add other controls.
179 if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
180   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
181   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
182 }
183 if (!$user->canManageTeam() && defined('READONLY_START_FINISH') && isTrue(READONLY_START_FINISH)) {
184   // Make the start and finish fields read-only.
185   $form->getElement('start')->setEnable(false);
186   $form->getElement('finish')->setEnable(false);        
187 }
188 if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
189   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
190 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height: 40px;','value'=>$cl_note));
191 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
192 if (in_array('iv', explode(',', $user->plugins)))
193   $form->addInput(array('type'=>'checkbox','name'=>'billable','data'=>1,'value'=>$cl_billable));
194 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
195 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
196   
197 // If we have custom fields - add controls for them.
198 if ($custom_fields && $custom_fields->fields[0]) {
199   // Only one custom field is supported at this time.
200   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
201         $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
202   } else if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
203     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
204       'style'=>'width: 250px;',
205       'value'=>$cl_cf_1,
206       'data'=>$custom_fields->options,
207       'empty'=>array(''=>$i18n->getKey('dropdown.select'))
208     ));
209   }
210 }
211
212 // Determine lock date. Time entries earlier than lock date cannot be created or modified. 
213 $lock_interval = $user->lock_interval;
214 $lockdate = 0;
215 if ($lock_interval > 0) {
216   $lockdate = new DateAndTime();
217   $lockdate->decDay($lock_interval);
218 }
219
220 // Submit.
221 if ($request->getMethod() == 'POST') {
222   if ($request->getParameter('btn_submit')) {
223         
224     // Validate user input.
225     if (in_array('cl', explode(',', $user->plugins)) && in_array('cm', explode(',', $user->plugins)) && !$cl_client)
226       $errors->add($i18n->getKey('error.client'));
227     if ($custom_fields) {
228       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $errors->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
229     }
230     if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
231       if (!$cl_project) $errors->add($i18n->getKey('error.project'));           
232     }
233     if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
234       if (!$cl_task) $errors->add($i18n->getKey('error.task'));
235     }      
236     if (!$cl_duration) {
237       if ('0' == $cl_duration)
238         $errors->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
239       else if ($cl_start || $cl_finish) {
240         if (!ttTimeHelper::isValidTime($cl_start))
241           $errors->add($i18n->getKey('error.field'), $i18n->getKey('label.start'));
242         if ($cl_finish) {
243           if (!ttTimeHelper::isValidTime($cl_finish))
244             $errors->add($i18n->getKey('error.field'), $i18n->getKey('label.finish'));
245           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
246             $errors->add($i18n->getKey('error.interval'), $i18n->getKey('label.finish'), $i18n->getKey('label.start'));
247         }
248       } else {
249         if ((TYPE_START_FINISH == $user->record_type) || (TYPE_ALL == $user->record_type)) {
250           $errors->add($i18n->getKey('error.empty'), $i18n->getKey('label.start'));
251           $errors->add($i18n->getKey('error.empty'), $i18n->getKey('label.finish'));
252         }
253         if ((TYPE_DURATION == $user->record_type) || (TYPE_ALL == $user->record_type))
254           $errors->add($i18n->getKey('error.empty'), $i18n->getKey('label.duration'));
255       }
256     } else {
257       if (!ttTimeHelper::isValidDuration($cl_duration))
258         $errors->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
259     }
260     if (!ttValidString($cl_note, true)) $errors->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
261     // Finished validating user input.
262
263     // Prohibit creating entries in future.
264     if (defined('FUTURE_ENTRIES') && !isTrue(FUTURE_ENTRIES)) {
265       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
266       if ($selected_date->after($browser_today))
267         $errors->add($i18n->getKey('error.future_date'));
268     }
269     
270     // Prohibit creating time entries in locked interval.
271     if($lockdate && $selected_date->before($lockdate))
272       $errors->add($i18n->getKey('error.period_locked'));
273     
274     // Prohibit creating another uncompleted record.
275     if ($errors->isEmpty()) {
276       if (($not_completed_rec = ttTimeHelper::getUncompleted($user->getActiveUser())) && (($cl_finish == '') && ($cl_duration == '')))
277         $errors->add($i18n->getKey('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->getKey('error.goto_uncompleted')."</a>");
278     }
279     
280     // Prohibit creating an overlapping record.
281     if ($errors->isEmpty()) {
282       if (ttTimeHelper::overlaps($user->getActiveUser(), $cl_date, $cl_start, $cl_finish))
283         $errors->add($i18n->getKey('error.overlap'));
284     }  
285
286     // Insert record.
287     if ($errors->isEmpty()) {
288       $id = ttTimeHelper::insert(array(
289         'date' => $cl_date,
290         'user_id' => $user->getActiveUser(),
291         'client' => $cl_client,
292         'project' => $cl_project,
293         'task' => $cl_task,
294         'start' => $cl_start,
295         'finish' => $cl_finish,
296         'duration' => $cl_duration,
297         'note' => $cl_note,
298         'billable' => $cl_billable));
299                 
300       // Insert a custom field if we have it.
301       $result = true;
302       if ($id && $custom_fields && $cl_cf_1) {
303         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
304           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
305         else if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
306           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
307       }
308       if ($id && $result) {
309         header('Location: time.php');
310         exit();
311       }
312       $errors->add($i18n->getKey('error.db'));
313     }
314   }
315   else if ($request->getParameter('btn_stop')) {
316         // Stop button pressed to finish an uncompleted record.
317         $record_id = $request->getParameter('record_id');
318         $record = ttTimeHelper::getRecord($record_id, $user->getActiveUser());
319         $browser_date = $request->getParameter('browser_date');
320         $browser_time = $request->getParameter('browser_time');
321         
322         // Can we complete this record?
323         if ($record['date'] == $browser_date                                // closing today's record
324           && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
325           && !ttTimeHelper::overlaps($user->getActiveUser(), $browser_date, $record['start'], $browser_time)) { // no overlap
326       $res = ttTimeHelper::update(array(
327           'id'=>$record['id'],  
328           'date'=>$record['date'],  
329           'user_id'=>$user->getActiveUser(),
330           'client'=>$record['client_id'],  
331           'project'=>$record['project_id'],  
332           'task'=>$record['task_id'],  
333           'start'=>$record['start'],  
334           'finish'=>$browser_time,
335           'note'=>$record['comment'],
336           'billable'=>$record['billable']));
337       if (!$res)
338         $errors->add($i18n->getKey('error.db'));
339         } else {
340       // Cannot complete, redirect for manual edit.
341       header('Location: time_edit.php?id='.$record_id);
342       exit();           
343         }
344   }
345   else if ($request->getParameter('onBehalfUser')) {
346     if($user->canManageTeam()) {
347       unset($_SESSION['behalf_id']);
348       unset($_SESSION['behalf_name']);
349         
350       if($on_behalf_id != $user->id) {
351         $_SESSION['behalf_id'] = $on_behalf_id;
352         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);                    
353       }
354       header('Location: time.php');
355       exit();
356     }
357   }
358 }
359
360 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
361
362 $smarty->assign('week_total', $week_total);
363 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($user->getActiveUser(), $cl_date));
364 $smarty->assign('time_records', ttTimeHelper::getRecords($user->getActiveUser(), $cl_date));
365 $smarty->assign('client_list', $client_list);
366 $smarty->assign('project_list', $project_list);
367 $smarty->assign('task_list', $task_list);
368 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
369 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
370 $smarty->assign('timestring', $selected_date->toString($user->date_format));
371 $smarty->assign('title', $i18n->getKey('title.time'));
372 $smarty->assign('content_page_name', 'time.tpl');
373 $smarty->display('index.tpl');