Beispiel #1
0
 /**
  * @param string $countryCode
  * @param string $vatNumber
  * @return bool
  */
 public function check($countryCode, $vatNumber)
 {
     $this->initClient();
     $vatNumber = preg_replace("/[ .]/", "", $vatNumber);
     try {
         $rs = $this->_client->checkVat(array('countryCode' => $countryCode, 'vatNumber' => $vatNumber));
     } catch (\SoapFault $e) {
         if ($e->getMessage() === 'INVALID_INPUT') {
             return false;
         }
         throw $e;
     }
     if ($rs->valid) {
         $this->_valid = true;
         list($denomination, $name) = strpos($rs->name, ' ') !== false ? explode(" ", $rs->name, 2) : array('', '');
         list($streetline, $cityline) = strpos($rs->address, "\n" !== false) ? explode("\n", $rs->address) : array('', '');
         preg_match('/(.+) ([^ ]*[0-9]+[^ ]*)/', $this->cleanUpString($streetline), $parts);
         if (count($parts) === 0) {
             $street = $this->cleanUpString($streetline);
             $number = "";
         } else {
             $street = $parts[1];
             $number = $parts[2];
         }
         list($zip, $city) = $cityline !== '' ? explode(' ', $this->cleanUpString($cityline), 2) : array('', '');
         $this->_data = array('denomination' => $denomination, 'name' => $this->cleanUpString($name), 'address' => $this->cleanUpString($rs->address), 'street' => $street, 'number' => $number, 'zip' => $zip, 'city' => $city, 'country' => $countryCode);
         return true;
     } else {
         $this->_valid = false;
         $this->_data = array();
         return false;
     }
 }
Beispiel #2
0
 private function eu_check()
 {
     $isp = Shineisp_Registry::get('ISP');
     $VIES = new SoapClient($this->vies_soap_url);
     if ($VIES) {
         try {
             $r = $VIES->checkVat(array('countryCode' => $this->countryCode, 'vatNumber' => $this->vat));
             foreach ($r as $chiave => $valore) {
                 $this->viesOutput[$chiave] = $valore;
             }
             return $r->valid;
         } catch (SoapFault $e) {
             $ret = $e->faultstring;
             $regex = '/\\{ \'([A-Z_]*)\' \\}/';
             $n = preg_match($regex, $ret, $matches);
             $ret = !empty($matches[1]) ? $matches[1] : $ret;
             $faults = array('INVALID_INPUT' => 'The provided CountryCode is invalid or the VAT number is empty', 'SERVICE_UNAVAILABLE' => 'The SOAP service is unavailable, try again later', 'MS_UNAVAILABLE' => 'The Member State service is unavailable, try again later or with another Member State', 'TIMEOUT' => 'The Member State service could not be reached in time, try again later or with another Member State', 'SERVER_BUSY' => 'The service cannot process your request. Try again later.');
             $ret = $faults[$ret];
             // adding a log message
             Shineisp_Commons_Utilities::log("Response from VIES: " . $ret);
             $subject = 'Invalid VAT code';
             $body = "Response from VIES: " . $ret;
             Shineisp_Commons_Utilities::SendEmail($isp->email, $isp->email, null, $subject, $body);
             return false;
         }
     } else {
         $subject = 'Connect to VIES';
         $body = "Impossible to connect with VIES";
         Shineisp_Commons_Utilities::SendEmail($isp->email, $isp->email, null, $subject, $body);
         // adding a log message
         Shineisp_Commons_Utilities::log("Response from VIES: " . $ret);
         return false;
     }
     return true;
 }
Beispiel #3
0
 /**
  * Check if this is a valid VIES VAT
  *
  * Code credits: Nicholas from AkeebaBackup.com
  */
 public function isValidVat($country, $vat)
 {
     $vat = trim(strtoupper($vat));
     $country = trim(strtoupper($country));
     // cache
     $data = json_decode($this->app->session->get('zoocart_vat_cache'), true);
     if ($data && array_key_exists($country . $vat, $data)) {
         return $data[$country . $vat];
     }
     if (!class_exists('SoapClient')) {
         $ret = false;
     } else {
         // Using the SOAP API
         // Code credits: Angel Melguiz / KMELWEBDESIGN SLNE (www.kmelwebdesign.com)
         try {
             $sClient = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl');
             $params = array('countryCode' => $country, 'vatNumber' => $vat);
             $response = $sClient->checkVat($params);
             if ($response->valid) {
                 $ret = true;
             } else {
                 $ret = false;
             }
         } catch (SoapFault $e) {
             $ret = false;
         }
     }
     $data[$country . $vat] = $ret;
     $this->app->session->set('zoocart_vat_cache', json_encode($data));
     // Return the result
     return $ret;
 }
 /**
  * Check a given VAT number with the europe VIES check
  *
  * @param string $country The country code to check with the VAT number.
  * @param string $vat_nr The VAT number to check.
  *
  * @return bool|null
  */
 private function check_vat($country, $vat_nr)
 {
     $country = trim($country);
     $vat_nr = trim($vat_nr);
     // Strip all spaces from the VAT number to improve usability of the VAT field.
     $vat_nr = str_replace(' ', '', $vat_nr);
     if (0 === strpos($vat_nr, $country)) {
         $vat_nr = trim(substr($vat_nr, strlen($country)));
     }
     try {
         // Do the remote request.
         $client = new \SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl');
         $returnVat = $client->checkVat(array('countryCode' => $country, 'vatNumber' => $vat_nr));
     } catch (\Exception $e) {
         error_log('VIES API Error for ' . $country . ' - ' . $vat_nr . ': ' . $e->getMessage());
         return 2;
     }
     // Return the response.
     if (isset($returnVat)) {
         if (true == $returnVat->valid) {
             return 1;
         } else {
             return 0;
         }
     }
     // Return null if the service is down.
     return 2;
 }
Beispiel #5
0
 protected function checkWithVIES($countryCode, $vatNumber)
 {
     try {
         ini_set("soap.wsdl_cache_enabled", 0);
         $client = new \SoapClient(__DIR__ . '/../Resources/wsdl/checkVatService.wsdl', array('soap_version' => SOAP_1_1, 'style' => SOAP_DOCUMENT, 'encoding' => SOAP_LITERAL, 'location' => 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService', 'trace' => 1));
         $result = $client->checkVat(array('countryCode' => $countryCode, 'vatNumber' => $vatNumber));
         return $result->valid ? true : false;
     } catch (\SoapFault $exception) {
         throw new VATException('SOAP fault', 0, $exception);
     }
 }
Beispiel #6
0
 private function getRequest()
 {
     try {
         $opts = array('http' => array('user_agent' => 'PHPSoapClient'));
         $context = stream_context_create($opts);
         $client = new \SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('stream_context' => $context, 'cache_wsdl' => WSDL_CACHE_NONE));
         $result = $client->checkVat(array('countryCode' => $this->_codiceComunitario, 'vatNumber' => $this->_partitaIVA));
         $this->_valid = $result->valid == 1 ? true : false;
         return true;
     } catch (\Exception $e) {
         return false;
     }
 }
Beispiel #7
0
 /**
  */
 protected function _ajaxUpdate(Horde_Variables $vars)
 {
     $html = '';
     $vatid = str_replace(' ', '', $vars->vatid);
     if (empty($vatid) || !preg_match('/^([A-Z]{2})([0-9A-Za-z\\+\\*\\.]{2,12})$/', $vatid, $matches)) {
         return '<br />' . $this->_error(_("Invalid VAT identification number format."));
     }
     if (empty($matches)) {
         return;
     }
     try {
         $client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('exceptions' => true));
         $result = $client->checkVat(array('countryCode' => $matches[1], 'vatNumber' => $matches[2]));
         if ($result->valid) {
             $html .= '<span style="color:green;font-weight:bold">' . _("This VAT identification number is valid.") . '</span><br />';
         } else {
             $html .= $this->_error(_("This VAT identification number is invalid.")) . '<br />';
         }
         $html .= '<em>' . _("Country") . ':</em> ' . $result->countryCode . '<br /><em>' . _("VAT number") . ':</em> ' . $result->vatNumber . '<br /><em>' . _("Date") . ':</em> ' . strftime($GLOBALS['prefs']->getValue('date_format'), strtotime($result->requestDate)) . '<br />';
         if (!empty($result->name)) {
             $html .= '<em>' . _("Name") . ':</em> ' . $result->name . '<br />';
         }
         if (!empty($result->address)) {
             $html .= '<em>' . _("Address") . ':</em> ' . $result->address . '<br />';
         }
     } catch (SoapFault $e) {
         $error = $e->getMessage();
         switch (true) {
             case strpos($error, 'INVALID_INPUT'):
                 $error = _("The provided country code is invalid.");
                 break;
             case strpos($error, 'SERVICE_UNAVAILABLE'):
                 $error = _("The service is currently not available. Try again later.");
                 break;
             case strpos($error, 'MS_UNAVAILABLE'):
                 $error = _("The member state service is currently not available. Try again later or with a different member state.");
                 break;
             case strpos($error, 'TIMEOUT'):
                 $error = _("The member state service could not be reached in time. Try again later or with a different member state.");
                 break;
             case strpos($error, 'SERVER_BUSY'):
                 $error = _("The service is currently too busy. Try again later.");
                 break;
         }
         $html .= $this->_error($error);
     }
     return $html;
 }
Beispiel #8
0
 /**
  * Attempt to validate a european VAT
  * ** This method is called by exec() and is designed to be HTTP accessible **
  *
  * @param $args ['vatNumber'=>"...", 'countryCode'=>'...']
  * @return Response
  * @throws \Exception
  */
 public function validateVatNumberHandler($args)
 {
     $this->testInputs(['vatNumber' => ['string'], 'countryCode' => ['string']], $args);
     $args['vatNumber'] = str_replace(' ', '', $args['vatNumber']);
     $args['vatNumber'] = strtoupper($args['vatNumber']);
     $this->state->vatNumber = null;
     $this->state->vatNumberStatus = null;
     $this->state->vatNumberCountryCode = null;
     $client = new \SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
     $soapResponse = null;
     try {
         $soapResponse = $client->checkVat(array('countryCode' => $args['countryCode'], 'vatNumber' => $args['vatNumber']));
         if ($soapResponse->valid) {
             // Valid
             $this->state->vatNumber = $args['vatNumber'];
             $this->state->vatNumberStatus = 'valid';
             $this->state->vatNumberCountryCode = $args['countryCode'];
         } else {
             // Invalid
             $this->state->vatNumber = null;
             $this->state->vatNumberCountryCode = null;
             $this->state->vatNumberStatus = 'invalid';
             $this->setFlashError("Sorry but the VAT number or country entered was incorrect.");
         }
     } catch (\SoapFault $e) {
         if ($e->getMessage() == "INVALID_INPUT") {
             // Invalid
             $this->state->vatNumber = null;
             $this->state->vatNumberCountryCode = null;
             $this->state->vatNumberStatus = 'invalid';
             $this->setFlashError("Sorry but the VAT number or country entered was incorrect.");
         } else {
             // Unknown due to technical error
             // We allow the vat number but flag it for manual checking
             $this->state->vatNumber = $args['vatNumber'];
             $this->state->vatNumberStatus = 'unknown';
             $this->state->vatNumberCountryCode = $args['countryCode'];
         }
     }
     $this->updateLineItemsAndTotal();
     // Render full component
     $this->updateState();
     return $this->render();
 }
Beispiel #9
0
 /**
  * verifies vies number
  * @param  string $vat_number   
  * @param  string $country_code 
  * @return boolean               
  */
 public static function verify_vies($vat_number, $country_code = NULL)
 {
     if ($vat_number == NULL or $vat_number == '' or strlen($vat_number) < 3) {
         return FALSE;
     }
     if ($country_code === NULL or empty($country_code)) {
         $country_code = self::country_code();
     }
     //first check if country is part of EU
     if (array_key_exists($country_code, self::get_vat_rates())) {
         $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
         $res = $client->checkVat(array('countryCode' => $country_code, 'vatNumber' => $vat_number));
         //not valid
         if (!$res->valid) {
             return FALSE;
         }
     }
     return TRUE;
 }
Beispiel #10
0
/**
 *
 * @ WHMCS FULL DECODED & NULLED
 *
 * @ Version  : 5.2.15
 * @ Author   : MTIMER
 * @ Release on : 2013-12-24
 * @ Website  : http://www.mtimer.cn
 *
 * */
function eu_vat_hook_validate_number($vars)
{
    $modulevars = array();
    $result = select_query("tbladdonmodules", "", array("module" => "eu_vat"));
    while ($data = mysql_fetch_array($result)) {
        $modulevars[$data['setting']] = $data['value'];
    }
    if (!$modulevars['enablevalidation']) {
        return false;
    }
    $result = select_query("tblcustomfields", "id", array("type" => "client", "fieldname" => $modulevars['vatcustomfield']));
    $data = mysql_fetch_array($result);
    $VAT_CUSTOM_FIELD_ID = $data['id'];
    $vatnumber = $_POST['customfield'][$VAT_CUSTOM_FIELD_ID];
    if ($vatnumber) {
        $vatnumber = strtoupper($vatnumber);
        $vatnumber = preg_replace("/[^A-Z0-9]/", "", $vatnumber);
        $vat_prefix = substr($vatnumber, 0, 2);
        $vat_num = substr($vatnumber, 2);
        $errorcheck = false;
        try {
            $taxCheck = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
            $taxValid = $taxCheck->checkVat(array("countryCode" => "" . $vat_prefix, "vatNumber" => "" . $vat_num));
        } catch (Exception $e) {
            $errorcheck = true;
        }
        if ($taxValid->valid != 1 || $errorcheck) {
            global $errormessage;
            global $_LANG;
            if (!$_LANG['vatnumberinvalid']) {
                $_LANG['vatnumberinvalid'] = "The supplied VAT Number is not valid";
            }
            $errormessage .= "<li>" . $_LANG['vatnumberinvalid'];
        }
    }
}
Beispiel #11
0
 /**
  * Checks online if USt.ID number is valid.
  * Returns true on success. On error sets error value.
  *
  * @param object $oCheckVat vat object
  *
  * @return bool
  */
 protected function _checkOnline($oCheckVat)
 {
     if ($this->_isServiceAvailable()) {
         $iTryMoreCnt = self::BUSY_RETRY_CNT;
         //T2009-07-02
         //how long socket should wait for server RESPONSE
         ini_set('default_socket_timeout', 5);
         // setting local error handler to catch possible soap errors
         set_error_handler(array($this, 'catchWarning'), E_WARNING);
         do {
             try {
                 //connection_timeout = how long we should wait to CONNECT to wsdl server
                 $oSoapClient = new SoapClient($this->getWsdlUrl(), array("connection_timeout" => 5));
                 $this->setError('');
                 $oRes = $oSoapClient->checkVat($oCheckVat);
                 $iTryMoreCnt = 0;
             } catch (SoapFault $e) {
                 $this->setError($e->faultstring);
                 if ($this->getError() == "SERVER_BUSY") {
                     usleep(self::BUSY_RETRY_WAITUSEC);
                 } else {
                     $iTryMoreCnt = 0;
                 }
             }
         } while (0 < $iTryMoreCnt--);
         // restoring previous error handler
         restore_error_handler();
         return (bool) $oRes->valid;
     } else {
         $this->setError("SERVICE_UNREACHABLE");
         return false;
     }
 }
Beispiel #12
0
 function validate_VAT($country_code, $vat_number)
 {
     try {
         $client = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', array('exceptions' => true));
         $result = $client->checkVat(array('countryCode' => $country_code, 'vatNumber' => $vat_number));
         return isset($result->valid) ? $result->valid : null;
     } catch (Exception $exception) {
         return null;
     }
 }
Beispiel #13
0
 function validateEUVat($args = array())
 {
     if ('' != $args['vatnumber']) {
         $vat_number = str_replace(array(' ', '.', '-', ',', ', '), '', $args['vatnumber']);
         $countryCode = substr($vat_number, 0, 2);
         $vatNumber = substr($vat_number, 2);
         if (strlen($countryCode) != 2 || is_numeric(substr($countryCode, 0, 1)) || is_numeric(substr($countryCode, 1, 2))) {
             return FALSE;
             //format error 'message' => 'Your VAT Number syntax is not correct. You should have something like this: BE805670816B01'
         }
         if ($args['country'] != $countryCode) {
             return FALSE;
             //'message' => 'Your VAT Number is not valid for the selected country.'
         }
         $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/services/checkVatService.wsdl");
         $params = array('countryCode' => $countryCode, 'vatNumber' => $vatNumber);
         $result = $client->checkVat($params);
         if (!$result->valid) {
             return FALSE;
             // 'message' => sprintf('Invalid VAT Number. Check the validity on the customer VAT Number via <a href="%s">Europa VAT Number validation webservice</a>', 'http://ec.europa.eu/taxation_customs/vies/lang.do?fromWhichPage=vieshome'));
         } else {
             return TRUE;
         }
     }
     return FALSE;
 }
Beispiel #14
0
 private function isVIESValidVAT($country, $vat)
 {
     // Validate VAT number
     $vat = trim(strtoupper($vat));
     $country = $country == 'GR' ? 'EL' : $country;
     // (remove the country prefix if present)
     if (substr($vat, 0, 2) == $country) {
         $vat = trim(substr($vat, 2));
     }
     // Is the validation already cached?
     $key = $country . $vat;
     $ret = null;
     if (array_key_exists('vat', $this->_cache)) {
         if (array_key_exists($key, $this->_cache['vat'])) {
             $ret = $this->_cache['vat'][$key];
         }
     }
     if (!is_null($ret)) {
         return $ret;
     }
     if (empty($vat)) {
         $ret = false;
     } else {
         if (!class_exists('SoapClient')) {
             $ret = false;
         } else {
             // Using the SOAP API
             // Code credits: Angel Melguiz / KMELWEBDESIGN SLNE (www.kmelwebdesign.com)
             try {
                 $sOptions = array('user_agent' => 'PHP');
                 $sClient = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', $sOptions);
                 $params = array('countryCode' => $country, 'vatNumber' => $vat);
                 $response = $sClient->checkVat($params);
                 if ($response->valid) {
                     $ret = true;
                 } else {
                     $ret = false;
                 }
             } catch (SoapFault $e) {
                 $ret = false;
             }
         }
     }
     // Cache the result
     if (!array_key_exists('vat', $this->_cache)) {
         $this->_cache['vat'] = array();
     }
     $this->_cache['vat'][$key] = $ret;
     $encodedCacheData = json_encode($this->_cache);
     $session = JFactory::getSession();
     $session->set('validation_cache_data', $encodedCacheData, 'com_akeebasubs');
     // Return the result
     return $ret;
 }
Beispiel #15
0
/**
 * Checks if a vat number is valid
 * 
 * @param type $vat_number VAT number to be checked
 * @return bool true if valid, else false
 */
function check_vat_number($vat_number)
{
    $vat = strtoupper(str_replace(array(" ", "-", ",", ".", "/", "\\"), "", $vat_number));
    if (preg_match("/^(AT|BE|BG|CY|CZ|DE|DK|EE|EL|ES|FI|FR|GB|HU|IE|IT|LT|LU|LV|MT|NL|PL|PT|RO|SE|SI|SK)(.*)/i", $vat, $matches)) {
        $country_code = strtoupper($matches[1]);
        $vat = $matches[2];
    }
    if (!isset($country_code)) {
        return false;
    }
    $regex = array('AT' => '/(U[0-9]{8})/i', 'BE' => '/(0[0-9]{9})/i', 'BG' => '/([0-9]{9,10})/i', 'CY' => '/([0-9]{8}[a-z])/i', 'CZ' => '/([0-9]{8}|[0-9]{9}|[0-9]{10})/i', 'DE' => '/([0-9]{9})/i', 'DK' => '/([0-9]{8})/i', 'EE' => '/([0-9]{9})/i', 'EL' => '/([0-9]{9})/i', 'ES' => '/([a-z][0-9]{8}|[0-9]{8}[a-z]|[a-z][0-9]{7}[a-z])/i', 'FI' => '/([0-9]{8})/i', 'FR' => '/([a-z0-9]{2}[0-9]{9})/i', 'GB' => '/([0-9]{9}|[0-9]{12}|GD[0-9]{3}|HA[0-9]{3})/i', 'HU' => '/([0-9]{8})/i', 'IE' => '/([0-9][a-z0-9\\+\\*][0-9]{5}[a-z])/i', 'IT' => '/([0-9]{11})/i', 'LT' => '/([0-9]{9}|[0-9]{12})/i', 'LU' => '/([0-9]{8})/i', 'LV' => '/([0-9]{11})/i', 'MT' => '/([0-9]{8})/i', 'NL' => '/([0-9]{9}B[0-9]{2})/i', 'PL' => '/([0-9]{10})/i', 'PT' => '/([0-9]{9})/i', 'RO' => '/([0-9]{2,10})/i', 'SE' => '/([0-9]{12})/i', 'SI' => '/([0-9]{8})/i', 'SK' => '/([0-9]{10})/i');
    if (!isset($regex[$country_code])) {
        return false;
    }
    if (!preg_match($regex[$country_code], $vat, $m)) {
        return false;
    }
    // only ask service is syntax-check is ok
    if ($m[1] == $vat) {
        try {
            $res = cache_get("vat_check_{$country_code}_{$vat}");
            if (!$res) {
                $sc = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
                $test = $sc->checkVat(array('countryCode' => $country_code, 'vatNumber' => $vat));
                if (!$test->valid) {
                    log_debug("VAT syntax ok, but SOAP says not", $vat_number, $country_code, $vat, $test);
                }
                $res = $test->valid ? "valid" : "invalid";
                cache_set("vat_check_{$country_code}_{$vat}", $res);
            } elseif ($res != "valid") {
                log_debug("VAT syntax ok, but CACHE says not", $vat_number, $country_code, $vat);
            }
            return $res == "valid";
        } catch (Exception $ex) {
            WdfException::Log($ex);
        }
        return true;
        // ignore service exceptions
    }
    return false;
}
<?php

$url = "https://sistemas.unipe.br:8443/uniservice/ws/segurancaWS?wsdl";
echo "#######################<BR/>";
try {
    $opts = array('https' => array('user_agent' => 'PHPSoapClient'));
    $context = stream_context_create($opts);
    $client = new SoapClient($url, array('stream_context' => $context));
    $result = $client->checkVat(array('u' => '003961', 'p' => ''));
    print_r($result);
} catch (Exception $e) {
    echo $e->getMessage();
}
Beispiel #17
0
 public function isVIESValidVAT($country, $vat, $company = '', &$err)
 {
     // Validate VAT number
     $vat = trim(strtoupper($vat));
     $country = $country == 'GR' ? 'EL' : $country;
     $country = $country == 'UK' ? 'GB' : $country;
     // (remove the country prefix if present)
     if (substr($vat, 0, 2) == $country) {
         $vat = trim(substr($vat, 2));
     }
     $vat = preg_replace('/[^A-Z0-9]/', '', $vat);
     // Remove spaces, dots and stuff
     // Is the validation already cached?
     $key = $country . $vat;
     $ret = null;
     if (array_key_exists('vat', $this->_cache)) {
         if (array_key_exists($key, $this->_cache['vat'])) {
             $ret = $this->_cache['vat'][$key];
         }
     }
     $country = strtoupper($country);
     if (!in_array($country, OPCvat::$european_states)) {
         $ret = false;
         $vat = '';
     }
     if (!is_null($ret)) {
         return $ret;
     }
     if (empty($vat)) {
         $ret = false;
     } else {
         if (!class_exists('SoapClient')) {
             $ret = false;
         } else {
             // Using the SOAP API
             // Code credits: Angel Melguiz / KMELWEBDESIGN SLNE (www.kmelwebdesign.com)
             try {
                 $sOptions = array('user_agent' => 'PHP');
                 $sClient = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', $sOptions);
                 $params = array('countryCode' => $country, 'vatNumber' => $vat);
                 $response = $sClient->checkVat($params);
                 if ($response->valid) {
                     $ret = true;
                 } else {
                     $ret = false;
                 }
             } catch (SoapFault $ex) {
                 $err = $ex->faultcode . ' ' . $ex->faultstring . ' ' . $ex->faultactor . ' ' . $ex->detail . ' ' . $ex->_name . ' ' . $ex->headerfault;
                 $ret = false;
                 return -1;
             }
         }
     }
     // Cache the result
     if (!array_key_exists('vat', $this->_cache)) {
         $this->_cache['vat'] = array();
     }
     $this->_cache['vat'][$key] = $ret;
     $encodedCacheData = json_encode($this->_cache);
     $session = JFactory::getSession();
     $session->set('validation_cache_data', $encodedCacheData, 'com_onepage');
     // Return the result
     return $ret;
 }
Beispiel #18
0
 /**
  * Validate EU VAT Number
  *
  * @param $vatNumber
  *
  * @return bool
  */
 public static function validateEUVATNumber($vatNumber)
 {
     // Remove spaces
     $vatNumber = preg_replace('/\\s+/', '', $vatNumber);
     // Check to see if the VAT Number passed is in valid format before calling webservices
     if (!self::preCheckVatNumber($vatNumber)) {
         return false;
     }
     // Use web service to validate the VAT number
     $countryCode = substr($vatNumber, 0, 2);
     $number = substr($vatNumber, 2);
     if (class_exists('SoapClient')) {
         $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
         $rs = $client->checkVat(array('countryCode' => $countryCode, 'vatNumber' => $number));
         return $rs->valid;
     } else {
         $url = "http://ec.europa.eu/taxation_customs/vies/viesquer.do?ms=" . $countryCode . "&vat=" . $number;
         $ch = curl_init($url);
         curl_setopt($ch, CURLOPT_URL, $url);
         curl_setopt($ch, CURLOPT_HEADER, 0);
         curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
         curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
         $resp = curl_exec($ch);
         curl_close($ch);
         if (strpos($resp, '="validStyle"') !== false) {
             return true;
         } else {
             return false;
         }
     }
 }
Beispiel #19
0
 function onlineCheck($vat)
 {
     JPluginHelper::importPlugin('hikashop');
     $dispatcher = JDispatcher::getInstance();
     $processed = false;
     $rc = $dispatcher->trigger('onBeforeVATOnlineCheck', array(&$this, &$processed, &$vat));
     if ($processed) {
         return $rc;
     }
     if (extension_loaded('soap')) {
         try {
             $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
             $countryCode = substr($vat, 0, 2);
             $result = $client->checkVat(array('countryCode' => $countryCode, 'vatNumber' => substr($vat, 2)));
             if (empty($result) || !$result->valid) {
                 $this->message = JText::_('VAT_NUMBER_NOT_VALID');
             }
         } catch (SoapFault $e) {
             $this->message = $e->__toString();
             return true;
         } catch (Exception $e) {
             $this->message = $e->__toString();
             return true;
         }
         if ($result === false || empty($result) || !$result->valid) {
             $app = JFactory::getApplication();
             if ($_REQUEST['tmpl'] == 'component') {
                 hikashop_display($this->message, 'error');
             } else {
                 $app->enqueueMessage($this->message);
             }
             return false;
         }
     } else {
         $app = JFactory::getApplication();
         $this->message = JText::_('SOAP_EXTENSION_NOT_FOUND');
         if ($_REQUEST['tmpl'] == 'component') {
             hikashop_display($this->message, 'error');
         } else {
             $app->enqueueMessage($this->message);
         }
         return false;
     }
     return true;
 }
Beispiel #20
0
 /**
  * Check if a vat number is correct.
  * 
  * @param string $countryCode The country code: eg. "NL" or "BE"
  * @param string $vat The vat number
  * @return boolean true
  */
 public static function checkVat($countryCode, $vat)
 {
     //remove unwanted characters
     $vat = preg_replace('/[^a-z0-9]/i', '', $vat);
     //strip country if included
     if (substr($vat, 0, 2) == $countryCode) {
         $vat = trim(substr($vat, 2));
     }
     //$wsdl = 'http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl';
     $wsdl = \GO::config()->root_path . 'go/vendor/wsdl/checkVatService.wsdl';
     $vies = new \SoapClient($wsdl);
     //lower the timeout becuase it can hang too long
     ini_set("default_socket_timeout", 5);
     /**
     	var_dump($vies->__getFunctions());
     	var_dump($vies->__getTypes());
     */
     $message = new \stdClass();
     $message->countryCode = $countryCode;
     $message->vatNumber = $vat;
     try {
         $ret = $vies->checkVat($message);
     } catch (\SoapFault $e) {
         $ret = $e->faultstring;
         $regex = '/\\{ \'([A-Z_]*)\' \\}/';
         $n = preg_match($regex, $ret, $matches);
         if (isset($matches[1])) {
             $ret = $matches[1];
             $faults = array('INVALID_INPUT' => 'The provided CountryCode is invalid or the VAT number is empty', 'SERVICE_UNAVAILABLE' => 'The SOAP service is unavailable, try again later', 'MS_UNAVAILABLE' => 'The VAT Member State service is unavailable, try again later or with another Member State', 'TIMEOUT' => 'The Member State service could not be reached in time, try again later or with another Member State', 'SERVER_BUSY' => 'The service cannot process your request. Try again later.');
             $msg = $faults[$ret];
         } else {
             $msg = $ret;
         }
         if ($ret != "INVALID_INPUT") {
             throw new \GO\Base\Exception\ViesDown();
         }
         throw new \Exception("Could not check VAT number: " . $msg);
     }
     return $ret->valid;
 }
Beispiel #21
0
	/**
	 * Checks an exact VAT number using EU VIES checkVat SOAP call
	 *
	 * @param  string  $vat_number
	 * @param  string  $userMessage  OUTPUT: String to customer
	 * @return boolean
	 */
	public function checkVatNumber( $vat_number, &$userMessage ) {
		$vatCountryCode				=	strtoupper( substr( $vat_number, 0, 2 ) );
		$cleanVatNumber				=	$this->cleanVatNumber( $vat_number );
		if ( ( $cleanVatNumber !== false ) && $this->checkCountryInEU( ( $vatCountryCode == 'EL' ? 'GR' : $vatCountryCode ) ) ) {
			try {
				$client				=	new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl", array( 'exceptions' => true ) );
				$params				=	array('countryCode' => $vatCountryCode, 'vatNumber' => $cleanVatNumber);
				/** @noinspection PhpUndefinedMethodInspection */
				$result				=	$client->checkVat( $params );
				$checked			=	true;
			}
			catch ( \SoapFault $e ) {
				$result				=	$e->getMessage();
				$checked			=	false;
			}

			if ( ( ! $checked ) || is_soap_fault( $result ) ) {
				if ( ! $checked ) {
					$userMessage	=	CBPTXT::Th("EU VIES VAT number verification server unreachable. VAT number could not be checked. Proceed with VAT or try again later.");
					return false;
				} elseif ( isset( $result->faultstring ) && ( $result->faultstring == 'INVALID_INPUT' ) ) {
					$userMessage	=	CBPTXT::T("Invalid EU VAT Number. EU VAT numbers start with country code and must be valid.");
					return false;
				} else {
					$userMessage	=	CBPTXT::T("Could not check EU VAT Number, EU or country service not available now.");
					return null;
				}
			}
			/** @var StdClass $result */
			if ( $result->valid ) {
				$userMessage		=	CBPTXT::T("EU VAT Number is valid.");
			} else {
				$userMessage		=	CBPTXT::T("Invalid EU VAT Number. EU VAT numbers start with country code and must be valid.");;
			}
			return $result->valid;
		} else {
			$userMessage			=	CBPTXT::T("Invalid EU VAT Number. EU VAT numbers start with country code and must be valid.");
			return false;
		}				
	}
Beispiel #22
0
 /**
  * Checks vat id with webservice
  * @access public
  * @return array assoziative array with success / error codes
  */
 public function sValidateVat()
 {
     if (empty($this->sSYSTEM->sCONFIG['sVATCHECKENDABLED'])) {
         return array();
     }
     if (empty($this->sSYSTEM->_POST["ustid"]) && empty($this->sSYSTEM->sCONFIG['sVATCHECKREQUIRED'])) {
         return array();
     }
     $messages = array();
     $ustid = preg_replace('#[^0-9A-Z\\+\\*\\.]#', '', strtoupper($this->sSYSTEM->_POST['ustid']));
     $country = $this->sSYSTEM->sDB_CONNECTION->GetOne('SELECT countryiso FROM s_core_countries WHERE id=?', array($this->sSYSTEM->_POST['country']));
     if (empty($this->sSYSTEM->_POST["ustid"])) {
         $messages[] = $this->snippetObject->get('VatFailureEmpty', 'Please enter a vat id');
     } elseif (empty($ustid) || !preg_match("#^([A-Z]{2})([0-9A-Z+*.]{2,12})\$#", $ustid, $vat)) {
         $messages[] = $this->snippetObject->get('VatFailureInvalid', 'The vat id entered is invalid');
     } elseif (empty($country) || $country != $vat[1]) {
         $field_names = explode(',', $this->snippetObject->get('VatFailureErrorFields', 'Company,City,Zip,Street,Country'));
         $field_name = isset($field_names[4]) ? $field_names[4] : 'Land';
         $messages[] = sprintf($this->snippetObject->get('VatFailureErrorField', 'The field %s does not match to the vat id entered'), $field_name);
     } elseif ($country == 'DE') {
     } elseif (!empty($this->sSYSTEM->sCONFIG['sVATCHECKADVANCEDNUMBER'])) {
         $data = array('UstId_1' => $this->sSYSTEM->sCONFIG['sVATCHECKADVANCEDNUMBER'], 'UstId_2' => $vat[1] . $vat[2], 'Firmenname' => '', 'Ort' => '', 'PLZ' => '', 'Strasse' => '', 'Druck' => empty($this->sSYSTEM->sCONFIG['sVATCHECKCONFIRMATION']) ? 'nein' : 'ja');
         if (!empty($this->sSYSTEM->sCONFIG['sVATCHECKADVANCED']) && strpos($this->sSYSTEM->sCONFIG['sVATCHECKADVANCEDCOUNTRIES'], $vat[1]) !== false) {
             $data['Firmenname'] = $this->sSYSTEM->_POST['company'];
             $data['Ort'] = $this->sSYSTEM->_POST['city'];
             $data['PLZ'] = $this->sSYSTEM->_POST['zipcode'];
             $data['Strasse'] = $this->sSYSTEM->_POST['street'] . ' ' . $this->sSYSTEM->_POST['streetnumber'];
         }
         $request = 'http://evatr.bff-online.de/evatrRPC?';
         $request .= http_build_query($data, '', '&');
         $context = stream_context_create(array('http' => array('method' => 'GET', 'header' => 'Content-Type: text/html; charset=utf-8', 'timeout' => 5, 'user_agent' => 'Shopware/' . $this->sSYSTEM->sCONFIG['sVERSION'])));
         $response = @file_get_contents($request, false, $context);
         $reg = '#<param>\\s*<value><array><data>\\s*<value><string>([^<]*)</string></value>\\s*<value><string>([^<]*)</string></value>\\s*</data></array></value>\\s*</param>#msi';
         if (!empty($response) && preg_match_all($reg, $response, $matches)) {
             $response = array_combine($matches[1], $matches[2]);
             $messages = $this->sCheckVatResponse($response);
         } elseif (empty($this->sSYSTEM->sCONFIG['sVATCHECKNOSERVICE'])) {
             $messages[] = sprintf($this->snippetObject->get('VatFailureUnknownError', 'An unknown error occurs while checking your vat id. Error code %d'), 10);
         }
     } elseif (false && class_exists('SoapClient')) {
         $url = 'http://ec.europa.eu/taxation_customs/vies/services/checkVatService.wsdl';
         if (!file_get_contents($url)) {
             $messages[] = sprintf($this->snippetObject->get('VatFailureUnknownError', 'An unknown error occurs while checking your vat id. Error code %d'), 11);
         } else {
             $client = new SoapClient($url, array('exceptions' => 0, 'connection_timeout' => 5));
             $response = $client->checkVat(array('countryCode' => $vat[1], 'vatNumber' => $vat[2]));
         }
         if (is_soap_fault($response)) {
             $messages[] = sprintf($this->snippetObject->get('VatFailureUnknownError', 'An unknown error occurs while checking your vat id. Error code %d'), 12);
             if (!empty($this->sSYSTEM->sCONFIG['sVATCHECKDEBUG'])) {
                 $messages[] = "SOAP-error: (errorcode: {$response->faultcode}, errormsg: {$response->faultstring})";
             }
         } elseif (empty($response->valid)) {
             $messages[] = $this->snippetObject->get('VatFailureInvalid', 'The vat id entered is invalid');
         }
     } else {
         $messages[] = sprintf($this->snippetObject->get('VatFailureUnknownError', 'An unknown error occurs while checking your vat id. Error code %d'), 20);
     }
     if (!empty($messages) && empty($this->sSYSTEM->sCONFIG['sVATCHECKREQUIRED'])) {
         $messages[] = $this->snippetObject->get('VatFailureErrorInfo', '');
         // todo@all In the case vat is not required in registration, this info message should occur
     }
     $messages = Enlight()->Events()->filter('Shopware_Modules_Admin_CheckTaxID_MessagesFilter', $messages, array('subject' => $this, "post" => $this->sSYSTEM->_POST));
     return $messages;
 }
Beispiel #23
0
$memberStateCode = $_POST['memberStateCode'];
$vat = $_POST['vat'];
$leVat .= $memberStateCode;
$leVat .= $vat;
//die();
$vatid = $leVat;
// replace for the VAT-ID you would like to check
$vatid = str_replace(array(' ', '.', '-', ',', ', '), '', trim($vatid));
$cc = substr($vatid, 0, 2);
$vn = substr($vatid, 2);
$client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
if ($client) {
    $valide = "Numeros de TVA existe !";
    $params = array('countryCode' => $cc, 'vatNumber' => $vn);
    try {
        $r = $client->checkVat($params);
        if ($r->valid == true) {
            // VAT-ID is valid
        } else {
            // VAT-ID is NOT valid
        }
        // This foreach shows every single line of the returned information
        $tableauJson = json_encode($r);
        foreach ($r as $k => $prop) {
            echo $k . ': ' . $prop . '<br>';
        }
    } catch (SoapFault $e) {
        echo 'Erreur, voir message: ' . $e->faultstring;
    }
} else {
    // Connection to host not possible, europe.eu down?
 function checkVatID_EU($vat_id, $country_id)
 {
     // Leerzeichen und sonderzeichen entfernen
     $remove = array(' ', '-', '/', '\\', '.', ':', ',');
     $vat_id = trim(chop($vat_id));
     $vat_id = str_replace($remove, '', $vat_id);
     $vatNumber = substr($vat_id, 2);
     // alles ab 2 Stellen der VAT (ohne Land)
     $soap_conn = new SoapClient(VAT_LIVE_CHECK_URL);
     // check connection
     if ($soap_conn) {
         $params = array('countryCode' => $country_id, 'vatNumber' => $vatNumber);
         try {
             $r = $soap_conn->checkVat($params);
             if ($r->valid == true) {
                 return 1;
             } else {
                 return 0;
             }
             // This foreach shows every single line of the returned information
             foreach ($r as $k => $prop) {
                 echo $k . ': ' . $prop;
             }
         } catch (SoapFault $e) {
             switch ($e->faultstring) {
                 case 'INVALID_INPUT':
                     $t_error_code = '94';
                     break;
                 case 'SERVICE_UNAVAILABLE':
                     $t_error_code = '95';
                     break;
                 case 'MS_UNAVAILABLE':
                     $t_error_code = '96';
                     break;
                 case 'TIMEOUT':
                     $t_error_code = '97';
                     break;
                 case 'SERVER_BUSY':
                     $t_error_code = '98';
                     break;
             }
             return $t_error_code;
         }
         return false;
     }
 }
Beispiel #25
0
 public static function isVIESValidVATNumber($country, $vat)
 {
     // Get the VAT validation cache from the session
     if (false && !array_key_exists('vat', self::$cache)) {
         $session = JFactory::getSession();
         $encodedCacheData = $session->get('vat_validation_cache_data', null, 'com_akeebasubs');
         if (!empty($encodedCacheData)) {
             self::$cache = json_decode($encodedCacheData, true);
         } else {
             self::$cache = array();
         }
     }
     if (!is_array(self::$cache)) {
         self::$cache = array();
     }
     // Sanitize the VAT number
     list($vat, $prefix) = self::sanitizeVATNumber($country, $vat);
     // Is the validation already cached?
     $key = $prefix . $vat;
     $ret = null;
     if (array_key_exists('vat', self::$cache)) {
         if (array_key_exists($key, self::$cache['vat'])) {
             $ret = self::$cache['vat'][$key];
         }
     }
     if (!is_null($ret)) {
         return $ret;
     }
     if (empty($vat)) {
         $ret = false;
     } else {
         if (!class_exists('SoapClient')) {
             $ret = false;
         } else {
             // Using the SOAP API
             // Code credits: Angel Melguiz / KMELWEBDESIGN SLNE (www.kmelwebdesign.com)
             try {
                 $sOptions = array('user_agent' => 'PHP');
                 $sClient = new SoapClient('http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl', $sOptions);
                 $params = array('countryCode' => $prefix, 'vatNumber' => $vat);
                 $response = $sClient->checkVat($params);
                 if ($response->valid) {
                     $ret = true;
                 } else {
                     $ret = false;
                 }
             } catch (SoapFault $e) {
                 $ret = false;
             }
         }
     }
     // Cache the result
     if (!array_key_exists('vat', self::$cache)) {
         self::$cache['vat'] = array();
     }
     self::$cache['vat'][$key] = $ret;
     $encodedCacheData = json_encode(self::$cache);
     $session = JFactory::getSession();
     $session->set('vat_validation_cache_data', $encodedCacheData, 'com_akeebasubs');
     // Return the result
     return $ret;
 }
Beispiel #26
-1
function validateVAT($vat, $presetLoc = NULL)
{
    //Prepare VAT input for validation
    $aUnwanted = array("/", "-", ",", ".", " ", "/\\s+/");
    $vatId = str_replace($aUnwanted, '', trim($vat));
    $valid = false;
    if (strlen($vatId) > 4) {
        $cc = substr($vatId, 0, 2);
        $vn = substr($vatId, 2);
        $errorSoap = true;
        $client = new SoapClient("http://ec.europa.eu/taxation_customs/vies/checkVatService.wsdl");
        //Connecting to european VIES site to check if the provided VAT number is registered
        if ($client) {
            $params = array('countryCode' => $cc, 'vatNumber' => $vn);
            try {
                $r = $client->checkVat($params);
                if ($r->valid == true) {
                    $valid = true;
                    $errorSoap = false;
                } else {
                    $valid = false;
                    $errorSoap = false;
                }
            } catch (SoapFault $e) {
                $errorSoap = true;
            }
        }
        //If an error occured while trying to connect to VIES or an error occured after trying to connect, run local validation for VAT
        if ($valid == false && $errorSoap == true) {
            //Lengths for the VAT numbers Area Based
            $aLengthRest = array('be' => 10, 'de' => 9, 'nl' => 12, 'lu' => 8, 'fr' => 11, 'ie' => array(8, 9), 'gb' => array(9, 12, 5));
            //Letters with their respective number for the Ireland's VAT check
            $relocLibrary = array('0' => 'w', '1' => 'a', '2' => 'b', '3' => 'c', '4' => 'd', '5' => 'e', '6' => 'f', '7' => 'g', '8' => 'h', '9' => 'i', '10' => 'j', '11' => 'k', '12' => 'l', '13' => 'm', '14' => 'n', '15' => 'o', '16' => 'p', '17' => 'q', '18' => 'r', '19' => 's', '20' => 't', '21' => 'u', '22' => 'v');
            //Regular Expressions for the VAT numbers Area Based
            $aExpr = array('be' => '/(1|0){1}[0-9]{9}/i', 'de' => '/[0-9]{9}/i', 'nl' => '/[0-9]{9}b[0-9]{2}/i', 'lu' => '/[0-9]{8}/i', 'fr' => '/[a-z0-9]{2}[0-9]{9}/i', 'ie' => '/(([0-9]{7}[a-z]{1})|([0-9]{7}[a-z]{1}w)|([0-9]{7}[a-z]{2})|([0-9]{1}[a-z]{1}[0-9]{5}[a-z]{1}))/i', 'gb' => '/(([0-9]{9})|([0-9]{12})|(gd[0-4]{1}[0-9]{2})|(ha[5-9]{1}[0-9]{2}))/i');
            $prefix = strtolower(substr($vat, 0, 2));
            $rest = strtolower(substr($vat, 2, strlen($vat) - 2));
            $rest = str_replace($aUnwanted, '', $rest);
            //check if the length is possible for a VAT number of that area
            $lengthCorrect = false;
            $lengteRest = strlen($rest);
            if (is_array($aLengthRest[$prefix])) {
                if (in_array($lengteRest, $aLengthRest[$prefix])) {
                    $lengthCorrect = true;
                }
            } else {
                if ($aLengthRest[$prefix] == $lengteRest) {
                    $lengthCorrect = true;
                }
            }
            //Formula for each area to figure out if the provided VAT number is potentially valid
            if ($lengthCorrect && preg_match($aExpr[$prefix], $rest)) {
                switch ($prefix) {
                    case 'be':
                        //9 total digits, 7 first = SIREN, 2 last = controle
                        //97-CMOD(SIREN, 97) = controle
                        $rNumber = intval(substr($rest, 1, 7));
                        $cNumber = intval(substr($rest, 8, 2));
                        $controle = 97 - intval(bcmod(strval($rNumber), strval(97)));
                        if ($controle == $cNumber) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'de':
                        //documentation not added due too much. Check http://zylla.wipos.p.lodz.pl/ut/translation.html or pdf backup for more info
                        $calcDigits = substr($rest, 0, 8);
                        $cDigit = intval(substr($rest, 8, 1));
                        $m = 10;
                        $n = 11;
                        $sum = 0;
                        $product = $m;
                        for ($i = 0, $l = strlen($calcDigits); $i < $l; $i++) {
                            $calcDigit = intval(substr($calcDigits, $i, 1));
                            $sum = $product + $calcDigit;
                            $sum = intval(bcmod(strval($sum), strval(10)));
                            $product = intval(bcmod(strval(2 * $sum), strval(11)));
                        }
                        $controle = 11 - intval($product);
                        if ($controle == $cDigit) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'nl':
                        //documentation not added due too much. Check http://zylla.wipos.p.lodz.pl/ut/translation.html or pdf backup for more info
                        $calcDigits = substr($rest, 0, 8);
                        $cDigit = intval(substr($rest, 8, 1));
                        $sum = 0;
                        for ($i = 0, $l = 8, $m = 9; $i < $l; $i++, $m--) {
                            $calcDigit = intval(substr($calcDigits, $i, 1));
                            $sum = $sum + $calcDigit * $m;
                        }
                        $controle = intval(bcmod(strval($sum), strval(11)));
                        if ($controle == $cDigit) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'lu':
                        //8 total digits, 6 first = SIREN, 2 last = controle
                        //CMOD(SIREN, 89) == Controle
                        $calcDigits = substr($rest, 0, 6);
                        $cDigit = intval(substr($rest, 6, 2));
                        $controle = intval(bcmod($calcDigits, strval(89)));
                        if ($controle == $cDigit) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'fr':
                        //11 total digits, 2 first = controle numbers, 9 last = SIREN
                        //Formula: cmod((12+3*(cmod(SIREN, 97))),97) = controle numbers
                        $cDigit = intval(substr($rest, 0, 2));
                        $calcDigits = substr($rest, 2, 9);
                        $controle = intval(bcmod(strval(12 + 3 * intval(bcmod($calcDigits, strval(97)))), strval(97)));
                        if ($controle == $cDigit) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'ie':
                        //documentation not added due too much. Check http://zylla.wipos.p.lodz.pl/ut/translation.html or pdf backup for more info
                        if (preg_match('([0-9]{1}[a-z]{1}[0-9]{5}[a-z]{1})', $rest)) {
                            //Reform VAT from old pattern to the new format
                            $first = substr($rest, 0, 1);
                            $middle = substr($rest, 2, 5);
                            $last = substr($rest, 7, 1);
                            $rest = strval(0) + strval($middle) + strval($first) + strval($last);
                        }
                        $calcDigits = substr($rest, 0, 7);
                        $cDigit = substr($rest, 7, 1);
                        $sum = 0;
                        for ($i = 0, $max = 7, $m = 8; $i < $max; $i++, $m--) {
                            $sum = $sum + intval(substr($calcDigits, $i, 1)) * $m;
                        }
                        $controle = $relocLibrary[strval(bcmod(strval($sum), strval(23)))];
                        if ($controle == $cDigit) {
                            $valid = true;
                            break;
                        } else {
                            $valid = false;
                            break;
                        }
                    case 'gb':
                        //documentation not added due too much. Check wikipedia for more information about what's being done here.
                        if (strlen($rest) == 9 || strlen($rest) == 12) {
                            $part1 = intval(substr($rest, 0, 7));
                            $modulusCheck = intval(substr($rest, 7, 2));
                            if ($modulusCheck < 97) {
                                $totaal = 0;
                                for ($i = 0, $m = 8, $l = strlen($part1); $i < $l; $i++, $m--) {
                                    $totaal = intval($totaal) + intval(substr($part1, $i, 1)) * $m;
                                }
                                while ($totaal > 0) {
                                    $totaal = $totaal - 97;
                                }
                                if ($totaal < 0) {
                                    $check = $totaal + intval($modulusCheck);
                                    if ($check == 0) {
                                        $valid = true;
                                        break;
                                    } else {
                                        break;
                                    }
                                } else {
                                    break;
                                }
                            } else {
                                break;
                            }
                        } else {
                            $valid = true;
                            break;
                        }
                    default:
                        $valid = true;
                        break;
                }
            }
        }
    }
    return $valid;
}