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