tags:

views:

621

answers:

14

Man, I just had this project given to me - expand on this they say.

This is an example of ONE function:

<?php


//500+ lines of pure wonder.
function page_content_vc($content) {
    global $_DBH, $_TPL, $_SET;

 $_SET['ignoreTimezone'] = true;

    lu_CheckUpdateLogin();

    if($_SESSION['dash']['VC']['switch'] == 'unmanned' || $_SESSION['dash']['VC']['switch'] == 'touchscreen') {
        if($content['page_name'] != 'vc') {
            header('Location: /vc/');
            die();
        }
    }

    if($_GET['l']) {
        unset($_SESSION['dash']['VC']);
        if($loc_id = lu_GetFieldValue('ID', 'Location', $_GET['l'])) {

            if(lu_CheckPermissions('vc', $loc_id)) {

    $timezone = lu_GetFieldValue('Time Zone', 'Location', $loc_id, 'ID');
    if(strlen($timezone) > 0) {
     $_SESSION['time_zone'] = $timezone;
    }

                $_SESSION['dash']['VC']['loc_ID'] = $loc_id;
                header('Location: /vc/');
                die();
            }
        }
    }

    if($_SESSION['dash']['VC']['loc_ID']) {

  $timezone = lu_GetFieldValue('Time Zone', 'Location', $_SESSION['dash']['VC']['loc_ID'], 'ID');
  if(strlen($timezone) > 0) {
   $_SESSION['time_zone'] = $timezone;
  }

        $loc_id = $_SESSION['dash']['VC']['loc_ID'];
        $org_id = lu_GetFieldValue('record_ID', 'Location', $loc_id);

        $_TPL->assign('loc_id', $loc_id);

        $location_name = lu_GetFieldValue('Location Name', 'Location', $loc_id);
        $_TPL->assign('LocationName', $location_name);

        $customer_name = lu_GetFieldValue('Customer Name', 'Organisation', $org_id);
        $_TPL->assign('CustomerName', $customer_name);

        $enable_visitor_snap = lu_GetFieldValue('VisitorSnap', 'Location', $loc_id);
        $_TPL->assign('EnableVisitorSnap', $enable_visitor_snap);

  $lacps = explode("\n", lu_GetFieldValue('Location Access Control Point', 'Location', $loc_id));
        array_walk($lacps, 'trim_value');

  if(count($lacps) > 0) {
   if(count($lacps) == 1) {
    $_SESSION['dash']['VC']['lacp'] = $lacps[0];
   }
   else {
    if($_GET['changeLACP'] && in_array($_GET['changeLACP'], $lacps)) {
     $_SESSION['dash']['VC']['lacp'] = $_GET['changeLACP'];
     header('Location: /vc/');
     die();
    }
    else if(!in_array($_SESSION['dash']['VC']['lacp'], $lacps)) {
     $_SESSION['dash']['VC']['lacp'] = $lacps[0];
    }
    $_TPL->assign('LACP_array', $lacps);
   }
   $_TPL->assign('current_LACP', $_SESSION['dash']['VC']['lacp']);
   $_TPL->assign('showContractorSearch', true);
   /*
   if($contractorStaff = lu_GetTableRow('ContractorStaff', $org_id, 'record_ID', 'record_Inactive != "checked"')) {
    foreach($contractorStaff['rows'] as $contractor) {
     $lacp_rights = lu_OrganiseCustomDataFunctionMultiselect($contractor[lu_GetFieldName('Location Access Rights', 'ContractorStaff')]);
     if(in_array($_SESSION['dash']['VC']['lacp'], $lacp_rights)) {
      $_TPL->assign('showContractorSearch', true);
     }
    }
   }
   */
  }

  $selectedOptions = explode(',', lu_GetFieldValue('Included Fields', 'Location', $_SESSION['dash']['VC']['loc_ID']));
  $newOptions = array();
  foreach($selectedOptions as $selOption) {
   $so_array = explode('|', $selOption, 2);
   if(count($so_array) > 1) {
    $newOptions[$so_array[0]] = $so_array[1];
   }
   else {
    $newOptions[$so_array[0]] = "Both";
   }
  }  

  if($newOptions[lu_GetFieldName('Expected Length of Visit', 'Visitor')]) {

   $alert = false;

            if($visitors = lu_OrganiseVisitors(
                lu_GetTableRow('Visitor', 'checked',
                    lu_GetFieldName('Checked In', 'Visitor'),
                    lu_GetFieldName('Location for Visit', 'Visitor').'="'.$_SESSION['dash']['VC']['loc_ID'].'"
                    AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"'), false, true, true)) {

                foreach($visitors['rows'] as $key => $visitor) {
     if($visitor['expected'] && $visitor['expected'] + (60*30) < time()) {
      $alert = true;
     }
                }
            }
   if($alert == true) {
    $_TPL->assign('showAlert', 'red');
   }
   else {
    //$_TPL->assign('showAlert', 'green');
   }
  }


        $_TPL->assign('switch', $_SESSION['dash']['VC']['switch']);
  if($_SESSION['dash']['VC']['switch'] == 'touchscreen') {
   $_TPL->assign('VC_unmanned', true);
  }

        if($_GET['check'] == 'in') {
   if($_SESSION['dash']['VC']['switch'] == 'touchscreen') {
    lu_CheckInTouchScreen();
            }
   else {
    lu_CheckIn();
   }
        }
        else if($_GET['check'] == 'out') {
   if($_SESSION['dash']['VC']['switch'] == 'touchscreen') {
    lu_CheckOutTouchScreen();
            }
   else {
    lu_CheckOut();
   }
        }
        else if($_GET['switch'] == 'unmanned') {
            $_SESSION['dash']['VC']['switch'] = 'unmanned';
            if($_GET['printing'] == true && (lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "")) {
                $_SESSION['dash']['VC']['printing'] = true;
            }
            else {
                $_SESSION['dash']['VC']['printing'] = false;
            }
            header('Location: /vc/');
            die();
        }
        else if($_GET['switch'] == 'touchscreen') {
            $_SESSION['dash']['VC']['switch'] = 'touchscreen';
            if($_GET['printing'] == true && (lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "")) {
                $_SESSION['dash']['VC']['printing'] = true;
            }
            else {
                $_SESSION['dash']['VC']['printing'] = false;
            }
            header('Location: /vc/');
            die();
        }

        else if($_GET['switch'] == 'manned') {
            if($_POST['password']) {
                if(md5($_POST['password']) == $_SESSION['dash']['password']) {
                    unset($_SESSION['dash']['VC']['switch']);
                    //setcookie('email', "", time() - 3600);
                    //setcookie('location', "", time() - 3600);
                    header('Location: /vc/');
                    die();
                }
                else {
                    $_TPL->assign('switchLoginError', 'Incorrect Password');
                }
            }

            $_TPL->assign('switchLogin', 'true');
        }
        else if($_GET['m'] == 'visitor') {
            lu_ModifyVisitorVC();
        }

        else if($_GET['m'] == 'enote') {
            lu_ModifyEnoteVC();
        }

        else if($_GET['m'] == 'medical') {
            lu_ModifyMedicalVC();
        }

        else if($_GET['print'] == 'label' && $_GET['v']) {
            lu_PrintLabelVC();
        }

        else {
            unset($_SESSION['dash']['VC']['checkin']);
            unset($_SESSION['dash']['VC']['checkout']);

            $_TPL->assign('icon', 'GroupCheckin');

            if($_SESSION['dash']['VC']['switch'] != 'unmanned' && $_SESSION['dash']['VC']['switch'] != 'touchscreen') {

                $staff_ids = array();
                if($staffs = lu_GetTableRow('Staff', $_SESSION['dash']['VC']['loc_ID'], 'record_ID')) {
                    foreach($staffs['rows'] as $staff) {
                        $staff_ids[] = $staff['ID'];
                    }
                }

                if($_GET['view'] == "tomorrow") {
                    $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m")  , date("d")+1, date("Y")));
                    $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m")  , date("d")+1, date("Y")));
                }
                else if($_GET['view'] == "month") {
                    $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+30, date("Y")));
                }
                else if($_GET['view'] == "week") {
                    $dateStart = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d"), date("Y")));
                    $dateEnd = date('Y-m-d', mktime(0, 0, 0, date("m"), date("d")+7, date("Y")));
                }
                else {
                    $dateStart = date('Y-m-d');
                    $dateEnd = date('Y-m-d');
                }

    if(lu_GetFieldValue('Enable Survey', 'Location', $_SESSION['dash']['VC']['loc_ID']) == 'checked'
     && lu_GetFieldValue('Add Survey', 'Location', $_SESSION['dash']['VC']['loc_ID']) == 'checked') {
      $_TPL->assign('enableSurvey', true);
    }

                //lu_GetFieldName('Checked In', 'Visitor')
                //!= "checked"

                //date('d/m/Y'), lu_GetFieldName('Date of Visit', 'Visitor')

                if($visitors = lu_OrganiseVisitors(lu_GetTableRow('Visitor', $_SESSION['dash']['VC']['loc_ID'], lu_GetFieldName('Location for Visit', 'Visitor'), lu_GetFieldName('Checked In', 'Visitor').' != "checked" AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked" AND '.lu_GetFieldName('Date of Visit', 'Visitor').' >= "'.$dateStart.'" AND '.lu_GetFieldName('Date of Visit', 'Visitor').' <= "'.$dateEnd.'"'))) {
                    foreach($visitors['days'] as $day => $visitors_day) {
                        foreach($visitors_day['rows'] as $key => $visitor) {
                            $visitors['days'][$day]['rows'][$key]['visiting'] = lu_GetTableRow('Staff', $visitor['record_ID'], 'ID');
                            $visitors['days'][$day]['rows'][$key]['visiting']['notify'] = $_DBH->getRow('SELECT * FROM lu_notification WHERE ent_ID = "'.$visitor['record_ID'].'"');
                        }
                    }

                    //array_dump($visitors);

                    $_TPL->assign('visitors', $visitors);
                }

    if($_GET['conGroup']) {
     if($_GET['action'] == 'add') {
      $_SESSION['dash']['VC']['conGroup'][$_GET['conGroup']] = $_GET['conGroup'];
     }
     else {
      unset($_SESSION['dash']['VC']['conGroup'][$_GET['conGroup']]);
     }
    }

    if(count($_SESSION['dash']['VC']['conGroup']) > 0) {
                    if($conGroupResult = lu_GetTableRow('ContractorStaff', '1', '1', ' ID IN ('.implode(',', $_SESSION['dash']['VC']['conGroup']).')')) {

      if($_POST['_submit'] == 'Check-In Group >>') {

                         $form = lu_GetForm('VisitorStandard');
       $standarddata = array();

       foreach($form['items'] as $key=>$item) {
        $standarddata[$key] = $_POST[lu_GetFieldName($item['name'], 'Visitor')];
       }

       foreach($conGroupResult['rows'] as $conStaff) {
        $data = $standarddata;

        foreach($form['items'] as $key=>$item) {
         if($key != 'ID' && $key != 'record_ID' && $conStaff[lu_GetFieldName(lu_GetNameField($key, 'Visitor'), 'ContractorStaff')]) {
          $data[$key] = $conStaff[lu_GetFieldName(lu_GetNameField($key, 'Visitor'), 'ContractorStaff')];
         }
        }

        $data['record_ID'] = $data[lu_GetFieldName('Visiting', 'Visitor')];
                          $data[lu_GetFieldName('Date of Visit', 'Visitor')] = date('Y-m-d');
                          $data[lu_GetFieldName('Time of Visit', 'Visitor')] = date('H:i');
                          $data[lu_GetFieldName('Checked In', 'Visitor')] = 'checked';
                          $data[lu_GetFieldName('Location for Visit', 'Visitor')] = $_SESSION['dash']['VC']['loc_ID'];
                          $data[lu_GetFieldName('ConStaff ID', 'Visitor')] = $conStaff['ID'];
        $data[lu_GetFieldName('From', 'Visitor')] = lu_GetFieldValue('Legal Name', 'Contractor', $conStaff[lu_GetFieldName('Contractor', 'ContractorStaff')]);

                          $id = lu_UpdateData($form, $data);
                          lu_VisitorCheckIn($id);

        //array_dump($data);
        //array_dump($id);
       }


       unset($_SESSION['dash']['VC']['conGroup']);
       header('Location: /vc/');
       die();
      }

      if(count($conGroupResult['rows'])) {
                         foreach($conGroupResult['rows'] as $key => $cstaff) {
                             $conGroupResult['rows'][$key]['contractor'] = lu_GetTableRow('Contractor', $cstaff[lu_GetFieldName('Contractor', 'ContractorStaff')], 'ID');
                         }
                         $_TPL->assign('conGroupResult', $conGroupResult);
      }

      $conGroupForm = lu_GetForm('VisitorConGroup');
      $conGroupForm = lu_OrganiseVisitorForm($conGroupForm, $_SESSION['dash']['VC']['loc_ID'], 'Contractor');

            $secure_options_array = lu_GetSecureOptions($org_id);
            if($secure_options_array[$_SESSION['dash']['VC']['loc_ID']]) {
             $conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]['options']['values'] = $secure_options_array[$_SESSION['dash']['VC']['loc_ID']];
       $conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]['name'] = 'Secure  Area';
      }
      else {
                unset($conGroupForm['items'][lu_GetFieldName('Secure Area', 'Visitor')]);
      }

         if($secure_options_array) {
             $form['items'][lu_GetFieldName('Secure Area', 'Visitor')]['options']['values'] = $secure_options_array;
       $form['items'][lu_GetFieldName('Secure Area', 'Visitor')]['name'] = 'Secure  Area';
         }
         else {
             unset($form['items'][lu_GetFieldName('Secure Area', 'Visitor')]);
         }

         $_TPL->assign('conGroupForm', $conGroupForm);
      $_TPL->assign('hideFormCancel', true);
     }
    }

                if($_GET['searchVisitors']) {
                    $_TPL->assign('searchVisitorsQuery', $_GET['searchVisitors']);
                    $where = '';

                    if($_GET['searchVisitorsIn'] == 'Yes') {
                        $where .= ' AND '.lu_GetFieldName('Checked In', 'Visitor').' = "checked"';
                        $_TPL->assign('searchVisitorsIn', 'Yes');
                    }
                    else {
                        $where .= ' AND '.lu_GetFieldName('Checked In', 'Visitor').' != "checked"';
                        $_TPL->assign('searchVisitorsIn', 'No');
                    }

                    if($_GET['searchVisitorsOut'] == 'Yes') {
                        $where = '';
                        $where .= ' AND '.lu_GetFieldName('Checked Out', 'Visitor').' = "checked"';
                        $_TPL->assign('searchVisitorsOut', 'Yes');
                    }
                    else {
                        $where .= ' AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"';
                        $_TPL->assign('searchVisitorsOut', 'No');
                    }

                    if($searchVisitors = lu_OrganiseVisitors(lu_GetTableRow('Visitor', $_GET['searchVisitors'], '#search#', lu_GetFieldName('Location for Visit', 'Visitor').'="'.$_SESSION['dash']['VC']['loc_ID'].'"'.$where))) {
                        foreach($searchVisitors['rows'] as $key => $visitor) {
                            $searchVisitors['rows'][$key]['visiting'] = lu_GetTableRow('Staff', $visitor['record_ID'], 'ID');
                        }

                        $_TPL->assign('searchVisitors', $searchVisitors);
                    }
                    else {
                        $_TPL->assign('searchVisitorsNotFound', true);
                    }
                }
                else if($_GET['searchStaff']) {

                    if($_POST['staff_id']) {
                        if(lu_CheckPermissions('staff', $_POST['staff_id'])) {
                            $_DBH->query('UPDATE '.lu_GetTableName('Staff').' SET '.lu_GetFieldName('Current Location', 'Staff').' = "'.$_POST['current_location'].'" WHERE ID="'.$_POST['staff_id'].'"');
                        }
                    }


                    $locations = lu_GetTableRow('Location', $org_id, 'record_ID');

                    if(count($locations['rows']) > 1) {
                        $_TPL->assign('staffLocations', $locations);
                    }

                    $loc_ids = array();
                    foreach($locations['rows'] as $location) {
                        $loc_ids[] = $location['ID'];
                    }

                    // array_dump($locations);
                    // array_dump($_POST);

                    $_TPL->assign('searchStaffQuery', $_GET['searchStaff']);
                    $where = ' AND record_Inactive != "checked"';

                    if($_GET['searchStaffIn'] == 'Yes' && $_GET['searchStaffOut'] != 'Yes') {
                        $where .= ' AND ('.lu_GetFieldName('Staff Status', 'Staff').' = "" OR '.lu_GetFieldName('Staff Status', 'Staff').' = "On-Site")'.

                        $_TPL->assign('searchStaffIn', 'Yes');
                        $_TPL->assign('searchStaffOut', 'No');
                    }
                    else if($_GET['searchStaffOut'] == 'Yes' && $_GET['searchStaffIn'] != 'Yes') {
                        $where .= ' AND ('.lu_GetFieldName('Staff Status', 'Staff').' != "" AND '.lu_GetFieldName('Staff Status', 'Staff').' != "On-Site")'.
                        $_TPL->assign('searchStaffOut', 'Yes');
                        $_TPL->assign('searchStaffIn', 'No');
                    }
                    else {
                        $_TPL->assign('searchStaffOut', 'Yes');
                        $_TPL->assign('searchStaffIn', 'Yes');
                    }

                    if($searchStaffs = lu_GetTableRow('Staff', $_GET['searchStaff'], '#search#', 'record_ID IN ('.implode(',', $loc_ids).')'.$where, lu_GetFieldName('First Name', 'Staff').','.lu_GetFieldName('Surname', 'Staff'))) {
                        $_TPL->assign('searchStaffs', $searchStaffs);
                    }
                    else {
                        $_TPL->assign('searchStaffNotFound', true);
                    }
                }
    else if($_GET['searchContractor']) {

                    $_TPL->assign('searchContractorQuery', $_GET['searchContractor']);
                    //$where = ' AND '.lu_GetTableName('ContractorStaff').'.record_Inactive != "checked"';
     $where = ' ';

                    if($_GET['searchContractorIn'] == 'Yes' && $_GET['searchContractorOut'] != 'Yes') {
                        $where .= ' AND ('.lu_GetFieldName('Onsite Status', 'ContractorStaff').' = "Onsite")';

                        $_TPL->assign('searchContractorIn', 'Yes');
                        $_TPL->assign('searchContractorOut', 'No');
                    }
                    else if($_GET['searchContractorOut'] == 'Yes' && $_GET['searchContractorIn'] != 'Yes') {
                        $where .= ' AND ('.lu_GetFieldName('Onsite Status', 'ContractorStaff').' != "Onsite")'.
                        $_TPL->assign('searchContractorOut', 'Yes');
                        $_TPL->assign('searchContractorIn', 'No');
                    }
                    else {
                        $_TPL->assign('searchContractorOut', 'Yes');
                        $_TPL->assign('searchContractorIn', 'Yes');
                    }

     $join = 'LEFT JOIN '.lu_GetTableName('Contractor').' ON '.lu_GetTableName('Contractor').'.ID = '.lu_GetTableName('ContractorStaff').'.'.lu_GetFieldName('Contractor', 'ContractorStaff');

     $extrasearch = array (
      lu_GetTableName('Contractor').'.'.lu_GetFieldName('Legal Name', 'Contractor')
     );

                    if($searchContractorResult = lu_GetTableRow('ContractorStaff', $_GET['searchContractor'], '#search#', lu_GetTableName('ContractorStaff').'.record_ID = "'.$org_id.'" '.$where, lu_GetFieldName('First Name', 'ContractorStaff').','.lu_GetFieldName('Surname', 'ContractorStaff'), $join, $extrasearch)) {

      /*
      foreach($searchContractorResult['rows'] as $key=>$contractor) {
       $lacp_rights = lu_OrganiseCustomDataFunctionMultiselect($contractor[lu_GetFieldName('Location Access Rights', 'ContractorStaff')]);
       if(!in_array($_SESSION['dash']['VC']['lacp'], $lacp_rights)) {
        unset($searchContractorResult['rows'][$key]);
       }
      }
      */

      if(count($searchContractorResult['rows'])) {
                         foreach($searchContractorResult['rows'] as $key => $cstaff) {
        /*
        if($cstaff[lu_GetFieldName('Onsite_Status', 'Contractor')] == 'Onsite')) {
         if($visitor['rows'][0][lu_GetFieldName('ConStaff ID', 'Visitor')]) {
                   $_DBH->query('UPDATE '.lu_GetTableName('ContractorStaff').' SET '.lu_GetFieldName('Onsite Status', 'ContractorStaff').' = "" WHERE ID="'.$visitor['rows'][0][lu_GetFieldName('ConStaff ID', 'Visitor')].'"');
         }
        }
        */
        if($cstaff[lu_GetFieldName('SACN Expiry Date', 'ContractorStaff')] != '0000-00-00') {
         if(strtotime($cstaff[lu_GetFieldName('SACN Expiry Date', 'ContractorStaff')]) < time()) {
          $searchContractorResult['rows'][$key]['sacn_expiry'] = true;
         }
         else {
          $searchContractorResult['rows'][$key]['sacn_expiry'] = false;
         }
        }
        else {
         $searchContractorResult['rows'][$key]['sacn_expiry'] = false;
        }

        if($cstaff[lu_GetFieldName('Induction Valid Until', 'ContractorStaff')] != '0000-00-00') {
         if(strtotime($cstaff[lu_GetFieldName('Induction Valid Until', 'ContractorStaff')]) < time()) {
          $searchContractorResult['rows'][$key]['induction_expiry'] = true;
         }
         else {
          $searchContractorResult['rows'][$key]['induction_expiry'] = false;
         }
        }
        else {
         $searchContractorResult['rows'][$key]['induction_expiry'] = false;
        }

                             $searchContractorResult['rows'][$key]['contractor'] = lu_GetTableRow('Contractor', $cstaff[lu_GetFieldName('Contractor', 'ContractorStaff')], 'ID');
                         }
                         $_TPL->assign('searchContractorResult', $searchContractorResult);
      }
      else {
                         $_TPL->assign('searchContractorNotFound', true);
      }
                    }
                    else {
                        $_TPL->assign('searchContractorNotFound', true);
                    }
    }

                $occupancy = array();
                $occupancy['staffNumber'] = $_DBH->getOne('SELECT count(*) FROM '.lu_GetTableName('Staff').' WHERE record_ID = "'.$_SESSION['dash']['VC']['loc_ID'].'" AND record_Inactive != "checked" AND '.lu_GetFieldName('Ignore Counts', 'Staff').' != "checked"');
                $occupancy['staffNumberOnsite']= $_DBH->getOne(
                        'SELECT count(*) FROM '.lu_GetTableName('Staff').' WHERE
                        (
                            (record_ID = "'.$_SESSION['dash']['VC']['loc_ID'].'"
                                AND
                                ('.lu_GetFieldName('Staff Status', 'Staff').' = "" OR  '.lu_GetFieldName('Staff Status', 'Staff').' = "On-Site"))
                                OR '.lu_GetFieldName('Current Location', 'Staff').' = "'.$_SESSION['dash']['VC']['loc_ID'].'")
                                AND record_Inactive != "checked"
        AND '.lu_GetFieldName('Ignore Counts', 'Staff').' != "checked"');

                $occupancy['visitorsOnsite'] = $_DBH->getOne('SELECT count(*) FROM '.lu_GetTableName('Visitor').' WHERE '.lu_GetFieldName('Location for Visit', 'Visitor').' = "'.$_SESSION['dash']['VC']['loc_ID'].'" AND '.lu_GetFieldName('Checked In', 'Visitor').' = "checked" AND '.lu_GetFieldName('Checked Out', 'Visitor').' != "checked"');
                $_TPL->assign('occupancy', $occupancy);

                if($enotes = lu_GetTableRow('Enote', $org_id, 'record_ID', lu_GetFieldName('Note Emailed', 'Enote').' = "0000-00-00" AND '.lu_GetFieldName('Note Passed On', 'Enote').' != "Yes"')) {
                    $_TPL->assign('EnoteNotice', true);
                }

                if($medical = lu_GetTableRow('MedicalRoom', $_SESSION['dash']['VC']['loc_ID'], 'record_ID', 'record_Inactive != "Yes"')) {
                    $_TPL->assign('MedicalNotice', true);
                }

                if(lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "No" && lu_GetFieldValue('Printing', 'Location', $_SESSION['dash']['VC']['loc_ID']) != "") {
                    $_TPL->assign('UnmannedPrinting', true);
                }
            }
            else {
                if($_SESSION['dash']['VC']['printing'] == true) {
                    $_TPL->assign('UnmannedPrinting', true);
                }
            }

   // enable if contractor check-in buttons should be enabled
            if(lu_GetFieldValue('Enable Contractor Check In', 'Location', $_SESSION['dash']['VC']['loc_ID']) == "checked") {
                $_TPL->assign('ContractorCheckin', true);
            }

        }


  if($_SESSION['dash']['entity_id'] && $_GET['fixupCon'] == 'true') {
         $conStaffs = lu_GetTableRow('ContractorStaff', $_SESSION['dash']['ModifyConStaffs']['org_ID'], 'record_ID', '', lu_GetFieldName('First Name', 'ContractorStaff').','.lu_GetFieldName('Surname', 'ContractorStaff'));
      foreach($conStaffs['rows'] as $key => $cstaff) {
    if($cstaff[lu_GetFieldName('Site Access Card Number', 'ContractorStaff')] && $cstaff[lu_GetFieldName('Site Access Card Type', 'ContractorStaff')]) {
     echo $cstaff['ID'].' ';
     $_DBH->query('UPDATE '.lu_GetTableName('Visitor').' SET '.lu_GetFieldName('Site Access Card Number', 'Visitor').' = "'.$cstaff[lu_GetFieldName('Site Access Card Number', 'ContractorStaff')].'", '.lu_GetFieldName('Site Access Card Type', 'Visitor').' = "'.$cstaff[lu_GetFieldName('Site Access Card Type', 'ContractorStaff')].'" WHERE '.lu_GetFieldName('ConStaff ID', 'Visitor').'="'.$cstaff['ID'].'"');
    }
      }
  }

    }
    else {
        if($_SESSION['dash']['staffs']) {
            foreach($_SESSION['dash']['staffs']['rows'] as $staff) {
                if($staff[lu_GetFieldName('Reception Manager', 'Staff')] == 'checked') {
                    $loc_id = $staff['record_ID'];
                    unset($_SESSION['dash']['VC']);
                    if($loc_id = lu_GetFieldValue('ID', 'Location', $loc_id)) {
                        $_SESSION['dash']['VC']['loc_ID'] = $loc_id;
                        header('Location: /vc/');
                        die();
                    }
                }
            }
        }

        $_TPL->assign('mode', 'public');
    }

    $content['page_content'] = $_TPL->fetch('modules/vc.htm');
    return $content;
}


?>

die();die();die();die();die();

This question will probably be closed - i just need some support from my coding brothers and sisters. *SOB*

+5  A: 

I would tell whomever dumped the project on me that a total re-write is necessary if they want to do anything with the site. (This advice not guaranteed not to get you fired.)

JP Alioto
Maybe the last sentence would be clearer by cancelling out the double negative "(This advice might get you fired.)", but +1 anyway :)
Daniel Daranas
+3  A: 

My normal response to inheriting code like that is to track down the home address of the original developer as a just-in-case-I-need-it kind of thing.

Brandon Bodnár
to beat him up when last hope fades out? :)
Arnis L.
+3  A: 

Hang on in there. I know how you feel.

Noam Gal
+1  A: 

I would second the rewriting option, however, if I would also recommend writing as much unit test cases for the original code, that covers almost eveything this code is doing before proceeding with a complete rewrite, it will become very important to validate that your rewrite is doing the same job.

bashmohandes
This code will be (dare I say) impossible to unit test. It has so many external variable dependencies, like the triple indirect $_SESSION['foo']['bar']['baz']. Lord knows where that's getting set. And the tens of query string parameter combinations don't help. Hand-crafting unit tests around this monstrosity could be a full-time job ;)
Crescent Fresh
bashmohandes
+24  A: 

Global search and replace are your friends.

Start by:

  1. Breaking the huge "if ... else" into individual functions which you can rename later once you figure out what they do.
  2. Do global search/replace on the $_GET[...] and $_SESSION['dash'] variables to give them more meaningful names
  3. Continue to clean up

In short, use the basic computer programming technique: Divide and conquer. Divide the functionality into smaller parts, then clean up the individual parts. Shouldn't take more than an hour.

razzed
And, as an additional note, I love cleaning up this kind of crap. But then, when it's a complete pile of poo, I don't - just rewrite it.
razzed
As long as all the code works. And is actually used. This is just one function, not one module. And where are the #includes?
le dorfier
One hour seems a low estimate. Biggest issue will be to make sure that it keeps working. And when the code quality is at that level, it's probably full of side-effects where you least expect them to be.
I was thinking for *that* function to clean it up and make it somewhat sensical. I can't see the entire thing, gladly.
razzed
+2  A: 

I used to write code like that when I was a kid. It was awful. The worst part was, large chunks of those functions just got copy/pasted elsewhere. I remember building an entire "fan finder" sort of registry for the fan site of a band. It gave you a world map and pointed to the locations of everyone who had signed it. You could click on different countries, search by name--etc, and you'd get lists and lists of all these fans all over the world all of whom had their own little profile that they could edit (favorite song, band member, etc). All in PHP that looked like this. All using flat text files... It was atrocious. I just re-wrote most of the file parsing functions EVERYWHERE, in every function I handled the text files again and again... My god it was awful. I realize you probably want to strangle me for this, which is why I'm glad that you don't know where I live.

Carson Myers
<i>"which is why I'm glad that you don't know where I live."</i>Estevan, Saskatchewan, Canadanot so difficult to find out
Aamir
It was really more of a joke than a challenge.
Carson Myers
+1  A: 

Looks like somebody needs a little refresher on the principle of high cohesion.

statenjason
+1  A: 

Tell the person who gave this to you it will require a rewrite.

It looks like this function determines user type, sets flags and content for a page generator. You could put this functionality in a flow chart and reorganize this project. This whole thing seems like it would mold very nicely to object-oriented programming. You could really lower the amount of interdependence on session globals, have smaller code and make this whole thing more robust.

MagikWorx
+1  A: 

I had a bunch of junk like this once. The best strategy I eventually came up with was to figure out what it did from the outside in, rather than the inside out. So this is kind of the opposite of the first responder (which describes what I started doing). Which makes sense if the code has some camouflaged structure, but that may not be something to take for granted. I ended up figuring out a bunch of code that could never have been called, for instance. In some of those cases, the same functionality was implemented several different ways. Lots of wasted time.

Eventually it produces a web page. It may be easier to figure out what the web page looks like and how it generally operates, and just use the code for hints about what's not self-evident.

le dorfier
+3  A: 

be strong, my friend.

It is ugly code indeed, but not impossibly unreadable.

My suggestion, beyond the earlier stated replace strategy (which I also suggest), is to take notes on what is happening in the function, as you understand it better - this can be in temporary comments in the code, in a separate text file, or on a piece of paper. What is important is that you have something to refer to in the case that you take a long break or the weekend comes. With nasty code comes the mind's habit of wanting to forget it - make sure you have your discoveries backed up.

Another suggestion, considering the length of your example function is that once you understand the code enough to determine sections of common logic, break these mega-functions into smaller ones. It will improve readability - for you and for others.

Demi
+5  A: 
ya23
I love this book.I wish I had more time at my job to thoroughly refactor existing disasters in our codebase... including ones I unfortunately put there too. :)
Mike
+8  A: 

Software is a business.

You have been handed code which is essentially unmaintainable, and been asked to do something with it. This will require heavy refactoring.

The bad news is that it will suck. The good news is that in exchange for your time the company will give you money, which you will be able to exchange for goods and services such as food, clothing, beer and concert tickets.

As long as everybody has a correct understanding of the time costs involved, you should be fine.

Daniel Daranas
With refactoring, nobody has a correct understanding of the time costs involved. Perhaps I'm being pessimistic, but "refactoring" is never a task I've been asked to do, or given time to do. I always have to dress it up as some other crucial development task in order to get time to do it, and even then run over whatever time I've been allotted.
jasonmp85
+1  A: 

Don't Touch It! Trust Me !

Suraj Chandran