posaune
[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('ttConfigHelper');
32 import('ttUserHelper');
33 import('ttGroupHelper');
34 import('ttClientHelper');
35 import('ttTimeHelper');
36 import('ttFileHelper');
37 import('DateAndTime');
38
39 // Access checks.
40 if (!(ttAccessAllowed('track_own_time') || ttAccessAllowed('track_time'))) {
41   header('Location: access_denied.php');
42   exit();
43 }
44 if ($user->behalf_id && (!$user->can('track_time') || !$user->checkBehalfId())) {
45   header('Location: access_denied.php'); // Trying on behalf, but no right or wrong user.
46   exit();
47 }
48 if (!$user->behalf_id && !$user->can('track_own_time') && !$user->adjustBehalfId()) {
49   header('Location: access_denied.php'); // Trying as self, but no right for self, and noone to work on behalf.
50   exit();
51 }
52 if ($request->isPost()) {
53   $userChanged = $request->getParameter('user_changed'); // Reused in multiple places below.
54   if ($userChanged && !($user->can('track_time') && $user->isUserValid($request->getParameter('user')))) {
55     header('Location: access_denied.php'); // Group changed, but no rght or wrong user id.
56     exit();
57   }
58 }
59 // End of access checks.
60
61 // Determine user for whom we display this page.
62 if ($request->isPost() && $userChanged) {
63   $user_id = $request->getParameter('user');
64   $user->setOnBehalfUser($user_id);
65 } else {
66   $user_id = $user->getUser();
67 }
68
69 $group_id = $user->getGroup();
70
71 $showClient = $user->isPluginEnabled('cl');
72 $trackingMode = $user->getTrackingMode();
73 $showProject = MODE_PROJECTS == $trackingMode || MODE_PROJECTS_AND_TASKS == $trackingMode;
74 $showTask = MODE_PROJECTS_AND_TASKS == $trackingMode;
75 $recordType = $user->getRecordType();
76 $showStart = TYPE_START_FINISH == $recordType || TYPE_ALL == $recordType;
77 $showFinish = $showStart;
78 $showDuration = TYPE_DURATION == $recordType || TYPE_ALL == $recordType;
79 $showFiles = $user->isPluginEnabled('at');
80
81 // Initialize and store date in session.
82 $cl_date = $request->getParameter('date', @$_SESSION['date']);
83 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
84 if($selected_date->isError())
85   $selected_date = new DateAndTime(DB_DATEFORMAT);
86 if(!$cl_date)
87   $cl_date = $selected_date->toString(DB_DATEFORMAT);
88 $_SESSION['date'] = $cl_date;
89
90 // Use custom fields plugin if it is enabled.
91 if ($user->isPluginEnabled('cf')) {
92   require_once('plugins/CustomFields.class.php');
93   $custom_fields = new CustomFields();
94   $smarty->assign('custom_fields', $custom_fields);
95 }
96
97 $config = new ttConfigHelper($user->getConfig());
98 $showNoteColumn = !$config->getDefinedValue('time_note_on_separate_row');
99 $showNoteRow = $config->getDefinedValue('time_note_on_separate_row');
100 if ($showNoteRow) {
101   // Determine column span for note field.
102   $colspan = 0;
103   if ($showClient) $colspan++;
104   if ($user->isPluginEnabled('cf')) $colspan++;
105   if ($showProject) $colspan++;
106   if ($showTask) $colspan++;
107   if ($showStart) $colspan++;
108   if ($showFinish) $colspan++;
109   $colspan++; // There is always a duration.
110   if ($showFiles) $colspan++;
111   $colspan++; // There is always an edit column.
112   // $colspan++; // There is always a delete column.
113   // $colspan--; // Remove one column for label.
114   $smarty->assign('colspan', $colspan);
115 }
116
117 if ($user->isPluginEnabled('mq')){
118   require_once('plugins/MonthlyQuota.class.php');
119   $quota = new MonthlyQuota();
120   $month_quota_minutes = $quota->getUserQuota($selected_date->mYear, $selected_date->mMonth);
121   $quota_minutes_from_1st = $quota->getUserQuotaFrom1st($selected_date);
122   $month_total = ttTimeHelper::getTimeForMonth($selected_date);
123   $month_total_minutes = ttTimeHelper::toMinutes($month_total);
124   $balance_left = $quota_minutes_from_1st - $month_total_minutes;
125   $minutes_left = $month_quota_minutes - $month_total_minutes;
126   
127   $smarty->assign('month_total', $month_total);
128   $smarty->assign('month_quota', ttTimeHelper::toAbsDuration($month_quota_minutes));
129   $smarty->assign('over_balance', $balance_left < 0);
130   $smarty->assign('balance_remaining', ttTimeHelper::toAbsDuration($balance_left));
131   $smarty->assign('over_quota', $minutes_left < 0);
132   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
133 }
134
135 // Initialize variables.
136 $cl_start = trim($request->getParameter('start'));
137 $cl_finish = trim($request->getParameter('finish'));
138 $cl_duration = trim($request->getParameter('duration'));
139 $cl_note = trim($request->getParameter('note'));
140 // Custom field.
141 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
142 $_SESSION['cf_1'] = $cl_cf_1;
143 $cl_billable = 1;
144 if ($user->isPluginEnabled('iv')) {
145   if ($request->isPost()) {
146     $cl_billable = $request->getParameter('billable');
147     $_SESSION['billable'] = (int) $cl_billable;
148   } else
149     if (isset($_SESSION['billable']))
150       $cl_billable = $_SESSION['billable'];
151 }
152 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
153 $_SESSION['client'] = $cl_client;
154 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
155 $_SESSION['project'] = $cl_project;
156 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
157 $_SESSION['task'] = $cl_task;
158
159 // Elements of timeRecordForm.
160 $form = new Form('timeRecordForm');
161 if ($user->can('track_time')) {
162   $rank = $user->getMaxRankForGroup($group_id);
163   if ($user->can('track_own_time'))
164     $options = array('status'=>ACTIVE,'max_rank'=>$rank,'include_self'=>true,'self_first'=>true);
165   else
166     $options = array('status'=>ACTIVE,'max_rank'=>$rank);
167   $user_list = $user->getUsers($options);
168   if (count($user_list) >= 1) {
169     $form->addInput(array('type'=>'combobox',
170       'onchange'=>'document.timeRecordForm.user_changed.value=1;document.timeRecordForm.submit();',
171       'name'=>'user',
172       'style'=>'width: 250px;',
173       'value'=>$user_id,
174       'data'=>$user_list,
175       'datakeys'=>array('id','name')));
176     $form->addInput(array('type'=>'hidden','name'=>'user_changed'));
177     $smarty->assign('user_dropdown', 1);
178   }
179 }
180
181 // Dropdown for clients in MODE_TIME. Use all active clients.
182 if (MODE_TIME == $trackingMode && $showClient) {
183   $active_clients = ttGroupHelper::getActiveClients(true);
184   $form->addInput(array('type'=>'combobox',
185     'onchange'=>'fillProjectDropdown(this.value);',
186     'name'=>'client',
187     'style'=>'width: 250px;',
188     'value'=>$cl_client,
189     'data'=>$active_clients,
190     'datakeys'=>array('id', 'name'),
191     'empty'=>array(''=>$i18n->get('dropdown.select'))));
192   // Note: in other modes the client list is filtered to relevant clients only. See below.
193 }
194
195 if ($showProject) {
196   // Dropdown for projects assigned to user.
197   $project_list = $user->getAssignedProjects();
198   $form->addInput(array('type'=>'combobox',
199     'onchange'=>'fillTaskDropdown(this.value);',
200     'name'=>'project',
201     'style'=>'width: 250px;',
202     'value'=>$cl_project,
203     'data'=>$project_list,
204     'datakeys'=>array('id','name'),
205     'empty'=>array(''=>$i18n->get('dropdown.select'))));
206
207   // Dropdown for clients if the clients plugin is enabled.
208   if ($showClient) {
209     $active_clients = ttGroupHelper::getActiveClients(true);
210     // We need an array of assigned project ids to do some trimming.
211     foreach($project_list as $project)
212       $projects_assigned_to_user[] = $project['id'];
213
214     // Build a client list out of active clients. Use only clients that are relevant to user.
215     // Also trim their associated project list to only assigned projects (to user).
216     foreach($active_clients as $client) {
217       $projects_assigned_to_client = explode(',', $client['projects']);
218       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
219         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
220       if ($intersection) {
221         $client['projects'] = implode(',', $intersection);
222         $client_list[] = $client;
223       }
224     }
225     $form->addInput(array('type'=>'combobox',
226       'onchange'=>'fillProjectDropdown(this.value);',
227       'name'=>'client',
228       'style'=>'width: 250px;',
229       'value'=>$cl_client,
230       'data'=>$client_list,
231       'datakeys'=>array('id', 'name'),
232       'empty'=>array(''=>$i18n->get('dropdown.select'))));
233   }
234 }
235
236 if ($showTask) {
237   $task_list = ttGroupHelper::getActiveTasks();
238   $form->addInput(array('type'=>'combobox',
239     'name'=>'task',
240     'style'=>'width: 250px;',
241     'value'=>$cl_task,
242     'data'=>$task_list,
243     'datakeys'=>array('id','name'),
244     'empty'=>array(''=>$i18n->get('dropdown.select'))));
245 }
246
247 // Add other controls.
248 if ($showStart) {
249   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
250   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
251   if ($user->punch_mode && !$user->canOverridePunchMode()) {
252     // Make the start and finish fields read-only.
253     $form->getElement('start')->setEnabled(false);
254     $form->getElement('finish')->setEnabled(false);
255   }
256 }
257 if ($showDuration)
258   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
259 if ($showFiles)
260   $form->addInput(array('type'=>'upload','name'=>'newfile','value'=>$i18n->get('button.submit')));
261 if (!defined('NOTE_INPUT_HEIGHT'))
262   define('NOTE_INPUT_HEIGHT', 40);
263 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 600px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
264 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
265
266
267
268 // TODO: refactoring ongoing down from here. Use $showBillable, perhaps?
269 if ($user->isPluginEnabled('iv'))
270   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
271 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
272 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
273
274 // If we have custom fields - add controls for them.
275 if ($custom_fields && $custom_fields->fields[0]) {
276   // Only one custom field is supported at this time.
277   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
278     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
279   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
280     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
281       'style'=>'width: 250px;',
282       'value'=>$cl_cf_1,
283       'data'=>CustomFields::getOptions($custom_fields->fields[0]['id']),
284       'empty'=>array(''=>$i18n->get('dropdown.select'))));
285   }
286 }
287
288 // If we have templates, add a dropdown to select one.
289 if ($user->isPluginEnabled('tp')){
290   $templates = ttGroupHelper::getActiveTemplates();
291   if (count($templates) >= 1) {
292     $form->addInput(array('type'=>'combobox',
293       'onchange'=>'fillNote(this.value);',
294       'name'=>'template',
295       'style'=>'width: 250px;',
296       'data'=>$templates,
297       'datakeys'=>array('id','name'),
298       'empty'=>array(''=>$i18n->get('dropdown.select'))));
299     $smarty->assign('template_dropdown', 1);
300     $smarty->assign('templates', $templates);
301   }
302 }
303
304 // Submit.
305 if ($request->isPost()) {
306   if ($request->getParameter('btn_submit')) {
307
308     // Validate user input.
309     if ($showClient && $user->isOptionEnabled('client_required') && !$cl_client)
310       $err->add($i18n->get('error.client'));
311     if ($custom_fields) {
312       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
313     }
314     if (MODE_PROJECTS == $user->getTrackingMode() || MODE_PROJECTS_AND_TASKS == $user->getTrackingMode()) {
315       if (!$cl_project) $err->add($i18n->get('error.project'));
316     }
317     if (MODE_PROJECTS_AND_TASKS == $user->getTrackingMode() && $user->task_required) {
318       if (!$cl_task) $err->add($i18n->get('error.task'));
319     }
320     if (strlen($cl_duration) == 0) {
321       if ($cl_start || $cl_finish) {
322         if (!ttTimeHelper::isValidTime($cl_start))
323           $err->add($i18n->get('error.field'), $i18n->get('label.start'));
324         if ($cl_finish) {
325           if (!ttTimeHelper::isValidTime($cl_finish))
326             $err->add($i18n->get('error.field'), $i18n->get('label.finish'));
327           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
328             $err->add($i18n->get('error.interval'), $i18n->get('label.finish'), $i18n->get('label.start'));
329         }
330       } else {
331         if ((TYPE_START_FINISH == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType())) {
332           $err->add($i18n->get('error.empty'), $i18n->get('label.start'));
333           $err->add($i18n->get('error.empty'), $i18n->get('label.finish'));
334         }
335         if ((TYPE_DURATION == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType()))
336           $err->add($i18n->get('error.empty'), $i18n->get('label.duration'));
337       }
338     } else {
339       if (false === ttTimeHelper::postedDurationToMinutes($cl_duration))
340         $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
341     }
342     if (!ttValidString($cl_note, true)) $err->add($i18n->get('error.field'), $i18n->get('label.note'));
343     if ($user->isPluginEnabled('tp') && !ttValidTemplateText($cl_note)) {
344       $err->add($i18n->get('error.field'), $i18n->get('label.note'));
345     }
346     if (!ttTimeHelper::canAdd()) $err->add($i18n->get('error.expired'));
347     // Finished validating user input.
348
349     // Prohibit creating entries in future.
350     if (!$user->future_entries) {
351       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
352       if ($selected_date->after($browser_today))
353         $err->add($i18n->get('error.future_date'));
354     }
355
356     // Prohibit creating entries in locked range.
357     if ($user->isDateLocked($selected_date))
358       $err->add($i18n->get('error.range_locked'));
359
360     // Prohibit creating another uncompleted record.
361     if ($err->no()) {
362       if (($not_completed_rec = ttTimeHelper::getUncompleted($user_id)) && (($cl_finish == '') && ($cl_duration == '')))
363         $err->add($i18n->get('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->get('error.goto_uncompleted')."</a>");
364     }
365
366     // Prohibit creating an overlapping record.
367     if ($err->no()) {
368       if (ttTimeHelper::overlaps($user_id, $cl_date, $cl_start, $cl_finish))
369         $err->add($i18n->get('error.overlap'));
370     }
371
372     // Insert record.
373     if ($err->no()) {
374       $id = ttTimeHelper::insert(array(
375         'date' => $cl_date,
376         'user_id' => $user_id,
377         'group_id' => $group_id,
378         'org_id' => $user->org_id,
379         'client' => $cl_client,
380         'project' => $cl_project,
381         'task' => $cl_task,
382         'start' => $cl_start,
383         'finish' => $cl_finish,
384         'duration' => $cl_duration,
385         'note' => $cl_note,
386         'billable' => $cl_billable));
387
388       // Insert a custom field if we have it.
389       $result = true;
390       if ($id && $custom_fields && $cl_cf_1) {
391         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
392           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
393         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
394           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
395       }
396
397       // Put a new file in storage if we have it.
398       if ($id && $showFiles && $_FILES['newfile']['name']) {
399         $fileHelper = new ttFileHelper($err);
400         $fields = array('entity_type'=>'time',
401           'entity_id' => $id,
402           'file_name' => $_FILES['newfile']['name']);
403         $fileHelper->putFile($fields);
404       }
405
406       if ($id && $result && $err->no()) {
407         header('Location: time.php');
408         exit();
409       }
410       $err->add($i18n->get('error.db'));
411     }
412   } elseif ($request->getParameter('btn_stop')) {
413     // Stop button pressed to finish an uncompleted record.
414     $record_id = $request->getParameter('record_id');
415     $record = ttTimeHelper::getRecord($record_id);
416     $browser_date = $request->getParameter('browser_date');
417     $browser_time = $request->getParameter('browser_time');
418
419     // Can we complete this record?
420     if ($record['date'] == $browser_date                                // closing today's record
421       && ttTimeHelper::isValidInterval($record['start'], $browser_time) // finish time is greater than start time
422       && !ttTimeHelper::overlaps($user_id, $browser_date, $record['start'], $browser_time)) { // no overlap
423       $res = ttTimeHelper::update(array(
424           'id'=>$record['id'],
425           'date'=>$record['date'],
426           'user_id'=>$user_id,
427           'client'=>$record['client_id'],
428           'project'=>$record['project_id'],
429           'task'=>$record['task_id'],
430           'start'=>$record['start'],
431           'finish'=>$browser_time,
432           'note'=>$record['comment'],
433           'billable'=>$record['billable']));
434       if (!$res)
435         $err->add($i18n->get('error.db'));
436     } else {
437       // Cannot complete, redirect for manual edit.
438       header('Location: time_edit.php?id='.$record_id);
439       exit();
440     }
441   }
442 } // isPost
443
444 $week_total = ttTimeHelper::getTimeForWeek($selected_date);
445 $timeRecords = ttTimeHelper::getRecords($cl_date, $showFiles);
446
447 $smarty->assign('selected_date', $selected_date);
448 $smarty->assign('week_total', $week_total);
449 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($cl_date));
450 $smarty->assign('time_records', $timeRecords);
451 $smarty->assign('show_navigation', $user->isPluginEnabled('wv') && !$user->isOptionEnabled('week_menu'));
452 $smarty->assign('show_client', $showClient);
453 $smarty->assign('show_cf_1', $user->isPluginEnabled('cf'));
454 $smarty->assign('show_project', $showProject);
455 $smarty->assign('show_task', $showTask);
456 $smarty->assign('show_start', $showStart);
457 $smarty->assign('show_finish', $showFinish);
458 $smarty->assign('show_duration', $showDuration);
459 $smarty->assign('show_note_column', $showNoteColumn);
460 $smarty->assign('show_note_row', $showNoteRow);
461 $smarty->assign('show_files', $showFiles);
462 $smarty->assign('client_list', $client_list);
463 $smarty->assign('project_list', $project_list);
464 $smarty->assign('task_list', $task_list);
465 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
466 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
467 $smarty->assign('timestring', $selected_date->toString($user->getDateFormat()));
468 $smarty->assign('title', $i18n->get('title.time'));
469 $smarty->assign('content_page_name', 'time.tpl');
470 $smarty->display('index.tpl');