Refactoring custom fields in progress.
[timetracker.git] / mobile / 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('ttGroupHelper');
33 import('ttClientHelper');
34 import('ttTimeHelper');
35 import('DateAndTime');
36
37 // Access checks.
38 if (!ttAccessAllowed('track_own_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 if ($request->isPost()) {
51   $userChanged = $request->getParameter('user_changed'); // Reused in multiple places below.
52   if ($userChanged && !($user->can('track_time') && $user->isUserValid($request->getParameter('user')))) {
53     header('Location: access_denied.php'); // Group changed, but no rght or wrong user id.
54     exit();
55   }
56 }
57 // End of access checks.
58
59 // Determine user for which we display this page.
60 if ($request->isPost() && $userChanged) {
61   $user_id = $request->getParameter('user');
62   $user->setOnBehalfUser($user_id);
63 } else {
64   $user_id = $user->getUser();
65 }
66
67 $group_id = $user->getGroup();
68
69 // Initialize and store date in session.
70 $cl_date = $request->getParameter('date', @$_SESSION['date']);
71 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
72 if($selected_date->isError())
73   $selected_date = new DateAndTime(DB_DATEFORMAT);
74 if(!$cl_date)
75   $cl_date = $selected_date->toString(DB_DATEFORMAT);
76 $_SESSION['date'] = $cl_date;
77
78 // Determine previous and next dates for simple navigation.
79 $prev_date = date('Y-m-d', strtotime('-1 day', strtotime($cl_date)));
80 $next_date = date('Y-m-d', strtotime('+1 day', strtotime($cl_date)));
81
82 // Use custom fields plugin if it is enabled.
83 if ($user->isPluginEnabled('cf')) {
84   require_once('../plugins/CustomFields.class.php');
85   $custom_fields = new CustomFields();
86   $smarty->assign('custom_fields', $custom_fields);
87 }
88
89 // Initialize variables.
90 $cl_start = trim($request->getParameter('start'));
91 $cl_finish = trim($request->getParameter('finish'));
92 $cl_duration = trim($request->getParameter('duration'));
93 $cl_note = trim($request->getParameter('note'));
94 // Custom field.
95 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
96 $_SESSION['cf_1'] = $cl_cf_1;
97 $cl_billable = 1;
98 if ($user->isPluginEnabled('iv')) {
99   if ($request->isPost()) {
100     $cl_billable = $request->getParameter('billable');
101     $_SESSION['billable'] = (int) $cl_billable;
102   } else 
103     if (isset($_SESSION['billable']))
104       $cl_billable = $_SESSION['billable'];
105 }
106 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
107 $_SESSION['client'] = $cl_client;
108 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
109 $_SESSION['project'] = $cl_project;
110 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
111 $_SESSION['task'] = $cl_task;
112
113 // Elements of timeRecordForm.
114 $form = new Form('timeRecordForm');
115 if ($user->can('track_time')) {
116   $rank = $user->getMaxRankForGroup($group_id);
117   if ($user->can('track_own_time'))
118     $options = array('status'=>ACTIVE,'max_rank'=>$rank,'include_self'=>true,'self_first'=>true);
119   else
120     $options = array('status'=>ACTIVE,'max_rank'=>$rank);
121   $user_list = $user->getUsers($options);
122   if (count($user_list) >= 1) {
123     $form->addInput(array('type'=>'combobox',
124       'onchange'=>'document.timeRecordForm.user_changed.value=1;document.timeRecordForm.submit();',
125       'name'=>'user',
126       'style'=>'width: 250px;',
127       'value'=>$user_id,
128       'data'=>$user_list,
129       'datakeys'=>array('id','name')));
130     $form->addInput(array('type'=>'hidden','name'=>'user_changed'));
131     $smarty->assign('user_dropdown', 1);
132   }
133 }
134
135 // Dropdown for clients in MODE_TIME. Use all active clients.
136 if (MODE_TIME == $user->getTrackingMode() && $user->isPluginEnabled('cl')) {
137     $active_clients = ttGroupHelper::getActiveClients(true);
138     $form->addInput(array('type'=>'combobox',
139       'onchange'=>'fillProjectDropdown(this.value);',
140       'name'=>'client',
141       'style'=>'width: 250px;',
142       'value'=>$cl_client,
143       'data'=>$active_clients,
144       'datakeys'=>array('id', 'name'),
145       'empty'=>array(''=>$i18n->get('dropdown.select'))));
146   // Note: in other modes the client list is filtered to relevant clients only. See below.
147 }
148
149 if (MODE_PROJECTS == $user->getTrackingMode() || MODE_PROJECTS_AND_TASKS == $user->getTrackingMode()) {
150   // Dropdown for projects assigned to user.
151   $project_list = $user->getAssignedProjects();
152   $form->addInput(array('type'=>'combobox',
153     'onchange'=>'fillTaskDropdown(this.value);',
154     'name'=>'project',
155     'style'=>'width: 250px;',
156     'value'=>$cl_project,
157     'data'=>$project_list,
158     'datakeys'=>array('id','name'),
159     'empty'=>array(''=>$i18n->get('dropdown.select'))));
160
161   // Dropdown for clients if the clients plugin is enabled.
162   if ($user->isPluginEnabled('cl')) {
163     $active_clients = ttGroupHelper::getActiveClients(true);
164     // We need an array of assigned project ids to do some trimming. 
165     foreach($project_list as $project)
166       $projects_assigned_to_user[] = $project['id'];
167
168     // Build a client list out of active clients. Use only clients that are relevant to user.
169     // Also trim their associated project list to only assigned projects (to user).
170     foreach($active_clients as $client) {
171       $projects_assigned_to_client = explode(',', $client['projects']);
172       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
173         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
174       if ($intersection) {
175         $client['projects'] = implode(',', $intersection);
176         $client_list[] = $client;
177       }
178     }
179     $form->addInput(array('type'=>'combobox',
180       'onchange'=>'fillProjectDropdown(this.value);',
181       'name'=>'client',
182       'style'=>'width: 250px;',
183       'value'=>$cl_client,
184       'data'=>$client_list,
185       'datakeys'=>array('id', 'name'),
186       'empty'=>array(''=>$i18n->get('dropdown.select'))));
187   }
188 }
189
190 if (MODE_PROJECTS_AND_TASKS == $user->getTrackingMode()) {
191   $task_list = ttGroupHelper::getActiveTasks();
192   $form->addInput(array('type'=>'combobox',
193     'name'=>'task',
194     'style'=>'width: 250px;',
195     'value'=>$cl_task,
196     'data'=>$task_list,
197     'datakeys'=>array('id','name'),
198     'empty'=>array(''=>$i18n->get('dropdown.select'))));
199 }
200 if ((TYPE_START_FINISH == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType())) {
201   $form->addInput(array('type'=>'text','name'=>'start','value'=>$cl_start,'onchange'=>"formDisable('start');"));
202   $form->addInput(array('type'=>'text','name'=>'finish','value'=>$cl_finish,'onchange'=>"formDisable('finish');"));
203   if ($user->punch_mode && !$user->canOverridePunchMode()) {
204     // Make the start and finish fields read-only.
205     $form->getElement('start')->setEnabled(false);
206     $form->getElement('finish')->setEnabled(false);
207   }
208 }
209 if ((TYPE_DURATION == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType()))
210   $form->addInput(array('type'=>'text','name'=>'duration','value'=>$cl_duration,'onchange'=>"formDisable('duration');"));
211 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height: 60px;','value'=>$cl_note));
212 if ($user->isPluginEnabled('iv'))
213   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
214 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'')); // User current date, which gets filled in on btn_submit click.
215 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->get('button.submit')));
216
217 // If we have custom fields - add controls for them.
218 if ($custom_fields && $custom_fields->fields[0]) {
219   // Only one custom field is supported at this time.
220   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
221     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
222   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
223     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
224       'style'=>'width: 250px;',
225       'value'=>$cl_cf_1,
226       'data'=>CustomFields::getOptions($custom_fields->fields[0]['id']),
227       'empty'=>array(''=>$i18n->get('dropdown.select'))));
228   }
229 }
230
231 // If we have templates, add a dropdown to select one.
232 if ($user->isPluginEnabled('tp')){
233   $templates = ttGroupHelper::getActiveTemplates();
234   if (count($templates) >= 1) {
235     $form->addInput(array('type'=>'combobox',
236       'onchange'=>'fillNote(this.value);',
237       'name'=>'template',
238       'style'=>'width: 250px;',
239       'data'=>$templates,
240       'datakeys'=>array('id','name'),
241       'empty'=>array(''=>$i18n->get('dropdown.select'))));
242     $smarty->assign('template_dropdown', 1);
243     $smarty->assign('templates', $templates);
244   }
245 }
246
247 // Submit.
248 if ($request->isPost()) {
249   if ($request->getParameter('btn_submit')) {
250
251     // Validate user input.
252     if ($user->isPluginEnabled('cl') && $user->isOptionEnabled('client_required') && !$cl_client)
253       $err->add($i18n->get('error.client'));
254     if ($custom_fields) {
255       if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->get('error.field'), $custom_fields->fields[0]['label']);
256     }
257     if (MODE_PROJECTS == $user->getTrackingMode() || MODE_PROJECTS_AND_TASKS == $user->getTrackingMode()) {
258       if (!$cl_project) $err->add($i18n->get('error.project'));
259     }
260     if (MODE_PROJECTS_AND_TASKS == $user->getTrackingMode() && $user->task_required) {
261       if (!$cl_task) $err->add($i18n->get('error.task'));
262     }
263     if (strlen($cl_duration) == 0) {
264       if ($cl_start || $cl_finish) {
265         if (!ttTimeHelper::isValidTime($cl_start))
266           $err->add($i18n->get('error.field'), $i18n->get('label.start'));
267         if ($cl_finish) {
268           if (!ttTimeHelper::isValidTime($cl_finish))
269             $err->add($i18n->get('error.field'), $i18n->get('label.finish'));
270           if (!ttTimeHelper::isValidInterval($cl_start, $cl_finish))
271             $err->add($i18n->get('error.interval'), $i18n->get('label.finish'), $i18n->get('label.start'));
272         }
273       } else {
274         if ((TYPE_START_FINISH == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType())) {
275           $err->add($i18n->get('error.empty'), $i18n->get('label.start'));
276           $err->add($i18n->get('error.empty'), $i18n->get('label.finish'));
277         }
278         if ((TYPE_DURATION == $user->getRecordType()) || (TYPE_ALL == $user->getRecordType()))
279           $err->add($i18n->get('error.empty'), $i18n->get('label.duration'));
280       }
281     } else {
282       if (false === ttTimeHelper::postedDurationToMinutes($cl_duration))
283         $err->add($i18n->get('error.field'), $i18n->get('label.duration'));
284     }
285     if (!ttValidString($cl_note, true)) $err->add($i18n->get('error.field'), $i18n->get('label.note'));
286     if ($user->isPluginEnabled('tp') && !ttValidTemplateText($cl_note)) {
287       $err->add($i18n->get('error.field'), $i18n->get('label.note'));
288     }
289     if (!ttTimeHelper::canAdd()) $err->add($i18n->get('error.expired'));
290     // Finished validating user input.
291
292     // Prohibit creating entries in future.
293     if (!$user->future_entries) {
294       $browser_today = new DateAndTime(DB_DATEFORMAT, $request->getParameter('browser_today', null));
295       if ($selected_date->after($browser_today))
296         $err->add($i18n->get('error.future_date'));
297     }
298
299     // Prohibit creating entries in locked range.
300     if ($user->isDateLocked($selected_date))
301       $err->add($i18n->get('error.range_locked'));
302
303     // Prohibit creating another uncompleted record.
304     if ($err->no()) {
305       if (($not_completed_rec = ttTimeHelper::getUncompleted($user_id)) && (($cl_finish == '') && ($cl_duration == '')))
306         $err->add($i18n->get('error.uncompleted_exists')." <a href = 'time_edit.php?id=".$not_completed_rec['id']."'>".$i18n->get('error.goto_uncompleted')."</a>");
307     }
308
309     // Prohibit creating an overlapping record.
310     if ($err->no()) {
311       if (ttTimeHelper::overlaps($user_id, $cl_date, $cl_start, $cl_finish))
312         $err->add($i18n->get('error.overlap'));
313     }
314
315     if ($err->no()) {
316       $id = ttTimeHelper::insert(array(
317         'date' => $cl_date,
318         'user_id' => $user_id,
319         'group_id' => $group_id,
320         'org_id' => $user->org_id,
321         'client' => $cl_client,
322         'project' => $cl_project,
323         'task' => $cl_task,
324         'start' => $cl_start,
325         'finish' => $cl_finish,
326         'duration' => $cl_duration,
327         'note' => $cl_note,
328         'billable' => $cl_billable));
329
330       // Insert a custom field if we have it.
331       $result = true;
332       if ($id && $custom_fields && $cl_cf_1) {
333         if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT)
334           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], null, $cl_cf_1);
335         elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN)
336           $result = $custom_fields->insert($id, $custom_fields->fields[0]['id'], $cl_cf_1, null);
337       }
338
339       if ($id && $result) {
340         header('Location: time.php');
341         exit();
342       }
343       $err->add($i18n->get('error.db'));
344     }
345   }
346 } // isPost
347
348 $smarty->assign('next_date', $next_date);
349 $smarty->assign('prev_date', $prev_date);
350 $smarty->assign('time_records', ttTimeHelper::getRecords($cl_date));
351 $smarty->assign('day_total', ttTimeHelper::getTimeForDay($cl_date));
352 $smarty->assign('client_list', $client_list);
353 $smarty->assign('project_list', $project_list);
354 $smarty->assign('task_list', $task_list);
355 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
356 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
357 $smarty->assign('timestring', $selected_date->toString($user->getDateFormat()));
358 $smarty->assign('title', $i18n->get('title.time'));
359 $smarty->assign('content_page_name', 'mobile/time.tpl');
360 $smarty->display('mobile/index.tpl');