sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function totp($secret, $timecounter = null) { if (is_null($timecounter)) { $timecounter = $this->getTimecounter(); } return $this->hotp($secret, $timecounter); }
/* (non-PHPdoc) @see Otp.OtpInterface::totp()
entailment
public function checkHotp($secret, $counter, $key) { return hash_equals($this->hotp($secret, $counter), $key); }
/* (non-PHPdoc) @see Otp.OtpInterface::checkHotp()
entailment
public function checkHotpResync($secret, $counter, $key, $counterwindow = 2) { if (!is_numeric($counter) || $counter < 0) { throw new \InvalidArgumentException('Invalid counter supplied'); } if(!is_numeric($counterwindow) || $counterwindow < 0){ throw new \InvalidArgumentException('Invalid counterwindow supplied'); } for($c = 0; $c <= $counterwindow; $c = $c + 1) { if(hash_equals($this->hotp($secret, $counter + $c), $key)){ return $counter + $c; } } return false; }
/* (non-PHPdoc) @see Otp.OtpInterface::checkHotpResync()
entailment
public function checkTotp($secret, $key, $timedrift = 1) { if (!is_numeric($timedrift) || $timedrift < 0) { throw new \InvalidArgumentException('Invalid timedrift supplied'); } // Counter comes from time now // Also we check the current timestamp as well as previous and future ones // according to $timerange $timecounter = $this->getTimecounter(); $start = $timecounter - ($timedrift); $end = $timecounter + ($timedrift); // We first try the current, as it is the most likely to work if (hash_equals($this->totp($secret, $timecounter), $key)) { return true; } elseif ($timedrift == 0) { // When timedrift is 0, this is the end of the checks return false; } // Well, that didn't work, so try the others for ($t = $start; $t <= $end; $t = $t + 1) { if ($t == $timecounter) { // Already tried that one continue; } if (hash_equals($this->totp($secret, $t), $key)) { return true; } } // if none worked, then return false return false; }
/* (non-PHPdoc) @see Otp.OtpInterface::checkTotp()
entailment
public function setAlgorithm($algorithm) { if (!in_array($algorithm, $this->allowedAlgorithms)) { throw new \InvalidArgumentException('Not an allowed algorithm: ' . $algorithm); } $this->algorithm = $algorithm; return $this; }
Changing the used algorithm for hashing Can only be one of the algorithms in the allowedAlgorithms property. @param string $algorithm @throws \InvalidArgumentException @return \Otp\Otp
entailment
private function truncate($hash) { $offset = ord($hash[strlen($hash)-1]) & 0xf; return ( ((ord($hash[$offset+0]) & 0x7f) << 24 ) | ((ord($hash[$offset+1]) & 0xff) << 16 ) | ((ord($hash[$offset+2]) & 0xff) << 8 ) | (ord($hash[$offset+3]) & 0xff) ) % pow(10, $this->digits); }
Creates the basic number for otp from hash This number is left padded with zeros to the required length by the calling function. @param string $hash hmac hash @return number
entailment
public function getArray() { try { $parsed = TomlParser::ParseFile($this->context); } catch (ParseException $e) { throw new InvalidFileException($e->getMessage()); } // if (! is_array($parsed)) { // throw new InvalidFileException('Unable to parse invalid TOML file at ' . $this->context); // } return $parsed; }
Retrieve the contents of a .toml file and convert it to an array of configuration options. @return array Array of configuration options
entailment
public function getArray() { $contents = include $this->context; if (gettype($contents) != 'array') { throw new InvalidFileException($this->context . ' does not return a valid array'); } return $contents; }
Retrieve the contents of a .php configuration file and convert it to an array of configuration options. @return array Array of configuration options
entailment
private function getUrlPattern(Router $router, $routeNameFromMappingFile, $baseUrl) { if (!empty($routeNameFromMappingFile)) { try { $route = $router->getRouteCollection()->get($routeNameFromMappingFile); if (empty($route)) { throw new Exception(); } } catch (Exception $e) { throw new RuntimeException( \sprintf('Route \'%s\' has not been defined as a Symfony route.', $routeNameFromMappingFile) ); } \preg_match_all('/{(.*?)}/', $route->getPath(), $matches); $pattern = []; if (!empty($matches)) { $pattern = \array_combine($matches[1], $matches[0]); } return $baseUrl.\urldecode($router->generate($routeNameFromMappingFile, $pattern, true)); } return (string) $routeNameFromMappingFile; }
@param Router $router @param string $routeNameFromMappingFile @return mixed @throws RuntimeException
entailment
public function getArray() { $parsed = @parse_ini_file($this->context, true); if (! $parsed) { throw new InvalidFileException('Unable to parse invalid INI file at ' . $this->context); } return $parsed; }
Retrieve the contents of a .ini file and convert it to an array of configuration options. @return array Array of configuration options
entailment
protected function doExecute(AssertionContext $context) { $context->getAssertion()->setVersion($this->version); $this->logger->debug( sprintf('Assertion Version set to "%s"', $this->version), LogHelper::getActionContext($context, $this) ); }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $profileContext = $context->getProfileContext(); $trustOptions = $profileContext->getTrustOptions(); if (false === $trustOptions->getEncryptAssertions()) { return; } if (null == $assertion = $context->getAssertion()) { throw new LightSamlContextException($context, 'Assertion for encryption is not set'); } $context->setAssertion(null); $query = $this->credentialResolver->query(); $query ->add(new EntityIdCriteria($profileContext->getPartyEntityDescriptor()->getEntityID())) ->add(new MetadataCriteria( ProfileContext::ROLE_IDP === $profileContext->getOwnRole() ? MetadataCriteria::TYPE_SP : MetadataCriteria::TYPE_IDP, SamlConstants::PROTOCOL_SAML2 )) ->add(new UsageCriteria(UsageType::ENCRYPTION)) ; $query->resolve(); /** @var CredentialInterface $credential */ $credential = $query->firstCredential(); if (null == $credential) { throw new LightSamlContextException($context, 'Unable to resolve encrypting credential'); } if (null == $credential->getPublicKey()) { throw new LightSamlContextException($context, 'Credential resolved for assertion encryption does not have a public key'); } $encryptedAssertionWriter = new EncryptedAssertionWriter( $trustOptions->getBlockEncryptionAlgorithm(), $trustOptions->getKeyTransportEncryptionAlgorithm() ); $encryptedAssertionWriter->encrypt($assertion, $credential->getPublicKey()); $context->setEncryptedAssertion($encryptedAssertionWriter); }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $profileContext = $context->getProfileContext(); $trustOptions = $profileContext->getTrustOptions(); if ($trustOptions->getSignAssertions()) { $signature = $this->signatureResolver->getSignature($profileContext); if ($signature) { $this->logger->debug( sprintf( 'Signing assertion with fingerprint %s', $signature->getCertificate()->getFingerprint() ), LogHelper::getActionContext($context, $this, array( 'certificate' => $signature->getCertificate()->getInfo(), )) ); $context->getAssertion()->setSignature($signature); } else { $this->logger->critical( 'Unable to resolve assertion signature, though signing enabled', LogHelper::getActionErrorContext($context, $this) ); } } else { $this->logger->debug('Assertion signing disabled', LogHelper::getActionContext($context, $this)); } }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $nameId = $this->nameIdProvider->getNameID($context); if ($nameId) { if (null == $context->getAssertion()->getSubject()) { $context->getAssertion()->setSubject(new Subject()); } $context->getAssertion()->getSubject()->setNameID($nameId); } }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $authnContext = new AuthnContext(); $authnContextClassRef = $this->sessionInfoProvider->getAuthnContextClassRef() ?: SamlConstants::AUTHN_CONTEXT_UNSPECIFIED; $authnContext->setAuthnContextClassRef($authnContextClassRef); $authnStatement = new AuthnStatement(); $authnStatement->setAuthnContext($authnContext); $sessionIndex = $this->sessionInfoProvider->getSessionIndex(); if ($sessionIndex) { $authnStatement->setSessionIndex($sessionIndex); } $authnInstant = $this->sessionInfoProvider->getAuthnInstant() ?: new \DateTime(); $authnStatement->setAuthnInstant($authnInstant); $subjectLocality = new SubjectLocality(); $subjectLocality->setAddress($context->getProfileContext()->getHttpRequest()->getClientIp()); $authnStatement->setSubjectLocality($subjectLocality); $context->getAssertion()->addItem($authnStatement); }
@param AssertionContext $context @return void
entailment
private function loadLanguageData(string $language = 'de') { if (\in_array($language, self::$availableLanguages, true) === false) { throw new StopWordsLanguageNotExists('language not supported: ' . $language); } $this->stopWords[$language] = $this->getData($language); }
Load language-data from one language. @param string $language @throws StopWordsLanguageNotExists
entailment
private function getData(string $file): array { static $RESULT_STOP_WORDS_CACHE = array(); if (isset($RESULT_STOP_WORDS_CACHE[$file])) { return $RESULT_STOP_WORDS_CACHE[$file]; } $file = __DIR__ . '/stopwords/' . $file . '.php'; if (file_exists($file)) { /** @noinspection PhpIncludeInspection */ $RESULT_STOP_WORDS_CACHE[$file] = require $file; } else { $RESULT_STOP_WORDS_CACHE[$file] = array(); } return $RESULT_STOP_WORDS_CACHE[$file]; }
Get data from "/data/*.php". @param string $file @return array <p>Will return an empty array on error.</p>
entailment
public function getStopWordsFromLanguage(string $language = 'de'): array { if (\in_array($language, self::$availableLanguages, true) === false) { throw new StopWordsLanguageNotExists('language not supported: ' . $language); } if (!isset($this->stopWords[$language])) { $this->loadLanguageData($language); } return $this->stopWords[$language]; }
Get the stop-words from one language. @param string $language @return array @throws StopWordsLanguageNotExists
entailment
protected function doExecute(ProfileContext $context) { $authnRequest = MessageContextHelper::asAuthnRequest($context->getInboundContext()); if (false == $authnRequest->getAssertionConsumerServiceURL()) { return; } $spEntityDescriptor = $context->getPartyEntityDescriptor(); foreach ($spEntityDescriptor->getAllSpSsoDescriptors() as $sp) { if ($sp->getAllAssertionConsumerServicesByUrl($authnRequest->getAssertionConsumerServiceURL())) { $this->logger->debug( sprintf( 'AuthnRequest has assertion consumer url "%s" that belongs to entity "%s"', $authnRequest->getAssertionConsumerServiceURL(), $spEntityDescriptor->getEntityID() ), LogHelper::getActionContext($context, $this) ); return; } } $message = sprintf( "Invalid ACS Url '%s' for '%s' entity", $authnRequest->getAssertionConsumerServiceURL(), $spEntityDescriptor->getEntityID() ); $this->logger->emergency($message, LogHelper::getActionErrorContext($context, $this)); throw new LightSamlValidationException($message); }
@param ProfileContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $context->getAssertion()->setIssueInstant($this->timeProvider->getTimestamp()); $this->logger->info( sprintf('Assertion IssueInstant set to "%s"', $context->getAssertion()->getIssueInstantString()), LogHelper::getActionContext($context, $this) ); }
@param AssertionContext $context @return void
entailment
public function map($callable) { foreach ($this->assertionActions as $k => $action) { $newAction = call_user_func($callable, $action); if ($newAction) { $this->assertionActions[$k] = $newAction; } } }
@param callable $callable @return ActionInterface|null
entailment
protected function doExecute(ProfileContext $context) { $response = MessageContextHelper::asResponse($context->getOutboundContext()); foreach ($this->assertionActions as $index => $action) { $name = sprintf('assertion_%s', $index); /** @var AssertionContext $assertionContext */ $assertionContext = $context->getSubContext($name, AssertionContext::class); $assertionContext->setId($index); $action->execute($assertionContext); if ($assertionContext->getEncryptedAssertion()) { $response->addEncryptedAssertion($assertionContext->getEncryptedAssertion()); } elseif ($assertionContext->getAssertion()) { $response->addAssertion($assertionContext->getAssertion()); } else { $this->logger->warning('No assertion was built', LogHelper::getActionContext($context, $this)); } } }
@param ProfileContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $partyEntityDescriptor = $context->getProfileContext()->getPartyEntityDescriptor(); $conditions = new Conditions(); $conditions->setNotBefore($this->timeProvider->getTimestamp()); $conditions->setNotOnOrAfter($conditions->getNotBeforeTimestamp() + $this->expirationSeconds); $audienceRestriction = new AudienceRestriction(array( $partyEntityDescriptor->getEntityID(), )); $conditions->addItem($audienceRestriction); $context->getAssertion()->setConditions($conditions); }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $ownEntityDescriptor = $context->getProfileContext()->getOwnEntityDescriptor(); $issuer = new Issuer($ownEntityDescriptor->getEntityID()); $issuer->setFormat(SamlConstants::NAME_ID_FORMAT_ENTITY); $context->getAssertion()->setIssuer($issuer); $this->logger->debug( sprintf('Assertion Issuer set to "%s"', $ownEntityDescriptor->getEntityID()), LogHelper::getActionContext($context, $this) ); }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $attributes = $this->attributeValueProvider->getValues($context); if ($attributes) { $attributeStatement = new AttributeStatement(); $context->getAssertion()->addItem($attributeStatement); foreach ($attributes as $attribute) { $attributeStatement->addAttribute($attribute); } } }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { if ($context->getAssertion()) { $this->sessionProcessor->processAssertions( array($context->getAssertion()), $context->getProfileContext()->getOwnEntityDescriptor()->getEntityID(), $context->getProfileContext()->getPartyEntityDescriptor()->getEntityID() ); } }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $profileContext = $context->getProfileContext(); $inboundMessage = $profileContext->getInboundContext()->getMessage(); $endpoint = $profileContext->getEndpoint(); $data = new SubjectConfirmationData(); if ($inboundMessage) { $data->setInResponseTo($inboundMessage->getID()); } $data->setAddress($profileContext->getHttpRequest()->getClientIp()); $data->setNotOnOrAfter($this->timeProvider->getTimestamp() + $this->expirationSeconds); $data->setRecipient($endpoint->getLocation()); $subjectConfirmation = new SubjectConfirmation(); $subjectConfirmation->setMethod(SamlConstants::CONFIRMATION_METHOD_BEARER); $subjectConfirmation->setSubjectConfirmationData($data); if (null === $context->getAssertion()->getSubject()) { $context->getAssertion()->setSubject(new Subject()); } $context->getAssertion()->getSubject()->addSubjectConfirmation($subjectConfirmation); }
@param AssertionContext $context @return void
entailment
protected function doExecute(AssertionContext $context) { $id = Helper::generateID(); $context->getAssertion()->setId($id); $this->logger->info( sprintf('Assertion ID set to "%s"', $id), LogHelper::getActionContext($context, $this, array('message_id' => $id)) ); }
@param AssertionContext $context @return void
entailment
protected function doExecute(ProfileContext $context) { if ($context->getInboundContext()->getMessage()) { MessageContextHelper::asStatusResponse($context->getOutboundContext())->setInResponseTo( MessageContextHelper::asSamlMessage($context->getInboundContext())->getID() ); } }
@param ProfileContext $context @return void
entailment
public function create($campaign) { if (is_array($campaign)) { $campaign["campaign_type"] = "PROMOTION"; } elseif (is_object($campaign)) { $campaign->campaign_type = "PROMOTION"; } return $this->campaigns->create($campaign); }
@param array|stdClass $campaign Create promotion campaign. @throws \Voucherify\ClientException
entailment
public function prepandRoutes(IRouter $router, array $routes): void { if (empty($routes)) { return; } if (!($router instanceof \Traversable) || !($router instanceof \ArrayAccess)) { throw new ApiRouteWrongRouterException(sprintf( 'ApiRoutesResolver can not add ApiRoutes to your router. Use for example %s instead', RouteList::class )); } $user_routes = $this->findAndDestroyUserRoutes($router); /** * Add ApiRoutes first */ foreach ($routes as $route) { $router[] = $route; } /** * User routes on second place */ foreach ($user_routes as $route) { $router[] = $route; } }
Place REST API routes at the beginnig of all routes
entailment
public static function toCamelCase($str, $capitalise_first_char = false) { if($capitalise_first_char) { $str[0] = strtoupper($str[0]); } $func = function($c) { return strtoupper($c[1]); }; return preg_replace_callback('/_([a-z])/', $func, $str); }
Translates a string with underscores into camel case (e.g. first_name -&gt; firstName) @param string $str String in underscore format @param bool $capitalise_first_char If true, capitalise the first char in $str @return string $str translated into camel caps
entailment
public static function convertSumupObjectToArray($object) { $results = []; foreach ($object->_keys as $property) { $v = $object->{$property}; if ($v instanceof SumupObject) { $results[$property] = $v->__toArray(); } elseif (is_array($v)) { $results[$property] = self::convertSumupObjectToArray($v); } else { $results[$property] = $v; } } return $results; }
Recursively converts the PHP Sumup object to an array. @param array $values The PHP Sumup object to convert. @return array
entailment
public function update($product) { $productId = ""; if (is_array($product)) { $productId = $product["id"]; unset($product["id"]); } elseif (is_object($product)) { $productId = $product->id; unset($product->id); } return $this->client->put("/products/" . rawurlencode($productId), $product); }
@param array|stdClass $product Product object Update product. @throws \Voucherify\ClientException
entailment
public function delete($productId, $force = null) { $options = (object)[]; $options->qs = [ "force" => ($force ? "true" : "false") ]; return $this->client->delete("/products/" . rawurlencode($productId), null, $options); }
@param string $productId @param boolean|null $force Delete product. @throws \Voucherify\ClientException
entailment
public function getSku($productId, $skuId) { return $this->client->get("/products/" . rawurlencode($productId) . "/skus/" . rawurlencode($skuId)); }
@param string $productId @param string $skuId Get product's sku. @throws \Voucherify\ClientException
entailment
public function updateSku($productId, $sku) { $skuId = ""; if (is_array($sku)) { $skuId = $sku["id"]; unset($sku["id"]); } elseif (is_object($sku)) { $skuId = $sku->id; unset($sku->id); } return $this->client->put("/products/" . rawurlencode($productId) . "/skus/" . rawurlencode($skuId), $sku); }
@param string $productId @param array|stdClass $sku Product's sku object Update product's sku. @throws \Voucherify\ClientException
entailment
public function update($customer) { $customerId = ""; if (is_array($customer)) { $customerId = $customer["id"]; } elseif (is_object($customer)) { $customerId = $customer->id; } return $this->client->put("/customers/" . rawurlencode($customerId), $customer, null); }
@param array|stdClass $customer Object with customer fields for update Update customer. @throws \Voucherify\ClientException
entailment
public function create($voucher) { if (isset($voucher->code)) { return $this->client->post("/vouchers/" . rawurlencode($voucher->code), $voucher, null); } else { return $this->client->post("/vouchers/", $voucher, null); } }
@param stdClass $voucher Create voucher. @throws \Voucherify\ClientException
entailment
public function update($voucher) { $code = ""; if (is_array($voucher)) { $code = $voucher["code"]; } elseif (is_object($voucher)) { $code = $voucher->code; } return $this->client->put("/vouchers/" . rawurlencode($code), $voucher, null); }
@param array|stdClass $voucher Update voucher. @throws \Voucherify\ClientException
entailment
public function addBalance($code, $balance) { $payload = (object)[]; $payload->amount = $balance; return $this->client->post("/vouchers/" . rawurlencode($code) . "/balance", $payload, null); }
@param string $code Increase Gif-Card type voucher's balance. @throws \Voucherify\ClientException
entailment
private function request($method, $endpoint, $params, $body) { $setParams = $params && in_array($method, ["GET", "POST", "DELETE"]); $setBody = $body && in_array($method, ["POST", "PUT", "DELETE"]); $method = strtoupper($method); $url = $this->basePath . $endpoint . ($setParams ? "?" . $this->encodeParams($params) : ""); $options = array(); $options[CURLOPT_URL] = $url; $options[CURLOPT_HTTPHEADER] = $this->headers; $options[CURLOPT_RETURNTRANSFER] = true; $options[CURLOPT_CUSTOMREQUEST] = $method; $options[CURLOPT_POSTFIELDS] = $setBody ? json_encode($body) : null; $options[CURLOPT_CONNECTTIMEOUT] = $this->getConnectionOption("connectTimeout"); $options[CURLOPT_TIMEOUT_MS] = $this->getConnectionOption("timeout"); $curl = curl_init(); if (isset($this->logger)) { $context = [ "options" => $options ]; $this->logger->info("[ApiClient][Request] Curl request;", $context); } curl_setopt_array($curl, $options); $result = curl_exec($curl); $statusCode = curl_getinfo($curl, CURLINFO_HTTP_CODE); $error = curl_error($curl); curl_close($curl); if (isset($this->logger)) { $context = [ "result" => $result, "statusCode" => $statusCode, "error" => $error ]; $this->logger->info("[ApiClient][Request] Curl response;", $context); } if ($result === false) { throw new ClientException($error); } elseif ($statusCode >= 400) { $error = json_decode($result); throw new ClientException($error, $statusCode); } return json_decode($result); }
@param string $method @param string $endpoint @param string|array|stdClass|null $params @param string|array|stdClass|null $body @throws \Voucherify\ClientException
entailment
public function addVoucher($name, $params = null) { return $this->client->post("/campaigns/" . rawurlencode($name) . "/vouchers/", $params); }
@param string $name - campaign name @param stdClass $params Add voucher to campaign. @throws \Voucherify\ClientException
entailment
public function addVoucherWithCode($name, $code, $params = null) { return $this->client->post("/campaigns/" . rawurlencode($name) . "/vouchers/" . rawurlencode($code), $params); }
@param string $name - campaign name @param string $code - voucher code @param stdClass $params Add voucher with certain code to campaign. @throws \Voucherify\ClientException
entailment
public function update($order) { $orderId = ""; if (is_array($order)) { $orderId = $order["id"]; } elseif (is_object($order)) { $orderId = $order->id; } return $this->client->put("/orders/" . rawurlencode($orderId), $order, null); }
@param array|stdClass $order Object with order fields for update Update order. @throws \Voucherify\ClientException
entailment
public static function verifyWebhookSignature($signature, $message, $secretKey) { $data = ""; if (is_string($message)) { $data = $message; } else { $data = json_encode($message); } return hash_hmac("sha256", $data, $secretKey) == $signature; }
@param array|stdClass $params Params object Verify webhook signature @throws \Voucherify\ClientException
entailment
public function request($method, $url, $params = null, $version = null, $headers = null) { $params = $params ?: []; $headers = $headers ?: []; if ($this->accessToken && $this->tokenType === 'Bearer') { $headers['Authorization'] = 'Bearer ' . $this->accessToken; } $payloadType = strcasecmp($method, 'get') === 0 ? 'query' : 'json'; $client = $this->httpClient(); if (!$this->noVersion) { $url = Sumup::getApiVersion() . '/' . $url; } try { $response = $client->request($method, $url, [ $payloadType => $params, 'headers' => $headers, 'http_errors' => false ]); } catch (\GuzzleHttp\Exception\ClientException $e) { throw new Error\ApiRequestorError($e->getMessage()); } return new ApiResponse($response); }
@param string $method @param string $url @param array|null $params @param array|null $headers @return array An array whose first element is an API response and second element is the API key used to make the request.
entailment
public static function authorizeUrl($params = null) { if (!$params) { $params = array(); } $params['client_id'] = self::_getConnectParam('client_id', $params); $params['redirect_uri'] = self::_getConnectParam('redirect_uri', $params); if (!array_key_exists('response_type', $params)) { $params['response_type'] = 'code'; } $query = Util\Util::urlEncode($params); return Sumup::$connectBase . '/authorize?' . $query; }
Generates a URL to Sumup's OAuth form. @param array|null $params @param array|null $opts @return string The URL to Sumup's OAuth form.
entailment
public static function getToken($params = null) { if (!$params) { $params = array(); } $requestor = new ApiRequestor(Sumup::$connectBase, true); $params['client_id'] = self::_getConnectParam('client_id', $params); $params['client_secret'] = self::_getConnectParam('client_secret', $params); $response = $requestor->request('post', '/token', $params); if ($response->raw->getStatusCode() !== 200) { throw new Error\AuthenticationError('Token request error'); } return new AccessToken($response); }
Use an authoriztion code to connect an account to your platform and fetch the user's credentials. @param array|null $params @param array|null $opts @return SumupObject Object containing the response from the API.
entailment
public static function refreshToken(AccessToken $token, $params = null) { if ($token->expires_at > new \DateTime()) { return $token; } $requestor = new ApiRequestor(Sumup::$connectBase, true); $params = [ 'grant_type' => 'refresh_token', 'client_id' => self::_getConnectParam('client_id', $params), 'client_secret' => self::_getConnectParam('client_secret', $params), 'refresh_token' => $token->refresh_token ]; $response = $requestor->request('post', '/token', $params); if ($response->raw->getStatusCode() !== 200) { throw new Error\AuthenticationError('Token request error'); } return new AccessToken($response); }
Use an authoriztion code to connect an account to your platform and fetch the user's credentials. @param array|null $params @param array|null $opts @return SumupObject Object containing the response from the API.
entailment
private static function _getConnectParam($paramName, $params = null) { $oauthParam = ($params && array_key_exists($paramName, $params)) ? $params[$paramName] : null; if ($oauthParam === null) { $funcName = 'get' . Util\Util::toCamelCase($paramName, true); $oauthParam = Sumup::{$funcName}(); } if ($oauthParam === null) { $msg = 'No '.$paramName.' provided. You can find your '. $paramName . ' in your Sumup dashboard at ' . 'https://me.sumup.com/developers, ' . 'after registering your account as a platform. See ' . 'https://sumupus.desk.com/ for details, ' . 'or email [email protected] if you have any questions.'; throw new Error\AuthenticationError($msg); } return $oauthParam; }
return the Connect param based on the name @param string $paramName @param array $params @return string
entailment
public function update($rule) { $ruleId = ""; if (is_array($rule)) { $ruleId = $rule["id"]; unset($rule["id"]); } elseif (is_object($rule)) { $ruleId = $rule->id; unset($rule->id); } return $this->client->put("/validation-rules/" . rawurlencode($ruleId), $rule); }
@param string $ruleId Validation rule id. @param array|stdClass $params Params object Upadate validation rule. @throws \Voucherify\ClientException
entailment
public function getAssignments($ruleId, $params = null) { return $this->client->get("/validation-rules/" . rawurlencode($ruleId) . "/assignments", $params); }
@param array|stdClass $params List validation rule assignments @throws \Voucherify\ClientException
entailment
public function deleteAssignment($ruleId, $assignmentId) { return $this->client->delete("/validation-rules/" . rawurlencode($ruleId) . "/assignments/" . rawurlencode($assignmentId)); }
@param array|stdClass $params Params object Delete validation rule assignment @throws \Voucherify\ClientException
entailment
private function redeemPromotionTier($promotionTier, $params) { $promotionTierId = ""; if (is_object($promotionTier)) { $promotionTierId = $promotionTier->id; } elseif (is_array($promotionTier)) { $promotionTierId = $promotionTier["id"]; } return $this->promotions->tiers->redeem($promotionTierId, $params); }
@param array|stdClass $promotionTier @param array|stdClass $params Redeem promotion tier. @throws \Voucherify\ClientException
entailment
private function redeemVoucher($code, $params) { $payload = null; $options = null; if (is_string($code) && !is_string($params)) { $payload = $params; } // Backward compatibility - Should always use string code as first param if (is_array($code)) { $payload = $code; $code = $payload["voucher"]; unset($payload["voucher"]); } // Backward compatibility - Check if params is string -> tracking_id if (is_string($params)) { $options = (object)[]; $options->qs = ["tracking_id" => $params]; } return $this->client->post("/vouchers/" . rawurlencode($code) . "/redemption/", $payload, $options); }
Voucher code or array with voucher (code), customer profile and order amount @param string|array $code Voucher code or array with voucher (code), customer profile and order amount @param string|null $params Provided tracking id Redeem voucher. @throws \Voucherify\ClientException
entailment
public function redeem($params, $context = null) { $redeemPromotionTier = (is_object($params) || is_array($params)) && (is_object($context) || is_array($context)); if ($redeemPromotionTier) { return $this->redeemPromotionTier($params, $context); } return $this->redeemVoucher($params, $context); }
@param string|array|stdClass $params Voucher code, Voucher validation data or Promotion tier data @param string|array|stdClass $context Voucher validation context data or Promotion tier validation context data Validate voucher or promotion tier. @throws \Voucherify\ClientException
entailment
public function rollback($redemptionId, $params = null) { $payload = null; $options = (object)[ "qs" => null ]; if (is_string($params)) { $options->qs = (object)[ "reason" => $params ]; } elseif (is_object($params)) { if (isset($params->reason)) { if (!isset($options->qs)) { $options->qs = (object)[]; } $options->qs->reason = $params->reason; } if (isset($params->tracking_id)) { if (!isset($options->qs)) { $options->qs = (object)[]; } $options->qs->tracking_id = $params->tracking_id; } if (isset($params->customer)) { $payload = (object)[ "customer" => $params->customer ]; } } elseif (is_array($params)) { if (isset($params["reason"])) { if (!isset($options->qs)) { $options->qs = (object)[]; } $options->qs->reason = $params["reason"]; } if (isset($params["tracking_id"])) { if (!isset($options->qs)) { $options->qs = (object)[]; } $options->qs->tracking_id = $params["tracking_id"]; } if (isset($params["customer"])) { $payload = (object)[ "customer" => $params["customer"] ]; } } return $this->client->post("/redemptions/" . rawurlencode($redemptionId) . "/rollback/", $payload, $options); }
@param string $redemptionId @param string|array|stdClass|null $params Rollback redemption. This operation creates a rollback entry in voucher's redemption history (`redemption.redemption_entries`) and gives 1 redemption back to the pool (decreases `redeemed_quantity` by 1). @throws \Voucherify\ClientException
entailment
public function redeem($promotionTierId, $params) { return $this->client->post("/promotions/tiers/" . rawurlencode($promotionTierId) . "/redemption/", $params, null); }
@param string $promotionTierId @param array|stdClass $params Validate promotion tier. @throws \Voucherify\ClientException
entailment
public function update($params) { $promotionTierId = ""; if (is_array($params)) { $promotionTierId = $params["id"]; } elseif (is_object($params)) { $promotionTierId = $params->id; } return $this->client->put("/promotions/tiers/" . rawurlencode($promotionTierId), $params, null); }
@param array|stdClass $params Update promotion tier. @throws \Voucherify\ClientException
entailment
public function getPlacehodlerParameters(): array { if (!empty($this->placeholder_order)) { return array_filter($this->placeholder_order); } $return = []; preg_replace_callback('/<(\w+)>/', function ($item) use (&$return) { $return[] = end($item); }, $this->path); return $return; }
Get all parameters from url mask
entailment
public function getRequiredParams(): array { $regex = '/\[[^\[]+?\]/'; $path = $this->getPath(); while (preg_match($regex, $path)) { $path = preg_replace($regex, '', $path); } $required = []; preg_replace_callback('/<(\w+)>/', function ($item) use (&$required) { $required[] = end($item); }, $path); return $required; }
Get required parameters from url mask
entailment
public function match(Nette\Http\IRequest $httpRequest): ?Request { /** * ApiRoute can be easily disabled */ if ($this->disable) { return null; } $url = $httpRequest->getUrl(); $path = $url->getPath(); /** * Build path mask */ $order = &$this->placeholder_order; $parameters = $this->parameters; $mask = preg_replace_callback('/(<(\w+)>)|\[|\]/', function ($item) use (&$order, $parameters) { if ($item[0] == '[' || $item[0] == ']') { if ($item[0] == '[') { $order[] = null; } return $item[0]; } [, , $placeholder] = $item; $parameter = $parameters[$placeholder] ?? []; $regex = $parameter['requirement'] ?? '\w+'; $has_default = array_key_exists('default', $parameter); $regex = preg_replace('~\(~', '(?:', $regex); if ($has_default) { $order[] = $placeholder; return sprintf('(%s)?', $regex); } $order[] = $placeholder; return sprintf('(%s)', $regex); }, $this->path); $mask = '^' . str_replace(['[', ']'], ['(', ')?'], $mask) . '$'; /** * Prepare paths for regex match (escape slashes) */ if (!preg_match_all($this->prepareForMatch($mask), $path, $matches)) { return null; } /** * Did some action to the request method exists? */ $this->resolveFormat($httpRequest); $method = $this->resolveMethod($httpRequest); $action = $this->actions[$method] ?? null; if (!$action) { return null; } /** * Basic params */ $params = $httpRequest->getQuery(); $params['action'] = $action; $required_params = $this->getRequiredParams(); /** * Route mask parameters */ array_shift($matches); foreach ($this->placeholder_order as $key => $name) { if ($name !== null&& isset($matches[$key])) { $params[$name] = reset($matches[$key]) ?: null; /** * Required parameters */ if (empty($params[$name]) && in_array($name, $required_params, true)) { return null; } } } $request = new Request( $this->presenter, $method, $params, $httpRequest->getPost(), $httpRequest->getFiles(), [Request::SECURED => $httpRequest->isSecured()] ); /** * Trigger event - route matches */ $this->onMatch($this, $request); return $request; }
Maps HTTP request to a Request object.
entailment
public function constructUrl(Request $request, Nette\Http\Url $url): ?string { if ($this->presenter != $request->getPresenterName()) { return null; } $base_url = $url->getBaseUrl(); $action = $request->getParameter('action'); $parameters = $request->getParameters(); unset($parameters['action']); $path = ltrim($this->getPath(), '/'); if (array_search($action, $this->actions, true) === false) { return null; } foreach ($parameters as $name => $value) { if (strpos($path, "<{$name}>") !== false && $value !== null) { $path = str_replace("<{$name}>", $value, $path); unset($parameters[$name]); } } $path = preg_replace_callback('/\[.+?\]/', function ($item) { if (strpos(end($item), '<')) { return ''; } return end($item); }, $path); /** * There are still some required parameters in url mask */ if (preg_match('/<\w+>/', $path)) { return null; } $path = str_replace(['[', ']'], '', $path); $query = http_build_query($parameters); return $base_url . $path . ($query ? '?' . $query : ''); }
Constructs absolute URL from Request object.
entailment
public function publish($params) { $payload = null; if (is_string($params)) { $payload = ["campaign" => $params]; } elseif (is_object($params) || is_array($params)) { $payload = $params; } return $this->client->post("/vouchers/publish", $payload, null); }
@param string|array|stdClass $params Campaign name or params object Publish voucher. @throws \Voucherify\ClientException
entailment
public function getError() { return (object) [ "code" => $this->getCode(), "message" => $this->getMessage(), "details" => $this->getDetails(), "key" => $this->getKey() ]; }
Get client error data @return {stdClass} Client error data
entailment
public function validateVoucher($code, $params = null) { return $this->client->post("/vouchers/" . rawurlencode($code) . "/validate", $params); }
@param string $code Voucher code @param array|stdClass $params Params object Validate voucher. @throws \Voucherify\ClientException
entailment
public function validate($params, $context = null) { $validatePromotion = is_array($params) || is_object($params); if ($validatePromotion) { return $this->promotions->validate($params); } return $this->validateVoucher($params, $context); }
@param string|array|stdClass $params Voucher code or Promotion data @param array|stdClass $context Voucher validation context data Validate voucher or promotion. @throws \Voucherify\ClientException
entailment
public function rollback($redemptionId, $trackingId = null, $reason = null) { $params = (object)[]; $params->tracking_id = $trackingId; $params->reason = $reason; return $this->redemptions->rollback($redemptionId, $params); }
@param string $redemptionId @param string|null $trackingId @param string|null $reason Rollback redemption. This operation creates a rollback entry in voucher's redemption history (`redemption.redemption_entries`) and gives 1 redemption back to the pool (decreases `redeemed_quantity` by 1). @throws \Voucherify\ClientException
entailment
public function fetch($method, $url, $call, array $additional = array()) { // Get the signed request URL $request = $this->getSignedRequest($method, $url, $call, $additional); // Initialise and execute a cURL request $handle = curl_init($request['url']); // Get the default options array $options = $this->defaultOptions; $options[CURLOPT_CAINFO] = dirname(__FILE__) . '/ca-bundle.pem'; if ($method == 'GET' && $this->outFile) { // GET $options[CURLOPT_RETURNTRANSFER] = false; $options[CURLOPT_HEADER] = false; $options[CURLOPT_FILE] = $this->outFile; $options[CURLOPT_BINARYTRANSFER] = true; $this->outFile = null; } elseif ($method == 'POST') { // POST $options[CURLOPT_POST] = true; $options[CURLOPT_POSTFIELDS] = $request['postfields']; } elseif ($method == 'PUT' && $this->inFile) { // PUT $options[CURLOPT_PUT] = true; $options[CURLOPT_INFILE] = $this->inFile; // @todo Update so the data is not loaded into memory to get its size $options[CURLOPT_INFILESIZE] = strlen(stream_get_contents($this->inFile)); fseek($this->inFile, 0); $this->inFile = null; } // Set the cURL options at once curl_setopt_array($handle, $options); // Execute, get any error and close $response = curl_exec($handle); $error = curl_error($handle); curl_close($handle); //Check if a cURL error has occured if ($response === false) { throw new CurlException($error); } else { // Parse the response if it is a string if (is_string($response)) { $response = $this->parse($response); } // Set the last response $this->lastResponse = $response; // The API doesn't return an error message for the 304 status code... // 304's are only returned when the path supplied during metadata calls has not been modified if ($response['code'] == 304) { $response['body'] = new \stdClass; $response['body']->error = 'The folder contents have not changed'; } // Check if an error occurred and throw an Exception if (!empty($response['body']->error)) { // Dropbox returns error messages inconsistently... if ($response['body']->error instanceof \stdClass) { $array = array_values((array) $response['body']->error); $message = $array[0]; } else { $message = $response['body']->error; } // Throw an Exception with the appropriate with the appropriate message and code switch ($response['code']) { case 304: throw new NotModifiedException($message, 304); case 400: throw new BadRequestException($message, 400); case 404: throw new NotFoundException($message, 404); case 406: throw new NotAcceptableException($message, 406); case 415: throw new UnsupportedMediaTypeException($message, 415); default: throw new Exception($message, $response['code']); } } return $response; } }
Execute an API call @todo Improve error handling @param string $method The HTTP method @param string $url The API endpoint @param string $call The API method to call @param array $additional Additional parameters @return string|object stdClass
entailment
private function parse($response) { // Explode the response into headers and body parts (separated by double EOL) list($headers, $response) = explode("\r\n\r\n", $response, 2); // Explode response headers $lines = explode("\r\n", $headers); // If the status code is 100, the API server must send a final response // We need to explode the response again to get the actual response if (preg_match('#^HTTP/1.1 100#', $lines[0])) { list($headers, $response) = explode("\r\n\r\n", $response, 2); $lines = explode("\r\n", $headers); } // Get the HTTP response code from the first line $first = array_shift($lines); $pattern = '#^HTTP/1.1 ([0-9]{3})#'; preg_match($pattern, $first, $matches); $code = $matches[1]; // Parse the remaining headers into an associative array $headers = array(); foreach ($lines as $line) { list($k, $v) = explode(': ', $line, 2); $headers[strtolower($k)] = $v; } // If the response body is not a JSON encoded string // we'll return the entire response body if (!$body = json_decode($response)) { $body = $response; } return array('code' => $code, 'body' => $body, 'headers' => $headers); }
Parse a cURL response @param string $response @return array
entailment
public function encrypt($token) { $iv = mcrypt_create_iv(self::IV_SIZE, self::IV_SOURCE); $cipherText = mcrypt_encrypt(self::CIPHER, $this->key, $token, self::MODE, $iv); return base64_encode($iv . $cipherText); }
Encrypt the OAuth token @param \stdClass $token Serialized token object @return string
entailment
public function decrypt($cipherText) { $cipherText = base64_decode($cipherText); $iv = substr($cipherText, 0, self::IV_SIZE); $cipherText = substr($cipherText, self::IV_SIZE); $token = mcrypt_decrypt(self::CIPHER, $this->key, $cipherText, self::MODE, $iv); return $token; }
Decrypt the ciphertext @param string $cipherText @return object \stdClass Unserialized token
entailment
public function connect($host, $db, $user, $pass, $port = 3306) { $dsn = 'mysql:host=' . $host . ';port=' . $port . ';dbname=' . $db; $this->pdo = new \PDO($dsn, $user, $pass, $this->options); }
Connect to the database @param string $host Database server hostname @param string $db Database to connect to @param string $user Database username @param string $pass Database user password @param int $port Database server port (Default: 3306) @return void
entailment
public function get($type) { if ($type != 'request_token' && $type != 'access_token') { throw new \Dropbox\Exception("Expected a type of either 'request_token' or 'access_token', got '$type'"); } elseif ($type == 'request_token') { return parent::get($type); } elseif ($token = parent::get($type)) { return $token; } else { try { $query = 'SELECT uid, userID, token FROM ' . $this->table . ' WHERE userID = ? LIMIT 1'; $stmt = $this->pdo->prepare($query); $stmt->execute(array($this->userID)); if ($result = $stmt->fetch()) { $token = $this->decrypt($result['token']); $_SESSION[$this->namespace][$this->userID][$type] = $result['token']; return $token; } } catch (\PDOException $e) { // Fetch error information from the statement handle $errorInfo = $stmt->errorInfo(); // Handle the PDOException based on the error code switch ($errorInfo[1]) { case 1146: // Table does not exist $this->createTable(); break; default: // Rethrow the PDOException throw $e; } } return false; } }
Get an OAuth token from the database or session (see below) Request tokens are stored in the session, access tokens in the database Once a token is retrieved it will be stored in the users session for subsequent requests to reduce overheads @param string $type Token type to retrieve @return array|bool
entailment
public function set($token, $type) { if ($type != 'request_token' && $type != 'access_token') { $message = "Expected a type of either 'request_token' or 'access_token', got '$type'"; throw new \Dropbox\Exception($message); } elseif ($type == 'request_token') { parent::set($token, $type); } else { $query = 'INSERT INTO ' . $this->table . ' (userID, token) VALUES (?, ?) ON DUPLICATE KEY UPDATE token = ?'; $stmt = $this->pdo->prepare($query); $token = $this->encrypt($token); $stmt->execute(array($this->userID, $token, $token)); $_SESSION[$this->namespace][$this->userID][$type] = $token; } }
Set an OAuth token in the database or session (see below) Request tokens are stored in the session, access tokens in the database @param \stdClass Token object to set @param string $type Token type @return void
entailment
public function delete() { try { parent::delete(); $query = 'DELETE FROM ' . $this->table . ' WHERE userID = ?'; $stmt = $this->pdo->prepare($query); $stmt->execute(array($this->userID)); return $stmt->rowCount() > 0; } catch(\PDOException $e) { return false; } }
Delete access token for the current user ID from the database @todo Add error checking @return bool
entailment
protected function createTable() { $template = file_get_contents(dirname(__FILE__) . '/TableSchema.sql'); $this->pdo->query(sprintf($template, $this->table)); }
Attempt to create the OAuth token table @return void
entailment
public function get($type) { if ($type != 'request_token' && $type != 'access_token') { throw new \Dropbox\Exception("Expected a type of either 'request_token' or 'access_token', got '$type'"); } else { if (isset($_SESSION[$this->namespace][$this->userID][$type])) { $token = $this->decrypt($_SESSION[$this->namespace][$this->userID][$type]); return $token; } return false; } }
Get an OAuth token from the session If the encrpytion object is set then decrypt the token before returning @param string $type Token type to retrieve @return array|bool
entailment
public function set($token, $type) { if ($type != 'request_token' && $type != 'access_token') { throw new \Dropbox\Exception("Expected a type of either 'request_token' or 'access_token', got '$type'"); } else { $token = $this->encrypt($token); $_SESSION[$this->namespace][$this->userID][$type] = $token; } }
Set an OAuth token in the session by type If the encryption object is set then encrypt the token before storing @param \stdClass Token object to set @param string $type Token type @return void
entailment
protected function encrypt($token) { // Serialize the token object $token = serialize($token); // Encrypt the token if there is an Encrypter instance if ($this->encrypter instanceof Encrypter) { $token = $this->encrypter->encrypt($token); } // Return the token return $token; }
Use the Encrypter to encrypt a token and return it If there is not encrypter object, return just the serialized token object for storage @param stdClass $token OAuth token to encrypt @return stdClass|string
entailment
protected function decrypt($token) { // Decrypt the token if there is an Encrypter instance if ($this->encrypter instanceof Encrypter) { $token = $this->encrypter->decrypt($token); } // Return the unserialized token return @unserialize($token); }
Decrypt a token using the Encrypter object and return it If there is no Encrypter object, assume the token was stored serialized and return the unserialized token object @param stdClass $token OAuth token to encrypt @return stdClass|string
entailment
public function setDirectory($dir) { if(!is_dir($dir) && !mkdir($dir, 0775, true)) { throw new \Dropbox\Exception('Unable to create directory ' . $dir); } else { $this->tokenDirectory = $dir; } }
Set the directory to store OAuth tokens This method MUST be called after instantiating the storage handler to avoid creating tokens in potentially vulnerable locations (i.e. inside web root) @param string $dir Path to token storage directory
entailment
public function get($type) { if ($type != 'request_token' && $type != 'access_token') { throw new \Dropbox\Exception("Expected a type of either 'request_token' or 'access_token', got '$type'"); } elseif ($type == 'request_token') { return parent::get($type); } elseif ($token = parent::get($type)) { return $token; } else { $file = $this->getTokenFilePath(); if(file_exists($file) && $token = file_get_contents($file)) { $_SESSION[$this->namespace][$this->userID][$type] = $token; return $this->decrypt($token); } return false; } }
Get an OAuth token from the file or session (see below) Request tokens are stored in the session, access tokens in the file Once a token is retrieved it will be stored in the user's session for subsequent requests to reduce overheads @param string $type Token type to retrieve @return array|bool
entailment
public function set($token, $type) { if ($type != 'request_token' && $type != 'access_token') { throw new \Dropbox\Exception("Expected a type of either 'request_token' or 'access_token', got '$type'"); } elseif ($type == 'request_token') { parent::set($token, $type); } else { $token = $this->encrypt($token); $file = $this->getTokenFilePath(); file_put_contents($file, $token); $_SESSION[$this->namespace][$this->userID][$type] = $token; } }
Set an OAuth token in the file or session (see below) Request tokens are stored in the session, access tokens in the file @param \stdClass Token object to set @param string $type Token type @return void
entailment
public function delete() { parent::delete(); $file = $this->getTokenFilePath(); return file_exists($file) && @unlink($file); }
Delete the access token stored on disk for the current user ID @return bool
entailment
private function getTokenFilePath() { if ($this->tokenDirectory === null) { throw new \Dropbox\Exception('OAuth token directory not set. See Filesystem::setDirectory()'); } else { return $this->tokenDirectory . '/' . md5($this->userID) . '.token'; } }
Get the token file path for the specified user ID @return string
entailment
public function putFile($file, $filename = false, $path = '', $overwrite = true) { if (file_exists($file)) { if (filesize($file) <= 157286400) { $call = 'files/' . $this->root . '/' . $this->encodePath($path); // If no filename is provided we'll use the original filename $filename = (is_string($filename)) ? $filename : basename($file); $params = array( 'filename' => $filename, 'file' => '@' . str_replace('\\', '/', $file) . ';filename=' . $filename, 'overwrite' => (int) $overwrite, ); $response = $this->fetch('POST', self::CONTENT_URL, $call, $params); return $response; } throw new Exception('File exceeds 150MB upload limit'); } // Throw an Exception if the file does not exist throw new Exception('Local file ' . $file . ' does not exist'); }
Uploads a physical file from disk Dropbox impose a 150MB limit to files uploaded via the API. If the file exceeds this limit or does not exist, an Exception will be thrown @param string $file Absolute path to the file to be uploaded @param string|bool $filename The destination filename of the uploaded file @param string $path Path to upload the file to, relative to root @param boolean $overwrite Should the file be overwritten? (Default: true) @return object stdClass
entailment
public function putStream($stream, $filename, $overwrite = true) { $this->OAuth->setInFile($stream); $path = $this->encodePath($filename); $call = 'files_put/' . $this->root . '/' . $path; $params = array('overwrite' => (int) $overwrite); $response = $this->fetch('PUT', self::CONTENT_URL, $call, $params); return $response; }
Uploads file data from a stream Note: This function is experimental and requires further testing @todo Add filesize check @param resource $stream A readable stream created using fopen() @param string $filename The destination filename, including path @param boolean $overwrite Should the file be overwritten? (Default: true) @return array
entailment
public function chunkedUpload($file, $filename = false, $path = '', $overwrite = true, $offset = 0, $uploadID = null) { if (file_exists($file)) { if ($handle = @fopen($file, 'r')) { // Seek to the correct position on the file pointer fseek($handle, $offset); // Read from the file handle until EOF, uploading each chunk while ($data = fread($handle, $this->chunkSize)) { // Open a temporary file handle and write a chunk of data to it $chunkHandle = fopen('php://temp', 'rw'); fwrite($chunkHandle, $data); // Set the file, request parameters and send the request $this->OAuth->setInFile($chunkHandle); $params = array('upload_id' => $uploadID, 'offset' => $offset); try { // Attempt to upload the current chunk $response = $this->fetch('PUT', self::CONTENT_URL, 'chunked_upload', $params); } catch (Exception $e) { $response = $this->OAuth->getLastResponse(); if ($response['code'] == 400) { // Incorrect offset supplied, return expected offset and upload ID $uploadID = $response['body']->upload_id; $offset = $response['body']->offset; return array('uploadID' => $uploadID, 'offset' => $offset); } else { // Re-throw the caught Exception throw $e; } } // On subsequent chunks, use the upload ID returned by the previous request if (isset($response['body']->upload_id)) { $uploadID = $response['body']->upload_id; } // Set the data offset if (isset($response['body']->offset)) { $offset = $response['body']->offset; } // Close the file handle for this chunk fclose($chunkHandle); } // Complete the chunked upload $filename = (is_string($filename)) ? $filename : basename($file); $call = 'commit_chunked_upload/' . $this->root . '/' . $this->encodePath(rtrim($path, '/') . '/' . $filename); $params = array('overwrite' => (int) $overwrite, 'upload_id' => $uploadID); $response = $this->fetch('POST', self::CONTENT_URL, $call, $params); return $response; } else { throw new Exception('Could not open ' . $file . ' for reading'); } } // Throw an Exception if the file does not exist throw new Exception('Local file ' . $file . ' does not exist'); }
Uploads large files to Dropbox in mulitple chunks @param string $file Absolute path to the file to be uploaded @param string|bool $filename The destination filename of the uploaded file @param string $path Path to upload the file to, relative to root @param boolean $overwrite Should the file be overwritten? (Default: true) @return stdClass
entailment
public function getFile($file, $outFile = false, $revision = null) { // Only allow php response format for this call if ($this->responseFormat !== 'php') { throw new Exception('This method only supports the `php` response format'); } $handle = null; if ($outFile !== false) { // Create a file handle if $outFile is specified if (!$handle = fopen($outFile, 'w')) { throw new Exception("Unable to open file handle for $outFile"); } else { $this->OAuth->setOutFile($handle); } } $file = $this->encodePath($file); $call = 'files/' . $this->root . '/' . $file; $params = array('rev' => $revision); $response = $this->fetch('GET', self::CONTENT_URL, $call, $params); // Close the file handle if one was opened if ($handle) fclose($handle); return array( 'name' => ($outFile) ? $outFile : basename($file), 'mime' => $this->getMimeType(($outFile) ?: $response['body'], $outFile), 'meta' => json_decode($response['headers']['x-dropbox-metadata']), 'data' => $response['body'], ); }
Downloads a file Returns the base filename, raw file data and mime type returned by Fileinfo @param string $file Path to file, relative to root, including path @param string $outFile Filename to write the downloaded file to @param string $revision The revision of the file to retrieve @return array
entailment
public function metaData($path = null, $rev = null, $limit = 10000, $hash = false, $list = true, $deleted = false) { $call = 'metadata/' . $this->root . '/' . $this->encodePath($path); $params = array( 'file_limit' => ($limit < 1) ? 1 : (($limit > 10000) ? 10000 : (int) $limit), 'hash' => (is_string($hash)) ? $hash : 0, 'list' => (int) $list, 'include_deleted' => (int) $deleted, 'rev' => (is_string($rev)) ? $rev : null, ); $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Retrieves file and folder metadata @param string $path The path to the file/folder, relative to root @param string $rev Return metadata for a specific revision (Default: latest rev) @param int $limit Maximum number of listings to return @param string $hash Metadata hash to compare against @param bool $list Return contents field with response @param bool $deleted Include files/folders that have been deleted @return object stdClass
entailment
public function delta($cursor = null) { $call = 'delta'; $params = array('cursor' => $cursor); $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Return "delta entries", intructing you how to update your application state to match the server's state Important: This method does not make changes to the application state @param null|string $cursor Used to keep track of your current state @return array Array of delta entries
entailment
public function revisions($file, $limit = 10) { $call = 'revisions/' . $this->root . '/' . $this->encodePath($file); $params = array( 'rev_limit' => ($limit < 1) ? 1 : (($limit > 1000) ? 1000 : (int) $limit), ); $response = $this->fetch('GET', self::API_URL, $call, $params); return $response; }
Obtains metadata for the previous revisions of a file @param string Path to the file, relative to root @param integer Number of revisions to return (1-1000) @return array
entailment
public function restore($file, $revision) { $call = 'restore/' . $this->root . '/' . $this->encodePath($file); $params = array('rev' => $revision); $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Restores a file path to a previous revision @param string $file Path to the file, relative to root @param string $revision The revision of the file to restore @return object stdClass
entailment
public function search($query, $path = '', $limit = 1000, $deleted = false) { $call = 'search/' . $this->root . '/' . $this->encodePath($path); $params = array( 'query' => $query, 'file_limit' => ($limit < 1) ? 1 : (($limit > 1000) ? 1000 : (int) $limit), 'include_deleted' => (int) $deleted, ); $response = $this->fetch('GET', self::API_URL, $call, $params); return $response; }
Returns metadata for all files and folders that match the search query @param mixed $query The search string. Must be at least 3 characters long @param string $path The path to the folder you want to search in @param integer $limit Maximum number of results to return (1-1000) @param boolean $deleted Include deleted files/folders in the search @return array
entailment
public function shares($path, $shortUrl = true) { $call = 'shares/' . $this->root . '/' .$this->encodePath($path); $params = array('short_url' => ($shortUrl) ? 1 : 0); $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Creates and returns a shareable link to files or folders The link returned is for a preview page from which the user an choose to download the file if they wish. For direct download links, see media(). @param string $path The path to the file/folder you want a sharable link to @return object stdClass
entailment
public function media($path) { $call = 'media/' . $this->root . '/' . $this->encodePath($path); $response = $this->fetch('POST', self::API_URL, $call); return $response; }
Returns a link directly to a file @param string $path The path to the media file you want a direct link to @return object stdClass
entailment
public function thumbnails($file, $format = 'JPEG', $size = 'small') { // Only allow php response format for this call if ($this->responseFormat !== 'php') { throw new Exception('This method only supports the `php` response format'); } $format = strtoupper($format); // If $format is not 'PNG', default to 'JPEG' if ($format != 'PNG') $format = 'JPEG'; $size = strtolower($size); $sizes = array('s', 'm', 'l', 'xl', 'small', 'medium', 'large'); // If $size is not valid, default to 'small' if (!in_array($size, $sizes)) $size = 'small'; $call = 'thumbnails/' . $this->root . '/' . $this->encodePath($file); $params = array('format' => $format, 'size' => $size); $response = $this->fetch('GET', self::CONTENT_URL, $call, $params); return array( 'name' => basename($file), 'mime' => $this->getMimeType($response['body']), 'meta' => json_decode($response['headers']['x-dropbox-metadata']), 'data' => $response['body'], ); }
Gets a thumbnail for an image @param string $file The path to the image you wish to thumbnail @param string $format The thumbnail format, either JPEG or PNG @param string $size The size of the thumbnail @return array
entailment
public function copy($from, $to, $fromCopyRef = null) { $call = 'fileops/copy'; $params = array( 'root' => $this->root, 'from_path' => $this->normalisePath($from), 'to_path' => $this->normalisePath($to), ); if ($fromCopyRef) { $params['from_path'] = null; $params['from_copy_ref'] = $fromCopyRef; } $response = $this->fetch('POST', self::API_URL, $call, $params); return $response; }
Copies a file or folder to a new location @param string $from File or folder to be copied, relative to root @param string $to Destination path, relative to root @param null|string $fromCopyRef Must be used instead of the from_path @return object stdClass
entailment