sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
protected function parseTransactionDebitCredit() { $results = []; if (preg_match('/^:61:\d+([CD])\d+/', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeDebitCredit($results[1]); } return ''; }
uses the 61 field to determine debit or credit of the transaction. @return string
entailment
protected function parseTransactionDescription() { $results = []; if (preg_match_all('/[\n]:86:(.*?)(?=\n(:6([12]))|$)/s', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeDescription(implode(PHP_EOL, $results[1])); } return ''; }
uses the 86 field to determine retrieve the full description of the transaction. @return string
entailment
protected function parseTransactionTimestamp($key) { $results = []; if (preg_match('/^:' . $key . ':(\d{6})/', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeTimestamp($results[1]); } return 0; }
This does the actual parsing of the transaction timestamp for given $key. @param string $key @return int
entailment
protected function parseTransactionCode() { $results = []; if (preg_match('/^:61:.*?N(.{3}).*/', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return trim($results[1]); } return ''; }
uses the 61 field to get the bank specific transaction code. @return string
entailment
protected function sanitizeAccount($string) { static $crudeReplacements = [ '.' => '', ' ' => '', 'GIRO' => 'P', ]; // crude IBAN to 'old' converter if (Mt940::$removeIBAN && preg_match('#[A-Z]{2}[\d]{2}[A-Z]{4}(.*)#', $string, $results) && !empty($results[1]) ) { $string = $results[1]; } $account = ltrim( str_replace( array_keys($crudeReplacements), $crudeReplacements, strip_tags(trim($string)) ), '0' ); if ($account !== '' && strlen($account) < 9 && strpos($account, 'P') === false) { $account = 'P' . $account; } return $account; }
@param string $string @return string
entailment
protected function sanitizeTimestamp($string, $inFormat = 'ymd') { $date = \DateTime::createFromFormat($inFormat, $string); $date->setTime(0, 0); if ($date !== false) { return (int)$date->format('U'); } return 0; }
@param string $string @param string $inFormat @return int
entailment
protected function sanitizeDebitCredit($string) { $debitOrCredit = strtoupper(substr((string)$string, 0, 1)); if ($debitOrCredit !== Transaction::DEBIT && $debitOrCredit !== Transaction::CREDIT) { trigger_error('wrong value for debit/credit (' . $string . ')', E_USER_ERROR); $debitOrCredit = ''; } return $debitOrCredit; }
@param string $string @return string
entailment
protected function sanitizePrice($string) { $floatPrice = ltrim(str_replace(',', '.', strip_tags(trim($string))), '0'); return (float)$floatPrice; }
@param string $string @return float
entailment
public static function isApplicable($string) { $firstline = strtok($string, "\r\n\t"); $secondline = strtok("\r\n\t"); return strpos($firstline, ':20:STARTUMS') !== false || ($firstline === '-' && $secondline === ':20:STARTUMS'); }
Overloaded: Is applicable if first or second line has :20:STARTUMS or first line has -. @inheritdoc
entailment
protected function parseTransactionAccount() { $results = []; // SEPA MT940 Structured if (preg_match('/^:61:.*\n(.*?)(\n|\:8)/im', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccount($results[1]); } if (preg_match('/^:61:.{26}(.{16})/m', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccount($results[1]); } return ''; }
Overloaded: Rabo has different way of storing account info. @inheritdoc
entailment
protected function parseTransactionAccountName() { $results = []; // SEPA MT940 Structured if (preg_match('#/NAME/(.+?)\n?/(REMI|ADDR|ISDT|CSID)/#ms', $this->getCurrentTransactionData(), $results)) { $accountName = trim($results[1]); if (!empty($accountName)) { return $this->sanitizeAccountName($accountName); } } if (preg_match('/^:61:.*? (.+)/m', $this->getCurrentTransactionData(), $results)) { $accountName = trim($results[1]); if (!empty($accountName)) { return $this->sanitizeAccountName($accountName); } } if (preg_match('/(.*) Betaalautomaat/', $this->parseTransactionDescription(), $results)) { $accountName = trim($results[1]); if (!empty($accountName)) { return $this->sanitizeAccountName($accountName); } } return ''; }
Overloaded: Rabo has different way of storing account name. @inheritdoc
entailment
protected function parseTransactionEntryTimestamp() { $results = []; if (preg_match('/^:60F:[C|D]([\d]{6})/m', $this->getCurrentStatementData(), $results) && !empty($results[1])) { return $this->sanitizeTimestamp($results[1]); } return 0; }
Overloaded: Rabo has different way of storing transaction value timestamps (ymd). @inheritdoc
entailment
protected function parseTransactionValueTimestamp() { $results = []; if (preg_match('/^:61:([\d]{6})[C|D]/', $this->getCurrentTransactionData(), $results) && !empty($results[1])) { return $this->sanitizeTimestamp($results[1]); } return 0; }
Overloaded: Rabo has different way of storing transaction value timestamps (ymd). @inheritdoc
entailment
protected function sanitizeAccount($string) { $account = parent::sanitizeAccount($string); if (strlen($account) > 20 && strpos($account, '80000') === 0) { $account = substr($account, 5); } return $account; }
Overloaded: Rabo uses longer strings for accountnumbers. @inheritdoc
entailment
public function bootstrap(Application $app) { $items = []; $app->instance('config', $config = new Repository($items)); $this->loadConfigurationFiles($app, $config); mb_internal_encoding('UTF-8'); }
Bootstrap the given application. @param \Illuminate\Contracts\Foundation\Application $app @return void
entailment
protected function loadConfigurationFiles(Application $app, RepositoryContract $config) { foreach ($this->getConfigurationFiles($app) as $key => $path) { $config->set($key, require $path); } }
Load the configuration items from all of the files. @param \Illuminate\Contracts\Foundation\Application $app @param \Illuminate\Contracts\Config\Repository $config @return void
entailment
protected function parseStatementAccount() { $results = []; if (preg_match('#:25:TRIODOSBANK/([\d\.]+)#', $this->getCurrentStatementData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccount($results[1]); } return parent::parseStatementAccount(); }
Overloaded: the bankaccount is always prefixed. @inheritdoc
entailment
protected function parseTransactionAccount() { $parts = $this->getDescriptionParts(); $account = $parts[0]; if (preg_match('#[A-Z]{2}[\d]{2}[A-Z]{4}(.*)#', $parts[2], $results)) { $account = $parts[2]; } elseif (preg_match('#10(\d+)#', $parts[0], $results)) { $account = $results[1]; } return $this->sanitizeAccount($account); }
Overloaded: It might be IBAN or not and depending on that return a different part of the description. @inheritdoc
entailment
protected function parseTransactionDescription() { $parts = $this->getTransactionAccountParts(); foreach ($parts as &$part) { $part = substr($part, 2); } return $this->sanitizeDescription(implode('', $parts)); }
Crude parsing of the combined iban / non iban description field. @inheritdoc
entailment
public static function isApplicable($string) { static $token = "\r\n\t"; /** @noinspection UnusedFunctionResultInspection */ strtok($string, $token); $secondline = strtok($token); return strpos($secondline, ':25:TRIODOSBANK') !== false; }
Overloaded: Is applicable if second line has :25:TRIODOSBANK. @inheritdoc
entailment
private function slugify($string, $replacement = '-', $lowercase = true) { $transliterateOptions = $this->transliterateOptions !== null ? $this->transliterateOptions : 'Any-Latin; Latin-ASCII; NFD; [:Nonspacing Mark:] Remove; NFKC;'; return (new Slugifier($transliterateOptions, $replacement, $lowercase))->slugify($string); }
@param string $string @param string $replacement @param bool $lowercase @return string
entailment
protected function generateUniqueSlug($baseSlug, $iteration) { return is_callable($this->uniqueSlugGenerator) ? call_user_func($this->uniqueSlugGenerator, $baseSlug, $iteration, $this->owner) : $baseSlug . $this->replacement . ($iteration + 1); }
@param string $baseSlug @param int $iteration @return string
entailment
protected function parseTransactionAccount() { $account = parent::parseTransactionAccount(); if ($account !== '') { return $account; } // IBAN $transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData()); $transactionData = preg_replace('![\r\n]+!', '', $transactionData); if (preg_match('#/CNTP/(.*?)/#', $transactionData, $results)) { $account = trim($results[1]); if (!empty($account)) { return $this->sanitizeAccount($account); } } if (preg_match('#:86:([A-Z]{2}[\d]{2}[A-Z]{4}[\d]+?) [A-Z]{6}[A-Z0-9]{0,4} #', $transactionData, $results)) { $account = trim($results[1]); if (!empty($account)) { return $this->sanitizeAccount($account); } } return ''; }
Overloaded: Added simple IBAN transaction handling. @inheritdoc
entailment
protected function parseTransactionAccountName() { $name = parent::parseTransactionAccountName(); if ($name !== '') { return $name; } // IBAN $transactionData = str_replace('Europese Incasso, doorlopend ', '', $this->getCurrentTransactionData()); $transactionData = preg_replace('![\r\n]+!', '', $transactionData); if (preg_match('#/CNTP/[^/]*/[^/]*/(.*?)/#', $transactionData, $results)) { $name = trim($results[1]); if (!empty($name)) { return $this->sanitizeAccountName($name); } } if (preg_match('#:86:.*? [^ ]+ (.*)#', $transactionData, $results) !== 1) { return ''; } return $this->parseNameFromTransactionData($results[1]); }
Overloaded: Added simple IBAN transaction handling. @inheritdoc
entailment
private function parseNameFromTransactionData($transactionData) { if (preg_match('#(.*) (Not-Provided|NOTPROVIDED)#', $transactionData, $results) === 1) { $name = trim($results[1]); if (!empty($name)) { return $this->sanitizeAccountName($name); } } if (preg_match('#\D+#', $transactionData, $results)) { $name = trim($results[0]); if (!empty($name)) { return $this->sanitizeAccountName($name); } } return ''; }
@param $transactionData @return string
entailment
protected function sanitizeDescription($string) { $description = parent::sanitizeDescription($string); if (strpos($description, '/REMI/USTD//') !== false && preg_match('#/REMI/USTD//(.*?)/#s', $description, $results) && !empty($results[1]) ) { return $results[1]; } if (strpos($description, '/REMI/STRD/CUR/') !== false && preg_match('#/REMI/STRD/CUR/(.*?)/#s', $description, $results) && !empty($results[1]) ) { return $results[1]; } return $description; }
Overloaded: ING encapsulates the description with /REMI/ for SEPA. @inheritdoc
entailment
protected function parseTransactionAccount() { $results = parent::parseTransactionAccount(); if (empty($results)) { $giroMatch = $ibanMatch = []; if (preg_match('/^:86:GIRO(.{9})/im', $this->getCurrentTransactionData(), $giroMatch) && !empty($giroMatch[1]) ) { $results = $giroMatch[1]; } if (preg_match('!^:86:/.*/IBAN/(.*?)/!m', $this->getCurrentTransactionData(), $ibanMatch) && !empty($ibanMatch[1]) ) { $results = $ibanMatch[1]; } } return $this->sanitizeAccount($results); }
Overloaded: ABN Amro shows the GIRO includes fix for 'for GIRO 1234567 TEST 201009063689 CLIEOP 21-9' and translates that into 1234567. @inheritdoc
entailment
protected function parseTransactionAccountName() { $results = parent::parseTransactionAccountName(); if ($results !== '') { return $results; } $results = []; if (preg_match('/:86:(GIRO|BGC\.)\s+[\d]+ (.+)/', $this->getCurrentTransactionData(), $results) && !empty($results[2]) ) { return $this->sanitizeAccountName($results[2]); } if (preg_match('/:86:.+\n(.*)\n/', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { return $this->sanitizeAccountName($results[1]); } return ''; }
Overloaded: ABN Amro shows the GIRO and fixes newlines etc. @inheritdoc
entailment
protected function parseTransactionEntryTimestamp() { $results = []; if (preg_match('/^:61:(\d{2})((\d{2})\d{2})((\d{2})\d{2})[C|D]/', $this->getCurrentTransactionData(), $results) && !empty($results[1]) ) { list(, $valueDateY, $valueDateMD, $valueDateM, $entryDateMD, $entryDateM) = $results; $entryDate = $valueDateY . $entryDateMD; if ($valueDateMD !== $entryDateMD && $valueDateM > $entryDateM) { $entryDate = ($valueDateY + 1) . $entryDateMD; } return $this->sanitizeTimestamp($entryDate); } return 0; }
Overloaded: ABNAMRO uses the :61: date-part of the field for two values: Valuetimestamp (YYMMDD) and Entry date (book date) (MMDD). @return int
entailment
public static function serve($host = '127.0.0.1', $port = 8000): void { static::stopServing(); $server = new DuskServer($host, $port); $server->stash(['class' => static::class]); $server->start(); static::$server = $server; }
Begin serving on a given host and port. @param string $host @param int $port @return void @throws \Orchestra\Testbench\Dusk\Exceptions\UnableToStartServer
entailment
public function tweakApplication(Closure $closure): void { $closure($this->app); static::$server->stash([ 'class' => static::class, 'tweakApplication' => serialize(SerializableClosure::from($closure)), ]); }
Make tweaks to the application, both inside the test and on the test server. @param \Closure $closure @return void
entailment
public function getFreshApplicationToServe(DuskServer $server) { static::$server = $server; $this->setUpDuskServer(); $serializedClosure = static::$server->getStash('tweakApplication'); if ($serializedClosure) { $closure = unserialize($serializedClosure)->getClosure(); $closure($this->app); } return $this->app; }
Build up a fresh application to serve, intended for use when we want to replicate the Application state during a Dusk test when we start our test server. See the main server file 'server.php'. @param \Orchestra\Testbench\Dusk\DuskServer $server @return \Illuminate\Foundation\Application
entailment
public function parse() { $results = []; foreach ($this->parseStatementData() as $this->currentStatementData) { $statement = new Statement(); if ($this->debug) { $statement->rawData = $this->currentStatementData; } $statement->setBank($this->parseStatementBank()); $statement->setAccount($this->parseStatementAccount()); $statement->setStartPrice($this->parseStatementStartPrice()); $statement->setEndPrice($this->parseStatementEndPrice()); $statement->setStartTimestamp($this->parseStatementStartTimestamp()); $statement->setEndTimestamp($this->parseStatementEndTimestamp()); $statement->setNumber($this->parseStatementNumber()); $statement->setCurrency($this->parseStatementCurrency()); foreach ($this->parseTransactionData() as $this->currentTransactionData) { $transaction = new HsbcTransaction(); if ($this->debug) { $transaction->rawData = $this->currentTransactionData; } $transaction->setAccount($this->parseTransactionAccount()); $transaction->setAccountName($this->parseTransactionAccountName()); $transaction->setPrice($this->parseTransactionPrice()); $transaction->setDebitCredit($this->parseTransactionDebitCredit()); $transaction->setCancellation($this->parseTransactionCancellation()); $transaction->setDescription($this->parseTransactionDescription()); $transaction->setValueTimestamp($this->parseTransactionValueTimestamp()); $transaction->setEntryTimestamp($this->parseTransactionEntryTimestamp()); $transaction->setTransactionCode($this->parseTransactionCode()); $transaction->setVirtualAccount($this->parseVirtualAccount()); $statement->addTransaction($transaction); } $results[] = $statement; } return $results; }
Overloaded: add support for virtual account. @return Statement[]
entailment
protected function parseTransactionAccount() { $results = []; // YYMMDD[MMDD]2a[1!a]15d1!a3!c16x[//16x][34x] // eg.: :61:1203290329DD20000,00NTRF1004688128 //6128522200250001 // Reference for the Account Owner (16x): 1004688128 // Reference of the Account Servicing Institution [//16x]: 6128522200250001 // Supplementary Details [34x]: null if (preg_match(self::PATTERN_TAG_61, $this->getCurrentTransactionData(), $results)) { return $this->sanitizeAccount($results[7]); } return ''; }
Overloaded: HSBC has different way of storing account info. {@inheritdoc}
entailment
protected function parseTransactionDebitCredit() { $results = []; if (preg_match(self::PATTERN_TAG_61, $this->getCurrentTransactionData(), $results)) { return $this->sanitizeDebitCredit($results[3]); } return ''; }
Overloaded: debit or credit of the transaction. @return string
entailment
protected function parseTransactionValueTimestamp() { $results = []; if (preg_match(self::PATTERN_TAG_61, $this->getCurrentTransactionData(), $results)) { return $this->sanitizeTimestamp($results[1]); } return 0; }
Overloaded: HSBC has different way of storing transaction value timestamps (ymd). {@inheritdoc}
entailment
public static function isApplicable($string) { $firstline = strtok($string, "\r\n\t"); return strpos($firstline, ':20:AI') !== false && strlen($firstline) === 20; }
Overloaded: Is applicable if first line starts with :20:AI. {@inheritdoc}
entailment
public function getAll(LibraryType $library, string $dir = '/') { $clippedBaseUri = $this->clipUri($this->client->getConfig('base_uri')); $response = $this->client->request( 'GET', $clippedBaseUri . '/repos/' . $library->id . '/dir/', [ 'query' => ['p' => $dir], ] ); $json = json_decode((string)$response->getBody()); $dirItemCollection = []; foreach ($json as $dirItemJson) { $dirItem = (new DirectoryItem)->fromJson($dirItemJson); // if dirItem has no value for "dir", set it here if ($dirItem->dir === '/') { $dirItem = $dirItem->fromArray(['dir' => $dir]); } $dirItemCollection[] = $dirItem; } return $dirItemCollection; }
Get all items of a directory in a library @param LibraryType $library Library type @param string $dir Directory path @return DirectoryItem[] @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function exists(LibraryType $library, string $dirItemName, string $parentDir = '/') { $directoryItems = $this->getAll($library, $parentDir); foreach ($directoryItems as $directoryItem) { if ($directoryItem->name === $dirItemName) { return true; } } return false; }
Check if $dirName exists within $parentDir @param LibraryType $library Library instance @param string $dirItemName DirectoryItem name @param string $parentDir Parent directory @return bool @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function create(LibraryType $library, string $dirName, string $parentDir = '/', bool $recursive = false) { if ($recursive) { $response = false; $parts = explode('/', trim($dirName, '/')); $tmp = []; foreach ($parts as $part) { $parentPath = '/' . implode('/', $tmp); $tmp[] = $part; if ($this->exists($library, $part, $parentPath) === false) { $response = $this->create($library, $part, $parentPath, false); } } return $response; } // only create folder which is not empty to prevent wrong implementation if (empty($dirName)) { return false; } // Do not create folders that already exist if ($this->exists($library, $dirName, $parentDir)) { return false; } $uri = sprintf( '%s/repos/%s/dir/?p=%s/%s', $this->clipUri($this->client->getConfig('base_uri')), $library->id, rtrim($parentDir, '/'), $dirName ); $response = $this->client->request( 'POST', $uri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => [ [ 'name' => 'operation', 'contents' => 'mkdir', ], ], ] ); return $response->getStatusCode() === 201; }
Create directory within $parentDir @param LibraryType $library Library instance @param string $dirName Directory name @param string $parentDir Parent directory @param bool $recursive Recursive create @return bool Success @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function remove(LibraryType $library, string $directoryPath) { // don't allow empty paths if (empty($directoryPath)) { return false; } $uri = sprintf( '%s/repos/%s/dir/?p=%s', $this->clipUri($this->client->getConfig('base_uri')), $library->id, rtrim($directoryPath, '/') ); $response = $this->client->request( 'DELETE', $uri, [ 'headers' => ['Accept' => 'application/json'], ] ); return $response->getStatusCode() === 200; }
Remove a directory @param LibraryType $library Library instance @param string $directoryPath Directory path @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function get($key) { if (isset($this->store[$key])) { return filter_var($this->store[$key], FILTER_SANITIZE_STRING); } return filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_STRING); }
Get cookie with FILTER_SANITIZE_STRING @param string $key @return string|null
entailment
public function getInt($key) { if (isset($this->store[$key])) { return (int) filter_var($this->store[$key], FILTER_SANITIZE_NUMBER_INT); } return (int) filter_input(INPUT_COOKIE, $key, FILTER_SANITIZE_NUMBER_INT); }
Get cookie with FILTER_SANITIZE_NUMBER_INT @param string $key @return int|null
entailment
public function set($key, $value) { $this->store[$key] = $value; return setcookie($key, $value); }
Set a cookie value @param string $key @param mixed $value @return bool
entailment
public function clear($key) { setcookie($key, '', time() - 3600); unset($_COOKIE[$key]); unset($this->store[$key]); return $this; }
Unset the key from the cookie @param string $key @return Cookie
entailment
public function fromArray(array $fromArray) // type is given in derived class { foreach ($fromArray as $key => $value) { $camelCaseKey = CaseHelperFactory::make(CaseHelperFactory::INPUT_TYPE_SNAKE_CASE)->toCamelCase($key); if (!property_exists($this, $camelCaseKey)) { continue; } switch ($key) { case 'creator': $this->{$key} = (new AccountType)->fromArray(['email' => $value]); break; case 'create_time': case 'ctime': case 'mtime': case 'mtime_created': $this->{$camelCaseKey} = $this->getDateTime((int)$value); break; default: $this->{$camelCaseKey} = $value; break; } } return $this; }
Populate from array @param array $fromArray Create from array @return self @throws \Exception
entailment
public function getDateTime(int $value): DateTime { if ($value > 9999999999) { // microseconds it is $value = floor($value / 1000000); } return DateTime::createFromFormat("U", $value); }
Time stamps vary a lot in Seafile. Sometimes it's seconds from 1970-01-01 00:00:00, sometimes it's microseconds. You never know. @param int $value Int time stamp, either seconds or microseconds @return DateTime
entailment
public function toArray(int $mode = self::ARRAY_ASSOC): array { switch ($mode) { case self::ARRAY_MULTI_PART: $caseHelper = CaseHelperFactory::make(CaseHelperFactory::INPUT_TYPE_CAMEL_CASE); $keyVals = $this->toArray(self::ARRAY_ASSOC); $multiPart = []; foreach ($keyVals as $key => $val) { $multiPart[] = ['name' => $caseHelper->toSnakeCase($key), 'contents' => "$val"]; } $array = $multiPart; break; default: $array = array_filter((array)$this); // removes empty values break; } return $array; }
Return instance as array @param int $mode Array mode @return array @throws \Exception
entailment
public function getAll(): array { $response = $this->client->request('GET', $this->client->getConfig('base_uri') . '/shared-links/'); $json = json_decode($response->getBody()); $sharedLinksCollection = []; foreach ($json->fileshares as $sharedLink) { $sharedLinksCollection[] = (new SharedLinkType)->fromJson($sharedLink); } return $sharedLinksCollection; }
List shared links @return SharedLinkType[] @throws Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function remove(SharedLinkType $sharedLinkType): bool { $uri = sprintf( '%s/shared-links/?t=%s', $this->clipUri($this->client->getConfig('base_uri')), basename($sharedLinkType->url) ); $response = $this->client->request( 'DELETE', $uri, [ 'headers' => ['Accept' => 'application/json'], ] ); return $response->getStatusCode() === 200; }
Remove shared link @param SharedLinkType $sharedLinkType SharedLinkType instance @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function create( LibraryType $library, string $path, int $expire = null, string $shareType = SharedLinkType::SHARE_TYPE_DOWNLOAD, string $password = null ): ?SharedLinkType { $uri = sprintf( '%s/repos/%s/file/shared-link/', $this->clipUri($this->client->getConfig('base_uri')), $library->id ); $multiPartParams = [ ['name' => 'p', 'contents' => $path], ['name' => 'share_type', 'contents' => $shareType], ]; if (!is_null($expire)) { $multiPartParams[] = ['name' => 'expire', 'contents' => "$expire"]; } if (!is_null($password)) { $multiPartParams[] = ['name' => 'password', 'contents' => $password]; } $response = $this->client->request( 'PUT', $uri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => $multiPartParams, ] ); if ($response->getStatusCode() !== 201 || $response->hasHeader('Location') === false) { return null; } $url = $response->getHeader('Location')[0]; return (new SharedLinkType)->fromArray([ 'url' => $url, 'expire' => $expire, 'password' => $password, 'path' => $path, 'shareType' => $shareType, ]); }
Create share link @param LibraryType $library Library instance @param string $path Path @param int $expire Expire in such many days @param string $shareType Share type @param string $password Optional password string @return SharedLinkType|null @throws Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function submit(array $data, array $curlOpts = []) { $originalCookie = $this->mautic->getCookie()->getSuperGlobalCookie(); $request = $this->prepareRequest($data); $ch = curl_init($request['url']); curl_setopt($ch, CURLOPT_POST, 1); curl_setopt($ch, CURLOPT_POSTFIELDS, $request['query']); if (isset($request['header'])) { curl_setopt($ch, CURLOPT_HTTPHEADER, $request['header']); } if (isset($request['referer'])) { curl_setopt($ch, CURLOPT_REFERER, $request['referer']); } if (isset($request['cookie'])) { curl_setopt($ch, CURLOPT_COOKIEFILE, $this->mautic->getCookie()->createCookieFile()); } curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); curl_setopt($ch, CURLOPT_VERBOSE, 1); curl_setopt($ch, CURLOPT_HEADER, 1); foreach ($curlOpts as $key => $value) { curl_setopt($ch, $key, $value); } $result = curl_exec($ch); $response = $this->prepareResponse($result); $response['info'] = curl_getinfo($ch); curl_close($ch); $contact = $this->mautic->getContact(); $httpHeader = new HttpHeader($response['header']); $sessionId = $httpHeader->getCookieValue(Cookie::MAUTIC_SESSION_ID); $deviceId = $httpHeader->getCookieValue(Cookie::MAUTIC_DEVICE_ID); $contactId = $httpHeader->getCookieValue($sessionId); if ($sessionId) { $contact->setSessionId($sessionId); } if ($deviceId) { $contact->setDeviceId($deviceId); } if ($contactId) { $contact->setId((int)$contactId); } return [ 'original_cookie' => $originalCookie, 'new_cookie' => $this->mautic->getCookie()->toArray(), 'request' => $request, 'response' => $response, ]; }
Submit the $data array to the Mautic form, using the optional $curlOpts array to override curl settings Returns array containing info about the request, response and cookie @param array $data @param array $curlOpts @return array
entailment
public function prepareRequest(array $data) { $contact = $this->mautic->getContact(); $request = ['header' => []]; $data['formId'] = $this->id; // return has to be part of the form data array so Mautic would accept the submission if (!isset($data['return'])) { $data['return'] = ''; } $request['url'] = $this->getUrl(); $request['data'] = ['mauticform' => $data]; if ($contactId = $contact->getId()) { $request['data']['mtc_id'] = $contactId; } if ($contactIp = $contact->getIp()) { $request['header'][] = "X-Forwarded-For: $contactIp"; $request['header'][] = "Client-Ip: $contactIp"; } if ($sessionId = $contact->getSessionId()) { $request['header'][] = "Cookie: mautic_session_id=$sessionId"; $request['header'][] = "Cookie: mautic_device_id=$sessionId"; } if (isset($_SERVER['HTTP_REFERER'])) { $request['referer'] = $_SERVER["HTTP_REFERER"]; } $request['query'] = http_build_query($request['data']); return $request; }
Prepares data for CURL request based on provided form data, $_COOKIE and $_SERVER @param array $data @return array
entailment
public function prepareResponse($result) { $response = ['header' => null, 'content' => null]; $d = "\r\n\r\n"; // Headers and content delimiter if (is_string($result) && strpos($result, $d) !== false) { list($header, $content) = explode($d, $result, 2); if (stripos($header, '100 Continue') !== false && strpos($content, $d) !== false) { list($header, $content) = explode($d, $content, 2); } $response['header'] = $header; $response['content'] = htmlentities($content); } return $response; }
Process the result and split into headers and content @param string|bool $result @return array
entailment
public function getContactId() { if ($mtcId = $this->getInt(self::MTC_ID)) { return $mtcId; } elseif ($mauticSessionId = $this->getSessionId()) { return $this->getInt($mauticSessionId); } return null; }
Get Mautic Contact ID from Cookie @return int|null
entailment
public function setContactId($contactId) { $this->set(self::MTC_ID, $contactId); if ($sessionId = $this->getSessionId()) { $this->set($sessionId, $contactId); } return $this; }
Set Mautic Contact ID cookies Note: Call setMauticSessionId prior to this @param int $contactId @return Cookie
entailment
public function unsetContactId() { $this->clear(self::MTC_ID); if ($sessionId = $this->getSessionId()) { $this->clear($sessionId); } return $this; }
Unet Mautic Contact ID cookies @return Cookie
entailment
public function getSessionId() { if ($mauticSessionId = $this->get(self::MAUTIC_SESSION_ID)) { return $mauticSessionId; } if ($mauticSessionId = $this->get(self::MTC_SID)) { return $mauticSessionId; } return null; }
Returns Mautic session ID if it exists in the cookie @return string|null
entailment
public function setSessionId($sessionId) { $this->set(self::MAUTIC_SESSION_ID, $sessionId); $this->set(self::MTC_SID, $sessionId); return $this; }
Set Mautic Session ID cookies @param string $sessionId @return Cookie
entailment
public function unsetSessionId() { $this->clear(self::MAUTIC_SESSION_ID); $this->clear(self::MTC_SID); return $this; }
Unset Mautic Session ID cookies @return Cookie
entailment
public function getAll(): array { $response = $this->client->request('GET', $this->resourceUri); $json = json_decode((string)$response->getBody()); $dirItemCollection = []; foreach ($json as $starredFile) { $dirItemCollection[] = (new DirectoryItem)->fromJson($starredFile); } return $dirItemCollection; }
Get all starred files @return DirectoryItem[] @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function star(LibraryType $library, DirectoryItem $dirItem): string { if ($dirItem->type !== 'file') { throw new \Exception('Cannot star other items than files.'); } $response = $this->client->request( 'POST', $this->resourceUri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => [ [ 'name' => 'repo_id', 'contents' => $library->id, ], [ 'name' => 'p', 'contents' => $dirItem->path, ], ], ] ); if ($response->getStatusCode() !== 201 || $response->hasHeader('Location') === false) { throw new \Exception('Could not star file'); } return $response->getHeader('Location')[0]; }
Create directory within $parentDir @param LibraryType $library Library instance @param DirectoryItem $dirItem DirectoryItem instance to star @return string URL of starred file list @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function unstar(LibraryType $library, DirectoryItem $dirItem): bool { $uri = sprintf( '%s/?repo_id=%s&p=%s', $this->resourceUri, $library->id, $dirItem->path ); $response = $this->client->request('DELETE', $uri); return $response->getStatusCode() === 200; }
Unstar a file @param LibraryType $library Library instance @param DirectoryItem $dirItem DirectoryItem instance @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function move( LibraryType $srcLibrary, array $srcPaths, LibraryType $dstLibrary, string $dstDirectoryPath ): bool { return $this->copy($srcLibrary, $srcPaths, $dstLibrary, $dstDirectoryPath, self::OPERATION_MOVE); }
Move multiple files or folders @param LibraryType $srcLibrary Source library object @param array $srcPaths Array with file/folder paths @param LibraryType $dstLibrary Destination library object @param string $dstDirectoryPath Destination directory Path @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function copy( LibraryType $srcLibrary, array $srcPaths, LibraryType $dstLibrary, string $dstDirectoryPath, int $operation = self::OPERATION_COPY ): bool { // do not allow empty paths if (empty($srcPaths) || empty($dstDirectoryPath)) { return false; } $operationMode = $operation === self::OPERATION_MOVE ? 'move' : 'copy'; // get the source folder path // this path must be the same for all files! $srcFolderPath = dirname($srcPaths[0]); $dstFileNames = $this->preparePaths($srcFolderPath, $srcPaths); if (empty($dstFileNames)) { return false; } $srcFolderPath = str_replace("\\", "/", $srcFolderPath); // windows compatibility $uri = sprintf( '%s/repos/%s/fileops/%s/?p=%s', $this->clipUri($this->client->getConfig('base_uri')), $srcLibrary->id, $operationMode, $srcFolderPath ); $response = $this->client->request( 'POST', $uri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => [ [ 'name' => 'file_names', 'contents' => $dstFileNames, ], [ 'name' => 'dst_repo', 'contents' => $dstLibrary->id, ], [ 'name' => 'dst_dir', 'contents' => $dstDirectoryPath, ], ], ] ); return $response->getStatusCode() === 200; }
Copy multiple files or folders @param LibraryType $srcLibrary Source library object @param array $srcPaths Array with file/folder paths (they must be in the same folder) @param LibraryType $dstLibrary Destination library object @param string $dstDirectoryPath Destination directory Path @param int $operation self::OPERATION_COPY or self::OPERATION_MOVE @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
protected function preparePaths(string $folder, array $paths, string $fileNames = ''): string { foreach ($paths as $path) { if (dirname($path) != $folder) { return ''; // all source paths must be the same } if ($fileNames != '') { $fileNames .= ':'; } $fileNames .= basename($path); } return $fileNames; }
check source folders paths and build the file_names string @param string $folder Folder path @param array $paths Paths of files @param string $fileNames Optional file names @return string
entailment
public function delete(LibraryType $library, array $paths): bool { // do not allow empty paths if (empty($paths)) { return false; } // get the folder path // this path must be the same for all files! $folderPath = dirname($paths[0]); $fileNames = $this->preparePaths($folderPath, $paths); if (empty($fileNames)) { return false; } $folderPath = str_replace("\\", "/", $folderPath); // windows compatibility $uri = sprintf( '%s/repos/%s/fileops/delete/?p=%s', $this->clipUri($this->client->getConfig('base_uri')), $library->id, $folderPath ); $response = $this->client->request( 'POST', $uri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => [ [ 'name' => 'file_names', 'contents' => $fileNames, ], ], ] ); return $response->getStatusCode() === 200; }
Delete multiple files or folders @param LibraryType $library Library object @param array $paths Array with file and folder paths (they must be in the same folder) @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function getUserAvatarByEmail(string $emailAddress, int $size = 80) { return $this->getUserAvatar((new AccountType)->fromArray(['email' => $emailAddress]), $size); }
Get user avatar by email address @param string $emailAddress Email address @param int $size Avatar size, defaults to 80 pixels @return AvatarType @throws \Exception
entailment
protected function getAvatar(Type $type, int $size) { if (!is_int($size) || $size < 1) { throw new \Exception('Illegal avatar size'); } switch (true) { case ($type instanceof GroupType): $id = $type->id; $resource = 'group'; break; case ($type instanceof AccountType): $id = $type->email; $resource = 'user'; break; default: throw new \Exception('Unsupported type to retrieve avatar information for.'); } $response = $this->client->get( $this->client->getConfig('base_uri') . '/avatars/' . $resource . '/' . $id . '/resized/' . $size . '/' ); $json = json_decode($response->getBody()); return (new AvatarType)->fromJson($json); }
Get avatar image @param Type|GroupType|AccountType $type Either AccountType or GroupType instance @param int $size Avatar size @return AvatarType @throws \Exception
entailment
public function createUserAvatar(AccountType $accountType): bool { $uri = sprintf( '%s/accounts/' . $accountType->email . '/', $this->clipUri($this->client->getConfig('base_uri')) ); $response = $this->client->put( $uri, [ 'headers' => ['Accept' => 'application/json; charset=utf-8'], 'multipart' => $accountType->toArray(Type::ARRAY_MULTI_PART), ] ); return $response->getStatusCode() === 201; }
Create a new user avatar @param AccountType $accountType AccountType instance with data for new account @return bool @throws \Exception
entailment
public function getHeaderValue($key) { return isset($this->headers[$key]) ? $this->headers[$key] : null; }
@param string $key @return string|null
entailment
public function getCookieValue($key) { return isset($this->cookies[$key]) ? $this->cookies[$key] : null; }
@param string $key @return string|null
entailment
private function parse($headers) { foreach (preg_split('/\r\n|\r|\n/', $headers) as $i => $line) { if ($i === 0) { $this->headers['http_code'] = $line; } else { list($key, $value) = explode(': ', $line); if ($key === 'Set-Cookie') { list($textCookie) = explode(';', $value); list($cookieKey, $cookieValue) = explode('=', $textCookie); $this->cookies[$cookieKey] = $cookieValue; } else { $this->headers[$key] = $value; } } } }
Parse text headers and fills in cookies and headers properites @param string $headers
entailment
private function shouldIgnoreLine(File $file, int $start, int $end): bool { return $this->containLongWords($file, $start, $end) || $this->isI18nFunction($file, $start, $end); }
Don't warn for lines that exceeds limit, but either are part of translations function first argument or contain single words that alone are longer that line limit (e.g. long URLs). @param File $file @param int $start @param int $end @return bool
entailment
public function getByEmail(string $emailAddress): AccountType { $response = $this->client->request( 'GET', // $emailAddress must not be urlencoded $this->client->getConfig('base_uri') . '/accounts/' . $emailAddress . '/' ); $json = json_decode($response->getBody()); return (new AccountType)->fromJson($json); }
Get AccountType instance by email address Requires admin permissions @param string $emailAddress Email address @return AccountType @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function create(AccountType $accountType): bool { // at least one of these fields is required $requirementsMet = !empty($accountType->password) || !empty($accountType->isStaff) || !empty($accountType->isActive); if (!$requirementsMet) { return false; } $uri = sprintf( '%s/accounts/' . $accountType->email . '/', $this->clipUri($this->client->getConfig('base_uri')) ); $response = $this->client->put( $uri, [ 'headers' => ['Accept' => 'application/json; charset=utf-8'], 'multipart' => $accountType->toArray(Type::ARRAY_MULTI_PART), ] ); return $response->getStatusCode() === 201; }
Create a new account Requires admin permissions @param AccountType $accountType AccountType instance with data for new account @return bool @throws \Exception
entailment
public function remove(AccountType $accountType): bool { if (empty($accountType->email)) { return false; } $uri = sprintf( '%s/accounts/%s/', $this->clipUri($this->client->getConfig('base_uri')), $accountType->email ); return $this->client->delete($uri)->getStatusCode() === 200; }
Remove account Requires admin permissions @param AccountType $accountType Account to remove @return bool
entailment
public function getPreparseFieldsContent(Element $element, string $eventHandle) { $content = []; $fieldLayout = $element->getFieldLayout(); if ($fieldLayout) { foreach ($fieldLayout->getFields() as $field) { if ($field && \get_class($field) === 'aelvan\preparsefield\fields\PreparseFieldType') { /** @var PreparseFieldType $field */ // only get field content for the right event listener $isBeforeSave = ($eventHandle === 'onBeforeSave'); $parseBeforeSave = (bool)$field->parseBeforeSave; if ($isBeforeSave === $parseBeforeSave) { $fieldValue = $this->parseField($field, $element); if ($fieldValue !== null) { $content[$field->handle] = $fieldValue; } } } } } return $content; }
Loops over fields in element to determine if they have preparse fields. @param Element $element @param string $eventHandle @return array
entailment
public function parseField(PreparseFieldType $field, Element $element) { $fieldTwig = $field->fieldTwig; $columnType = $field->columnType; $decimals = $field->decimals; $fieldValue = null; $elementTemplateName = 'element'; if (method_exists($element, 'refHandle')) { $elementTemplateName = strtolower($element->refHandle()); } // Enable generateTransformsBeforePageLoad always $generateTransformsBeforePageLoad = Craft::$app->config->general->generateTransformsBeforePageLoad; Craft::$app->config->general->generateTransformsBeforePageLoad = true; // save cp template path and set to site templates $oldMode = Craft::$app->view->getTemplateMode(); Craft::$app->view->setTemplateMode(View::TEMPLATE_MODE_SITE); // render value from the field template try { $vars = array_merge(['element' => $element], [$elementTemplateName => $element]); $fieldValue = Craft::$app->view->renderString($fieldTwig, $vars); } catch (\Exception $e) { Craft::error('Couldn’t render value for element with id “'.$element->id.'” and preparse field “'. $field->handle.'” ('.$e->getMessage().').', __METHOD__); } // restore cp template paths Craft::$app->view->setTemplateMode($oldMode); // set generateTransformsBeforePageLoad back to whatever it was Craft::$app->config->general->generateTransformsBeforePageLoad = $generateTransformsBeforePageLoad; if (null === $fieldValue) { return null; } if ($columnType === Schema::TYPE_FLOAT || $columnType === Schema::TYPE_INTEGER) { if ($decimals > 0) { return number_format(trim($fieldValue), $decimals, '.', ''); } return number_format(trim($fieldValue), 0, '.', ''); } return $fieldValue; }
Parses field for a given element. @param PreparseFieldType $field @param Element $element @return null|string
entailment
public function shouldParseElementOnMove(Element $element): bool { $fieldLayout = $element->getFieldLayout(); if ($fieldLayout) { foreach ($fieldLayout->getFields() as $field) { if ($field && \get_class($field) === 'aelvan\preparsefield\fields\PreparseFieldType') { /** @var PreparseFieldType $field */ $parseOnMove = $field->parseOnMove; if ($parseOnMove) { return true; } } } } return false; }
Checks to see if an element has a prepase field that should be saved on move @param $element @return bool
entailment
public function getAll(): array { $response = $this->client->request('GET', $this->client->getConfig('base_uri') . '/groups/'); $json = json_decode($response->getBody()); $groupCollection = []; foreach ($json->groups as $group) { $groupCollection[] = (new GroupType)->fromJson($group); } return $groupCollection; }
List groups @return GroupType[] @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function init() { parent::init(); self::$plugin = $this; $this->preparsedElements = [ 'onBeforeSave' => [], 'onSave' => [], 'onMoveElement' => [], ]; // Register our fields Event::on(Fields::class, Fields::EVENT_REGISTER_FIELD_TYPES, function (RegisterComponentTypesEvent $event) { $event->types[] = PreparseFieldType::class; } ); // Before save element event handler Event::on(Elements::class, Elements::EVENT_BEFORE_SAVE_ELEMENT, function (ElementEvent $event) { /** @var Element $element */ $element = $event->element; $key = $element->id . '__' . $element->siteId; if (!\in_array($key, $this->preparsedElements['onBeforeSave'], true)) { $this->preparsedElements['onBeforeSave'][] = $key; $content = self::$plugin->preparseFieldService->getPreparseFieldsContent($element, 'onBeforeSave'); if (!empty($content)) { $this->resetUploads(); $element->setFieldValues($content); } } } ); // After save element event handler Event::on(Elements::class, Elements::EVENT_AFTER_SAVE_ELEMENT, function (ElementEvent $event) { /** @var Element $element */ $element = $event->element; $key = $element->id . '__' . $element->siteId; if (!\in_array($key, $this->preparsedElements['onSave'], true)) { $this->preparsedElements['onSave'][] = $key; $content = self::$plugin->preparseFieldService->getPreparseFieldsContent($element, 'onSave'); if (!empty($content)) { $this->resetUploads(); if ($element instanceof Asset) { $element->setScenario(Element::SCENARIO_DEFAULT); } $element->setFieldValues($content); $success = Craft::$app->getElements()->saveElement($element, true, false); // if no success, log error if (!$success) { Craft::error('Couldn’t save element with id “' . $element->id . '”', __METHOD__); } } } } ); // After move element event handler Event::on(Structures::class, Structures::EVENT_AFTER_MOVE_ELEMENT, function (MoveElementEvent $event) { /** @var Element $element */ $element = $event->element; $key = $element->id . '__' . $element->siteId; if (self::$plugin->preparseFieldService->shouldParseElementOnMove($element) && !\in_array($key, $this->preparsedElements['onMoveElement'], true)) { $this->preparsedElements['onMoveElement'][] = $key; if ($element instanceof Asset) { $element->setScenario(Element::SCENARIO_DEFAULT); } $success = Craft::$app->getElements()->saveElement($element, true, false); // if no success, log error if (!$success) { Craft::error('Couldn’t move element with id “' . $element->id . '”', __METHOD__); } } } ); }
Plugin init method
entailment
public function rules() { $rules = parent::rules(); $rules = array_merge($rules, [ ['fieldTwig', 'string'], ['fieldTwig', 'default', 'value' => ''], ['columnType', 'string'], ['columnType', 'default', 'value' => ''], ['decimals', 'number'], ['decimals', 'default', 'value' => 0], ['textareaRows', 'number'], ['textareaRows', 'default', 'value' => 5], ['parseBeforeSave', 'boolean'], ['parseBeforeSave', 'default', 'value' => false], ['parseOnMove', 'boolean'], ['parseOnMove', 'default', 'value' => false], ['displayType', 'string'], ['displayType', 'default', 'value' => 'hidden'], ['allowSelect', 'boolean'], ['allowSelect', 'default', 'value' => false], ]); return $rules; }
=========================================================================
entailment
public function getInputHtml($value, ElementInterface $element = null): string { // Get our id and namespace $id = Craft::$app->getView()->formatInputId($this->handle); $namespacedId = Craft::$app->getView()->namespaceInputId($id); // Render the input template return Craft::$app->getView()->renderTemplate( 'preparse-field/_components/fields/_input', [ 'name' => $this->handle, 'value' => $value, 'field' => $this, 'id' => $id, 'namespacedId' => $namespacedId, ] ); }
@param mixed $value @param ElementInterface|null $element @return string
entailment
public function getAll(): array { $response = $this->client->request('GET', $this->client->getConfig('base_uri') . '/repos/'); $json = json_decode($response->getBody()); $libCollection = []; foreach ($json as $lib) { $libCollection[] = (new LibraryType)->fromJson($lib); } return $libCollection; }
List libraries @return LibraryType[] @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function getById($libraryId): LibraryType { $response = $this->client->request( 'GET', $this->client->getConfig('base_uri') . '/repos/' . $libraryId . '/' ); $json = json_decode($response->getBody()); return (new LibraryType)->fromJson($json); }
Get library info @param string $libraryId Library ID @return LibraryType @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function decrypt($libraryId, array $options): bool { $hasQueryParams = array_key_exists('query', $options); $hasPassword = $hasQueryParams && array_key_exists('password', $options['query']); if (!$hasQueryParams || !$hasPassword) { throw new \Exception('Password query parameter is required to decrypt library'); } $response = $this->client->request( 'POST', $this->client->getConfig('base_uri') . '/repos/' . $libraryId . '/', $options ); return json_decode($response->getBody()) === 'success'; }
Decrypt library @param string $libraryId Library ID @param array $options Options @return bool Decryption success @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function exists($value, $attribute = 'name'): bool { $libraries = $this->getAll(); foreach ($libraries as $lib) { if (isset($lib->{$attribute}) && $lib->{$attribute} === $value) { return true; } } return false; }
Check if library with certain attribute value exists @param string $value Library name @param string $attribute Attribute name of library @return bool @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function create($name, $description = "new repo", $password = ''): bool { // only create a library which is not empty to prevent wrong implementation if (empty($name)) { return false; } // Do not create libraries that already exist if ($this->exists($name)) { return false; } $uri = sprintf( '%s/repos/', $this->clipUri($this->client->getConfig('base_uri')) ); $multipartData = [ [ 'name' => 'name', 'contents' => $name, ], [ 'name' => 'desc', 'contents' => $description, ], ]; if ($password !== '') { $multipartData[] = [ 'name' => 'passwd', 'contents' => $password, ]; } $response = $this->client->request( 'POST', $uri, [ 'headers' => ['Accept' => 'application/json'], 'multipart' => $multipartData, ] ); return $response->getStatusCode() === 200; }
Create a new library @param string $name Library name @param string $description Library description @param string $password false means no encryption, any other string is used as password @return bool @throws \Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function remove($libraryId): bool { // do not allow empty IDs if (empty($libraryId)) { return false; } $uri = sprintf( '%s/repos/%s/', $this->clipUri($this->client->getConfig('base_uri')), $libraryId ); $response = $this->client->request( 'DELETE', $uri, [ 'headers' => ['Accept' => 'application/json'], ] ); return $response->getStatusCode() === 200; }
Remove a library @param string $libraryId Library ID @return bool @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function sharePersonal($libraryId, array $users, string $permission = Resource::PERMISSION_R): bool { $uri = sprintf( '%s/shared-repos/%s/?share_type=personal&users=%s&permission=%s', $this->clipUri($this->client->getConfig('base_uri')), $libraryId, join(',', $users), $permission ); $response = $this->client->put($uri); return $response->getStatusCode() === 200; }
Share a library, share type is always "personal" @param string $libraryId Library ID @param array $users Comma separated list of user email addresses @param string $permission The permission of the shared library @return bool
entailment
public function getIpFromServer() { $ip = ''; $ipHolders = [ 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_FORWARDED', 'HTTP_X_CLUSTER_CLIENT_IP', 'HTTP_FORWARDED_FOR', 'HTTP_FORWARDED', 'REMOTE_ADDR' ]; foreach ($ipHolders as $key) { if (!empty($_SERVER[$key])) { $ip = $_SERVER[$key]; if (strpos($ip, ',') !== false) { // Multiple IPs are present so use the last IP which should be // the most reliable IP that last connected to the proxy $ips = explode(',', $ip); $ips = array_map('trim', $ips); $ip = end($ips); } $ip = trim($ip); break; } } return $ip; }
Guesses IP address from $_SERVER @return string
entailment
private function areNullableReturnTypesSupported(): bool { $testVersion = trim(PHPCompatibility\PHPCSHelper::getConfigData('testVersion') ?: ''); if (!$testVersion) { return false; } preg_match('`^(\d+\.\d+)(?:\s*-\s*(?:\d+\.\d+)?)?$`', $testVersion, $matches); $min = $matches[1] ?? null; return $min && version_compare($min, '7.1', '>='); }
Return true if _min_ supported version is PHP 7.1. @return bool
entailment
public function getDownloadUrl(LibraryType $library, DirectoryItem $item, string $dir = '/', int $reuse = 1) { $url = $this->client->getConfig('base_uri') . '/repos/' . $library->id . '/file/' . '?reuse=' . $reuse . '&p=' . $this->urlEncodePath($dir . $item->name); $response = $this->client->request('GET', $url); $downloadUrl = (string)$response->getBody(); return preg_replace("/\"/", '', $downloadUrl); }
Get download URL of a file @param LibraryType $library Library instance @param DirectoryItem $item Item instance @param string $dir Dir string @param int $reuse Reuse more than once per hour @return string @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function downloadFromDir( LibraryType $library, DirectoryItem $item, string $localFilePath, string $dir, int $reuse = 1 ): Response { if (is_readable($localFilePath)) { throw new Exception('File already exists'); } $downloadUrl = $this->getDownloadUrl($library, $item, $dir, $reuse); return $this->client->request('GET', $downloadUrl, ['save_to' => $localFilePath]); }
Get download URL of a file from a Directory item @param LibraryType $library Library instance @param DirectoryItem $item Item instance @param string $localFilePath Save file to path @param string $dir Dir string @param int $reuse Reuse more than once per hour @return Response @throws Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function download(LibraryType $library, string $filePath, string $localFilePath, int $reuse = 1) { $item = new DirectoryItem(); $item->name = basename($filePath); $dir = str_replace("\\", "/", dirname($filePath)); // compatibility for windows return $this->downloadFromDir($library, $item, $localFilePath, $dir, $reuse); }
Get download URL of a file @param LibraryType $library Library instance @param string $filePath Save file to path @param string $localFilePath Local file path @param int $reuse Reuse more than once per hour @return Response @throws Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function update(LibraryType $library, string $localFilePath, string $dir = '/', $filename = false): Response { return $this->upload($library, $localFilePath, $dir, $filename, false); }
Update file @param LibraryType $library Library instance @param string $localFilePath Local file path @param string $dir Library dir @param mixed $filename File name, or false to use the name from $localFilePath @return Response @throws Exception
entailment
public function getUploadUrl(LibraryType $library, bool $newFile = true) { $url = $this->client->getConfig('base_uri') . '/repos/' . $library->id . '/' . ($newFile ? 'upload' : 'update') . '-link/'; $response = $this->client->request('GET', $url); $uploadLink = (string)$response->getBody(); return preg_replace("/\"/", '', $uploadLink); }
Get upload URL @param LibraryType $library Library instance @param bool $newFile Is new file (=upload) or not (=update) @return String Upload link @throws \GuzzleHttp\Exception\GuzzleException
entailment
public function getMultiPartParams( string $localFilePath, string $dir, bool $newFile = true, $newFilename = false ): array { if ($newFilename === false) { $fileBaseName = basename($localFilePath); } else { $fileBaseName = $newFilename; } $multiPartParams = [ [ 'headers' => ['Content-Type' => 'application/octet-stream'], 'name' => 'file', 'contents' => fopen($localFilePath, 'r'), ], [ 'name' => 'name', 'contents' => $fileBaseName, ], [ 'name' => 'filename', 'contents' => $fileBaseName, ], ]; if ($newFile) { $multiPartParams[] = [ 'name' => 'parent_dir', 'contents' => $dir, ]; } else { $multiPartParams[] = [ 'name' => 'target_file', 'contents' => rtrim($dir, "/") . "/" . $fileBaseName, ]; } return $multiPartParams; }
Get multipart params for uploading/updating file @param string $localFilePath Local file path @param string $dir Library dir @param bool $newFile Is new file (=upload) or not (=update) @param mixed $newFilename New file name, or false to use the name from $localFilePath @return array
entailment
public function upload( LibraryType $library, string $localFilePath, string $dir = '/', $newFilename = false, bool $newFile = true ): Response { if (!is_readable($localFilePath)) { throw new Exception('File ' . $localFilePath . ' could not be read or does not exist'); } return $this->client->request( 'POST', $this->getUploadUrl($library, $newFile), [ 'headers' => ['Accept' => '*/*'], 'multipart' => $this->getMultiPartParams($localFilePath, $dir, $newFile, $newFilename), ] ); }
Upload file @param LibraryType $library Library instance @param string $localFilePath Local file path @param string $dir Library dir @param mixed $newFilename New file name, or false to use the name from $localFilePath @param bool $newFile Is new file (=upload) or not (=update) @return Response @throws Exception @throws \GuzzleHttp\Exception\GuzzleException
entailment