sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function build() { $operation = $this->buildOperation('CreateCustomer'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $pType = $this->document->createElement('pType', $this->pType); $operation->appendChild($pType); $paymentData = $this->document->createElement('paymentData'); $paymentData->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:type', 'etp:PaymentData' . $this->pType); $paymentData = $operation->appendChild($paymentData); $this->appendArray($paymentData, $this->paymentData); $customerID = $this->document->createElement('customerID', $this->customerId); $operation->appendChild($customerID); $this->appendArray($operation, $this->additional); }
Build the Body ot the Request and add it to $this->document
entailment
protected function build() { $operation = $this->buildOperation('ManualCallback'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $xmlMPayTid = $this->document->createElement('mpayTID', $this->mpayTid); $operation->appendChild($xmlMPayTid); $paymentCallback = $this->document->createElement('paymentCallback'); $paymentCallback->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:type', "etp:Callback $this->type"); $paymentCallback = $operation->appendChild($paymentCallback); if ($this->amount) { $price = $this->document->createElement('amount', $this->amount); $paymentCallback->appendChild($price); } if ($this->cancel) { $cancel = $this->document->createElement('cancel', $this->cancel); $paymentCallback->appendChild($cancel); } if ($this->order) { // TODO:: Add the order to the request } }
Build the Body ot the Request and add it to $this->document
entailment
public function getProfile($i) { if (isset($this->profiles[$i])) { return $this->profiles[$i]; } else { return false; } }
Get the transaction values, returned from mPAY24 @param int $i The index of the transaction profile @return array|bool
entailment
protected function parseResponse($body) { $this->totalNumber = (int)$body->getElementsByTagName('all')->item(0)->nodeValue; $this->profileCount = (int)$body->getElementsByTagName('profile')->length; if ($this->profileCount > 0) { for ($i = 0; $i < $this->profileCount; $i++) { $profile = $body->getElementsByTagName('profile')->item($i); $this->profiles[$i]['customerID'] = $profile->getElementsByTagName('customerID')->item(0)->nodeValue; $this->profiles[$i]['updated'] = $profile->getElementsByTagName('updated')->item(0)->nodeValue; if ($profile->getElementsByTagName('payment')->length) { $this->profiles[$i]['payment'] = $profile->getElementsByTagName('payment')->item(0)->nodeValue; $this->profiles[$i]['paymentProfiles'] = $this->parsePaymentProfiles($profile->getElementsByTagName('payment')); } } } }
Parse the ListProfilesResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
protected function parseResponse($body) { if ($body->getElementsByTagName('token')->length > 0) { $this->token = $body->getElementsByTagName('token')->item(0)->nodeValue; } if ($body->getElementsByTagName('apiKey')->length > 0) { $this->apiKey = $body->getElementsByTagName('apiKey')->item(0)->nodeValue; } if ($body->getElementsByTagName('errNo')->length > 0) { $this->errNo = (int)$body->getElementsByTagName('errNo')->item(0)->nodeValue; } if ($body->getElementsByTagName('errText')->length > 0) { $this->errText = $body->getElementsByTagName('errText')->item(0)->nodeValue; } if ($body->getElementsByTagName('location')->length > 0) { $this->location = $body->getElementsByTagName('location')->item(0)->nodeValue; } }
Parse the SelectPaymentResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
public function setMerchantID($merchantID) { if (preg_match('/^(7|9)\d{4}$/', $merchantID) !== 1) { if ($this->isTestSystem()) { throw new InvalidArgumentException("The merchant ID '$merchantID' you have given is wrong, it must be 5-digit number and starts with 7 or 9!"); } else { throw new Exception(); } } $this->merchantID = $merchantID; }
@param string $merchantID @throws InvalidArgumentException @throws Exception
entailment
public function setProxyPort($proxyPort) { if ($proxyPort != null && preg_match('/^d{4}$/', $proxyPort) !== 1) { if ($this->isTestSystem()) { throw new InvalidArgumentException("The proxy port '$proxyPort' you have given must be numeric!"); } else { throw new Exception(); } } $this->proxyPort = $proxyPort; }
@param int $proxyPort @throws InvalidArgumentException @throws Exception
entailment
protected function build() { $operation = $this->buildOperation('CreatePaymentToken'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $pType = $this->document->createElement('pType', $this->pType); $operation->appendChild($pType); if ($this->templateSet) { $templateSet = $this->document->createElement('templateSet', $this->templateSet); $operation->appendChild($templateSet); } if ($this->style) { $style = $this->document->createElement('style', $this->style); $operation->appendChild($style); } if ($this->customerId) { $customerId = $this->document->createElement('customerID', $this->customerId); $operation->appendChild($customerId); } if ($this->profileId) { $profileId = $this->document->createElement('profileID', $this->profileId); $operation->appendChild($profileId); } if ($this->domain) { $domain = $this->document->createElement('domain', $this->domain); $operation->appendChild($domain); } if ($this->language) { $language = $this->document->createElement('language', $this->language); $operation->appendChild($language); } }
Build the Body ot the Request and add it to $this->document
entailment
protected function build() { $operation = $this->buildOperation('SelectPayment'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $xmlMdxi = $this->document->createElement('mdxi', $this->mdxi); $operation->appendChild($xmlMdxi); }
Build the Body ot the Request and add it to $this->document
entailment
protected function build() { $operation = $this->buildOperation('ListPaymentMethods'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); if ($this->pType) { $pType = $this->document->createElement('pType', $this->pType); $operation->appendChild($pType); } }
Build the Body ot the Request and add it to $this->document
entailment
public function getEncryptedParams( // parameter values $invoice_id, $amount, $currency = null, $language = null, $user_field = null, $mode = null, $salutation = null, $name = null, $street = null, $street2 = null, $zip = null, $city = null, $country = null, $email = null, $phone = null, $success = null, $error = null, $confirmation = null, // parameters names $invoice_idVar = "TID", $amountVar = "AMOUNT", $currencyVar = "CURRENCY", $languageVar = "LANGUAGE", $user_fieldVar = "USER_FIELD", $modeVar = "MODE", $salutationVar = "SALUTATION", $nameVar = "NAME", $streetVar = "STREET", $street2Var = "STREET2", $zipVar = "ZIP", $cityVar = "CITY", $countryVar = "COUNTRY", $emailVar = "EMAIL", $phoneVar = "PHONE", $successVar = "SUCCESS_URL", $errorVar = "ERROR_URL", $confirmationVar = "CONFIRMATION_URL" ) { if (!$this->mpay24Sdk) { die("You are not allowed to define a constructor in the child class of Mpay24flexLink!"); } $params[$invoice_idVar] = $invoice_id; $params[$amountVar] = $amount; if ($currency == null) { $currency = "EUR"; } $params[$currencyVar] = $currency; if ($language == null) { $language = "DE"; } $params[$languageVar] = $language; $params[$user_fieldVar] = $user_field; /* if ($description == null) { //TODO: undefined variable $description => check where this is coming from $description = "Rechnungsnummer:"; } $params[$descriptionVar] = $description; //TODO: undefined variable $descriptionVar => check where this is coming from */ if ($mode == null) { $mode = "ReadWrite"; } $params[$modeVar] = $mode; $params[$nameVar] = $name; $params[$streetVar] = $street; $params[$street2Var] = $street2; $params[$zipVar] = $zip; $params[$cityVar] = $city; if ($country == null) { $country = "AT"; } $params[$countryVar] = $country; $params[$emailVar] = $email; $params[$successVar] = $success; $params[$errorVar] = $error; $params[$confirmationVar] = $confirmation; $parameters = $this->mpay24Sdk->flexLink($params); return $parameters; }
Encrypt the parameters you want to post to mPAY24 - see details @param string $invoice_id The invoice ID of the transaction @param string $amount The amount which should be invoiced in 12.34 @param string $currency length = 3 (ISO currency code, e. g. "EUR") @param string $language length = 2 (ISO currency code, e. g. "DE") @param string $user_field A placeholder for free chosen user information @param string $mode BillingAddress Mode (ReadWrite or ReadOnly) @param string $salutation Salutation of the customer @param string $name Name of the customer @param string $street Billing address street @param string $street2 Billing address street2 @param string $zip Billing address zip @param string $city Billing address city @param string $country Billing address country, length = 2 (ISO country code, e. g. "AT") @param string $email Billing address e-mail @param string $phone Billing address phone @param string $success Success-URL @param string $error Error-URL @param string $confirmation Confirmation-URL @param string $invoice_idVar Default = TID @param string $amountVar Default = AMOUNT @param string $currencyVar Default = CURRENCY @param string $languageVar Default = LANGUAGE @param string $user_fieldVar Default = USER_FIELD @param string $modeVar Default = MODE @param string $salutationVar Default = SALUTATION @param string $nameVar Default = NAME @param string $streetVar Default = STREET @param string $street2Var Default = STREET2 @param string $zipVar Default = ZIP @param string $cityVar Default = CITY @param string $countryVar Default = COUNTRY @param string $emailVar Default = EMAIL @param string $phoneVar Default = PHONE @param string $successVar Default = SUCCCESS_URL @param string $errorVar Default = ERROR_URL @param string $confirmationVar Default = CONFIRMATION_URL @return string
entailment
public function getParam($name) { if (isset($this->transaction[$name])) { return $this->transaction[$name]; } else { return false; } }
Get the parameter's value, returned from mPAY24 @param string $name The name of a parameter (for example: STATUS, PRICE, CURRENCY, etc) @return string|bool
entailment
protected function parseResponse($body) { $this->paramCount = $body->getElementsByTagName('parameter')->length; if ($this->paramCount > 0) { for ($i = 0; $i < $this->paramCount; $i++) { $parameter = $body->getElementsByTagName('parameter')->item($i); $name = $parameter->getElementsByTagName('name')->item(0)->nodeValue; $value = $parameter->getElementsByTagName('value')->item(0)->nodeValue; $this->transaction[$name] = $value; } } }
Parse the TransactionStatusResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
protected function build() { $operation = $this->buildOperation('TransactionStatus'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); if ($this->mpayTid) { $xmlMPayTid = $this->document->createElement('mpayTID', $this->mpayTid); $operation->appendChild($xmlMPayTid); } if ($this->tid) { $xmlTid = $this->document->createElement('tid', $this->tid); $operation->appendChild($xmlTid); } }
Build the Body ot the Request and add it to $this->document
entailment
protected function buildEnvelope() { $soap_xml = new DOMDocument("1.0", "UTF-8"); $soap_xml->formatOutput = true; $envelope = $soap_xml->createElementNS(self::SOAP_ENVELOPE, 'SOAP-ENV:Envelope'); $envelope->setAttributeNS(self::XML_NS, 'xmlns:etp', self::ETP_NAME_SPACE); $envelope->setAttributeNS(self::XML_NS, 'xmlns:xsd', 'http://www.w3.org/2001/XMLSchema'); $envelope->setAttributeNS(self::XML_NS, 'xmlns:xsi', 'http://www.w3.org/2001/XMLSchema-instance'); $envelope = $soap_xml->appendChild($envelope); $body = $soap_xml->createElementNS(self::SOAP_ENVELOPE, 'SOAP-ENV:Body'); $envelope->appendChild($body); return $soap_xml; }
Create a DOMDocument and prepare it for SOAP request: set Envelope, NameSpaces, create empty Body @return DOMDocument
entailment
protected function buildOperation($operation) { $body = $this->document->getElementsByTagNameNS(self::SOAP_ENVELOPE, 'Body')->item(0); $operation = $this->document->createElementNS(self::ETP_NAME_SPACE, 'etp:' . $operation); return $body->appendChild($operation); }
@param string $operation @return DOMNode
entailment
protected function parseResponse($body) { if (!$body instanceof \DOMElement) { return; } if ($body->getElementsByTagName('mpayTID')->length > 0) { $this->mpayTid = (int)$body->getElementsByTagName('mpayTID')->item(0)->nodeValue; } if ($body->getElementsByTagName('errNo')->length > 0) { $this->errNo = (int)$body->getElementsByTagName('errNo')->item(0)->nodeValue; } if ($body->getElementsByTagName('errText')->length > 0) { $this->errText = $body->getElementsByTagName('errText')->item(0)->nodeValue; } if ($body->getElementsByTagName('location')->length > 0) { $this->location = $body->getElementsByTagName('location')->item(0)->nodeValue; } }
Parse the SelectPaymentResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
protected function build() { $operation = $this->buildOperation('ManualCredit'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $xmlMPayTid = $this->document->createElement('mpayTID', $this->mpayTid); $operation->appendChild($xmlMPayTid); if ($this->stateId) { $stateId = $this->document->createElement('stateID', $this->stateId); $operation->appendChild($stateId); } if ($this->amount) { $amount = $this->document->createElement('amount', $this->amount); $operation->appendChild($amount); } }
Build the Body ot the Request and add it to $this->document
entailment
protected function build() { $operation = $this->buildOperation('AcceptPayment'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $tid = $this->document->createElement('tid', $this->tid); $operation->appendChild($tid); $pType = $this->document->createElement('pType', $this->pType); $operation->appendChild($pType); $payment = $this->document->createElement('payment'); $payment->setAttributeNS('http://www.w3.org/2001/XMLSchema-instance', 'xsi:type', 'etp:Payment' . $this->pType); $payment = $operation->appendChild($payment); $this->appendArray($payment, $this->payment); $this->appendArray($operation, $this->additional); }
Build the Body ot the Request and add it to $this->document
entailment
public static function cleanUpArray(array $parameters) { $cleanup = []; foreach ($parameters as $name => $value) { if (array_key_exists($name, self::CONFIRMATION_PROPERTIES)) { $cleanup[$name] = $value; } } return $cleanup; }
Set the parameters of the Confirmation object @param array $parameters cleanUp the given Array to only the once valid property names, see CONFIRMATION_PROPERTIES @return array
entailment
protected function validateValue($property, $value) { $this->isPropertyValid($property); $regEx = '/^' . self::CONFIRMATION_PROPERTIES[$property] . '$/'; if (preg_match($regEx, $value) != 1) { throw new InvalidArgumentException("The value " . $value . " for the property " . $property . ", is invalid"); } return $value; }
@param string $property @param mixed $value @return mixed @throws InvalidArgumentException
entailment
protected function parseResponse($body) { if ($body->getElementsByTagName('transaction')->length > 0) { $transaction = $body->getElementsByTagName('transaction')->item(0); $this->mpayTid = $transaction->getElementsByTagName('mpayTID')->item(0)->nodeValue; $this->tStatus = $transaction->getElementsByTagName('tStatus')->item(0)->nodeValue; $this->tid = $transaction->getElementsByTagName('tid')->item(0)->nodeValue; if ($transaction->getElementsByTagName('stateID')->length > 0) { $this->stateId = $transaction->getElementsByTagName('stateID')->item(0)->nodeValue; } } }
Parse the Response message and save the data to the corresponding attributes @param \DOMElement $body
entailment
protected function build() { $operation = $this->buildOperation('ListProfiles'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); if ($this->customerId) { $xmlMPayTid = $this->document->createElement('customerID', $this->customerId); $operation->appendChild($xmlMPayTid); } if ($this->expiredBy) { $xmlMPayTid = $this->document->createElement('expiredBy', $this->expiredBy); $operation->appendChild($xmlMPayTid); } if ($this->begin) { $xmlMPayTid = $this->document->createElement('begin', $this->begin); $operation->appendChild($xmlMPayTid); } if ($this->size) { $xmlMPayTid = $this->document->createElement('size', $this->size); $operation->appendChild($xmlMPayTid); } }
Build the Body ot the Request and add it to $this->document
entailment
public function configureFlexLINK($spid, $password, $test) { $this->config->setSpid($spid); $this->config->setFlexLinkPassword($password); $this->config->useFlexLinkTestSystem($test); }
Set the basic (mandatory) settings for the requests @param string $spid The SPID of your account, supported by mPAY24 @param string $password The flexLINK password, supported by mPAY24 @param bool $test TRUE - when you want to use the TEST system FALSE - when you want to use the LIVE system @deprecated Use Configuration Object instated
entailment
public function permissionError() { $errors = error_get_last(); $message = $errors['message']; $path = substr( $message, strpos($message, 'fopen(') + 6, strpos($message, ')') - (strpos($message, 'fopen(') + 6) ); $this->dieWithMsg("Can't open file '$path'! Please set the needed read/write rights!"); }
Die with an error message, which show the path in case of read/write permission errors
entailment
public function listPaymentMethods() { $request = new ListPaymentMethods($this->config->getMerchantId()); $this->request = $request->getXml(); $this->send(); $result = new ListPaymentMethodsResponse($this->response); return $result; }
Get all the payment methods, that are available for the merchant by mPAY24 @return ListPaymentMethodsResponse
entailment
public function selectPayment($mdxi) { $request = new SelectPayment($this->config->getMerchantId()); $request->setMdxi($mdxi); $this->request = $request->getXml(); $this->send(); $result = new SelectPaymentResponse($this->response); return $result; }
Start a secure payment through the mPAY24 payment window - the sensible data (credit card numbers, bank account numbers etc) is (will be) not saved in the shop @param string $mdxi The mdxi xml, which contains the shopping cart @return SelectPaymentResponse
entailment
public function createTokenPayment($pType, array $additional = []) { $request = new CreatePaymentToken($this->config->getMerchantId()); $request->setPType($pType); $request->setAdditional($additional); $this->request = $request->getXml(); $this->send(); $result = new CreatePaymentTokenResponse($this->response); return $result; }
Start a secure payment using the mPAY24 Tokenizer. @param string $pType The payment type used for the tokenization (currently supported 'CC') @param array $additional @return CreatePaymentTokenResponse
entailment
public function acceptPayment($type, $tid, $payment = [], $additional = []) { $request = new AcceptPayment($this->config->getMerchantId()); $request->setPType($type); $request->setTid($tid); $request->setPayment($payment); $request->setAdditional($additional); $this->request = $request->getXml(); $this->send(); $result = new AcceptPaymentResponse($this->response); return $result; }
Initialize a manual callback to mPAY24 in order to check the information provided by PayPal @param $type @param string $tid The TID used for the transaction @param array $payment @param array $additional @return AcceptPaymentResponse
entailment
public function manualCallback($mpayTid, $paymentType, $amount = null, $cancel = false, $order = null) { $request = new ManualCallback($this->config->getMerchantId()); $request->setMpayTid($mpayTid); $request->setType($paymentType); $request->setAmount($amount); $request->setCancel($cancel); $request->setOrder($order); $this->request = $request->getXml(); $this->send(); $result = new ManualCallbackResponse($this->response); return $result; }
Initialize a manual callback to mPAY24 in order to check the information provided by PayPal @param int $mpayTid @param string $paymentType The payment type which will be used for the express checkout (PAYPAL or MASTERPASS) @param int $amount @param bool $cancel @param null $order @return ManualCallbackResponse @internal param string $requestString The callback request to mPAY24
entailment
public function manualClear($mpayTid, $amount) { $request = new ManualClear($this->config->getMerchantId()); $request->setMpayTid($mpayTid); $request->setAmount($amount); $this->request = $request->getXml(); $this->send(); $result = new ManualClearResponse($this->response); return $result; }
Clear a transaction with an amount @param int $mpayTid The mPAY24 transaction ID @param int $amount The amount to be cleared multiplay by 100 @return ManualClearResponse
entailment
public function manualCredit($mpayTid, $amount) { $request = new ManualCredit($this->config->getMerchantId()); $request->setMpayTid($mpayTid); $request->setAmount($amount); $this->request = $request->getXml(); $this->send(); $result = new ManualCreditResponse($this->response); return $result; }
Credit a transaction with an amount @param int $mpayTid The mPAY24 transaction ID @param int $amount The amount to be credited multiplay by 100 @return ManualCreditResponse
entailment
public function manualReverse($mpayTid) { $request = new ManualReverse($this->config->getMerchantId()); $request->setMpayTid($mpayTid); $this->request = $request->getXml(); $this->send(); $result = new ManualReverseResponse($this->response); return $result; }
Cancel a transaction @param int $mpayTid The mPAY24 transaction ID for the transaction you want to cancel @return ManualReverseResponse
entailment
public function transactionStatus($mpay24tid = null, $tid = null) { $request = new TransactionStatus($this->config->getMerchantId()); $request->setMpayTid($mpay24tid); $request->setTid($tid); $this->request = $request->getXml(); $this->send(); $result = new TransactionStatusResponse($this->response); return $result; }
Get all the information for a transaction, supported by mPAY24 @param int $mpay24tid The mPAY24 transaction ID @param string $tid The transaction ID from your shop @return TransactionStatusResponse
entailment
public function transactionHistory($mpayTid = null) { $request = new TransactionHistory($this->config->getMerchantId()); $request->setMpayTid($mpayTid); $this->request = $request->getXml(); $this->send(); $result = new TransactionHistoryResponse($this->response); return $result; }
Get all the information for a transaction, supported by mPAY24 @param int $mpayTid The mPAY24 transaction ID @return TransactionHistoryResponse
entailment
public function listProfiles($customerId = null, $expiredBy = null, $begin = null, $size = null) { $request = new ListProfiles($this->config->getMerchantId()); $request->setCustomerId($customerId); $request->setExpiredBy($expiredBy); $request->setBegin($begin); $request->setSize($size); $this->request = $request->getXml(); $this->send(); $result = new ListProfilesResponse($this->response); return $result; }
Get all the information for a transaction, supported by mPAY24 @param string $customerId @param string $expiredBy @param int $begin @param int $size @return ListProfilesResponse @internal param int $mpay24tid The mPAY24 transaction ID
entailment
public function createCustomer($type, $customerId ,$payment = [], $additional = []) { $request = new CreateCustomer($this->config->getMerchantId()); $request->setPType($type); $request->setPaymentData($payment); $request->setCustomerId($customerId); $request->setAdditional($additional); $this->request = $request->getXml(); $this->send(); $result = new CreateCustomerResponse($this->response); return $result; }
Create a new customer for recurring payments @param $type @param array $payment @param string $customerId @param array $additional @return CreateCustomerResponse
entailment
public function deleteProfile($customerId, $profileId = null) { $request = new DeleteProfile($this->config->getMerchantId()); $request->setCustomerId($customerId); $request->setProfileId($profileId); $this->request = $request->getXml(); $this->send(); $result = new DeleteProfileResponse($this->response); return $result; }
Deletes a profile. @param string $customerId @param string|null $profileId @return DeleteProfileResponse
entailment
public function flexLink($params) { $paramsString = ""; foreach ($params as $key => $value) { $paramsString .= "$key=$value&"; } $encryptedParams = $this->ssl_encrypt($this->config->getFlexLinkPassword(), $paramsString); return $encryptedParams; }
Encoded the parameters (AES256-CBC) for the pay link and return them @param array $params The parameters, which are going to be posted to mPAY24 @return string
entailment
protected function send() { $userAgent = 'mpay24-php/' . self::VERSION; $ch = curl_init($this->getEtpURL()); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_USERPWD, 'u' . $this->config->getMerchantId() . ':' . $this->config->getSoapPassword()); curl_setopt($ch, CURLOPT_USERAGENT, $userAgent); curl_setopt($ch, CURLOPT_POSTFIELDS, $this->request); curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); if ($this->config->isEnableCurlLog()) { $fh = fopen($this->getMpay24CurlLogPath(), 'a+') or $this->permissionError(); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_STDERR, $fh); } try { curl_setopt($ch, CURLOPT_CAINFO, $this->config->getCaCertPath() . $this->config->getCaCertFileName()); if ($this->config->getProxyHost()) { curl_setopt($ch, CURLOPT_PROXY, $this->config->getProxyHost() . ':' . $this->config->getProxyPort()); if ($this->config->getProxyUser()) { curl_setopt($ch, CURLOPT_PROXYUSERPWD, $this->config->getProxyUser() . ':' . $this->config->getProxyPass()); } if ($this->config->isVerifyPeer() !== true) { curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, $this->config->isVerifyPeer()); } } $this->response = curl_exec($ch); curl_close($ch); } catch (\Exception $e) { if ($this->config->isTestSystem()) { $dieMSG = "Your request couldn't be sent because of the following error:" . "\n" . curl_error( $ch ) . "\n" . $e->getMessage() . ' in ' . $e->getFile() . ', line: ' . $e->getLine() . '.'; } else { $dieMSG = self::LIVE_ERROR_MSG; } echo $dieMSG; } if (isset($fh) && $this->config->isEnableCurlLog()) { fclose($fh); } }
Create a curl request and send the created SOAP XML
entailment
protected function ssl_encrypt($pass, $data) { // Used encryption method $method = "aes-256-cbc"; $key_len = 32; $iv_len = openssl_cipher_iv_length($method); // Set a random salt $salt = openssl_random_pseudo_bytes(8); $total_len = $key_len + $iv_len; $salted = ''; $dx = ''; // Generate key and iv, see: EVP_BytesToKey while (strlen($salted) < $total_len) { $dx = md5($dx . $pass . $salt, true); $salted .= $dx; } $key = substr($salted, 0, $key_len); $iv = substr($salted, $key_len, $iv_len); $encrypted_data = openssl_encrypt($data, $method, $key, true, $iv); return chunk_split(array_shift(unpack('H*', 'Salted__' . $salt . $encrypted_data)), 32, "\r\n"); }
Encode data (aes-256-cbc) using a password @param string $pass The password, used for the encoding @param string $data The data, that should be encoded @return string
entailment
protected function parseResponse($body) { $this->location = $body->getElementsByTagName('location')->item(0)->nodeValue; if ($body->getElementsByTagName('errNo')->length > 0) { $this->errNo = (int)$body->getElementsByTagName('errNo')->item(0)->nodeValue; } if ($body->getElementsByTagName('errText')->length > 0) { $this->errText = $body->getElementsByTagName('errText')->item(0)->nodeValue; } }
Parse the SelectPaymentResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
public function getTransactionHistory($i) { if (isset($this->history[$i])) { return $this->history[$i]; } else { return false; } }
Get the transaction values, returned from mPAY24 @param int $i The index of the transaction history @return array|bool
entailment
protected function parseResponse($body) { $this->historyCount = (int)$body->getElementsByTagName('historyEntry')->length; if ($this->historyCount > 0) { for ($i = 0; $i < $this->historyCount; $i++) { $this->history[$i] = []; $historyEntry = $body->getElementsByTagName('historyEntry')->item($i); for ($j = 0; $j < $historyEntry->childNodes->length; $j++) { $name = $historyEntry->childNodes->item($j)->tagName; $value = $historyEntry->childNodes->item($j)->nodeValue; $this->history[$i][$name] = $value; } } } }
Parse the TransactionHistoryResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
public function paymentMethods() { $this->integrityCheck(); $paymentMethods = $this->mpay24Sdk->listPaymentMethods(); $this->recordedLastMessageExchange("PaymentMethods"); return $paymentMethods; }
Get a list which includes all the payment methods (activated by mPAY24) for your mechant ID @return Responses\ListPaymentMethodsResponse
entailment
public function paymentPage($mdxi) { $this->integrityCheck(); libxml_use_internal_errors(true); if (!$mdxi || !$mdxi instanceof Mpay24Order) { $this->mpay24Sdk->dieWithMsg("To be able to use the Mpay24Api you must create an Mpay24Order object (Mpay24Order.php) and fulfill it with a MDXI!"); } $mdxiXML = $mdxi->toXML(); $payResult = $this->mpay24Sdk->selectPayment($mdxiXML); $this->recordedLastMessageExchange('PaymentPage'); return $payResult; }
Return a redirect URL to start a payment @param $mdxi @return Responses\SelectPaymentResponse
entailment
public function payment($paymentType, $tid, $payment, $additional) { $this->integrityCheck(); $payBackend2BackendResult = $this->mpay24Sdk->acceptPayment($paymentType, $tid, $payment, $additional); $this->recordedLastMessageExchange('Payment'); return $payBackend2BackendResult; }
Start a backend to backend payment @param string $paymentType The payment type which will be used for the payment (EPS, SOFORT, PAYPAL, MASTERPASS or TOKEN) @param $tid @param $payment @param $additional @return Responses\AcceptPaymentResponse
entailment
public function paymentHistory($mpayTid) { $this->integrityCheck(); $response = $this->mpay24Sdk->transactionHistory($mpayTid); $this->recordedLastMessageExchange('TransactionHistory'); return $response; }
Get all transaction's states for specified mPAYTID @param string $mpayTid @return Responses\TransactionHistoryResponse
entailment
public function listCustomers($customerId = null, $expiredBy = null, $begin = null, $size = null) { $this->integrityCheck(); $response = $this->mpay24Sdk->listProfiles($customerId, $expiredBy, $begin, $size); $this->recordedLastMessageExchange('ListProfiles'); return $response; }
Get all profile according to the given parameters @param string $customerId @param string $expiredBy @param int $begin @param int $size @return Responses\ListProfilesResponse @internal param string $mpayTid
entailment
public function token($paymentType, array $additional = []) { $this->integrityCheck(); if ($paymentType !== 'CC') { die("The payment type '$paymentType' is not allowed! Currently allowed is only: 'CC'"); } $tokenResult = $this->mpay24Sdk->createTokenPayment($paymentType, $additional); $this->recordedLastMessageExchange('CreatePaymentToken'); return $tokenResult; }
Return a redirect URL to include in your web page @param string $paymentType The payment type which will be used for the express checkout (CC) @param array $additional Additional parameters @return Responses\CreatePaymentTokenResponse
entailment
public function capture($mpayTid, $amount) { $this->integrityCheck(); $this->validateAmount($amount); $clearAmountResult = $this->mpay24Sdk->manualClear($mpayTid, $amount); $this->recordedLastMessageExchange('CaptureAmount'); return $clearAmountResult; }
Capture an amount of an authorized transaction @param string $mpayTid The transaction ID, for the transaction you want to clear @param int $amount The amount you want to clear multiply by 100 @return Responses\ManualClearResponse
entailment
public function refund($mpayTid, $amount) { $this->integrityCheck(); $this->validateAmount($amount); $creditAmountResult = $this->mpay24Sdk->manualCredit($mpayTid, $amount); $this->recordedLastMessageExchange('RefundAmount'); return $creditAmountResult; }
Refund an amount of a captured transaction @param string $mpayTid The transaction ID, for the transaction you want to credit @param int $amount The amount you want to credit multiply by 100 @return Responses\ManualCreditResponse
entailment
public function cancel($mpayTid) { $this->integrityCheck(); $cancelTransactionResult = $this->mpay24Sdk->manualReverse($mpayTid); $this->recordedLastMessageExchange('CancelTransaction'); return $cancelTransactionResult; }
Cancel a authorized transaction @param string $mpayTid The transaction ID, for the transaction you want to cancel @return Responses\AbstractTransactionResponse
entailment
public function createCustomer($paymentType, $customerId, $payment, $additional = []) { $this->integrityCheck(); $createCustomerRes = $this->mpay24Sdk->createCustomer($paymentType, $customerId, $payment, $additional); $this->recordedLastMessageExchange('CreateCustomer'); return $createCustomerRes; }
Create a customer for recurring payments @param string $paymentType The payment type which will be used for the payment (CC or TOKEN) @param $customerId @param $payment @param $additional @return Responses\CreateCustomerResponse
entailment
public function deleteProfile($customerId, $profileId = null) { $this->integrityCheck(); $response = $this->mpay24Sdk->deleteProfile($customerId, $profileId); $this->recordedLastMessageExchange('DeleteProfile'); return $response; }
Delete a profile. @param string $customerId @param string|null $profileId @return Responses\DeleteProfileResponse
entailment
protected function writeLog($operation, $info_to_log) { $serverName = php_uname('n'); if (isset($_SERVER['SERVER_NAME'])) { $serverName = $_SERVER['SERVER_NAME']; } $fh = fopen($this->mpay24Sdk->getMpay24LogPath(), 'a+') or die("can't open file"); $MessageDate = date("Y-m-d H:i:s"); $Message = $MessageDate . " " . $serverName . " Mpay24 : "; $result = $Message . "$operation : $info_to_log\n"; fwrite($fh, $result); fclose($fh); }
Write a log into a file, file system, data base @param string $operation The operation, which is to log: GetPaymentMethods, Pay, PayWithProfile, Confirmation, UpdateTransactionStatus, ClearAmount, CreditAmount, CancelTransaction, etc. @param string $info_to_log The information, which is to log: request, response, etc.
entailment
protected function transactionStatus($mpayTid = null, $tid = null) { $this->integrityCheck(); $result = $this->mpay24Sdk->transactionStatus($mpayTid, $tid); $this->recordedLastMessageExchange('TransactionStatus'); return $result; }
@param null $mpayTid @param null $tid @return Responses\TransactionStatusResponse
entailment
public function subscribeCustomerToPlan($planId, $paymentToken, $customerEmail, $couponId = null) { $customer = Customer::create([ 'source' => $paymentToken, 'email' => $customerEmail ]); $data = [ 'customer' => $customer->id, 'plan' => $planId, ]; if ($couponId) { $data['coupon'] = $couponId; } $subscription = Subscription::create($data); return $customer; }
Associate a new Customer object to an existing Plan. @throws HttpException: - If the planId is invalid (the plan does not exists...) - If the payment token is invalid (payment failed) @see https://stripe.com/docs/subscriptions/tutorial#create-subscription @param string $planId: The plan ID as defined in your Stripe dashboard @param string $paymentToken: The payment token returned by the payment form (Stripe.js) @param string $customerEmail: The customer email @param string|null $couponId: An optional coupon ID @return Customer
entailment
public function subscribeExistingCustomerToPlan($customerId, $planId, $parameters = []) { $data = [ 'customer' => $customerId, 'plan' => $planId ]; if ($parameters && is_array($parameters)) { $data = array_merge($parameters, $data); } return Subscription::create($data); }
Associate an existing Customer object to an existing Plan. @throws HttpException: - If the customerId is invalid (the customer does not exists...) - If the planId is invalid (the plan does not exists...) @see https://stripe.com/docs/api#create_subscription @param string $customerId: The customer ID as defined in your Stripe dashboard @param string $planId: The plan ID as defined in your Stripe dashboard @param array $parameters: Optional additional parameters, the complete list is available here: https://stripe.com/docs/api#create_subscription @return Subscription
entailment
public function createCharge($chargeAmount, $chargeCurrency, $paymentToken, $stripeAccountId = null, $applicationFee = 0, $chargeDescription = '', $chargeMetadata = []) { $chargeOptions = [ 'amount' => $chargeAmount, 'currency' => $chargeCurrency, 'source' => $paymentToken, 'description' => $chargeDescription, 'metadata' => $chargeMetadata ]; if ($applicationFee && intval($applicationFee) > 0) { $chargeOptions['application_fee'] = intval($applicationFee); } $connectedAccountOptions = []; if ($stripeAccountId) { $connectedAccountOptions['stripe_account'] = $stripeAccountId; } return Charge::create($chargeOptions, $connectedAccountOptions); }
Create a new Charge from a payment token, to an optional connected stripe account, with an optional application fee. @throws HttpException: - If the payment token is invalid (payment failed) @see https://stripe.com/docs/charges @param int $chargeAmount: The charge amount in cents @param string $chargeCurrency: The charge currency to use @param string $paymentToken: The payment token returned by the payment form (Stripe.js) @param string $stripeAccountId: The connected stripe account ID @param int $applicationFee: The fee taken by the platform, in cents @param string $description: An optional charge description @param array $metadata: An optional array of metadatas @return Charge
entailment
public function createDestinationCharge($chargeAmount, $chargeCurrency, $paymentToken, $stripeAccountId, $applicationFee, $chargeDescription = '', $chargeMetadata = []) { $chargeOptions = [ 'amount' => $chargeAmount, 'currency' => $chargeCurrency, 'source' => $paymentToken, 'description' => $chargeDescription, 'metadata' => $chargeMetadata, 'destination' => [ 'amount' => $chargeAmount - $applicationFee, 'account' => $stripeAccountId ] ]; return Charge::create($chargeOptions); }
Create a new Destination Charge from a payment token, to a connected stripe account, with an application fee. @throws HttpException: - If the payment token is invalid (payment failed) @see https://stripe.com/docs/connect/destination-charges @param int $chargeAmount: The charge amount in cents @param string $chargeCurrency: The charge currency to use @param string $paymentToken: The payment token returned by the payment form (Stripe.js) @param string $stripeAccountId: The connected stripe account ID @param int $applicationFee: The fee taken by the platform, in cents @param string $chargeDescription: An optional charge description @param array $chargeMetadata: An optional array of metadatas @return Charge
entailment
public function chargeCustomer($chargeAmount, $chargeCurrency, $customerId, $stripeAccountId = null, $applicationFee = 0, $chargeDescription = '', $chargeMetadata = []) { $chargeOptions = [ 'amount' => $chargeAmount, 'currency' => $chargeCurrency, 'customer' => $customerId, 'description' => $chargeDescription, 'metadata' => $chargeMetadata ]; if ($applicationFee && intval($applicationFee) > 0) { $chargeOptions['application_fee'] = intval($applicationFee); } $connectedAccountOptions = []; if ($stripeAccountId) { $connectedAccountOptions['stripe_account'] = $stripeAccountId; } return Charge::create($chargeOptions, $connectedAccountOptions); }
Create a new Charge on an existing Customer object, to an optional connected stripe account, with an optional application fee @throws HttpException: - If the payment token is invalid (payment failed) @see https://stripe.com/docs/charges#saving-credit-card-details-for-later @param int $chargeAmount: The charge amount in cents @param string $chargeCurrency: The charge currency to use @param string $customerId: The Stripe Customer object ID @param string $stripeAccountId: The connected stripe account ID @param int $applicationFee: The fee taken by the platform, in cents @param string $description: An optional charge description @param array $metadata: An optional array of metadatas @return Charge
entailment
public function refundCharge($chargeId, $refundAmount = null, $metadata = [], $reason = 'requested_by_customer', $refundApplicationFee = true, $reverseTransfer = false, $stripeAccountId = null) { $refundOptions = [ 'charge' => $chargeId, 'metadata' => $metadata, 'reason' => $reason, 'refund_application_fee' => (bool) $refundApplicationFee, 'reverse_transfer' => (bool) $reverseTransfer ]; if ($refundAmount) { $refundOptions['amount'] = intval($refundAmount); } $connectedAccountOptions = []; if ($stripeAccountId) { $connectedAccountOptions['stripe_account'] = $stripeAccountId; } return Refund::create($refundOptions, $connectedAccountOptions); }
Create a new Refund on an existing Charge (by its ID). @throws HttpException: - If the charge id is invalid (the charge does not exists...) - If the charge has already been refunded @see https://stripe.com/docs/connect/direct-charges#issuing-refunds @param string $chargeId: The charge ID @param int $refundAmount: The charge amount in cents @param array $metadata: optional additional informations about the refund @param string $reason: The reason of the refund, either "requested_by_customer", "duplicate" or "fraudulent" @param bool $refundApplicationFee: Wether the application_fee should be refunded aswell. @param bool $reverseTransfer: Wether the transfer should be reversed @param string $stripeAccountId: The optional connected stripe account ID on which charge has been made. @return Refund
entailment
protected function build() { $operation = $this->buildOperation('DeleteProfile'); $merchantID = $this->document->createElement( 'merchantID', $this->merchantId ); $operation->appendChild($merchantID); $customerId = $this->document->createElement( 'customerID', $this->customerId ); $operation->appendChild($customerId); if ($this->profileId) { $profileId = $this->document->createElement( 'profileID', $this->profileId ); $operation->appendChild($profileId); } }
Build the request document body.
entailment
protected function build() { $operation = $this->buildOperation('ManualReverse'); $merchantID = $this->document->createElement('merchantID', $this->merchantId); $operation->appendChild($merchantID); $xmlMPayTid = $this->document->createElement('mpayTID', $this->mpayTid); $operation->appendChild($xmlMPayTid); }
Build the Body ot the Request and add it to $this->document
entailment
protected function parseResponse($body) { $this->all = (int)$body->getElementsByTagName('paymentMethod')->length; if ($this->all > 0) { for ($i = 0; $i < $this->all; $i++) { $paymentMethod = $body->getElementsByTagName('paymentMethod')->item($i); $this->pMethIds[$i] = $paymentMethod->getAttribute("id"); $this->pTypes[$i] = $paymentMethod->getElementsByTagName('pType')->item(0)->nodeValue; $this->brands[$i] = $paymentMethod->getElementsByTagName('brand')->item(0)->nodeValue; $this->descriptions[$i] = $paymentMethod->getElementsByTagName('description')->item(0)->nodeValue; } } }
Parse the ListPaymentMethodsResponse message and save the data to the corresponding attributes @param \DOMElement $body
entailment
protected function xmlEncode($txt) { $txt = str_replace('<', '&lt;', $txt); $txt = str_replace('>', '&gt;', $txt); $txt = str_replace('&amp;apos;', "'", $txt); $txt = str_replace('&amp;quot;', '"', $txt); return $txt; }
Encode the XML-characters in a string @param string $txt A string to be encoded @return string
entailment
protected function fromCamelCase($str) { $func = function ($str) { return ' '.$str[0]; }; $value = preg_replace_callback('/([A-Z])/', $func, $str); $value = ucfirst($value); return trim($value); }
@param string $str @return string
entailment
public function create($type) { $twigEngine = $this->getTwigEngine(); if (!$twigEngine) { throw new \Exception('Twig Engine not found. Please see https://github.com/mmucklo/DtcGridBundle/README.md for instructions.'); } switch ($type) { case 'datatables': $renderer = new DataTablesRenderer($this->twigEngine, $this->router); break; case 'jq_grid': $renderer = new JQGridRenderer($this->twigEngine, $this->router); break; case 'table': $renderer = new TableGridRenderer($this->twigEngine, $this->router); break; default: throw new \Exception("No renderer for type '$type''"); } if (method_exists($renderer, 'setThemeCss')) { $renderer->setThemeCss($this->themeCss); } if (method_exists($renderer, 'setThemeJs')) { $renderer->setThemeJs($this->themeJs); } if (method_exists($renderer, 'setJQuery')) { $renderer->setJQuery($this->jQuery); } if (method_exists($renderer, 'setPurl')) { $renderer->setPurl($this->purl); } if (method_exists($renderer, 'setPageDivStyle')) { $renderer->setPageDivStyle($this->pageDivStyle); } if (method_exists($renderer, 'setJqGridCss')) { $renderer->setJqGridCss($this->jqGridCss); } if (method_exists($renderer, 'setJqGridJs')) { $renderer->setJqGridJs($this->jqGridJs); } if (method_exists($renderer, 'setDataTablesCss')) { $renderer->setDataTablesCss($this->dataTablesCss); } if (method_exists($renderer, 'setDataTablesJs')) { $renderer->setDataTablesJs($this->dataTablesJs); } if (method_exists($renderer, 'setDatatablesClass') && $this->dataTablesClass) { $renderer->setDatatablesClass($this->dataTablesClass); } return $renderer; }
Creates a new renderer of type $type, throws an exception if it's not known how to create a renderer of type $type. @param $type @return AbstractRenderer
entailment
protected function populateAnnotationCacheFilename() { if (isset($this->annotationCacheFilename)) { return $this->annotationCacheFilename; } $directory = $this->cacheDir.'/DtcGridBundle'; $metadata = $this->getClassMetadata(); $reflectionClass = $metadata->getReflectionClass(); $name = $reflectionClass->getName(); $namespace = $reflectionClass->getNamespaceName(); $namespace = str_replace('\\', DIRECTORY_SEPARATOR, $namespace); $namespaceDir = $directory.DIRECTORY_SEPARATOR.$namespace; $umask = decoct(umask()); $umask = str_pad($umask, 4, '0', STR_PAD_LEFT); // Is there a better way to do this? $permissions = '0777'; $permissions[1] = intval($permissions[1]) - intval($umask[1]); $permissions[2] = intval($permissions[2]) - intval($umask[2]); $permissions[3] = intval($permissions[3]) - intval($umask[3]); if (!is_dir($namespaceDir) && !mkdir($namespaceDir, octdec($permissions), true)) { throw new \Exception("Can't create: ".$namespaceDir); } $name = str_replace('\\', DIRECTORY_SEPARATOR, $name); $this->annotationCacheFilename = $directory.DIRECTORY_SEPARATOR.$name.'.php'; return $this->annotationCacheFilename; }
Populates the filename for the annotationCache. @return string @throws \Exception
entailment
protected function getAnnotationColumns() { if (!isset($this->reader)) { return null; } if (!isset($this->cacheDir)) { return null; } if (!isset($this->annotationCacheFilename)) { $this->populateAnnotationCacheFilename(); } if (!$this->debug && null !== $this->annotationColumns) { return $this->annotationColumns ?: null; } // Check mtime of class if (is_file($this->annotationCacheFilename)) { $result = $this->tryIncludeAnnotationCache(); if ($result) { return $this->annotationColumns; } } // cache annotation $this->populateAndCacheAnnotationColumns(); return $this->annotationColumns ?: null; }
Attempt to discover columns using the GridColumn annotation. @throws \Exception
entailment
protected function tryIncludeAnnotationCache() { if (!$this->debug) { $this->includeAnnotationCache(); return true; } $metadata = $this->getClassMetadata(); $reflectionClass = $metadata->getReflectionClass(); $filename = $reflectionClass->getFileName(); if ($filename && is_file($filename)) { $mtime = filemtime($filename); if (($currentfileMtime = filemtime(__FILE__)) > $mtime) { $mtime = $currentfileMtime; } $mtimeAnnotation = filemtime($this->annotationCacheFilename); if ($mtime && $mtimeAnnotation && $mtime <= $mtimeAnnotation) { $this->includeAnnotationCache(); return true; } } return false; }
Cached annotation info from the file, if the mtime of the file has not changed (or if not in debug). @return bool
entailment
protected function includeAnnotationCache() { $annotationInfo = include $this->annotationCacheFilename; $this->annotationColumns = $annotationInfo['columns']; $this->annotationSort = $annotationInfo['sort']; if ($this->annotationSort) { $this->validateSortInfo($this->annotationSort, $this->annotationColumns); } }
Retrieves the cached annotations from the cache file.
entailment
protected function populateAndCacheAnnotationColumns() { $gridAnnotations = $this->readGridAnnotations(); $annotationColumns = $gridAnnotations['columns']; $sort = $gridAnnotations['sort']; if ($annotationColumns) { $output = "<?php\nreturn array('columns' => array(\n"; foreach ($annotationColumns as $field => $info) { $class = $info['class']; $output .= "'$field' => new $class("; $first = true; foreach ($info['arguments'] as $argument) { if ($first) { $first = false; } else { $output .= ','; } $output .= var_export($argument, true); } $output .= '),'; } $output .= "), 'sort' => array("; foreach ($sort as $key => $value) { $output .= "'$key'".' => '; if (null === $value) { $output .= 'null,'; } else { $output .= "'$value',"; } } $output .= "));\n"; } else { $output = "<?php\nreturn false;\n"; } file_put_contents($this->annotationCacheFilename, $output); $this->includeAnnotationCache(); }
Caches the annotation columns result into a file.
entailment
protected function readGridAnnotations() { $metadata = $this->getClassMetadata(); $reflectionClass = $metadata->getReflectionClass(); $properties = $reflectionClass->getProperties(); /** @var Grid $gridAnnotation */ $sort = null; if ($gridAnnotation = $this->reader->getClassAnnotation($reflectionClass, 'Dtc\GridBundle\Annotation\Grid')) { $actions = $gridAnnotation->actions; $sort = $gridAnnotation->sort; } $gridColumns = []; foreach ($properties as $property) { /** @var \Dtc\GridBundle\Annotation\Column $annotation */ $annotation = $this->reader->getPropertyAnnotation($property, 'Dtc\GridBundle\Annotation\Column'); if ($annotation) { $name = $property->getName(); $label = $annotation->label ?: $this->fromCamelCase($name); $gridColumns[$name] = ['class' => '\Dtc\GridBundle\Grid\Column\GridColumn', 'arguments' => [$name, $label]]; $gridColumns[$name]['arguments'][] = null; if ($annotation->sortable) { $gridColumns[$name]['arguments'][] = ['sortable' => true]; } else { $gridColumns[$name]['arguments'][] = []; } $gridColumns[$name]['arguments'][] = $annotation->searchable; $gridColumns[$name]['arguments'][] = $annotation->order; } } // Fall back to default column list if list is not specified if (!$gridColumns) { $gridColumnList = $this->getReflectionColumns(); /** @var GridColumn $gridColumn */ foreach ($gridColumnList as $field => $gridColumn) { $gridColumns[$field] = ['class' => '\Dtc\GridBundle\Grid\Column\GridColumn', 'arguments' => [$field, $gridColumn->getLabel(), null, ['sortable' => true], true, null]]; } } if (isset($actions)) { $field = '\$-action'; $actionArgs = [$field]; $actionDefs = []; /* @var Action $action */ foreach ($actions as $action) { $actionDef = ['label' => $action->label, 'route' => $action->route]; if ($action instanceof ShowAction) { $actionDef['action'] = 'show'; } if ($action instanceof DeleteAction) { $actionDef['action'] = 'delete'; } $actionDefs[] = $actionDef; } $actionArgs[] = $actionDefs; $gridColumns[$field] = ['class' => '\Dtc\GridBundle\Grid\Column\ActionGridColumn', 'arguments' => $actionArgs, ]; } $this->sortGridColumns($gridColumns); try { $sortInfo = $this->extractSortInfo($sort); $this->validateSortInfo($sortInfo, $gridColumns); } catch (\InvalidArgumentException $exception) { throw new \InvalidArgumentException($reflectionClass->getName().' - '.$exception->getMessage(), $exception->getCode(), $exception); } return ['columns' => $gridColumns, 'sort' => $sortInfo]; }
Generates a list of property name and labels based on finding the GridColumn annotation. @return array Hash of grid annotation results: ['columns' => array, 'sort' => string]
entailment
protected function validateSortInfo(array $sortInfo, array $gridColumns) { if ($sortInfo['direction']) { switch ($sortInfo['direction']) { case 'ASC': case 'DESC': break; default: throw new \InvalidArgumentException("Grid's sort annotation direction '{$sortInfo['direction']}' is invalid"); } } if (isset($sortInfo['column'])) { $column = $sortInfo['column']; if (!isset($sortInfo['direction'])) { throw new \InvalidArgumentException("Grid's sort annotation column '$column' specified but a sort direction was not"); } foreach (array_keys($gridColumns) as $name) { if ($name === $column) { return; } } throw new \InvalidArgumentException("Grid's sort annotation column '$column' not in list of columns (".implode(', ', array_keys($gridColumns)).')'); } }
@param array $sortInfo @param array $gridColumns @throws \InvalidArgumentException
entailment
protected function extractSortInfo($sortAnnotation) { $sortInfo = ['direction' => null, 'column' => null]; if ($sortAnnotation) { $direction = $sortAnnotation->direction; $sortInfo['direction'] = $direction; $column = $sortAnnotation->column; $sortInfo['column'] = $column; } return $sortInfo; }
@param Sort|null $sortAnnotation @return array
entailment
protected function getReflectionColumns() { $metadata = $this->getClassMetadata(); $fields = $metadata->getFieldNames(); $identifier = $metadata->getIdentifier(); $identifier = isset($identifier[0]) ? $identifier[0] : null; $columns = array(); foreach ($fields as $field) { $mapping = $metadata->getFieldMapping($field); if (isset($mapping['options']) && isset($mapping['options']['label'])) { $label = $mapping['options']['label']; } else { $label = $this->fromCamelCase($field); } if ($identifier === $field) { if (isset($mapping['strategy']) && 'auto' == $mapping['strategy']) { continue; } } $columns[$field] = new GridColumn($field, $label); } return $columns; }
Generate Columns based on document's Metadata.
entailment
protected function getGridSource($manager, $entityOrDocument) { $repository = $manager->getRepository($entityOrDocument); if ($repository) { $className = $repository->getClassName(); $classMetadata = $manager->getClassMetadata($className); $name = $classMetadata->getName(); $reflectionClass = $classMetadata->getReflectionClass(); $annotation = $this->reader->getClassAnnotation($reflectionClass, 'Dtc\GridBundle\Annotation\Grid'); if (!$annotation) { throw new \Exception("GridSource requested for '$entityOrDocument' but no Grid annotation found"); } if ($manager instanceof EntityManagerInterface) { $gridSource = new EntityGridSource($manager, $name); } else { $gridSource = new DocumentGridSource($manager, $name); } $gridSource->setAnnotationReader($this->reader); $gridSource->setCacheDir($this->cacheDir); $gridSource->setDebug($this->debug); $gridSource->autoDiscoverColumns(); $this->sourcesByName[$name] = $gridSource; $this->sourcesByClass[$className] = $gridSource; $gridSource->setId($className); return $gridSource; } return null; }
@param ObjectManager $manager @param $entityOrDocument @return DocumentGridSource|EntityGridSource|null
entailment
public function get($entityOrDocumentNameOrId) { // @Support legacy method of adding/removing grid sources if (isset($this->extraGridSources[$entityOrDocumentNameOrId])) { return $this->extraGridSources[$entityOrDocumentNameOrId]; } if (isset($this->sourcesByClass[$entityOrDocumentNameOrId])) { return $this->sourcesByClass[$entityOrDocumentNameOrId]; } if (isset($this->sourcesByName[$entityOrDocumentNameOrId])) { return $this->sourcesByName[$entityOrDocumentNameOrId]; } try { if ($this->registry && ($manager = $this->registry->getManagerForClass($entityOrDocumentNameOrId)) && $gridSource = $this->getGridSource($manager, $entityOrDocumentNameOrId)) { return $gridSource; } } catch (\ReflectionException $exception) { } if ($this->mongodbRegistry && ($manager = $this->mongodbRegistry->getManagerForClass($entityOrDocumentNameOrId)) && $gridSource = $this->getGridSource($manager, $entityOrDocumentNameOrId)) { return $gridSource; } throw new \Exception("Can't find grid source for $entityOrDocumentNameOrId"); }
Get a gridsource. @param string $id Entity or Document @param EntityManager|DocumentManager|null $manager (optional) Entity or Document manager to use (overrides default) @return GridSourceInterface|null @throws \Exception
entailment
public function gridAction(Request $request) { $class = $request->get('class'); if (!$class) { throw $this->createNotFoundException('No class passed in'); } if ($rendererId = $request->get('renderer')) { if (!$this->container->has($rendererId)) { throw new \Exception("No renderer found with id $rendererId"); } if (!($renderer = $this->container->has($rendererId)) instanceof AbstractRenderer) { throw new \Exception("Rennderer $rendererId must be instanace of Dtc\GridBundle\Grid\Renderer\AbstractRenderer"); } if (!($view = $request->get('view'))) { throw new \Exception("No view parameter specified for renderer $rendererId"); } } else { $rendererType = $request->get('type', 'table'); $renderer = $this->get('dtc_grid.renderer.factory')->create($rendererType); $view = '@DtcGrid/Page/'.$rendererType.'.html.twig'; } $gridSource = $this->get('dtc_grid.manager.source')->get($class); $renderer->bind($gridSource); return $this->render($view, $renderer->getParams()); }
@Route("/grid", name="dtc_grid") @param Request $request
entailment
public function showAction(Request $request) { $gridSource = $this->get('dtc_grid.manager.source')->get($request->get('id')); $id = $request->get('identifier'); $result = $gridSource->find($id); $responseResult = []; if (!$result) { return new Response('Not Found', 404); } if (is_array($result)) { foreach ($result as $key => $value) { $responseResult[$this->fromCamelCase($key)] = $value; } } elseif (method_exists($gridSource, 'getClassMetadata')) { $classMetadata = $gridSource->getClassMetadata(); $fieldNames = $classMetadata->getFieldNames(); foreach ($fieldNames as $fieldName) { $method = 'get'.ucfirst($fieldName); if (method_exists($result, $method)) { $responseResult[$this->fromCamelCase($fieldName)] = $result->$method(); } } } return new JsonResponse($responseResult); }
@Route("/show", name="dtc_grid_show") @param Request $request @return JsonResponse|Response
entailment
public function deleteAction(Request $request) { $gridSource = $this->get('dtc_grid.manager.source')->get($request->get('id')); $id = $request->get('identifier'); $gridSource->remove($id); $response = new Response(); $response->setStatusCode(204); return $response; }
@Route("/delete", name="dtc_grid_delete") @param Request $request @return Response
entailment
public function fillForm($selector, $data = array(), $submit = false) { $jsonData = json_encode($data); $jsonSubmit = ($submit) ? 'true' : 'false'; $fragment = <<<FRAGMENT casper.then(function () { this.fill('$selector', $jsonData, $jsonSubmit); }); FRAGMENT; $this->script .= $fragment; return $this; }
fill the form with the array of data then submit it if submit is true @param string $selector @param array $data @param string|bool $submit @return \Browser\Casper
entailment
public function sendKeys($selector, $string) { $jsonData = json_encode($string); $fragment = <<<FRAGMENT casper.then(function () { this.sendKeys('$selector', $jsonData); }); FRAGMENT; $this->script .= $fragment; return $this; }
Sends native keyboard events to the element matching the provided selector: @param string $selector @param string $string @return \Browser\Casper
entailment
public function capture(array $area, $filename) { $top = $area['top']; $left = $area['left']; $width = $area['width']; $height = $area['height']; $fragment = <<<FRAGMENT casper.then(function() { this.capture('$filename', { top: $top, left: $left, width: $width, height: $height }); }); FRAGMENT; $this->script .= $fragment; return $this; }
take a screenshot of the page area defined by array(top left width height) @param array $area @param string $filename @return $this
entailment
public function run() { $output = array(); $fragment = <<<FRAGMENT casper.then(function () { this.echo('$this->TAG_CURRENT_URL' + this.getCurrentUrl()); this.echo('$this->TAG_CURRENT_TITLE' + this.getTitle()); this.echo('$this->TAG_CURRENT_PAGE_CONTENT' + this.getPageContent().replace(new RegExp('\\r?\\n','g'), '')); this.echo('$this->TAG_CURRENT_HTML' + this.getHTML().replace(new RegExp('\\r?\\n','g'), '')); this.echo('$this->TAG_CURRENT_HEADERS' + JSON.stringify(this.currentResponse.headers)); this.echo('$this->TAG_CURRENT_STATUS' + this.currentResponse.status); this.echo('$this->TAG_CURRENT_STATUS_TEXT' + this.currentResponse.statusText); this.echo('$this->TAG_CURRENT_COOKIES' + JSON.stringify(phantom.cookies)); }); casper.run(); FRAGMENT; $this->script .= $fragment; $filename = tempnam($this->tempDir, 'php-casperjs-'); file_put_contents($filename, $this->script); // options parsing $options = ''; foreach ($this->options as $option => $value) { $options .= ' --' . $option . '=' . $value; } exec($this->path2casper . 'casperjs ' . $filename . $options, $output); if (empty($output)) { throw new \Exception('Can not find CasperJS.'); } $this->setOutput($output); $this->processOutput(); unlink($filename); return $output; }
run the casperJS script and return the stdOut in using the output variable @return array @throws \Exception
entailment
private function processOutput() { foreach ($this->getOutput() as $outputLine) { if (strpos($outputLine, $this->TAG_CURRENT_URL) !== false) { $this->currentUrl = str_replace( $this->TAG_CURRENT_URL, '', $outputLine ); } if (strpos($outputLine, "Navigation requested: url=") !== false) { $frag0 = explode('Navigation requested: url=', $outputLine); $frag1 = explode(', type=', $frag0[1]); $this->requestedUrls[] = $frag1[0]; } if ($this->isDebug()) { syslog(LOG_INFO, '[PHP-CASPERJS] ' . $outputLine); } if (strpos( $outputLine, $this->TAG_CURRENT_PAGE_CONTENT ) !== false ) { $this->currentPageContent = str_replace( $this->TAG_CURRENT_PAGE_CONTENT, '', $outputLine ); } if (strpos($outputLine, $this->TAG_CURRENT_HTML) !== false) { $this->currentHtml = str_replace( $this->TAG_CURRENT_HTML, '', $outputLine ); } if (strpos($outputLine, " steps in ") !== false) { $frag = explode(' steps in ', $outputLine); $this->loadTime = $frag[1]; } if (0 === strpos($outputLine, $this->TAG_CURRENT_HEADERS)) { $this->headers = json_decode(str_replace($this->TAG_CURRENT_HEADERS, '', $outputLine), true); } if (0 === strpos($outputLine, $this->TAG_CURRENT_STATUS)) { $this->status = (int) str_replace($this->TAG_CURRENT_STATUS, '', $outputLine); } if (0 === strpos($outputLine, $this->TAG_CURRENT_STATUS_TEXT)) { $this->statusText = trim(str_replace($this->TAG_CURRENT_STATUS_TEXT, '', $outputLine)); } if (0 === strpos($outputLine, $this->TAG_CURRENT_COOKIES)) { $this->cookies = json_decode(str_replace($this->TAG_CURRENT_COOKIES, '', $outputLine), true); } } }
process the output after navigation and fill the differents attributes for later usage
entailment
public function create(CanResetPasswordContract $user, $type) { $email = $user->getEmailForPasswordReset(); $this->deleteExisting($user, $type); // We will create a new, random token for the user so that we can e-mail them // a safe link to the password reset form. Then we will insert a record in // the database so that we can verify the token within the actual reset. $token = $this->createNewToken(); $this->getTable()->insert($this->getPayload($email, $token, $type)); return $token; }
Create a new token record. @param \Kbwebs\MultiAuth\PasswordResets\CanResetPassword $user @param string $type @return string
entailment
protected function deleteExisting(CanResetPasswordContract $user, $type) { return $this->getTable()->where('email', $user->getEmailForPasswordReset())->where('type', $type)->delete(); }
Delete all existing reset tokens from the database. @param \Kbwebs\MultiAuth\PasswordResets\CanResetPassword $user @param string $type @return int
entailment
protected function tokenExpired($token) { $expirationTime = strtotime($token['created_at']) + $this->expires; return $expirationTime < $this->getCurrentTime(); }
Determine if the token has expired. @param array $token @return bool
entailment
public function delete($token, $type) { $this->getTable()->where('token', $token)->where('type', $type)->delete(); }
Delete a token record by token. @param string $token @param string $type @return void
entailment
public function getUser(array $credentials) { $credentials = array_except($credentials, ['token']); $user = $this->users->retrieveByCredentials($credentials); if ($user && !$user instanceof CanResetPasswordContract) { throw new UnexpectedValueException(ucfirst($this->type).' must implement CanResetPassword interface.'); } return $user; }
Get the user for the given credentials. @param array $credentials @return \Kbwebs\MultiAuth\PasswordResets\CanResetPassword @throws \UnexpectedValueException
entailment
protected function registerAuthenticator() { $this->app->singleton('auth', function ($app) { // Once the authentication service has actually been requested by the developer // we will set a variable in the application indicating such. This helps us // know that we need to set any queued cookies in the after event later. $app['auth.loaded'] = true; return new MultiManager($app); }); $this->app->singleton('auth.driver', function ($app) { return $app['auth']->driver(); }); }
Register bindings in the container. @return void
entailment
public function fire() { $fullPath = $this->createBaseMigration(); $this->files->put($fullPath, $this->getMigrationStub()); $this->info('Migration created successfully!'); }
Execute the console command. @return void
entailment
public function createDatabaseDriver() { $provider = $this->createDatabaseProvider(); return new Guard($provider, $this->app['session.store'], $this->name); }
Create an instance of the database driver. @return \Kbwebs\MultiAuth\Guard
entailment
public function createEloquentDriver() { $provider = $this->createEloquentProvider(); return new Guard($provider, $this->app['session.store'], $this->name); }
Create an instance of the Eloquent driver. @return \Kbwebs\MultiAuth\Guard
entailment
public function setConfig($key, $value) { $this->validConfigItem($key, $value); $this->config->$key = $value; }
@param string $key Nome da chave do config que receberá o conteúdo do segundo parâmetro @param string $value mixed valor que será armazenado na chave do config fornecido pelo primeiro parâmentro @see Client::$config @see Client::validConfig Sobrescreve as chaves do config
entailment
public function createAuthUrl() { $this->validConfig(); $query_string = filter_var_array((array) $this->config, array( 'client_id' => FILTER_SANITIZE_STRING, 'scope' => FILTER_SANITIZE_STRING, 'redirect_uri' => FILTER_SANITIZE_STRING, 'response_type' => FILTER_SANITIZE_STRING, )); $auth_url = filter_var($this->config->auth_url, FILTER_SANITIZE_STRING); return $auth_url.'/?'.\http_build_query(array( 'client_id' => $query_string['client_id'], 'scope' => $query_string['scope'], 'redirect_uri' => $query_string['redirect_uri'], 'response_type' => $query_string['response_type'], )); }
Cria a url para ser usada no link para pagina da olx de liberação do serviço pelo cliente com Oauth. Ele usa os dados setados no config para gerar a url. @see Client::setConfig
entailment
private function validConfigItem($key, $value) { if (!isset($this->struct_config[$key])) { throw new Olx_Auth_Exception("Chave fornecida [$key] é inválida para o config"); } else { if (isset($this->struct_config[$key]['valores']) && !in_array($value, $this->struct_config[$key]['valores'])) { if ($key == 'scope') { $array_scope = explode(' ', $value); foreach ($array_scope as $v) { if (!in_array($v, $this->struct_config[$key]['valores'])) { throw new Olx_Auth_Exception("Valor inválido ($value) para Chave fornecida ($key)"); } } } else { throw new Olx_Auth_Exception("Valor inválido ($value) para Chave fornecida ($key)"); } } } }
@param string $key Nome da chave a ser validada @param string $value mixed valor que será validado @see Client::setConfig @return bool Valida a chave e o valor que será setado no config
entailment