sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
private function processLocale(LocaleEntity $locale) { $result = 0; $this->logger->info(sprintf('Processing %s (%s)', $locale->getName(), $locale->getID())); $aspiringGroup = $this->groupsHelper->getAspiringTranslators($locale); $aspiringGroupMemberIDs = $aspiringGroup->getGroupMemberIDs(); $numberOfAspiringMembers = count($aspiringGroupMemberIDs); if ($numberOfAspiringMembers === 0) { $this->logger->info(' - No pending requests found.'); } else { foreach ($aspiringGroupMemberIDs as $memberID) { if ($this->processAspiring($locale, $aspiringGroup, $memberID)) { ++$result; } } $this->logger->info(sprintf(' - %d out of %d requests accepted.', $result, $numberOfAspiringMembers)); } return $result; }
@param LocaleEntity $locale @return int The number of accepted join requests
entailment
private function processAspiring(LocaleEntity $locale, CoreGroup $aspiringGroup, $memberID) { $result = false; if ($this->dateLimit === null) { $dateLimitReached = true; } else { $enteredOnString = $aspiringGroup->getGroupDateTimeEntered($memberID); if ($enteredOnString === null) { $dateLimitReached = true; } else { $enteredOnDateTime = new DateTime($enteredOnString); $dateLimitReached = ($enteredOnDateTime < $this->dateLimit) ? true : false; } } if ($dateLimitReached === true) { $accessLevel = $this->accessHelper->getLocaleAccess($locale, $memberID); if ($accessLevel > AccessHelper::ASPRIRING) { // The user belongs to the aspiring group, but is also a member of a user group with higher privileges. // In this case, let's simply remove it from the aspiring group $user = CoreUser::getByUserID($memberID); if ($user) { $user->exitGroup($aspiringGroup); } } else { $userEntity = $this->em->find(UserEntity::class, $memberID); $this->accessHelper->setLocaleAccess($locale, AccessHelper::TRANSLATE, $memberID); $this->notificationRepository->newTranslatorApproved($locale, $memberID, USER_SUPER_ID, true); $this->logger->info(sprintf(' - User accepted: %s (ID: %d)', $userEntity->getUserName(), $userEntity->getUserID())); $result = true; } } else { $userEntity = $this->em->find(UserEntity::class, $memberID); $this->logger->debug(sprintf(' - Request from %s (ID: %d) still too recent', $userEntity->getUserName(), $userEntity->getUserID())); } return $result; }
@param LocaleEntity $locale @param CoreGroup $aspiringGroup @param int $memberID @return bool Returns true if the user has been promoted to the translators group
entailment
private function predict(array $image, $modelType, $language = null) { $data['inputs'] = [ [ 'data' => [ 'image' => $image, ], ], ]; if ($language) { $data['model'] = [ 'output_info' => [ 'output_config' => [ 'language' => $language, ], ], ]; } return $this->getRequest()->request( 'POST', $this->getRequestUrl(sprintf('models/%s/outputs', $modelType)), $data ); }
The actual predict call @param array $image @param $modelType @param string|null $language Language to return results in @return array
entailment
public function predictUrl($url, $modelType, $language = null) { return $this->predict(['url' => $url], $modelType, $language); }
Predict by url @param string $url Url of image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function predictPath($path, $modelType, $language = null) { if (!file_exists($path)) { throw new FileNotFoundException($path); } return $this->predict( [ 'base64' => base64_encode(file_get_contents($path)), ], $modelType, $language ); }
Predict by image path @param string $path Path to image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function predictEncoded($hash, $modelType, $language = null) { return $this->predict( [ 'base64' => $hash, ], $modelType, $language ); }
Predict base64 encoded image @param string $hash base64 encoded image @param string $modelType Type of model to predict @param string|null $language Language to return results in @return array
entailment
public function train(string $id) { $modelResult = $this->getRequest()->request( 'POST', $this->getRequestUrl(sprintf('models/%s/versions', $id)) ); return $this->getModelFromResult($modelResult); }
Train the model @param string $id @return Model
entailment
public function create(Model $model) { $data['model'] = $this->createModelData($model); $modelResult = $this->getRequest()->request( 'POST', $this->getRequestUrl('models'), $data ); return $this->getModelFromResult($modelResult); }
Create new Model @param Model $model @return Model @throws \Exception
entailment
public function update(Model $model) { $data['models'] = []; $data['models'][] = $this->createModelData($model); $data['action'] = 'merge'; $modelResult = $this->getRequest()->request( 'PATCH', $this->getRequestUrl('models'), $data ); return $this->getModelsFromResult($modelResult); }
Update the model @param Model $model @return Model[]
entailment
public function createModelData(Model $model) { $data = []; if ($model->getId()) { $data['id'] = $model->getId(); } if ($model->getName()) { $data['name'] = $model->getName(); } if ($model->getConcepts()) { $data['output_info']['data'] = []; $data['output_info']['data'] = $this->addModelConcepts($data['output_info']['data'], $model->getConcepts()); } $data['output_info']['output_config'] = $model->getOutputConfig(); return $data; }
Create Model data for Request @param Model $model @return array
entailment
public function get() { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl('models') ); return $this->getModelsFromResult($modelResult); }
Gets All Models @return array @throws \Exception
entailment
public function getById($id) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s', $id)) ); return $this->getModelFromResult($modelResult); }
Gets Model By Id @param $id @return Model @throws \Exception
entailment
public function getModelVersions($id) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions', $id)) ); if (!isset($modelResult['model_versions'])) { throw new \Exception('Model Versions Not Found'); } $modelVersions = []; foreach ($modelResult['model_versions'] as $version) { $modelVersion = new ModelVersion($version); $modelVersions[] = $modelVersion; } return $modelVersions; }
Gets Model Versions @param $id @return array @throws \Exception
entailment
public function getModelVersionById($modelId, $versionId) { $modelResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions/%s', $modelId, $versionId)) ); if (isset($modelResult['model_version'])) { $modelVersion = new ModelVersion($modelResult['model_version']); } else { throw new \Exception('Model Versions Not Found'); } return $modelVersion; }
Gets Model Version By Id @param string $modelId @param string $versionId @return ModelVersion @throws \Exception
entailment
public function updateModelConcepts(array $modelsArray, $action) { $data['models'] = []; foreach ($modelsArray as $modelId => $modelConcepts) { $model = []; $model['id'] = (string)$modelId; $model['output_info'] = []; $model['output_info']['data'] = []; $model['output_info']['data'] = $this->addModelConcepts($model['output_info']['data'], $modelConcepts); $data['models'][] = $model; } $data['action'] = $action; $updateResult = $this->getRequest()->request( 'PATCH', $this->getRequestUrl('models'), $data ); return $this->getModelsFromResult($updateResult); }
Common Model's Concepts Update Method @param array $modelsArray @param $action @return array
entailment
public function getModelsFromResult($modelResult) { $modelsArray = []; if (isset($modelResult['models'])) { foreach ($modelResult['models'] as $model) { $model = new Model($model); $modelsArray[] = $model; } } else { throw new \Exception('Models Not Found'); } return $modelsArray; }
Parses Request Result and gets Models @param $modelResult @return Model[] @throws \Exception
entailment
public function addModelConcepts(array $data, array $concepts) { $data['concepts'] = []; foreach ($concepts as $concept) { $data['concepts'][] = [ 'id' => $concept->getId(), ]; } return $data; }
Adds Model's Concepts to Model's Data @param array $data @param array $concepts @return array
entailment
public function deleteById(string $modelId) { $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl(sprintf('models/%s', $modelId)) ); return $deleteResult['status']; }
Delete Model By Id @param string $modelId @return array
entailment
public function deleteVersionById(string $modelId, string $versionId) { $deleteResult = $this->getRequest()->request( 'DELETE', $this->getRequestUrl(sprintf('models/%s/versions/%s', $modelId, $versionId)) ); return $deleteResult['status']; }
Delete Model Version By Id @param string $modelId @param string $versionId @return array
entailment
public function getTrainingInputsById(string $modelId) { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/inputs', $modelId)) ); return $this->getInputsFromResult($inputResult); }
Get Model Training Inputs By Model Id @param string $modelId @return array
entailment
public function getTrainingInputsByVersion(string $modelId, string $versionId) { $inputResult = $this->getRequest()->request( 'GET', $this->getRequestUrl(sprintf('models/%s/versions/%s/inputs', $modelId, $versionId)) ); return $this->getInputsFromResult($inputResult); }
Get Model Training Inputs By Model Id @param string $modelId @param string $versionId @return array
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { foreach ($this->headers as $header) { if ($request->hasHeader($header)) { $request = $request->withoutHeader($header); } } return $next($request); }
{@inheritdoc}
entailment
public static function generateTitleFromRoute($path) { $path = str_replace([':', '*', '$'], '', $path); $path = preg_replace('/\<(.*)\>/iU', '', $path); $path = str_replace(' ', '', ucwords(str_replace('/', ' ', $path))); return $path; }
Generates an title "BarFoo" based on an PSX route "/bar/:foo" @param string $path @return string
entailment
public function searchByNameAndType($name = null, $type = null) { $searchResult = $this->getRequest()->request( 'POST', $this->getRequestUrl('models/searches'), [ 'model_query' => [ 'name' => $name, 'type' => $type, ], ] ); return $this->getModelsFromResult($searchResult); }
Searches Models by It's name and type @param string $name @param string $type @return Model[] array
entailment
public function setString($context, $text, $plural = '') { $this->context = (string) $context; $this->text = (string) $text; $this->plural = (string) $plural; $this->hash = md5($this->plural ? $this->context . "\004" . $this->text . "\005" . $this->plural : $this->context . "\004" . $this->text); }
Set the translatable text. @param string $context The string context @param string $text The string text (singular form) @param string $plural The string text (plural form)
entailment
protected function innerSet($key, $val) { $setMethod = 'set' . ucfirst($key); if ( !in_array($key, $this->notsetters()) && method_exists($this, $setMethod) ) { $this->$setMethod($val); } else { $validateMethod = 'validate' . ucfirst($key); if (method_exists($this, $validateMethod)) { $errors = new Exceptions(); try { $validateResult = $this->$validateMethod($val); if (false === $validateResult) { return; } if ($validateResult instanceof \Generator) { foreach ($validateResult as $error) { if ($error instanceof \Throwable) { $errors->add($error); } } } } catch (\Throwable $e) { $errors->add($e); } if (!$errors->empty()) { throw $errors; } } $sanitizeMethod = 'sanitize' . ucfirst($key); if (method_exists($this, $sanitizeMethod)) { $val = $this->$sanitizeMethod($val); } if (null === $key) { $this->__data[] = $val; } else { $this->__data[$key] = $val; } } }
This method is reloaded for on-set validation and sanitizing @param string $key @param mixed $val @throws \Runn\Core\Exceptions
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { // Check in storage if (array_key_exists($request->getRequestTarget(), $this->redirectStorage)) { $uri = $this->redirectStorage[$request->getRequestTarget()]['uri']; $statusCode = $this->redirectStorage[$request->getRequestTarget()]['status']; $redirectRequest = $this->buildRedirectRequest($request, $uri, $statusCode); return $first($redirectRequest); } return $next($request)->then(function (ResponseInterface $response) use ($request, $first) { $statusCode = $response->getStatusCode(); if (!array_key_exists($statusCode, $this->redirectCodes)) { return $response; } $uri = $this->createUri($response, $request); $redirectRequest = $this->buildRedirectRequest($request, $uri, $statusCode); $chainIdentifier = spl_object_hash((object) $first); if (!array_key_exists($chainIdentifier, $this->circularDetection)) { $this->circularDetection[$chainIdentifier] = []; } $this->circularDetection[$chainIdentifier][] = $request->getRequestTarget(); if (in_array($redirectRequest->getRequestTarget(), $this->circularDetection[$chainIdentifier])) { throw new CircularRedirectionException('Circular redirection detected', $request, $response); } if ($this->redirectCodes[$statusCode]['permanent']) { $this->redirectStorage[$request->getRequestTarget()] = [ 'uri' => $uri, 'status' => $statusCode, ]; } // Call redirect request in synchrone $redirectPromise = $first($redirectRequest); return $redirectPromise->wait(); }); }
{@inheritdoc}
entailment
protected function buildRedirectRequest(RequestInterface $request, UriInterface $uri, $statusCode) { $request = $request->withUri($uri); if (false !== $this->redirectCodes[$statusCode]['switch'] && !in_array($request->getMethod(), $this->redirectCodes[$statusCode]['switch']['unless'])) { $request = $request->withMethod($this->redirectCodes[$statusCode]['switch']['to']); } if (is_array($this->preserveHeader)) { $headers = array_keys($request->getHeaders()); foreach ($headers as $name) { if (!in_array($name, $this->preserveHeader)) { $request = $request->withoutHeader($name); } } } return $request; }
Builds the redirect request. @param RequestInterface $request Original request @param UriInterface $uri New uri @param int $statusCode Status code from the redirect response @return MessageInterface|RequestInterface
entailment
private function createUri(ResponseInterface $response, RequestInterface $request) { if ($this->redirectCodes[$response->getStatusCode()]['multiple'] && (!$this->useDefaultForMultiple || !$response->hasHeader('Location'))) { throw new MultipleRedirectionException('Cannot choose a redirection', $request, $response); } if (!$response->hasHeader('Location')) { throw new HttpException('Redirect status code, but no location header present in the response', $request, $response); } $location = $response->getHeaderLine('Location'); $parsedLocation = parse_url($location); if (false === $parsedLocation) { throw new HttpException(sprintf('Location %s could not be parsed', $location), $request, $response); } $uri = $request->getUri(); if (array_key_exists('scheme', $parsedLocation)) { $uri = $uri->withScheme($parsedLocation['scheme']); } if (array_key_exists('host', $parsedLocation)) { $uri = $uri->withHost($parsedLocation['host']); } if (array_key_exists('port', $parsedLocation)) { $uri = $uri->withPort($parsedLocation['port']); } if (array_key_exists('path', $parsedLocation)) { $uri = $uri->withPath($parsedLocation['path']); } if (array_key_exists('query', $parsedLocation)) { $uri = $uri->withQuery($parsedLocation['query']); } else { $uri = $uri->withQuery(''); } if (array_key_exists('fragment', $parsedLocation)) { $uri = $uri->withFragment($parsedLocation['fragment']); } else { $uri = $uri->withFragment(''); } return $uri; }
Creates a new Uri from the old request and the location header. @param ResponseInterface $response The redirect response @param RequestInterface $request The original request @throws HttpException If location header is not usable (missing or incorrect) @throws MultipleRedirectionException If a 300 status code is received and default location cannot be resolved (doesn't use the location header or not present) @return UriInterface
entailment
public function invalidateResourceIndex(FilterInterface $filter = null) { $this->cache->deleteItem($this->getResourceIndexKey($filter)); }
Invalidates the cached resource index
entailment
public function invalidateResource($sourcePath, $version = null) { $this->cache->deleteItem($this->getResourceKey($sourcePath, $version)); }
Invalidates a cached resource @param string $sourcePath @param integer|null $version
entailment
public function invalidateResourceCollection($version = null, FilterInterface $filter = null) { $this->cache->deleteItem($this->getResourceCollectionKey($version, $filter)); }
Invalidates the cached resource collection @param integer|null $version
entailment
protected function materializeResource(Resource $resource) { foreach ($resource as $method) { $request = $method->getRequest(); if ($request) { $method->setRequest(new Schema($request->getDefinition())); } $responses = $method->getResponses(); foreach ($responses as $statusCode => $response) { $method->addResponse($statusCode, new Schema($response->getDefinition())); } } }
A resource can contain schema definitions which are only resolved if we actual call the getDefinition method i.e. the schema is stored in a database. So before we cache the documentation we must get the actual definition object which we can serialize @param \PSX\Api\Resource $resource
entailment
public function getSynopsis($short = false) { $key = $short ? 'short' : 'long'; if (!isset($this->synopsis[$key])) { $this->synopsis[$key] = trim(sprintf( '%s %s', $_SERVER['PHP_SELF'], $this->getDefinition()->getSynopsis($short) )); } return $this->synopsis[$key]; }
{@inheritdoc} @SuppressWarnings(PHPMD.Superglobals)
entailment
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient) { $notificationData = $notification->getNotificationData(); $pvr = $this->app->make(PackageVersionRepository::class); $qb = $pvr->createQueryBuilder('pv'); $or = $qb->expr()->orX(); foreach ($notificationData['packageVersionIDs'] as $packageVersionID) { $or->add('pv.id = ' . (int) $packageVersionID); } $packageVersions = []; if ($or->count() > 0) { foreach ($qb->where($or)->getQuery()->iterate() as $packageVersionRow) { $packageVersion = $packageVersionRow[0]; $packageVersionURL = $this->getBlockPageURL('CommunityTranslation Search Packages', 'package/' . $packageVersion->getPackage()->getHandle() . '/' . $packageVersion->getVersion()); $packageVersions[] = [ 'url' => $packageVersionURL, 'name' => $packageVersion->getDisplayName(), ]; $qb->getEntityManager()->detach($packageVersion); } } if (count($packageVersions) === 0) { throw new Exception(t('Unable to find any package versions')); } return [ 'packageVersions' => $packageVersions, ] + $this->getCommonMailParameters($notification, $recipient); }
{@inheritdoc} @see Category::getMailParameters()
entailment
public function feed() { $page = TypiCMS::getPageLinkedToModule('news'); if (!$page) { return; } $feed = app('feed'); if (config('typicms.cache')) { $feed->setCache(60, 'typicmsNewsFeed'); } if (!$feed->isCached()) { $models = $this->repository->latest(10); $feed->title = $page->title.' – '.TypiCMS::title(); $feed->description = $page->body; if (config('typicms.image')) { $feed->logo = url('storage/settings/'.config('typicms.image')); } $feed->link = url()->route(config('app.locale').'::news-feed'); $feed->setDateFormat('datetime'); // 'datetime', 'timestamp' or 'carbon' if (isset($models[0]) && $models[0]->date) { $feed->pubdate = $models[0]->date; } $feed->lang = config('app.locale'); $feed->setShortening(true); // true or false $feed->setTextLimit(100); // maximum length of description text foreach ($models as $model) { $feed->add($model->title, null, url($model->uri()), $model->date, $model->summary, $model->present()->body); } } return $feed->render('atom'); }
Generate Atom feed.
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { $promise = $next($request); return $promise->then(function (ResponseInterface $response) use ($request) { return $this->transformResponseToException($request, $response); }); }
{@inheritdoc}
entailment
protected function transformResponseToException(RequestInterface $request, ResponseInterface $response) { if ($response->getStatusCode() >= 400 && $response->getStatusCode() < 500) { throw new ClientErrorException($response->getReasonPhrase(), $request, $response); } if ($response->getStatusCode() >= 500 && $response->getStatusCode() < 600) { throw new ServerErrorException($response->getReasonPhrase(), $request, $response); } return $response; }
Transform response to an error if possible. @param RequestInterface $request Request of the call @param ResponseInterface $response Response of the call @throws ClientErrorException If response status code is a 4xx @throws ServerErrorException If response status code is a 5xx @return ResponseInterface If status code is not in 4xx or 5xx return response
entailment
protected function getRecipientIDs(NotificationEntity $notification) { $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->find($notificationData['localeID']); if ($locale === null && $locale->isApproved()) { // The request has already been approved/refused $result = []; } else { $group = $this->getGroupsHelper()->getGlobalAdministrators(); $result = $group->getGroupMemberIDs(); } return $result; }
{@inheritdoc} @see Category::getRecipientIDs()
entailment
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient) { $notificationData = $notification->getNotificationData(); $locale = $this->app->make(LocaleRepository::class)->find($notificationData['localeID']); if ($locale === null) { throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID'])); } $requestedBy = $locale->getRequestedBy(); return [ 'requestedBy' => $requestedBy, 'localeName' => $locale->getDisplayName(), 'teamsUrl' => $this->getBlockPageURL('CommunityTranslation Team List'), 'notes' => $notificationData['notes'] ? $this->app->make('helper/text')->makenice($notificationData['notes']) : '', ] + $this->getCommonMailParameters($notification, $recipient); }
{@inheritdoc} @see Category::getMailParameters()
entailment
public function register() { $this->registerCommands(); $this->app->singleton(AdminInterface::class, function () { return new Admin($this->nodes(), $this->navigation(), $this->app, $this->app->make(Route::class)); }); //$this->app->singleton(ModelRouterInterface::class, ModelRouter::class); $this->app->singleton(NodeModelConfigurationInterface::class, NodeModelConfiguration::class); $this->app->singleton(FormManagerInterface::class, FormTable::class); $this->app->singleton(TableInterface::class, DataTable::class); $this->app->singleton(ComponentManagerBuilderInterface::class, ComponentManagerBuilder::class); $this->app->singleton(TabsInterface::class, Tabs::class); $this->app->singleton(UploadFileInterface::class, UploadFile::class); $this->app->singleton(ChildRowsInterface::class, ChildRows::class); $this->app->singleton(ActionTableInterface::class, ActionTable::class); }
Register the application services. @return void
entailment
public function parseDirectory($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { if (!$this->filesystem->isDirectory($path)) { throw new UserMessageException(t('Unable to find the directory %s', $path)); } if ('' === (string) $relDirectory && '' !== (string) $packageHandle) { switch ($packageHandle) { case 'concrete5': $relDirectory = 'concrete'; break; default: $relDirectory = 'packages/' . $packageHandle; break; } } $result = null; $pot = new Translations(); $pot->setLanguage($this->app->make('community_translation/sourceLocale')); C5TLParser::clearCache(); $m = null; if (preg_match('/^' . preg_quote(Version::DEV_PREFIX, '/') . '(\d+(?:\.\d+)*)/', $packageVersion, $m)) { $checkVersion = $m[1] . '.99.99'; } else { $checkVersion = $packageVersion; } foreach (C5TLParser::getAllParsers() as $parser) { /* @var C5TLParser $parser */ if ($parser->canParseDirectory()) { if ($packageHandle !== 'concrete5' || $parser->canParseConcreteVersion($checkVersion)) { $parser->parseDirectory($path, $relDirectory, $pot); } } } if (count($pot) > 0) { $result = new Parsed(); $result->setSourceStrings($pot); } if ($searchDictionaryFiles !== self::DICTIONARY_NONE) { foreach ($this->filesystem->allFiles($path) as $file) { $kind = self::DICTIONARY_NONE; switch (strtolower($file->getExtension())) { case 'pot': if ($searchDictionaryFiles & self::DICTIONARY_SOURCE) { $kind = self::DICTIONARY_SOURCE; } break; case 'po': if ($searchDictionaryFiles & self::DICTIONARY_LOCALIZED_SOURCE) { $kind = self::DICTIONARY_LOCALIZED_SOURCE; } break; case 'mo': if ($searchDictionaryFiles & self::DICTIONARY_LOCALIZED_COMPILED) { $kind = self::DICTIONARY_LOCALIZED_COMPILED; } break; } if ($kind === self::DICTIONARY_NONE) { continue; } $parsed = $this->parseDictionaryFile($packageHandle, $packageVersion, $file->getPathname(), $kind); if ($parsed !== null) { if ($result === null) { $result = $parsed; } else { $result->mergeWith($parsed); } } } } return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseDirectory()
entailment
public function parseDictionaryFile($packageHandle, $packageVersion, $path, $kinds) { if (!$this->filesystem->isFile($path)) { throw new UserMessageException(t('Unable to find the file %s', $path)); } $translations = null; if ($kinds & (self::DICTIONARY_SOURCE | self::DICTIONARY_LOCALIZED_SOURCE)) { try { $translations = Translations::fromPoFile($path); if (count($translations) === 0) { $translations = null; } } catch (Exception $x) { $translations = null; } } if ($translations === null && ($kinds & self::DICTIONARY_LOCALIZED_COMPILED)) { try { $translations = Translations::fromMoFile($path); if (count($translations) === 0) { $translations = null; } } catch (Exception $x) { $translations = null; } } $result = null; if ($translations !== null) { $locale = null; $localeID = $translations->getLanguage(); $locale = $localeID ? $this->app->make(LocaleRepository::class)->findApproved($localeID) : null; if ($locale === null) { if ($kinds & self::DICTIONARY_SOURCE) { $translations->setLanguage($this->app->make('community_translation/sourceLocale')); foreach ($translations as $translation) { $translation->setTranslation(''); $translation->setPluralTranslation(''); } $result = new Parsed(); $result->setSourceStrings($translations); } } else { if ($kinds & (self::DICTIONARY_LOCALIZED_SOURCE | self::DICTIONARY_LOCALIZED_COMPILED)) { $translations->setLanguage($locale->getID()); $result = new Parsed(); $result->setTranslations($locale, $translations); } } } return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\Parser::parseDictionaryFile()
entailment
public function parseSourceFile($packageHandle, $packageVersion, $path, $relDirectory = '') { if (!$this->filesystem->isFile($path)) { throw new UserMessageException(t('Unable to find the file %s', $path)); } $tmp = $this->app->make(VolatileDirectory::class); $workDir = $tmp->getPath(); if (!@$this->filesystem->copy($path, $workDir . '/' . basename($path))) { unset($tmp); throw new UserMessageException(t('Failed to copy a temporary file')); } $result = $this->parseDirectory($packageHandle, $packageVersion, $workDir, $relDirectory, ''); unset($tmp); return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\Parser::parseSourceFile()
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { foreach ($this->cookieJar->getCookies() as $cookie) { if ($cookie->isExpired()) { continue; } if (!$cookie->matchDomain($request->getUri()->getHost())) { continue; } if (!$cookie->matchPath($request->getUri()->getPath())) { continue; } if ($cookie->isSecure() && ('https' !== $request->getUri()->getScheme())) { continue; } $request = $request->withAddedHeader('Cookie', sprintf('%s=%s', $cookie->getName(), $cookie->getValue())); } return $next($request)->then(function (ResponseInterface $response) use ($request) { if ($response->hasHeader('Set-Cookie')) { $setCookies = $response->getHeader('Set-Cookie'); foreach ($setCookies as $setCookie) { $cookie = $this->createCookie($request, $setCookie); // Cookie invalid do not use it if (null === $cookie) { continue; } // Restrict setting cookie from another domain if (false === strpos($cookie->getDomain(), $request->getUri()->getHost())) { continue; } $this->cookieJar->addCookie($cookie); } } return $response; }); }
{@inheritdoc}
entailment
private function createCookie(RequestInterface $request, $setCookie) { $parts = array_map('trim', explode(';', $setCookie)); if (empty($parts) || !strpos($parts[0], '=')) { return; } list($name, $cookieValue) = $this->createValueKey(array_shift($parts)); $maxAge = null; $expires = null; $domain = $request->getUri()->getHost(); $path = $request->getUri()->getPath(); $secure = false; $httpOnly = false; // Add the cookie pieces into the parsed data array foreach ($parts as $part) { list($key, $value) = $this->createValueKey($part); switch (strtolower($key)) { case 'expires': $expires = \DateTime::createFromFormat(\DateTime::COOKIE, $value); if (true !== ($expires instanceof \DateTime)) { throw new TransferException( sprintf( 'Cookie header `%s` expires value `%s` could not be converted to date', $name, $value ) ); } break; case 'max-age': $maxAge = (int) $value; break; case 'domain': $domain = $value; break; case 'path': $path = $value; break; case 'secure': $secure = true; break; case 'httponly': $httpOnly = true; break; } } return new Cookie($name, $cookieValue, $maxAge, $domain, $path, $secure, $httpOnly, $expires); }
Creates a cookie from a string. @param RequestInterface $request @param $setCookie @return Cookie|null @throws \Http\Client\Exception\TransferException
entailment
public function parse($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { if (is_object($path) && ($path instanceof DecompressedPackage)) { $result = $this->parseDirectory($packageHandle, $packageVersion, $path->getExtractedWorkDir(), $relDirectory, $searchDictionaryFiles); } elseif ($this->filesystem->isFile($path)) { $result = $this->parseFile($packageHandle, $packageVersion, $path, $relDirectory, $searchDictionaryFiles); } elseif ($this->filesystem->isDirectory($path)) { $result = $this->parseDirectory($packageHandle, $packageVersion, $path, $relDirectory, $searchDictionaryFiles); } else { throw new UserMessageException(t('Unable to find the file/directory %s', $path)); } return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parse()
entailment
public function parseFile($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { $zip = $this->app->make(DecompressedPackage::class, ['packageArchive' => $path, 'volatileDirectory' => null]); try { $zip->extract(); } catch (UserMessageException $foo) { $zip = null; } if ($zip !== null) { $result = $this->parseDirectory($packageHandle, $packageVersion, $zip->getExtractedWorkDir(), $relDirectory, $searchDictionaryFiles); } else { $result = null; if ($searchDictionaryFiles !== self::DICTIONARY_NONE) { $result = $this->parseDictionaryFile($packageHandle, $packageVersion, $path, $searchDictionaryFiles); } if ($result === null) { $result = $this->parseSourceFile($packageHandle, $packageVersion, $path, $relDirectory); } } return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseFile()
entailment
public function parseZip($packageHandle, $packageVersion, $path, $relDirectory = '', $searchDictionaryFiles = self::DICTIONARY_ALL) { $zip = $this->app->make(DecompressedPackage::class, ['packageArchive' => $path, 'volatileDirectory' => null]); $zip->extract(); $result = $this->parseDirectory($packageHandle, $packageVersion, $zip->getExtractedWorkDir(), $relDirectory, $searchDictionaryFiles); unset($zip); return $result; }
{@inheritdoc} @see \CommunityTranslation\Parser\ParserInterface::parseZip()
entailment
public function convertTranslationsToString(Translations $translations) { \Gettext\Generators\Mo::$includeEmptyTranslations = true; return $translations->toMoString(); }
{@inheritdoc} @see ConverterInterface::convertTranslationsToString()
entailment
public function mapConfig(array &$scopeSettings, $currentScope, ContextualizerInterface $contextualizer) { // common settings if (isset($scopeSettings['providers'])) { $contextualizer->setContextualParameter('providers', $currentScope, $scopeSettings['providers']); } if (isset($scopeSettings['template'])) { $contextualizer->setContextualParameter('template', $currentScope, $scopeSettings['template']); } // Facebook like settings if (isset($scopeSettings['facebook_like.layout'])) { $contextualizer->setContextualParameter('facebook_like.layout', $currentScope, $scopeSettings['facebook_like.layout']); } if (isset($scopeSettings['facebook_like.width'])) { $contextualizer->setContextualParameter('facebook_like.width', $currentScope, $scopeSettings['facebook_like.width']); } if (isset($scopeSettings['facebook_like.show_faces'])) { $contextualizer->setContextualParameter('facebook_like.show_faces', $currentScope, $scopeSettings['facebook_like.show_faces']); } if (isset($scopeSettings['facebook_like.share'])) { $contextualizer->setContextualParameter('facebook_like.share', $currentScope, $scopeSettings['facebook_like.share']); } // Facebook recommend settings if (isset($scopeSettings['facebook_recommend.layout'])) { $contextualizer->setContextualParameter('facebook_recommend.layout', $currentScope, $scopeSettings['facebook_recommend.layout']); } if (isset($scopeSettings['facebook_recommend.width'])) { $contextualizer->setContextualParameter('facebook_recommend.width', $currentScope, $scopeSettings['facebook_recommend.width']); } if (isset($scopeSettings['facebook_recommend.show_faces'])) { $contextualizer->setContextualParameter('facebook_recommend.show_faces', $currentScope, $scopeSettings['facebook_recommend.show_faces']); } if (isset($scopeSettings['facebook_recommend.share'])) { $contextualizer->setContextualParameter('facebook_recommend.share', $currentScope, $scopeSettings['facebook_recommend.share']); } // Twitter settings if (isset($scopeSettings['twitter.show_username'])) { $contextualizer->setContextualParameter('twitter.show_username', $currentScope, $scopeSettings['twitter.show_username']); } if (isset($scopeSettings['twitter.large_button'])) { $contextualizer->setContextualParameter('twitter.large_button', $currentScope, $scopeSettings['twitter.large_button']); } if (isset($scopeSettings['twitter.language'])) { $contextualizer->setContextualParameter('twitter.language', $currentScope, $scopeSettings['twitter.language']); } // LinkedIn settings if (isset($scopeSettings['linkedin.count_mode'])) { $contextualizer->setContextualParameter('linkedin.count_mode', $currentScope, $scopeSettings['linkedin.count_mode']); } if (isset($scopeSettings['linkedin.language'])) { $contextualizer->setContextualParameter('linkedin.language', $currentScope, $scopeSettings['linkedin.language']); } // Google Plus settings if (isset($scopeSettings['google_plus.size'])) { $contextualizer->setContextualParameter('google_plus.size', $currentScope, $scopeSettings['google_plus.size']); } if (isset($scopeSettings['google_plus.annotation'])) { $contextualizer->setContextualParameter('google_plus.annotation', $currentScope, $scopeSettings['google_plus.annotation']); } if (isset($scopeSettings['google_plus.width'])) { $contextualizer->setContextualParameter('google_plus.width', $currentScope, $scopeSettings['google_plus.width']); } if (isset($scopeSettings['google_plus.language'])) { $contextualizer->setContextualParameter('google_plus.language', $currentScope, $scopeSettings['google_plus.language']); } // Xing settings if (isset($scopeSettings['xing.shape'])) { $contextualizer->setContextualParameter('xing.shape', $currentScope, $scopeSettings['xing.shape']); } if (isset($scopeSettings['xing.counter'])) { $contextualizer->setContextualParameter('xing.counter', $currentScope, $scopeSettings['xing.counter']); } if (isset($scopeSettings['xing.language'])) { $contextualizer->setContextualParameter('xing.language', $currentScope, $scopeSettings['xing.language']); } }
{@inheritdoc}
entailment
public function setRawConcepts(array $rawConcepts) { $concepts = []; foreach ($rawConcepts as $rawConcept) { $concept = new Concept($rawConcept); $concepts[] = $concept; } $this->concepts = $concepts; return $this; }
Sets concepts from Raw Data @param array $rawConcepts @return $this
entailment
public function generateRawData() { $rawData = ['id' => $this->getId()]; $rawData['output_info'] = []; $rawData['output_info']['data'] = []; if ($this->getName()) { $rawData['name'] = $this->getName(); } if ($this->getAppId()) { $rawData['app_id'] = $this->getAppId(); } if ($this->getCreatedAt()) { $rawData['created_at'] = $this->getCreatedAt(); } if ($this->getConcepts()) { $rawData['output_info']['data']['concepts'] = []; foreach ($this->getConcepts() as $concept) { $rawData['output_info']['data']['concepts'][] = $concept->generateRawData(); } } if ($this->isConceptsMutuallyExclusive() || $this->isClosedEnvironment()) { $rawData['output_info']['output_config'] = $this->getOutputConfig(); } if ($this->getModelVersion()) { $rawData['model_version'] = $this->getModelVersion()->generateRawData(); } return $rawData; }
Generates rawData from Model @return array
entailment
public static function create(Version $packageVersion, Locale $locale) { $result = new static(); $result->packageVersion = $packageVersion; $result->locale = $locale; $result->lastUpdated = null; $result->total = 0; $result->translated = 0; return $result; }
@param Version $packageVersion @param Locale $locale @return static
entailment
public function getPercentage($round = true) { if ($this->translated === 0 || $this->total === 0) { $result = $round ? 0 : 0.0; } elseif ($this->translated === $this->total) { $result = $round ? 100 : 100.0; } else { $result = $this->translated * 100.0 / $this->total; if ($round) { $result = max(1, min(99, (int) round($result))); } } return $result; }
Get the translation percentage. @param bool $round Set to true to get a rounded value (0 if no translations at all, 100 if all strings are translated, 1...99 otherwise), @return int|float
entailment
private function getCurrentUserID($required) { $result = null; if (User::isLoggedIn()) { $u = new User(); if ($u->isRegistered()) { $uID = (int) $u->getUserID(); if ($uID !== 0) { $result = $uID; } } } if ($result === null && $required) { throw new UserMessageException(t('No logged in user')); } return $result; }
@param bool $required @return int|null
entailment
private function getCurrentUser($required) { $result = null; $id = $this->getCurrentUserID($required); if ($id !== null) { $result = $this->getEntityManager()->find(UserEntity::class, $id); } if ($result === null && $required) { throw new UserMessageException(t('No logged in user')); } return $result; }
@param bool $required @return UserEntity|null
entailment
public function handleRequest(RequestInterface $request, callable $next, callable $first) { if (!$request->hasHeader('Content-Length')) { $stream = $request->getBody(); // Cannot determine the size so we use a chunk stream if (null === $stream->getSize()) { $stream = new ChunkStream($stream); $request = $request->withBody($stream); $request = $request->withAddedHeader('Transfer-Encoding', 'chunked'); } else { $request = $request->withHeader('Content-Length', $stream->getSize()); } } return $next($request); }
{@inheritdoc}
entailment
public static function getTypesInfo() { $locale = Localization::activeLocale(); if (!isset(self::$typesInfo[$locale])) { $list = [ self::ADJECTIVE => [ 'name' => tc('TermType', 'Adjective'), 'short' => tc('TermType_short', 'adj.'), 'description' => t('A word that describes a noun or pronoun (examples: big, happy, obvious).'), ], self::ADVERB => [ 'name' => tc('TermType', 'Adverb'), 'short' => tc('TermType_short', 'adv.'), 'description' => t('A word that describes or gives more information about a verb, adjective or other adverb (examples: carefully, quickly, very).'), ], self::CONJUNCTION => [ 'name' => tc('TermType', 'Conjunction'), 'short' => tc('TermType_short', 'conj.'), 'description' => t('A word that connects words, phrases, and clauses in a sentence (examples: and, but, while, although).'), ], self::INTERJECTION => [ 'name' => tc('TermType', 'Interjection'), 'short' => tc('TermType_short', 'interj.'), 'description' => t('A word that is used to show a short sudden expression of emotion (examples: Bye!, Cheers!, Goodbye!, Hi!, Hooray!).'), ], self::NOUN => [ 'name' => tc('TermType', 'Noun'), 'short' => tc('TermType_short', 'n.'), 'description' => t('A word that refers to a person, place, thing, event, substance, or quality (examples: Andrew, house, pencil, table).'), ], self::PREPOSITION => [ 'name' => tc('TermType', 'Preposition'), 'short' => tc('TermType_short', 'prep.'), 'description' => t('A word that is used before a noun, a noun phrase, or a pronoun, connecting it to another word (examples: at, for, in, on, under).'), ], self::PRONOUN => [ 'name' => tc('TermType', 'Pronoun'), 'short' => tc('TermType_short', 'pron.'), 'description' => t('A word that is used instead of a noun or a noun phrase (examples: I, me, mine, myself).'), ], self::VERB => [ 'name' => tc('TermType', 'Verb'), 'short' => tc('TermType_short', 'v.'), 'description' => t('A word or phrase that describes an action, condition, or experience (examples: listen, read, write).'), ], ]; $comparer = new Comparer($locale); uasort($list, function (array $a, array $b) use ($comparer) { return $comparer->compare($a['name'], $b['name']); }); self::$typesInfo[$locale] = $list; } return self::$typesInfo[$locale]; }
Get all the allowed type names, short names and descriptions. @return array
entailment
public static function isValidType($type) { if ($type === '') { $result = true; } else { $valid = self::getTypesInfo(); $result = isset($valid[$type]); } return $result; }
Check if a term type is valid. @param string $type @return bool
entailment
protected function configure() { $this ->setName(self::COMMAND_NAME) ->setDescription('lint an xml file') ->addArgument( self::ARGUMENT_FILE, InputArgument::REQUIRED, 'the path/to/file.xml to lint a single file or a path/to/directory to lint all xml ' . 'files in a directory.' ) ->addOption( self::OPTION_RECURSIVE, 'r', InputOption::VALUE_OPTIONAL, 'Whether to scan directories recursive.', true ) ->addOption( self::OPTION_EXCLUDE, 'e', InputOption::VALUE_REQUIRED, 'Path(s) to exclude from linting, can be several separated by comma' ) ->addOption( self::OPTION_PATTERN, 'p', InputOption::VALUE_REQUIRED, 'Filter files with one or more patterns, e.g.: *.svg,*.xml. Separate patterns by comma.' ) ->addOption( self::OPTION_NO_XSD, 's', InputOption::VALUE_NONE, 'Skip downloading and checking against XSD-files.' ) ; }
{@inheritdoc}
entailment
protected function execute(InputInterface $input, OutputInterface $output) { $this->start = microtime(true); $this->output = $output; $this->input = $input; if ($input->getOption(self::OPTION_NO_XSD)) { $this->validator = ValidationFactory::createLintOnlyValidation(); } else { $this->validator = ValidationFactory::createDefaultCollection(); } $file = $input->getArgument(self::ARGUMENT_FILE); $output->writeln('progress: '); if (is_dir($file)) { $status = $this->lintDir($file); } else { $status = $this->lintFile(new \SplFileInfo($file)); } $output->writeln(''); if (false === $status) { $this->printReportsOfFilesWithProblems(); } $this->output->writeln(sprintf( PHP_EOL . '%d files / %1.2f seconds <info>done</info>', count($this->reports), microtime(true) - $this->start )); return $status ? 0 : 1; }
{@inheritdoc}
entailment
private function lintDir($dir) { $finder = Finder::create(); $finder->files() ->in($dir); $patterns = $this->input->getOption(self::OPTION_PATTERN); if (!empty($patterns)) { $patterns = explode(',', $patterns); foreach ($patterns as $pattern) { $finder->name(trim($pattern)); } } else { $finder->name('*.xml.dist') ->name('*.xml'); } if (!$this->input->getOption(self::OPTION_RECURSIVE)) { $finder->depth(0); } if ($this->input->hasOption(self::OPTION_EXCLUDE)) { $exclude = explode(',', $this->input->getOption(self::OPTION_EXCLUDE)); $finder->exclude($exclude); } $totalFiles = $finder->count(); $counter = 0; $ret = true; /** @var SplFileInfo $file */ foreach ($finder as $file) { $ret = $this->lintFile($file) && $ret; if (0 == ++$counter % 30) { $this->output->writeln(sprintf( ' %8d/%d %6.2f%%', $counter, $totalFiles, $counter / $totalFiles * 100 )); } } return $ret; }
lint the content of a directory, recursive if defined. @param string $dir path/to/dir @return bool
entailment
private function printReportsOfFilesWithProblems() { $this->output->writeln(PHP_EOL . '<error>errors:</error>'); foreach ($this->reports as $report) { if (false === $report->hasProblems()) { continue; } $file = $report->getFile(); $this->output->writeln('file: ' . $file->getPath() . DIRECTORY_SEPARATOR . $file->getFilename()); foreach ($report->getProblems() as $problem) { $this->output->write( ' > ' . $problem->getMessage() . PHP_EOL ); } $this->output->write(' - - ' . PHP_EOL); } }
format and print the errors from the queue to the output.
entailment
private function lintFile(\SplFileInfo $file) { if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { $this->output->write('lint file ' . $file . ' ... '); } $report = FileReport::create($file); $this->reports[] = $report; $status = $this->validator->validateFile($report); if ($this->output->getVerbosity() >= OutputInterface::VERBOSITY_VERBOSE) { if (false === $status) { $this->output->writeln('<error>errors</error>'); } else { $this->output->writeln('<info>passed.</info>'); } } else { if (false === $status) { $this->output->write('<error>F</error>'); } else { $this->output->write('.'); } } return $status; }
lint a file, pass errors to the queue. @param \SplFileInfo $file @return bool
entailment
public function setTypeField(array $arrTypeField) { foreach ($arrTypeField as $nameField => $item) { if (is_array($item)) { //проверяем подключена ли к полю другая таблица if (!empty($item[3]) and $item[2] === 'multiple') { $this->setOtherTable($nameField, $item[3]); } if (!empty($item[3]) and $item[2] === 'one-to-one') { $this->setOtherTable($nameField, $item[3]); } if (!empty($item[3]) and $item[2] === 'one-to-many') { $this->setOneToMany($nameField, $item[3]); } switch ($item[0]) { case 'file': $this->setFileUploadSeting($nameField, $item); break; case 'select': //проверяем если класс if (isset($item[1][0])) { //можем передать имя класса или обьект модели if (is_object($item[1][0])) { $this->modelTableSelect = $item[1][0]; } elseif (class_exists($item[1][0])) { $this->modelTableSelect = $this->app->make($item[1][0]); } $this->objClassSelectAjax[$nameField] = [ 'id' => $item[1][1], 'select' => $item[1][2], 'model' => $this->modelTableSelect ]; } break; } } } $this->setTypeField = $arrTypeField; return $this; }
@param array $arrTypeField todo выбор поля который будет отображатся в форме например input select file с настройками
entailment
public function getIdentify($email, $name = '', $properties = []) { if (!$email) { throw new InvalidArgumentException('E-mail cannot be empty or null'); } //props that we will combine with default props $props = [ PayloadProperties::EMAIL => Encryption::decode($email) ]; if ($name) { $props[PayloadProperties::NAME] = $name; } if ($properties) { $props[PayloadProperties::PROPERTIES] = $properties; } return $this->getTrackPayload(ActionTypes::IDENTIFY, $props); }
Generates payload for identify events @param $email @param string $name @param array $properties @return array @throws InvalidArgumentException
entailment
public function getPageView($url, $properties = []) { if (empty($url)) { throw new Exception('url cannot be empty'); } $props = [ PayloadProperties::URL => $url ]; if ($properties) { $props[PayloadProperties::PROPERTIES] = $properties; } return $this->getTrackPayload(ActionTypes::PAGE_VIEWED, $props); }
Generates payload for page view events @param $url @param array $properties @return array @throws Exception
entailment
public function getAddToOrder(Models\Product $product) { return $this->getTrackPayload(ActionTypes::ADDED_TO_ORDER, [ PayloadProperties::PROPERTIES => [ [ PayloadProperties::PRODUCT => $product->toArray() ] ] ]); }
Generates payload for add to order events @param Models\Product $product @return array
entailment
public function getOrderCompleted(Models\Order $order) { if (!$order->hasProducts()) { throw new \Exception('$order should have at least one product'); } return $this->getTrackPayload(ActionTypes::ORDER_COMPLETED, [ PayloadProperties::PROPERTIES => [ [ PayloadProperties::ORDER_TOTAL_PRICE => $order->getOrderTotal(), PayloadProperties::PRODUCTS => $order->toArray() ] ] ]); }
Generates payload for order completed events @param Models\Order $order @throws Exception @return array
entailment
public function getCustom($event, $properties = []) { $properties = empty($properties) ? [] : [PayloadProperties::PROPERTIES => $properties]; return $this->getTrackPayload($event, $properties); }
Generates payload for custom events @param $event @param array $properties @return array
entailment
public static function create(Entry $entry, Locale $locale) { $result = new static(); $result->entry = $entry; $result->locale = $locale; $result->comments = ''; return $result; }
@param Entry $entry @param Locale $locale @param string $text @param string $comments @return static
entailment
private function getTransifexAccount(InputInterface $input, OutputInterface $output) { $this->transifexUsername = trim((string) $input->getOption('username')); if ($this->transifexUsername === '') { if (!$input->isInteractive()) { throw new Exception('Please specify the Transifex username'); } $question = new Question('Please specify the Transifex username: ', ''); $this->transifexUsername = trim((string) $this->getHelper('question')->ask($input, $output, $question)); if ($this->transifexUsername === '') { throw new Exception('Operation aborted'); } } $this->transifexPassword = (string) $input->getOption('password'); if ($this->transifexPassword === '') { if (!$input->isInteractive()) { throw new Exception('Please specify the Transifex password'); } $question = new Question('Please specify the Transifex password (will be hidden): ', ''); $question->setHidden(true); $this->transifexPassword = (string) $this->getHelper('question')->ask($input, $output, $question); if ($this->transifexPassword === '') { throw new Exception('Operation aborted'); } } }
@param InputInterface $input @param OutputInterface $output @throws Exception
entailment
private function fetchTransifexLocales($transifexProject) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/languages/") ->setMethod('GET') ->send() ; if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw new Exception($response->getReasonPhrase()); } $rawLocales = @json_decode($response->getBody(), true); if (!is_array($rawLocales)) { throw new Exception('Failed to decode response'); } $sourceLocale = $this->app->make('community_translation/sourceLocale'); $sourceVariants = [strtolower($sourceLocale)]; $m = null; if (preg_match('/^(.+?)[\-_]/', $sourceLocale, $m)) { $sourceVariants[] = strtolower($m[1]); } $result = []; foreach ($rawLocales as $rawLocale) { $id = $rawLocale['language_code']; if (!in_array(strtolower($id), $sourceVariants)) { $result[] = $id; } } sort($result); return $result; }
@param string $transifexProject @throws Exception @return string[]
entailment
private function fetchTransifexResources($transifexProject) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/resources/") ->setMethod('GET') ->send() ; if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw new Exception($response->getReasonPhrase()); } $rawResources = @json_decode($response->getBody(), true); if (!is_array($rawResources)) { throw new Exception('Failed to decode response'); } $result = []; foreach ($rawResources as $rawResource) { $result[] = $rawResource['slug']; } sort($result); return $result; }
@param string $transifexProject @throws Exception @return string[]
entailment
private function fetchTransifexTranslations($transifexProject, $transifexResource, $transifexLocale) { $client = $this->getHttpClient(); $response = $client ->setUri("https://www.transifex.com/api/2/project/$transifexProject/resource/$transifexResource/translation/$transifexLocale/") ->setMethod('GET') ->send() ; if ($response->getStatusCode() < 200 || $response->getStatusCode() >= 300) { throw new Exception($response->getReasonPhrase()); } $data = @json_decode($response->getBody(), true); if (!is_array($data) || !isset($data['mimetype']) || $data['mimetype'] !== 'text/x-po' || !isset($data['content']) || !is_string($data['content']) || $data['content'] === '') { throw new Exception('Failed to decode response'); } return $data['content']; }
@param string $transifexProject @param string $transifexResource @param string $transifexLocale @throws Exception @return string
entailment
private function parseTranslations($translationsData) { $translations = Translations::fromPoString($translationsData); if (count($translations) < 1) { throw new Exception('No translations downloaded'); } return $translations; }
@param string $translationsData @throws Exception @return Translations
entailment
private function translationsNeedsPluralFix(Translations $translations, LocaleEntity $locale, &$translationsPluralCount) { $txPlurals = $translations->getPluralForms(); $translationsPluralCount = isset($txPlurals) ? $txPlurals[0] : null; return $translationsPluralCount !== $locale->getPluralCount(); }
@param Translations $translations @param LocaleEntity $locale @return bool
entailment
public function generateRawData() { $rawData = ['id' => $this->getId()]; if ($this->getValue()) { $rawData['value'] = $this->getValue(); } if ($this->getName()) { $rawData['name'] = $this->getName(); } if ($this->getAppId()) { $rawData['app_id'] = $this->getAppId(); } if ($this->getLanguage()) { $rawData['language'] = $this->getLanguage(); } if ($this->getCreatedAt()) { $rawData['created_at'] = $this->getCreatedAt(); } if ($this->getUpdatedAt()) { $rawData['updated_at'] = $this->getUpdatedAt(); } return $rawData; }
Generates rawData from Concept @return array
entailment
public static function create(Locale $locale, $numTranslatable, $numApprovedTranslations) { $result = new static(); $result->locale = $locale; $result->numTranslatable = (int) $numTranslatable; $result->numApprovedTranslations = (int) $numApprovedTranslations; return $result; }
Create a new (unsaved) instance. @param Locale $locale @param int $numTranslatable @param int $numApprovedTranslations @return static
entailment
public function getPercentage($round = true) { if ($this->numApprovedTranslations === 0 || $this->numTranslatable === 0) { $result = $round ? 0 : 0.0; } elseif ($this->numApprovedTranslations === $this->numTranslatable) { $result = $round ? 100 : 100.0; } else { $result = $this->numApprovedTranslations * 100.0 / $this->numTranslatable; if ($round) { $result = max(1, min(99, (int) round($result))); } } return $result; }
Get the translation progress. @param bool $round @return int|float
entailment
private function getPackageHandlesToTry(RemotePackageRepository $repo, DateTime $dateLimit) { $qb = $repo->createQueryBuilder('rp'); $expr = $qb->expr(); $qb ->distinct() ->select('rp.handle') ->where($expr->isNull('rp.processedOn')) ->andWhere($expr->eq('rp.approved', 0)) ->andWhere($expr->gte('rp.createdOn', ':minCreatedOn'))->setParameter('minCreatedOn', $dateLimit) ; foreach ($qb->getQuery()->iterate() as $tryPackage) { $row = array_pop($tryPackage); yield $row['handle']; } }
@param RemotePackageRepository $repo @param DateTime $dateLimit @return string[]|\Generator
entailment
private function processRemotePackage(Connection $connection, RemotePackageRepository $repo, RemotePackageImporter $importer, RemotePackageEntity $remotePackage, $recordFailures) { $this->logger->debug(sprintf('Processing package %s v%s', $remotePackage->getHandle(), $remotePackage->getVersion())); $em = $repo->createQueryBuilder('r')->getEntityManager(); $remotePackage->setProcessedOn(new DateTime()); $em->persist($remotePackage); $em->flush($remotePackage); $connection->beginTransaction(); $error = null; try { $importer->import($remotePackage); $connection->commit(); } catch (Exception $x) { $error = $x; } catch (Throwable $x) { $error = $x; } if ($error !== null) { try { $connection->rollBack(); } catch (Exception $foo) { } $remotePackage->setProcessedOn(null); if ($recordFailures) { $remotePackage ->setFailCount($remotePackage->getFailCount() + 1) ->setLastError($error->getMessage()) ; } $em->persist($remotePackage); $em->flush($remotePackage); if ($error instanceof DownloadException && $error->getHttpCode() === 404) { $this->logger->debug(sprintf(' NOT FOUND!')); } else { throw $error; } } }
@param Connection $connection @param RemotePackageRepository $repo @param RemotePackageImporter $importer @param RemotePackageEntity $remotePackage @param bool $recordFailures @throws Exception @throws Throwable
entailment
private function tryProcessRemotePackage(Connection $connection, RemotePackageRepository $repo, RemotePackageImporter $importer, $remotePackageHandle) { $result = false; $this->logger->debug(sprintf('Trying unapproved package with handle %s', $remotePackageHandle)); $remotePackage = $repo->findOneBy( [ 'handle' => $remotePackageHandle, 'processedOn' => null, 'approved' => 0, ], [ 'createdOn' => 'DESC', ] ); if ($remotePackage === null) { $this->logger->debug(' - FAILED: entity not found (???)'); } else { $error = null; try { $this->processRemotePackage($connection, $repo, $importer, $remotePackage, false); } catch (Exception $x) { $error = $x; } catch (Throwable $x) { $error = $x; } if ($error !== null) { $this->logger->debug(sprintf(' - FAILED: %s', trim($error->getMessage()))); } else { $this->logger->debug(' - SUCCEEDED: marking the package as approved'); $qb = $repo->createQueryBuilder('rp'); $qb ->update() ->set('rp.approved', true) ->where($qb->expr()->eq('rp.handle', ':handle'))->setParameter('handle', $remotePackageHandle) ->getQuery()->execute(); $result = true; } } return $result; }
@param Connection $connection @param RemotePackageRepository $repo @param RemotePackageImporter $importer @param string $remotePackageHandle @return bool
entailment
protected function registerRegistry() { $this->app['registry'] = $this->app->share(function($app) { $config = $app->config->get('registry', array()); return new Registry($app['db'], $app['registry.cache'], $config); }); }
Register the collection repository. @return void
entailment
public function import(Translations $translations, LocaleEntity $locale, UserEntity $user, ImportOptions $options = null) { if ($options === null) { $options = ImportOptions::forTranslators(); } $allFuzzy = $options->getAllFuzzy(); $unapproveFuzzy = $options->getUnapproveFuzzy(); $pluralCount = $locale->getPluralCount(); $connection = $this->em->getConnection(); $nowExpression = $connection->getDatabasePlatform()->getNowExpression(); $sqlNow = (new DateTime())->format($connection->getDatabasePlatform()->getDateTimeFormatString()); $translatablesChanged = []; $result = new ImportResult(); $insertParams = []; $insertCount = 0; // gettext strongly discourages the use of these characters $invalidCharsMap = [ "\x07" => '\\a', "\x08" => '\\b', "\x0C" => '\\f', "\x0D" => '\\r', "\x0B" => '\\v', ]; $invalidChars = implode('', array_keys($invalidCharsMap)); $connection->beginTransaction(); try { // Prepare some queries $querySearch = $connection->prepare(' select CommunityTranslationTranslatables.id as translatableID, CommunityTranslationTranslations.* from CommunityTranslationTranslatables left join CommunityTranslationTranslations on CommunityTranslationTranslatables.id = CommunityTranslationTranslations.translatable and ' . $connection->quote($locale->getID()) . ' = CommunityTranslationTranslations.locale where CommunityTranslationTranslatables.hash = ? ')->getWrappedStatement(); $queryInsert = $connection->prepare( $this->buildInsertTranslationsSQL($connection, $locale, self::IMPORT_BATCH_SIZE, $user) )->getWrappedStatement(); $queryUnsetCurrentTranslation = $connection->prepare( 'UPDATE CommunityTranslationTranslations SET current = NULL, currentSince = NULL, approved = ? WHERE id = ? LIMIT 1' )->getWrappedStatement(); $querySetCurrentTranslation = $connection->prepare( 'UPDATE CommunityTranslationTranslations SET current = 1, currentSince = ' . $nowExpression . ', approved = ? WHERE id = ? LIMIT 1' )->getWrappedStatement(); $queryResubmitTranslation = $connection->prepare( 'UPDATE CommunityTranslationTranslations SET approved = NULL, createdBy = ' . $user->getUserID() . ' WHERE id = ? LIMIT 1' )->getWrappedStatement(); // Check every strings to be imported foreach ($translations as $translationKey => $translation) { /* @var GettextTranslation $translation */ // Check if the string is translated if ($translation->hasTranslation() === false) { // This $translation instance is not translated ++$result->emptyTranslations; continue; } $isPlural = $translation->hasPlural(); if ($isPlural === true && $pluralCount > 1 && $translation->hasPluralTranslation() === false) { // This plural form of the $translation instance is not translated ++$result->emptyTranslations; continue; } $allTranslations = $translation->getTranslation(); if ($isPlural && $pluralCount > 1) { $allTranslations .= implode('', $translation->getPluralTranslation()); } $s = strpbrk($allTranslations, $invalidChars); if ($s !== false) { throw new UserMessageException( t('The translation for the string \'%1$s\' contains the invalid character \'%2$s\'.', $translation->getOriginal(), $invalidCharsMap[$s[0]]) . "\n" . t('Translations can not contain these characters: %s', "'" . implode("', '", array_values($invalidCharsMap)) . "'") ); } $this->checkXSS($translation); $this->checkFormat($translation); // Let's look for the current translation and for an existing translation exactly the same as the one we're importing $translatableID = null; $currentTranslation = null; $sameTranslation = null; $hash = md5($isPlural ? ("$translationKey\005" . $translation->getPlural()) : $translationKey); $querySearch->execute([$hash]); while (($row = $querySearch->fetch()) !== false) { if ($translatableID === null) { $translatableID = (int) $row['translatableID']; } if (!isset($row['id'])) { break; } if ($currentTranslation === null && $row['current'] === '1') { $currentTranslation = $row; } if ($sameTranslation === null && $this->rowSameAsTranslation($row, $translation, $isPlural, $pluralCount)) { $sameTranslation = $row; } } $querySearch->closeCursor(); // Check if the translation doesn't have a corresponding translatable string if ($translatableID === null) { ++$result->unknownStrings; continue; } // Check if the new translation is approved or not if ($allFuzzy) { $isFuzzy = true; } else { $isFuzzy = in_array('fuzzy', $translation->getFlags(), true); } if ($sameTranslation === null) { // This translation is not already present - Let's add it if ($currentTranslation === null) { // No current translation for this string: add this new one and mark it as the current one $addAsCurrent = 1; if ($isFuzzy) { $addAsApproved = null; ++$result->newApprovalNeeded; } else { $addAsApproved = 1; } $translatablesChanged[] = $translatableID; ++$result->addedAsCurrent; } elseif ($isFuzzy === false || !$currentTranslation['approved']) { // There's already a current translation for this string, but we'll activate this new one if ($isFuzzy === false && $currentTranslation['approved'] === null) { $queryUnsetCurrentTranslation->execute([0, $currentTranslation['id']]); } else { $queryUnsetCurrentTranslation->execute([$currentTranslation['approved'], $currentTranslation['id']]); } $addAsCurrent = 1; if ($isFuzzy) { $addAsApproved = null; ++$result->newApprovalNeeded; } else { $addAsApproved = 1; } $translatablesChanged[] = $translatableID; ++$result->addedAsCurrent; } else { // Let keep the previously current translation as the current one, but let's add this new one $addAsCurrent = null; $addAsApproved = null; ++$result->addedNotAsCurrent; ++$result->newApprovalNeeded; } // Add the new record to the queue $insertParams[] = $addAsCurrent; $insertParams[] = ($addAsCurrent === 1) ? $sqlNow : null; $insertParams[] = $addAsApproved; $insertParams[] = $translatableID; $insertParams[] = $translation->getTranslation(); for ($p = 1; $p <= 5; ++$p) { $insertParams[] = ($isPlural && $p < $pluralCount) ? $translation->getPluralTranslation($p - 1) : ''; } ++$insertCount; if ($insertCount === self::IMPORT_BATCH_SIZE) { // Flush the add queue $queryInsert->execute($insertParams); $insertParams = []; $insertCount = 0; } } elseif ($currentTranslation === null) { // This translation is already present, but there's no current translation: let's make it the current one if ($isFuzzy) { $querySetCurrentTranslation->execute([$sameTranslation['approved'], $sameTranslation['id']]); } else { $querySetCurrentTranslation->execute([1, $sameTranslation['id']]); if (!$sameTranslation['approved']) { ++$result->newApprovalNeeded; } } $translatablesChanged[] = $translatableID; ++$result->addedAsCurrent; } elseif ($sameTranslation['current'] === '1') { // This translation is already present and it's the current one if ($isFuzzy === false && !$sameTranslation['approved']) { // Let's mark the translation as approved $querySetCurrentTranslation->execute([1, $sameTranslation['id']]); ++$result->existingCurrentApproved; } elseif ($isFuzzy === true && $sameTranslation['approved'] && $unapproveFuzzy) { $querySetCurrentTranslation->execute([0, $sameTranslation['id']]); ++$result->existingCurrentUnapproved; } else { ++$result->existingCurrentUntouched; } } else { // This translation exists, but we have already another translation that's the current one if ($isFuzzy === false || !$currentTranslation['approved']) { // Let's make the new translation the current one if ($isFuzzy === false && $currentTranslation['approved'] === null) { $queryUnsetCurrentTranslation->execute([0, $currentTranslation['id']]); } else { $queryUnsetCurrentTranslation->execute([$currentTranslation['approved'], $currentTranslation['id']]); } $querySetCurrentTranslation->execute([1, $sameTranslation['id']]); $translatablesChanged[] = $translatableID; ++$result->existingActivated; } else { // The new translation already exists, it is fuzzy (not approved) and the current translation is approved if ($sameTranslation['approved'] !== null) { // Let's re-submit the existing translation for approval, as if it's a new translation $queryResubmitTranslation->execute([$sameTranslation['id']]); ++$result->addedNotAsCurrent; ++$result->newApprovalNeeded; } else { ++$result->existingNotCurrentUntouched; } } } } if ($insertCount > 0) { // Flush the add queue $connection->executeQuery( $this->buildInsertTranslationsSQL($connection, $locale, $insertCount, $user), $insertParams ); } $connection->commit(); } catch (Exception $x) { try { $connection->rollBack(); } catch (Exception $foo) { } throw $x; } catch (Throwable $x) { try { $connection->rollBack(); } catch (Exception $foo) { } throw $x; } if (count($translatablesChanged) > 0) { try { $this->events->dispatch( 'community_translation.translationsUpdated', new GenericEvent( $locale, [ 'translatableIDs' => $translatablesChanged, ] ) ); } catch (Exception $foo) { } } if ($result->newApprovalNeeded > 0) { try { $this->events->dispatch( 'community_translation.newApprovalNeeded', new GenericEvent( $locale, [ 'number' => $result->newApprovalNeeded, ] ) ); } catch (Exception $foo) { } } return $result; }
Import translations into the database. This function works directly with the database, not with entities (so that working on thousands of strings requires seconds instead of minutes). This implies that entities related to translations may become invalid. @param Translations $translations The translations to be imported @param LocaleEntity $locale The locale of the translations @param UserEntity $user The user to which new translations should be associated @param ImportOptions $options Import options (if not specified: we assume regular translator options) @throws UserMessageException @return ImportResult
entailment
private function buildInsertTranslationsSQL(Connection $connection, LocaleEntity $locale, $numRecords, UserEntity $user) { $fields = '(locale, createdOn, createdBy, current, currentSince, approved, translatable, text0, text1, text2, text3, text4, text5)'; $values = ' (' . implode(', ', [ // locale $connection->quote($locale->getID()), // createdOn $connection->getDatabasePlatform()->getNowExpression(), // createdBy $user->getUserID(), // current '?', // currentSince '?', // approved '?', // translatable '?', // text0... text5 '?, ?, ?, ?, ?, ?', ]) . '),'; $sql = 'INSERT INTO CommunityTranslationTranslations '; $sql .= ' ' . $fields; $sql .= ' VALUES ' . rtrim(str_repeat($values, $numRecords), ','); return $sql; }
@param Connection $connection @param int $numRecords @param UserEntity $user @return string
entailment
private function rowSameAsTranslation(array $row, GettextTranslation $translation, $isPlural, $pluralCount) { if ($row['text0'] !== $translation->getTranslation()) { return false; } if ($isPlural === false) { return true; } $same = true; switch ($pluralCount) { case 6: if ($same && $row['text5'] !== $translation->getPluralTranslation(4)) { $same = false; } /* @noinspection PhpMissingBreakStatementInspection */ case 5: if ($same && $row['text4'] !== $translation->getPluralTranslation(3)) { $same = false; } /* @noinspection PhpMissingBreakStatementInspection */ case 4: if ($same && $row['text3'] !== $translation->getPluralTranslation(2)) { $same = false; } /* @noinspection PhpMissingBreakStatementInspection */ case 3: if ($same && $row['text2'] !== $translation->getPluralTranslation(1)) { $same = false; } /* @noinspection PhpMissingBreakStatementInspection */ case 2: if ($same && $row['text1'] !== $translation->getPluralTranslation(0)) { $same = false; } break; } return $same; }
Is a database row the same as the translation? @param array $row @param GettextTranslation $translation @param bool $isPlural @param int $pluralCount @return bool
entailment
private function checkXSS(GettextTranslation $translation) { $sourceText = $translation->getOriginal(); $translatedText = $translation->getTranslation(); if ($translation->hasPlural()) { $sourceText .= "\n" . $translation->getPlural(); $translatedText .= "\n" . implode("\n", $translation->getPluralTranslation()); } $checkTags = false; foreach (['<', '=', '"'] as $char) { if (strpos($sourceText, $char) === false) { if (strpos($translatedText, $char) !== false) { throw new UserMessageException(t('The translation for the string \'%1$s\' can\'t contain the character \'%2$s\'.', $translation->getOriginal(), $char)); } } else { if ($char === '<') { $checkTags = true; } } } if ($checkTags) { $m = null; $sourceTags = preg_match_all('/<\\w+/', $sourceText, $m) ? array_unique($m[0]) : []; $translatedTags = preg_match_all('/<\\w+/', $translatedText, $m) ? array_unique($m[0]) : []; $extraTags = array_diff($translatedTags, $sourceTags); switch (count($extraTags)) { case 0: break; case 1: throw new UserMessageException(t('The translation for the string \'%1$s\' can\'t contain the string \'%2$s\'.', $translation->getOriginal(), current($extraTags))); default: $error = t('The translation for the string \'%1$s\' can\'t contain these strings:', $translation->getOriginal()); $error .= "\n- " . implode("\n- ", $extraTags); throw new UserMessageException($error); } } }
Check that translated text doesn't contain potentially harmful code. @param \Gettext\Translation $translation @throws \Concrete\Core\Error\UserMessageException
entailment
private function checkFormat(GettextTranslation $translation) { // placeholder := %[position][flags][width][.precision]specifier // position := \d+$ // flags := ([\-+ 0]|('.))* // width := \d* // precision := (\.\d*)? // specifier := [bcdeEfFgGosuxX] // $placeholdersRX = %(?:\d+\$)?(?:[\-+ 0]|('.))*\d*(?:\.\d*)?[bcdeEfFgGosuxX] $placeholdersRX = "/%(?:\\d+\\$)?(?:[\\-+ 0]|(?:'.))*\\d*(?:\\.\\d*)?[bcdeEfFgGosuxX]/"; $matches = null; preg_match_all($placeholdersRX, $translation->getOriginal(), $matches); sort($matches[0]); $sourcePlaceholdersList = ['singular' => $matches[0]]; if ($translation->hasPlural()) { preg_match_all($placeholdersRX, $translation->getPlural(), $matches); sort($matches[0]); $sourcePlaceholdersList['plural'] = $matches[0]; } $translatedTexts = [$translation->getTranslation()]; if ($translation->hasPlural()) { $translatedTexts = array_merge($translatedTexts, $translation->getPluralTranslation()); } foreach ($translatedTexts as $translatedText) { preg_match_all($placeholdersRX, $translatedText, $matches); sort($matches[0]); $translatedPlaceholders = $matches[0]; foreach ($sourcePlaceholdersList as $sourcePlaceholders) { if ($translatedPlaceholders !== $sourcePlaceholders) { if (count($sourcePlaceholders) === 0) { throw new UserMessageException(t( 'The translation should not contain any placeholder, but it contains %s', '"' . implode('", "', $translatedPlaceholders) . '"' )); } if (count($translatedPlaceholders) === 0) { throw new UserMessageException(t( 'The translation does not contain any placeholder, but it should contain %s', '"' . implode('", "', $sourcePlaceholders) . '"' )); } throw new UserMessageException(t( 'The translation should contain %1$s, but it contains %2$s', '"' . implode('", "', $sourcePlaceholders) . '"', '"' . implode('", "', $translatedPlaceholders) . '"' )); } } } }
Check that translated text doesn't contain potentially harmful code. @param \Gettext\Translation $translation @throws \Concrete\Core\Error\UserMessageException
entailment
protected function buildErrorResponse($error, $code = null) { if ($code !== null && (!is_int($code) || $code < 400)) { $code = null; } if (is_object($error)) { if ($error instanceof AccessDeniedException) { $error = $error->getMessage(); if ($code === null) { $code = Response::HTTP_UNAUTHORIZED; } } elseif ($error instanceof UserMessageException) { if ($error->getCode() >= 400) { $code = $error->getCode(); } $error = $error->getMessage(); } elseif ($error instanceof Exception || $error instanceof Throwable) { $error = t('An unexpected error occurred'); } elseif (is_callable([$error, '__toString'])) { $error = (string) $error; } else { $error = get_class($error); } } if ($code === null) { $code = Response::HTTP_INTERNAL_SERVER_ERROR; } return $this->getResponseFactory()->create( $error, $code, [ 'Content-Type' => 'text/plain; charset=UTF-8', ] ); }
Build an error response. @param string|Exception|Throwable $error @param int $code @return Response
entailment
protected function getRequestJson() { if ($this->request->getContentType() !== 'json') { throw new UserMessageException(t('Invalid request Content-Type: %s', $this->request->headers->get('Content-Type', '')), Response::HTTP_NOT_ACCEPTABLE); } $contentBody = $this->request->getContent(); $contentJson = @json_decode($contentBody, true); if (!is_array($contentJson)) { throw new UserMessageException(t('Failed to parse the request body as JSON'), Response::HTTP_NOT_ACCEPTABLE); } return $contentJson; }
Check if the request is a JSON request and returns the posted parameters. @throws UserMessageException @return array
entailment
protected function getPackageVersion(PackageEntity $package, $packageVersion, &$isBastMatch = null) { if ($packageVersion === 'best-match-version') { $isBastMatch = true; $result = null; if ($this->request->query->has('v')) { $v = $this->request->query->get('v'); if (is_string($v) && $v !== '') { $versionComparer = new VersionComparer(); $result = $versionComparer->matchPackageVersionEntities($package->getVersions(), $v); } } } else { $isBastMatch = false; $result = $this->app->make(PackageVersionRepository::class)->findByHandleAndVersion($package->getHandle(), $packageVersion); } return $result; }
@param PackageEntity $package @param string $packageVersionID @param bool $isBastMatch [out] @param string $packageVersion @return \CommunityTranslation\Entity\Package\Version|null
entailment
protected function finish(Response $response) { if ($this->requestedResultsLocale !== '') { $this->getLocalization()->popActiveContext(); } if (!$response->headers->has('X-Frame-Options')) { $response->headers->set('X-Frame-Options', 'DENY'); } if (!$response->headers->has('Access-Control-Allow-Origin')) { $config = $this->app->make('community_translation/config'); $response->headers->set('Access-Control-Allow-Origin', (string) $config->get('options.api.accessControlAllowOrigin')); } return $response; }
@param Response $response @return Response
entailment
public function getRateLimit() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $rateLimit = $this->getUserControl()->getRateLimit(); if ($rateLimit === null) { $result = $this->buildJsonResponse(null); } else { list($maxRequests, $timeWindow) = $rateLimit; $visits = $this->getUserControl()->getVisitsCountFromCurrentIP($timeWindow); $result = $this->buildJsonResponse([ 'maxRequests' => $maxRequests, 'timeWindow' => $timeWindow, 'currentCounter' => $visits, ]); } } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get the current rate limit status. @return Response @example http://www.example.com/api/rate-limit/
entailment
public function getLocales() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $locales = $this->app->make(LocaleRepository::class)->getApprovedLocales(); $result = $this->buildJsonResponse($this->localesToArray($locales)); } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get the list of approved locales. @return Response @example http://www.example.com/api/locales/
entailment
public function getPackages() { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $repo = $this->app->make(PackageRepository::class); $packages = $repo->createQueryBuilder('p') ->select('p.handle, p.name') ->getQuery()->getArrayResult(); $result = $this->buildJsonResponse($packages); } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get the list of packages. @return Response @example http://www.example.com/api/packages/
entailment
public function getPackageVersions($packageHandle) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $this->getUserControl()->checkGenericAccess(__FUNCTION__); $package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageHandle]); if ($package === null) { throw new UserMessageException(t('Unable to find the specified package'), Response::HTTP_NOT_FOUND); } $versions = []; foreach ($package->getSortedVersions(true, null) as $packageVersion) { $versions[] = $packageVersion->getVersion(); } $result = $this->buildJsonResponse($versions); } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get the list of versions of a package. @param string $packageHandle @return Response @example http://www.example.com/api/package/concrete5/versions/
entailment
public function getPackageVersionLocales($packageHandle, $packageVersion, $minimumLevel = null) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $accessibleLocales = $this->getUserControl()->checkLocaleAccess(__FUNCTION__); $package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageHandle]); if ($package === null) { throw new UserMessageException(t('Unable to find the specified package'), Response::HTTP_NOT_FOUND); } $isBestMatch = null; $version = $this->getPackageVersion($package, $packageVersion, $isBestMatch); if ($version === null) { throw new UserMessageException(t('Unable to find the specified package version'), Response::HTTP_NOT_FOUND); } $minimumLevel = (int) $minimumLevel; $stats = $this->app->make(StatsRepository::class)->get($version, $accessibleLocales); $utc = new DateTimeZone('UTC'); $resultData = $this->localesToArray( $accessibleLocales, function (LocaleEntity $locale, array $item) use ($stats, $minimumLevel, $utc) { $result = null; foreach ($stats as $stat) { if ($stat->getLocale() === $locale) { if ($stat->getPercentage() >= $minimumLevel) { $item['total'] = $stat->getTotal(); $item['translated'] = $stat->getTranslated(); $item['progress'] = $stat->getPercentage(true); $dt = $stat->getLastUpdated(); if ($dt === null) { $item['updated'] = null; } else { $dt = clone $dt; $dt->setTimezone($utc); $item['updated'] = $dt->format('c'); } $result = $item; } break; } } return $result; } ); if ($isBestMatch) { $resultData = [ 'versionHandle' => $version->getVersion(), 'versionName' => $version->getDisplayVersion(), 'locales' => $resultData, ]; } $result = $this->buildJsonResponse($resultData); } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get some stats about the translations of a package version. @param string $packageHandle @param string $packageVersion @param null|int $minimumLevel @return Response @example http://www.example.com/api/package/concrete5/8.2/locales/80/ @example http://www.example.com/api/package/concrete5/best-match-version/locales/80/?v=8.2rc1
entailment
public function getPackageVersionTranslations($packageHandle, $packageVersion, $localeID, $formatHandle) { $this->start(); try { $this->getUserControl()->checkRateLimit(); $accessibleLocales = $this->getUserControl()->checkLocaleAccess(__FUNCTION__); $locale = $this->app->make(LocaleRepository::class)->findApproved($localeID); if ($locale === null) { throw new UserMessageException(t('Unable to find the specified locale'), Response::HTTP_NOT_FOUND); } if (!in_array($locale, $accessibleLocales, true)) { throw AccessDeniedException::create(t('Access denied to the specified locale')); } $package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $packageHandle]); if ($package === null) { throw new UserMessageException(t('Unable to find the specified package'), Response::HTTP_NOT_FOUND); } $version = $this->getPackageVersion($package, $packageVersion); if ($version === null) { throw new UserMessageException(t('Unable to find the specified package version'), Response::HTTP_NOT_FOUND); } $format = $this->app->make(TranslationsConverterProvider::class)->getByHandle($formatHandle); if ($format === null) { throw new UserMessageException(t('Unable to find the specified translations format'), Response::HTTP_NOT_FOUND); } $translationsFile = $this->app->make(TranslationsFileExporter::class)->getSerializedTranslationsFile($version, $locale, $format); $this->app->make(DownloadStatsRepository::class)->logDownload($locale, $version); $result = BinaryFileResponse::create( // $file $translationsFile, // $status Response::HTTP_OK, // $headers [ 'Content-Type' => 'application/octet-stream', 'Content-Transfer-Encoding' => 'binary', ] )->setContentDisposition( 'attachment', 'translations-' . $locale->getID() . '.' . $format->getFileExtension() ); } catch (Exception $x) { $result = $this->buildErrorResponse($x); } catch (Throwable $x) { $result = $this->buildErrorResponse($x); } return $this->finish($result); }
Get the translations of a package version. @param string $packageHandle @param string $packageVersion @param string $localeID @param string $formatHandle @return Response @example http://www.example.com/api/package/concrete5/8.2/translations/it_IT/mo/ @example http://www.example.com/api/package/concrete5/best-match-version/translations/it_IT/mo/?v=8.2rc1
entailment