HEX
Server: Apache/2.2.15 (CentOS)
System: Linux ip-10-0-2-146.eu-west-1.compute.internal 2.6.32-754.35.1.el6.centos.plus.x86_64 #1 SMP Sat Nov 7 11:33:42 UTC 2020 x86_64
User: root (0)
PHP: 5.6.40
Disabled: NONE
Upload Files
File: /www/exchange0old/exchange/classes/Controller/CExtraLogin.php
<?php
class Controller_CExtraLogin
{
     /**
     * array of data for authorization
     * array('login'=>'','password'=>'')
     * @var array
     */
    private $_authorise = array();

    /**
     * Index authorization status
     * @var bool
     */
    private $_auth = false;

    /**
     * array of data
     * @var array
     */
    private $_data = array();

    /**
     * model for user registration
     * @var Model_MRegister
     */
    private $_register = null;

    /**
     * Authorisation Error
     */
    const ERROR_AUTHORISATION = 'Authorisation error';
/**
     * token for authorization
     * @var null
     */
    public $_token = null;

    /**
     * message
     * @var null
     */
    public $_message = null;

    /**
     * db instance
     * @var null
     */
    private $db = null;

    /**
     * Error: invalid data
     */
    const ERROR_WRONG_DATA = 'Wrong data !!!';

    /**
     * Error: bad sql request
     */
    const ERROR_SQL = 'SQL error';

    /**
     * Error: empty data
     */
    const ERROR_EMPTY = 'Mandatory field';

    /**
     * Error: the string length
     */
    const ERROR_LENGTH = '<str> must contain 8 or more characters';

    /**
     * Error: Invalid parameter
     */
    const ERROR_UNAVAILABLE = 'Username unavailable. Try inserting additional letters or numbers to this username';

    /**
     * Error: different passwords
     */
    const ERROR_DIFFERENT_PASSWORDS = 'The Password and the Confirm Password do not match';

    /**
     * Error: invalid email
     */
    const ERROR_EMAIL = 'Enter a valid email address';

    /**
     * Error: exist email
     */
    const ERROR_EXIST_EMAIL = 'An account with this email address already exists.  Create a new account or login to the existing account';

    /**
     * Error: no exist email
     */
    const ERROR_NO_EXIST_EMAIL = 'No account associated with this email address.  Enter a valid email address';

    /**
     * Error: Only numbers
     * @deprecated
     */
    const ERROR_NUMBER = 'Use numbers only. No spaces permitted';

    /**
     * Error: too much description
     */
    const ERROR_DESC = 'Words less than 20';

    /**
     * Error: invalid type of member
     */
    const ERROR_MEMBER_TYPE = 'Wrong member category';

    /**
     * Error: Invalid promotional code
     */
    const ERROR_PROMOCODE = 'Enter a Valid Promotional Code';

    /**
     * Error: Invalid certificate
     */
    const ERROR_CERTIFICATE = 'Certificate Error!';

    /**
     * Error: Invalid verification
     */
    const ERROR_VERIFICATION = 'Verification is not passed';

    /**
     * Error: Invalid apply_id
     */
    const ERROR_APPLY_ID = 'Invalid apply id';

    /**
     * Error: Authorization error
     */
    const ERROR_AUTHORIZATION = 'Invalid Username and | or Password';

    /**
     * Error: Terminated account
     */
    const ERROR_TERMINATED_ACCOUNT = 'This User Account has been Terminated';

    /**
     * Error: Suspended account
     */
    const ERROR_SUSPENDED_ACCOUNT = 'This User Account has been Suspended';

    /**
     * Error: Waiting account
     */
    const ERROR_ACTIVATION_ACCOUNT = 'Your Account is waiting for activation';

    /**
     * Error: File size
     */
    const ERROR_FILE_SIZE = 'Account Document  size should be less than 4MB';
    /**
     * Error: File type
     */
    const ERROR_FILE_TYPE = 'Only the following formats: .csv, .xls, .xlsx';

    /**
     * Error: Access token
     */
    const ERROR_ACCESS_TOKEN = 'Access denied';

    /**
     * Error: Certificate receive error
     */
    const ERROR_CERTIFICATE_RECEIVE = 'An error occurred whilst attempting to collect the certificate. Please contact Support for further assistance.';

    /**
     * Error: Certificate expired error
     */
    const ERROR_CERTIFICATE_EXPIRED = 'This resource has already expired. For further assistance, please contact Support.';

    /**
     * Error: Certificate password error
     */
    const ERROR_CERTIFICATE_PASSWORD = 'Incorrect password';

    /**
     * Member type: investor
     */
    const TYPE_INVESTOR = 2;

    /**
     * Member type: originator
     */
    const TYPE_ORIGINATOR = 3;

    /**
     * Member type: agent
     */
    const TYPE_AGENT = 4;

    /**
     * Member type: intermediary
     */
    const TYPE_INTERMEDIARY = 5;

    public function __construct()
    {
        include_once(ROOT_FOLDER . '/includes/helpers.php');
        include_once(ROOT_FOLDER . 'api/classes/Model/MRegister.php');

        //global $json;
        $jsondd = file_get_contents('php://input');
        $postArray  = json_decode($jsondd, true);

       // print_r($postArray);
        $this->_data = $this->filterData(array_get($postArray, 'data', array()));
        /* $this->_authorise = array_get($postArray, 'authorise', array());
       // print_r($this->_data); 
       // print_r($this->_authorise); 
        
        if ($this->_authorise) {
            $this->authorise();
        } */

        //$this->_register = new Model_MRegister($this->_data);
        //$this->_register = $this->manageManualRegister($this->_data);
    }

   public function manageManualRegister()
   {
        /*  AND temp_registration.password = '" . Bin_Security::hashPassword($this->_data['password']) . "' */
        if (!empty($this->_data['login']) and !empty($this->_data['password'])) 
        {
       
            $user_type = (isset($this->_data['type'])) ? $this->_data['type'] : USER_ORIGINATOR;
            $query = new Bin_Query();
            $query->executeQuery("SELECT temp_reg_id,status,temp_registration.user_id AS temp_user_id, user_login.user_id,user_login.user_status,user_login.user_type, ref_id, COUNT(user_sessions.user_id) AS logins, organisation_reference_id,organisation_id
                                FROM temp_registration
                                LEFT JOIN user_login ON user_login.user_id = temp_registration.user_id
                                LEFT JOIN user_sessions ON user_sessions.user_id = user_login.user_id
                                LEFT JOIN organisation_details ON organisation_details.user_id = user_login.user_id
                                WHERE temp_registration.username ='" . $this->_data['login'] . "'
                                AND temp_registration.password = '" . Bin_Security::hashPassword($this->_data['password']) . "'
                                AND temp_registration.user_type = '" . $user_type . "'");
            $user = current($query->records);

            if ($user['temp_reg_id']) {
                if ($user['status'] == '6') {
                    $this->_errors['authorization'] = $this::ERROR_TERMINATED_ACCOUNT;
                } elseif ($user['status'] == '5') {
                    $this->_errors['authorization'] = $this::ERROR_SUSPENDED_ACCOUNT;
                } elseif (!empty($user['temp_user_id'])) {
                    $token = md5(uniqid());

                    $query = new Bin_Query();
                    $query->executeQuery("INSERT INTO user_auth
                                        (user_id, token, created_at)
                                        VALUES (" . $user['temp_user_id'] . ", '$token', NOW())");

                    $this->_status = true;
                    $this->_token = $token;
                } else {
                    $this->_errors['authorization'] = $this::ERROR_ACTIVATION_ACCOUNT;
                }
            }
        }
        if (!$this->_status and empty($this->_errors['authorization'])) {
            $this->_errors['authorization'] = $this::ERROR_AUTHORIZATION;
        }
    }

    /**
     * data filtration
     * @param $data
     * @return array
     */
    private function filterData($data)
    {
        $filterData = array_map('trim', $data);
        $filterData = array_map('strip_tags', $filterData);
        $filterData = array_map('htmlspecialchars', $filterData);
        $filterData = array_map('mysql_real_escape_string', $filterData);

        return $filterData;
    }

    /**
     * user authorisation
     */
    public function authorise()
    {
        if (!empty($this->_authorise['login']) AND !empty($this->_authorise['password'])) {
            $config = new Bin_Configuration();
            if ($config->config['api_login'] == $this->_authorise['login']
                AND $config->config['api_password'] == $this->_authorise['password']
            ) {
                $this->_auth = true;
            } else {
                $this->_auth = false;
            }
        }
    }

    /**
     *
     */
    function showIndex()
    {
        exit('api');
    }

    /**
     * user registration
     * method: post
     * url: /exchange/api/index.php?do=register
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "wemail": "test@test.com", // user email
     *          "password": "password", // user password
     *          "fname": "Jhon", // First Name
     *          "lname": "Smit", // Last Name
     *          "jtitle": "MyJob", // Job Tiltle
     *          "oname": "OrganisationName", // Organisation Name
     *          "addr1": "street 8", // Organisation Address 1
     *          "addr2": "house 45", // Organisation Address 2
     *          "pcode": "1029", // Postcode
     *          "city": "Kiev", // Town/City
     *          "stateid": "Kiev", // County/Area
     *          "country": "220", // Country
     *          // Phone Number
     *          "phone": "0035334546",
     *          "accounting_software": "program",
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     *      "user": "1" // new user id
     * }
     */
    public function registerUser()
    {
        $this->assertRequest('POST');
        $this->_register->validate();
        $this->_register->save();

        // activate user
        $this->activateUser();

        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors,
            'user' => $this->_register->_user
        ));
    }

    /**
     * activate user before registration
     */
    public function activateUser()
    {
        if($this->_register->_status and $this->_register->_user){
            include_once(ROOT_FOLDER . 'admin/classes/Model/user_actions.php');
            $model = new User_actions();
            $model->inviteUser($this->_register->_user, 2, 'trader');
        }
    }

    /**
     * RSA Offer
     * method: post
     * url: /exchange/api/index.php?do=rsaoffer
     * example:
    /*  $_POST['json'] = json_encode(
            array(
                'authorise' => array(
                    'login' => 'test', // authorisation login
                    'password' => 'test' // authorization password
                ),
                'data' => array(
                    'first_name'	=> 'vfb-241', // First Name
                    'last_name'		=> 'vfb-265', // Last Name
                    'email'			=> 'da@da.da', // Email Address
                    'job_title'		=> 'Job Tiltle', // Job Tiltle
                    'organisation_name'	=> 'Organisation Name', // Organisation Name
                    'country'		=> '104', // Country
                    // Phone Number
                    'dc_code'	=> '263', // country
                    'da_code'	=> '263', // area
                    'dph_code'	=> '263', // phone number
                    // Mobile Phone Number
                    'mc_code'	=> '26', // country
                    'ma_code'	=> '46', // area
                    'mph_code'	=> '46', // phone number
                    'turn_over'	=> '1', // Estimated Annual Turnover
                    'overdraft_limit'	=> '1', // Overdraft limit (if any)
                    'capital_facility'	=> '1', // Finance Facility I Need
                    'how_found'	=> '', // How you found us
                    'promocode'	=> '', // Promotional Code
                    "debtors_country"=> array("12", "12"),
                    "debtors_name" => array("BALLYKEA PRODUCTIONS 111 LIMITED", "AWAS 1114 LLC"),
                    "debtors_code" => array("IE258601", "IE908171"),
                    "debtors_revenue" => array(1,2),
                )
            )
        );
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     * }
     */
    public function rsaOffer()
    {
        $this->assertRequest('POST');
        include_once(ROOT_FOLDER . "api/classes/Model/MRsaOffer.php");

        $rsaOffer = new Model_MRsaOffer($this->_data);
        $rsaOffer->validate();
        $rsaOffer->save();

        echo json_encode(array(
            'status' => $rsaOffer->_status,
            'errors' => $rsaOffer->_errors,
        ));
    }

    /**
     * apply user email
     * method: post
     * url: /exchange/api/index.php?do=apply
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "wemail": "test@example.com", // Corporate Email Address
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     * }
     */
    public function apply()
    {
        $this->assertRequest('POST');
        $this->_register->validateApply();
        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors
        ));
    }

    /**
     * verification user email
     * method: post
     * url: /exchange/api/index.php?do=verification
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "wemail": ""test@example.com"", // Email Address
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     * }
     */
    public function emailVerification()
    {
        $this->assertRequest('POST');
        $this->_register->verification();

        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors,
        ));
    }

    /**
     * login user to credebt
     * method: post
     * url: /exchange/api/index.php?do=token
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "login": "login", // user login
     *          "password": "password" // user password
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     *      "token": "41f0e4f4f031d44f51e3023c34cd5b30" // authorization token
     * }
     */
    public function getToken()
    {
        $this->assertRequest('POST');
        $this->manageManualRegister();

        $redirect = null;
        if($this->_token)
        {
            $redirect = 'https://www.credebtexchange.com/eui/index.php?do=validate_extra_login&token='.$this->_token;
        }

        return $this->getResponse(array(
            'status' => $this->_status,
            'errors' => $this->_errors,
            'redirect' => $redirect
        ));
    }


    /**
     * forgot password
     * method: post
     * url: /exchange/api/index.php?do=forgotpass
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "email": "test@example.com", // user email
     *          "login_url": "convertibill.com/login.php" // url for login
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     *      "message": "Your login details has been sent to your email address" // errors array
     * }
     */
    public function forgotPassword()
    {
        $this->assertRequest('POST');
        $this->_register->forgotPassword();
        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors,
            'message' => $this->_register->_message
        ));
    }

    /**
     * upload file
     * method: post
     * url: /exchange/api/index.php?do=upload
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "id": "123" // user id
 *          }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     *      "message": "message" // errors array
     * }
     * $_FILES = array(
     *              'uged_c' => array(),
     *              'ugred_d' => array()
     *          )
     */
    public function uploadFiles()
    {
        $this->assertRequest('POST');
        $this->_register->validateFiles();
        $this->_register->uploadFiles($this->_data['id']);
        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors,
            'message' => $this->_register->_message
        ));
    }

	/**
	 * Method: POST
	 * Params: hash - Hash of ConsentRequest
	 */
	public function getAgreement(){
		$this->assertRequest('POST');
		require_once ROOT_FOLDER.'/admin/classes/Model/MDirector.php';
		require_once ROOT_FOLDER.'/classes/Model/MTerms.php';
		$hash = array_get($this->_data, 'hash');
		if(!$hash){
			$this->showErrorNotFound();
		}

		$director = Model_MDirector::getDirectorInfoByConsentRequest(mysql_real_escape_string($hash));

		if(!$director){
			$this->showErrorNotFound();
		}

		$query = new Bin_Query();

		$userSql = "SELECT first_name, last_name FROM temp_registration WHERE user_id= '".$director['user_id']."' LIMIT 1;";

		if(!$query->executeQuery($userSql)){
			$this->showErrorNotFound();
		}
		$user = $query->records[0];

		$response = array(
			'firstName' => $user['first_name'],
			'lastName' => $user['last_name'],
			'organisationName' => $director['organisation_name'],
			'agreementText' => base64_encode(Model_MTerms::getCombinedAgreement($director['id'],1))
		);
		$this->getResponse($response);

	}

	/**
	 * Method: POST
	 * Params: hash - Hash of ConsentRequest
	 */
	public function confirmAgreement(){
		$this->assertRequest('POST');
		require_once ROOT_FOLDER.'/admin/classes/Model/MDirector.php';
		$hash = array_get($this->_data, 'hash');
		if(!$hash){
			$this->showErrorNotFound();
		}
		$hash = mysql_real_escape_string($hash);

		$confirmResult = Model_MDirector::confirmConsentAgreement($hash);

		if(!$confirmResult){
			$this->showErrorNotFound('Unable confirm, incorrect hash');
		}else{
			$this->getResponse($confirmResult);
		}
	}

    /**
     * get list of accounting_software
     * method: post
     * url: /exchange/api/index.php?do=software
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      }
     *  }"
     * return {
     *          "1":"Accounts IQ",
     *          "2":"Big Red Book",
     *          "3":"Big Red Cloud",
     *          "4":"Exact",
     *          "5":"Exact Online"
     *          ...
     *        }
     */
    public function getSoftware()
    {
        $this->assertRequest('POST');
        echo json_encode($this->_register->getSoftware());
    }

    /**
     * get list of rates
     * method: post
     * url: /exchange/api/index.php?do=rates
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      }
     *  }"
     */
    public function getRates()
    {
        $this->assertRequest('POST');
		$this->getResponse($this->_register->getRates());
    }

    /**
     * get list of raf values
     * method: post
     * url: /exchange/api/index.php?do=raf
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      }
     *  }"
     */
    public function getRafValues()
    {
        $this->assertRequest('POST');
        $this->getResponse($this->_register->getRafValues());
    }

    /**
     * check access token
     * method: post
     * url: /exchange/api/index.php?do=checkaccess
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "token":"test",
     *          "ip_address":"127.0.0.1"
     *      }
     *  }"
     */
    public function checkAccessToken()
    {
        $this->assertRequest('POST');
        $this->_register->checkToken();
        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors
        ));
    }

    /**
     * Register bank details
     * method: post
     * url: /exchange/api/index.php?do=bankdetails
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "email":"test@test.com",
     *          "bank_number":"1234",
     *          "swift":"1234"
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     * }
     */
    public function bankDetails()
    {
        $this->assertRequest('POST');
        $this->_register->saveBankDetails();

        echo json_encode(array(
            'status' => $this->_register->_status,
            'errors' => $this->_register->_errors,
        ));
    }

    /**
     * Receive certificate
     * method: post
     * url: /exchange/api/index.php?do=receivecertificate
     * example:
     * $_POST['json'] =
     * "{
     *      "authorise": {
     *          "login": "test", // authorisation login
     *          "password": "test" // authorization password
     *      },
     *      "data": {
     *          "certificate_url_hash":"iuriu1718",
     *          "password":"1234"
     *      }
     *  }"
     * return {
     *      "status": "true", // true or false
     *      "errors": {}, // errors array
     * }
     */
    public function receiveCertificate()
    {
        $this->assertRequest('POST');
        $userLinkHash = Bin_Array::get($this->_data, 'certificate_url_hash');
        $userPassword = Bin_Array::get($this->_data, 'password');
        $resultArray = array(
            'status' => false,
            'errors' => array()
        );

        if (!$this->_register->isValidCertificateReceiveRequest($userLinkHash, $userPassword)) {
            //Invalid request
            $resultArray['errors']['certificate_error'] = Model_MRegister::ERROR_CERTIFICATE_PASSWORD;
            $this->getResponse($resultArray);
            return;
        }


        //Receive user by link
        $user = $this->_register->getUserByLink($userLinkHash);
        $userId = Bin_Array::get($user, 'user_id');
        $certificateExpireDate = Bin_Array::get($user, 'certificate_expired_date');
        $userPasswordHash = Bin_Array::get($user, 'user_password_hash');
        $certificatePasswordHash = Bin_Array::get($user, 'certificate_password_hash');
        $consentStatus = Bin_Array::get($user, 'consent_status');

        if ($certificateExpireDate == null) { // if expired date is empty and should regenerate
            $this->_register->generateCertificate($userId, $userPassword, $consentStatus);
        } elseif (!$this->_register->isCertificateExpired($certificateExpireDate)) { // if certificate is not expired
            if ($userPasswordHash != $certificatePasswordHash) {
                $resultArray['errors']['certificate_error'] = Model_MRegister::ERROR_CERTIFICATE_RECEIVE;
                $this->getResponse($resultArray);
                return;
            }
        } else { // if certificate id expired
            $resultArray['errors']['certificate_error'] = Model_MRegister::ERROR_CERTIFICATE_EXPIRED;
            $this->getResponse($resultArray);
            return;
        }
        
        $certificate = $this->_register->getUserCertificate($userId);
        $this->getResponse(array(
            'status' => true,
            'certificate' => base64_encode(Bin_Array::get($certificate, 'certificate')),
            'certificate_name' => Bin_Array::get($certificate, 'certificate_name'),
        ));
    }

	protected function assertAuth(){
		if(!$this->_auth){
			//$this->showError("Auth required",401);
		}
	}

	protected function assertMethod($method){
		if(strtoupper($_SERVER['REQUEST_METHOD']) != strtoupper($method)){
			$this->showError('Invalid method',405);
		}
	}

	protected function assertRequest($method){
		$this->assertMethod($method);
		$this->assertAuth();
	}

	protected function showError($message,$code=500){
		header("HTTP/1.0 $code $message");
		echo $message;
		exit;
	}

	protected function showErrorNotFound($message='Not found'){
		$this->showError($message);
	}

	protected function getResponse(array $values){
		header('Content-Type: application/json');
		echo json_encode($values);
	}
}