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.
 
  11 // | There are only two ways to violate the license:
 
  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).
 
  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).
 
  21 // | This license applies to this document only, not any other software
 
  22 // | that it may be combined with.
 
  24 // +----------------------------------------------------------------------+
 
  26 // | https://www.anuko.com/time_tracker/credits.htm
 
  27 // +----------------------------------------------------------------------+
 
  29 require_once('initialize.php');
 
  31 import('form.DefaultCellRenderer');
 
  33 import('form.TextField');
 
  34 import('ttUserHelper');
 
  35 import('ttTeamHelper');
 
  36 import('ttWeekViewHelper');
 
  37 import('ttClientHelper');
 
  38 import('ttTimeHelper');
 
  39 import('DateAndTime');
 
  42 if (!ttAccessAllowed('track_own_time') || !$user->isPluginEnabled('wv')) {
 
  43   header('Location: access_denied.php');
 
  47 // Initialize and store date in session.
 
  48 $cl_date = $request->getParameter('date', @$_SESSION['date']);
 
  49 $selected_date = new DateAndTime(DB_DATEFORMAT, $cl_date);
 
  50 if($selected_date->isError())
 
  51   $selected_date = new DateAndTime(DB_DATEFORMAT);
 
  53   $cl_date = $selected_date->toString(DB_DATEFORMAT);
 
  54 $_SESSION['date'] = $cl_date;
 
  56 // Determine selected week start and end dates.
 
  57 $weekStartDay = $user->week_start;
 
  58 $t_arr = localtime($selected_date->getTimestamp());
 
  59 $t_arr[5] = $t_arr[5] + 1900;
 
  60 if ($t_arr[6] < $weekStartDay)
 
  61   $startWeekBias = $weekStartDay - 7;
 
  63   $startWeekBias = $weekStartDay;
 
  64 $startDate = new DateAndTime();
 
  65 $startDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+$startWeekBias,$t_arr[5]));
 
  66 $endDate = new DateAndTime();
 
  67 $endDate->setTimestamp(mktime(0,0,0,$t_arr[4]+1,$t_arr[3]-$t_arr[6]+6+$startWeekBias,$t_arr[5]));
 
  68 // The above is needed to set date range (timestring) in page title.
 
  70 // Use custom fields plugin if it is enabled.
 
  71 if ($user->isPluginEnabled('cf')) {
 
  72   require_once('plugins/CustomFields.class.php');
 
  73   $custom_fields = new CustomFields($user->team_id);
 
  74   $smarty->assign('custom_fields', $custom_fields);
 
  77 // Use Monthly Quotas plugin, if applicable.
 
  78 if ($user->isPluginEnabled('mq')){
 
  79   require_once('plugins/MonthlyQuota.class.php');
 
  80   $quota = new MonthlyQuota();
 
  81   $month_quota = $quota->get($selected_date->mYear, $selected_date->mMonth);
 
  82   $month_total = ttTimeHelper::getTimeForMonth($user->getActiveUser(), $selected_date);
 
  83   $minutes_left = round(60*$month_quota) - ttTimeHelper::toMinutes($month_total);
 
  85   $smarty->assign('month_total', $month_total);
 
  86   $smarty->assign('over_quota', $minutes_left < 0);
 
  87   $smarty->assign('quota_remaining', ttTimeHelper::toAbsDuration($minutes_left));
 
  90 // Initialize variables.
 
  92 $cl_cf_1 = trim($request->getParameter('cf_1', ($request->isPost() ? null : @$_SESSION['cf_1'])));
 
  93 $_SESSION['cf_1'] = $cl_cf_1;
 
  95 if ($user->isPluginEnabled('iv')) {
 
  96   if ($request->isPost()) {
 
  97     $cl_billable = $request->getParameter('billable');
 
  98     $_SESSION['billable'] = (int) $cl_billable;
 
 100     if (isset($_SESSION['billable']))
 
 101       $cl_billable = $_SESSION['billable'];
 
 103 $on_behalf_id = $request->getParameter('onBehalfUser', (isset($_SESSION['behalf_id'])? $_SESSION['behalf_id'] : $user->id));
 
 104 $cl_client = $request->getParameter('client', ($request->isPost() ? null : @$_SESSION['client']));
 
 105 $_SESSION['client'] = $cl_client;
 
 106 $cl_project = $request->getParameter('project', ($request->isPost() ? null : @$_SESSION['project']));
 
 107 $_SESSION['project'] = $cl_project;
 
 108 $cl_task = $request->getParameter('task', ($request->isPost() ? null : @$_SESSION['task']));
 
 109 $_SESSION['task'] = $cl_task;
 
 110 $cl_note = $request->getParameter('note', ($request->isPost() ? null : @$_SESSION['note']));
 
 111 $_SESSION['note'] = $cl_note;
 
 113 // Get the data we need to display week view.
 
 114 // Get column headers, which are day numbers in month.
 
 115 $dayHeaders = ttWeekViewHelper::getDayHeadersForWeek($startDate->toString(DB_DATEFORMAT));
 
 116 $lockedDays = ttWeekViewHelper::getLockedDaysForWeek($startDate->toString(DB_DATEFORMAT));
 
 117 // Get already existing records.
 
 118 $records = ttWeekViewHelper::getRecordsForInterval($user->getActiveUser(), $startDate->toString(DB_DATEFORMAT), $endDate->toString(DB_DATEFORMAT));
 
 119 // Build data array for the table. Format is described in ttWeekViewHelper::getDataForWeekView function.
 
 121   $dataArray = ttWeekViewHelper::getDataForWeekView($records, $dayHeaders);
 
 123   $dataArray = ttWeekViewHelper::prePopulateFromPastWeeks($startDate->toString(DB_DATEFORMAT), $dayHeaders);
 
 125 // Build day totals (total durations for each day in week).
 
 126 $dayTotals = ttWeekViewHelper::getDayTotals($dataArray, $dayHeaders);
 
 128 // Define rendering class for a label field to the left of durations.
 
 129 class LabelCellRenderer extends DefaultCellRenderer {
 
 130   function render(&$table, $value, $row, $column, $selected = false) {
 
 133     $this->setOptions(array('width'=>200,'valign'=>'middle'));
 
 135     // Special handling for a new week entry (row 0, or 0 and 1 if we show notes).
 
 137       $this->setOptions(array('style'=>'text-align: center; font-weight: bold; vertical-align: top;'));
 
 138     } else if ($user->isPluginEnabled('wvns') && (1 == $row)) {
 
 139       $this->setOptions(array('style'=>'text-align: right; vertical-align: top;'));
 
 140     } else if ($user->isPluginEnabled('wvns') && (0 != $row % 2)) {
 
 141       $this->setOptions(array('style'=>'text-align: right;'));
 
 143     // Special handling for not billable entries.
 
 144     $ignoreRow = $user->isPluginEnabled('wvns') ? 1 : 0; 
 
 145     if ($row > $ignoreRow) {
 
 146       $row_id = $table->getValueAtName($row,'row_id');
 
 147       $billable = ttWeekViewHelper::parseFromWeekViewRow($row_id, 'bl');
 
 149         if (($user->isPluginEnabled('wvns') && (0 == $row % 2)) || !$user->isPluginEnabled('wvns')) {
 
 150           $this->setOptions(array('style'=>'color: red;')); // TODO: style it properly in CSS.
 
 154     $this->setValue(htmlspecialchars($value)); // This escapes HTML for output.
 
 155     return $this->toString();
 
 159 // Define rendering class for a single cell for a time or a comment entry in week view table.
 
 160 class WeekViewCellRenderer extends DefaultCellRenderer {
 
 161   function render(&$table, $value, $row, $column, $selected = false) {
 
 164     $field_name = $table->getValueAt($row,$column)['control_id']; // Our text field names (and ids) are like x_y (row_column).
 
 165     $field = new TextField($field_name);
 
 166     // Disable control if the date is locked.
 
 168     if ($lockedDays[$column-1])
 
 169       $field->setEnabled(false);
 
 170     $field->setFormName($table->getFormName());
 
 171     $field->setStyle('width: 60px;'); // TODO: need to style everything properly, eventually.
 
 172     // Provide visual separation for new entry row.
 
 173     $rowToSeparate = $user->isPluginEnabled('wvns') ? 1 : 0;
 
 174     if ($rowToSeparate == $row) {
 
 175       $field->setStyle('width: 60px; margin-bottom: 40px');
 
 177     if ($user->isPluginEnabled('wvns')) {
 
 179         $field->setValue($table->getValueAt($row,$column)['duration']); // Duration for even rows.
 
 181         $field->setValue($table->getValueAt($row,$column)['note']);     // Comment for odd rows.
 
 182         $field->setTitle($table->getValueAt($row,$column)['note']);     // Tooltip to help view the entire comment.
 
 185       $field->setValue($table->getValueAt($row,$column)['duration']);
 
 186       // $field->setTitle($table->getValueAt($row,$column)['note']); // Tooltip to see comment. TODO - value not available.
 
 188     // Disable control when time entry mode is TYPE_START_FINISH and there is no value in control
 
 189     // because we can't supply start and finish times in week view - there are no fields for them.
 
 190     if (!$field->getValue() && TYPE_START_FINISH == $user->record_type) {
 
 191         $field->setEnabled(false);
 
 193     $this->setValue($field->getHtml());
 
 194     return $this->toString();
 
 198 // Elements of weekTimeForm.
 
 199 $form = new Form('weekTimeForm');
 
 201 if ($user->can('track_time')) {
 
 202   $user_list = ttTeamHelper::getActiveUsers(array('putSelfFirst'=>true));
 
 203   if (count($user_list) > 1) {
 
 204     $form->addInput(array('type'=>'combobox',
 
 205       'onchange'=>'this.form.submit();',
 
 206       'name'=>'onBehalfUser',
 
 207       'style'=>'width: 250px;',
 
 208       'value'=>$on_behalf_id,
 
 210       'datakeys'=>array('id','name')));
 
 211     $smarty->assign('on_behalf_control', 1);
 
 215 // Create week_durations table.
 
 216 $table = new Table('week_durations', 'week_view_table');
 
 217 $table->setTableOptions(array('width'=>'100%','cellspacing'=>'1','cellpadding'=>'3','border'=>'0'));
 
 218 $table->setRowOptions(array('class'=>'tableHeaderCentered'));
 
 219 $table->setData($dataArray);
 
 220 // Add columns to table.
 
 221 $table->addColumn(new TableColumn('label', '', new LabelCellRenderer(), $dayTotals['label']));
 
 222 for ($i = 0; $i < 7; $i++) {
 
 223   $table->addColumn(new TableColumn($dayHeaders[$i], $dayHeaders[$i], new WeekViewCellRenderer(), $dayTotals[$dayHeaders[$i]]));
 
 225 $table->setInteractive(false);
 
 226 $form->addInputElement($table);
 
 228 // Dropdown for clients in MODE_TIME. Use all active clients.
 
 229 if (MODE_TIME == $user->tracking_mode && $user->isPluginEnabled('cl')) {
 
 230   $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
 
 231   $form->addInput(array('type'=>'combobox',
 
 232     'onchange'=>'fillProjectDropdown(this.value);',
 
 234     'style'=>'width: 250px;',
 
 236     'data'=>$active_clients,
 
 237     'datakeys'=>array('id', 'name'),
 
 238     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
 
 239   // Note: in other modes the client list is filtered to relevant clients only. See below.
 
 242 if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
 
 243   // Dropdown for projects assigned to user.
 
 244   $project_list = $user->getAssignedProjects();
 
 245   $form->addInput(array('type'=>'combobox',
 
 246     'onchange'=>'fillTaskDropdown(this.value);',
 
 248     'style'=>'width: 250px;',
 
 249     'value'=>$cl_project,
 
 250     'data'=>$project_list,
 
 251     'datakeys'=>array('id','name'),
 
 252     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
 
 254   // Dropdown for clients if the clients plugin is enabled.
 
 255   if ($user->isPluginEnabled('cl')) {
 
 256     $active_clients = ttTeamHelper::getActiveClients($user->team_id, true);
 
 257     // We need an array of assigned project ids to do some trimming.
 
 258     foreach($project_list as $project)
 
 259       $projects_assigned_to_user[] = $project['id'];
 
 261     // Build a client list out of active clients. Use only clients that are relevant to user.
 
 262     // Also trim their associated project list to only assigned projects (to user).
 
 263     foreach($active_clients as $client) {
 
 264       $projects_assigned_to_client = explode(',', $client['projects']);
 
 265       if (is_array($projects_assigned_to_client) && is_array($projects_assigned_to_user))
 
 266         $intersection = array_intersect($projects_assigned_to_client, $projects_assigned_to_user);
 
 268         $client['projects'] = implode(',', $intersection);
 
 269         $client_list[] = $client;
 
 272     $form->addInput(array('type'=>'combobox',
 
 273       'onchange'=>'fillProjectDropdown(this.value);',
 
 275       'style'=>'width: 250px;',
 
 277       'data'=>$client_list,
 
 278       'datakeys'=>array('id', 'name'),
 
 279       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
 
 283 if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
 
 284   $task_list = ttTeamHelper::getActiveTasks($user->team_id);
 
 285   $form->addInput(array('type'=>'combobox',
 
 287     'style'=>'width: 250px;',
 
 290     'datakeys'=>array('id','name'),
 
 291     'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
 
 293 if (!defined('NOTE_INPUT_HEIGHT'))
 
 294   define('NOTE_INPUT_HEIGHT', 40);
 
 295 $form->addInput(array('type'=>'textarea','name'=>'note','style'=>'width: 250px; height:'.NOTE_INPUT_HEIGHT.'px;','value'=>$cl_note));
 
 297 // Add other controls.
 
 298 $form->addInput(array('type'=>'calendar','name'=>'date','value'=>$cl_date)); // calendar
 
 299 if ($user->isPluginEnabled('iv'))
 
 300   $form->addInput(array('type'=>'checkbox','name'=>'billable','value'=>$cl_billable));
 
 301 $form->addInput(array('type'=>'hidden','name'=>'browser_today','value'=>'get_date()')); // User current date, which gets filled in on btn_submit click.
 
 302 $form->addInput(array('type'=>'submit','name'=>'btn_submit','onclick'=>'browser_today.value=get_date()','value'=>$i18n->getKey('button.submit')));
 
 304 // If we have custom fields - add controls for them.
 
 305 if ($custom_fields && $custom_fields->fields[0]) {
 
 306   // Only one custom field is supported at this time.
 
 307   if ($custom_fields->fields[0]['type'] == CustomFields::TYPE_TEXT) {
 
 308     $form->addInput(array('type'=>'text','name'=>'cf_1','value'=>$cl_cf_1));
 
 309   } elseif ($custom_fields->fields[0]['type'] == CustomFields::TYPE_DROPDOWN) {
 
 310     $form->addInput(array('type'=>'combobox','name'=>'cf_1',
 
 311       'style'=>'width: 250px;',
 
 313       'data'=>$custom_fields->options,
 
 314       'empty'=>array(''=>$i18n->getKey('dropdown.select'))));
 
 319 if ($request->isPost()) {
 
 320   if ($request->getParameter('btn_submit')) {
 
 321     // Validate user input for row 0.
 
 322     // Determine if a new entry was posted.
 
 323     $newEntryPosted = false;
 
 324     foreach($dayHeaders as $dayHeader) {
 
 325       $control_id = '0_'.$dayHeader;
 
 326       if ($request->getParameter($control_id)) {
 
 327         $newEntryPosted = true;
 
 331     if ($newEntryPosted) {
 
 332       if ($user->isPluginEnabled('cl') && $user->isPluginEnabled('cm') && !$cl_client)
 
 333         $err->add($i18n->getKey('error.client'));
 
 334       if ($custom_fields) {
 
 335         if (!ttValidString($cl_cf_1, !$custom_fields->fields[0]['required'])) $err->add($i18n->getKey('error.field'), $custom_fields->fields[0]['label']);
 
 337       if (MODE_PROJECTS == $user->tracking_mode || MODE_PROJECTS_AND_TASKS == $user->tracking_mode) {
 
 338         if (!$cl_project) $err->add($i18n->getKey('error.project'));
 
 340       if (MODE_PROJECTS_AND_TASKS == $user->tracking_mode && $user->task_required) {
 
 341         if (!$cl_task) $err->add($i18n->getKey('error.task'));
 
 344     // Finished validating user input for row 0.
 
 346     // Process the table of values.
 
 349       // Obtain values. Iterate through posted parameters one by one,
 
 350       // see if value changed, apply one change at a time until we see an error.
 
 353       // Iterate through existing rows.
 
 354       foreach ($dataArray as $row) {
 
 355         // Iterate through days.
 
 356         foreach ($dayHeaders as $key => $dayHeader) {
 
 357           // Do not process locked days.
 
 358           if ($lockedDays[$key]) continue;
 
 359           // Make control id for the cell.
 
 360           $control_id = $rowNumber.'_'.$dayHeader;
 
 362           // Handle durations and comments in separate blocks of code.
 
 363           if (!$user->isPluginEnabled('wvns') || (0 == $rowNumber % 2)) {
 
 364             // Handle durations row here.
 
 366             // Obtain existing and posted durations.
 
 367             $postedDuration = $request->getParameter($control_id);
 
 368             $existingDuration = $dataArray[$rowNumber][$dayHeader]['duration'];
 
 369             // If posted value is not null, check and normalize it.
 
 370             if ($postedDuration) {
 
 371               if (false === ttTimeHelper::postedDurationToMinutes($postedDuration)) {
 
 372                 $err->add($i18n->getKey('error.field'), $i18n->getKey('label.duration'));
 
 373                 $result = false; break; // Break out. Stop any further processing.
 
 375                 $minutes = ttTimeHelper::postedDurationToMinutes($postedDuration);
 
 376                 $postedDuration = ttTimeHelper::minutesToDuration($minutes);
 
 379             // Do not process if value has not changed.
 
 380             if ($postedDuration == $existingDuration)
 
 382             // Posted value is different.
 
 383             if ($existingDuration == null) {
 
 384               // Skip inserting 0 duration values.
 
 385               if (0 == ttTimeHelper::toMinutes($postedDuration))
 
 387               // Insert a new record.
 
 389               $fields['row_id'] = $dataArray[$rowNumber]['row_id'];
 
 390               if (!$fields['row_id']) {
 
 391                 // Special handling for row 0, a new entry. Need to construct new row_id.
 
 393                 $record['client_id'] = $cl_client;
 
 394                 $record['billable'] = $cl_billable ? '1' : '0';
 
 395                 $record['project_id'] = $cl_project;
 
 396                 $record['task_id'] = $cl_task;
 
 397                 $record['cf_1_value'] = $cl_cf_1;
 
 398                 $fields['row_id'] = ttWeekViewHelper::makeRowIdentifier($record).'_0';
 
 399                 // Note: no need to check for a possible conflict with an already existing row
 
 400                 // because we are doing an insert that does not affect already existing data.
 
 402                 if ($user->isPluginEnabled('wvn')) {
 
 403                   $fields['note'] = $request->getParameter('note');
 
 406               $fields['day_header'] = $dayHeader;
 
 407               $fields['start_date'] = $startDate->toString(DB_DATEFORMAT); // To be able to determine date for the entry using $dayHeader.
 
 408               $fields['duration'] = $postedDuration;
 
 409               $fields['browser_today'] = $request->getParameter('browser_today', null);
 
 410               if ($user->isPluginEnabled('wvns')) {
 
 411                 // Take note value from the control below duration.
 
 412                 $noteRowNumber = $rowNumber + 1;
 
 413                 $note_control_id =  $noteRowNumber.'_'.$dayHeader;
 
 414                 $fields['note'] = $request->getParameter($note_control_id);
 
 416               $result = ttWeekViewHelper::insertDurationFromWeekView($fields, $custom_fields, $err);
 
 417             } elseif ($postedDuration == null || 0 == ttTimeHelper::toMinutes($postedDuration)) {
 
 418               // Delete an already existing record here.
 
 419               $result = ttTimeHelper::delete($dataArray[$rowNumber][$dayHeader]['tt_log_id'], $user->getActiveUser());
 
 422               $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
 
 423               $fields['duration'] = $postedDuration;
 
 424               $result = ttWeekViewHelper::modifyDurationFromWeekView($fields, $err);
 
 426             if (!$result) break; // Break out of the loop in case of first error.
 
 428           } else if ($user->isPluginEnabled('wvns')) {
 
 429             // Handle commments row here.
 
 431             // Obtain existing and posted comments.
 
 432             $postedComment = $request->getParameter($control_id);
 
 433             $existingComment = $dataArray[$rowNumber][$dayHeader]['note'];
 
 434             // If posted value is not null, check it.
 
 435             if ($postedComment && !ttValidString($postedComment, true)) {
 
 436               $err->add($i18n->getKey('error.field'), $i18n->getKey('label.note'));
 
 437               $result = false; break; // Break out. Stop any further processing.
 
 439             // Do not process if value has not changed.
 
 440             if ($postedComment == $existingComment)
 
 443             // Posted value is different.
 
 444             // TODO: handle new entries separately in the durations block above.
 
 446             // Here, only update the comment on an already existing record.
 
 448             $fields['tt_log_id'] = $dataArray[$rowNumber][$dayHeader]['tt_log_id'];
 
 449             if ($fields['tt_log_id']) {
 
 450               $fields['comment'] = $postedComment;
 
 451               $result = ttWeekViewHelper::modifyCommentFromWeekView($fields);
 
 453             if (!$result) break; // Break out of the loop in case of first error.
 
 456         if (!$result) break; // Break out of the loop in case of first error.
 
 460         header('Location: week.php'); // Normal exit.
 
 465   elseif ($request->getParameter('onBehalfUser')) {
 
 466     if($user->can('track_time')) {
 
 467       unset($_SESSION['behalf_id']);
 
 468       unset($_SESSION['behalf_name']);
 
 470       if($on_behalf_id != $user->id) {
 
 471         $_SESSION['behalf_id'] = $on_behalf_id;
 
 472         $_SESSION['behalf_name'] = ttUserHelper::getUserName($on_behalf_id);
 
 474       header('Location: week.php');
 
 480 $week_total = ttTimeHelper::getTimeForWeek($user->getActiveUser(), $selected_date);
 
 482 $smarty->assign('selected_date', $selected_date);
 
 483 $smarty->assign('week_total', $week_total);
 
 485 $smarty->assign('client_list', $client_list);
 
 486 $smarty->assign('project_list', $project_list);
 
 487 $smarty->assign('task_list', $task_list);
 
 488 $smarty->assign('forms', array($form->getName()=>$form->toArray()));
 
 489 $smarty->assign('onload', 'onLoad="fillDropdowns()"');
 
 490 $smarty->assign('timestring', $startDate->toString($user->date_format).' - '.$endDate->toString($user->date_format));
 
 491 $smarty->assign('time_records', $records);
 
 493 $smarty->assign('title', $i18n->getKey('title.time'));
 
 494 $smarty->assign('content_page_name', 'week.tpl');
 
 495 $smarty->display('index.tpl');