sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getUnreviewedSelectQuery(LocaleEntity $locale)
{
$cn = $this->app->make(EntityManager::class)->getConnection();
$queryLocaleID = $cn->quote($locale->getID());
return $cn->executeQuery(
$this->getBaseSelectString($locale, false, false) .
" inner join
(
select distinct
translatable
from
CommunityTranslationTranslations
where
locale = $queryLocaleID
and
(
(approved is null)
or
(current = 1 and approved = 0)
)
) as tNR on CommunityTranslationTranslatables.id = tNR.translatable
order by
CommunityTranslationTranslatables.text
"
);
} | Get the recordset of all the translations of a locale that needs to be reviewed.
@param LocaleEntity $locale
@return PDOStatement | entailment |
public function getPackageSelectQuery(PackageVersionEntity $packageVersion, LocaleEntity $locale, $excludeUntranslatedStrings = false)
{
$cn = $this->app->make(EntityManager::class)->getConnection();
$queryPackageVersionID = (int) $packageVersion->getID();
return $cn->executeQuery(
$this->getBaseSelectString($locale, true, $excludeUntranslatedStrings) .
"
where
CommunityTranslationTranslatablePlaces.packageVersion = $queryPackageVersionID
order by
CommunityTranslationTranslatablePlaces.sort
"
);
} | Get recordset of the translations for a specific package, version and locale.
@param PackageVersionEntity $packageVersion
@param LocaleEntity $locale
@param bool $excludeUntranslatedStrings
@return PDOStatement | entailment |
public function forPackage($packageOrHandleVersion, LocaleEntity $locale, $excludeUntranslatedStrings = false)
{
if ($packageOrHandleVersion instanceof PackageVersionEntity) {
$packageVersion = $packageOrHandleVersion;
} elseif (is_array($packageOrHandleVersion) && isset($packageOrHandleVersion['handle']) && isset($packageOrHandleVersion['version'])) {
$packageVersion = $this->app->make(PackageVersionRepository::class)->findOneBy([
'handle' => $packageOrHandleVersion['handle'],
'version' => $packageOrHandleVersion['version'],
]);
} elseif (is_array($packageOrHandleVersion) && isset($packageOrHandleVersion[0]) && isset($packageOrHandleVersion[1])) {
$packageVersion = $this->app->make(PackageVersionRepository::class)->findOneBy([
'handle' => $packageOrHandleVersion[0],
'version' => $packageOrHandleVersion[1],
]);
} else {
$packageVersion = null;
}
if ($packageVersion === null) {
throw new UserMessageException(t('Invalid translated package version specified'));
}
$rs = $this->getPackageSelectQuery($packageVersion, $locale, $excludeUntranslatedStrings);
$result = $this->buildTranslations($locale, $rs);
$result->setHeader('Project-Id-Version', $packageVersion->getPackage()->getHandle() . ' ' . $packageVersion->getVersion());
return $result;
} | Get the translations for a specific package, version and locale.
@param PackageVersionEntity|array $packageOrHandleVersion The package version for which you want the translations (a Package\Version entity instance of an array with handle and version)
@param LocaleEntity $locale the locale that you want
@param bool $excludeUntranslatedStrings set to true to filter out untranslated strings
@return Translations | entailment |
public function unreviewed(LocaleEntity $locale)
{
$rs = $this->getUnreviewedSelectQuery($locale);
$result = $this->buildTranslations($locale, $rs);
$result->setHeader('Project-Id-Version', 'unreviewed');
return $result;
} | Get the unreviewed translations for a locale.
@param LocaleEntity $locale the locale that you want
@param bool $excludeUntranslatedStrings set to true to filter out untranslated strings
@return Translations | entailment |
protected function buildTranslations(LocaleEntity $locale, PDOStatement $rs)
{
$translations = new Translations();
$translations->setLanguage($locale->getID());
$numPlurals = $locale->getPluralCount();
while (($row = $rs->fetch()) !== false) {
$translation = new \Gettext\Translation($row['context'], $row['text'], $row['plural']);
foreach (unserialize($row['locations']) as $location) {
$translation->addReference($location);
}
foreach (unserialize($row['comments']) as $comment) {
$translation->addExtractedComment($comment);
}
if ($row['text0'] !== null) {
if (!$row['approved']) {
$translation->addFlag('fuzzy');
}
$translation->setTranslation($row['text0']);
if ($translation->hasPlural()) {
switch ($numPlurals) {
case 6:
$translation->setPluralTranslation($row['text5'], 4);
/* @noinspection PhpMissingBreakStatementInspection */
case 5:
$translation->setPluralTranslation($row['text4'], 3);
/* @noinspection PhpMissingBreakStatementInspection */
case 4:
$translation->setPluralTranslation($row['text3'], 2);
/* @noinspection PhpMissingBreakStatementInspection */
case 3:
$translation->setPluralTranslation($row['text2'], 1);
/* @noinspection PhpMissingBreakStatementInspection */
case 2:
$translation->setPluralTranslation($row['text1'], 0);
/* @noinspection PhpMissingBreakStatementInspection */
break;
}
}
}
$translations->append($translation);
}
$rs->closeCursor();
return $translations;
} | @param LocaleEntity $locale
@param PDOStatement $rs
@return Translations | entailment |
public function localeHasPendingApprovals(LocaleEntity $locale)
{
$cn = $this->app->make(EntityManager::class)->getConnection();
$rs = $cn->executeQuery(
'
select
CommunityTranslationTranslations.id
from
CommunityTranslationTranslations
inner join CommunityTranslationTranslatablePlaces on CommunityTranslationTranslations.translatable = CommunityTranslationTranslatablePlaces.translatable
where
CommunityTranslationTranslations.locale = ?
and (
(CommunityTranslationTranslations.approved is null)
or
(CommunityTranslationTranslations.current = 1 and CommunityTranslationTranslations.approved = 0)
)
limit 1
',
[
$locale->getID(),
]
);
$result = $rs->fetchColumn() !== false;
$rs->closeCursor();
return $result;
} | Does a locale have translation strings that needs review?
@param LocaleEntity $locale
@return bool | entailment |
public function getConfigTreeBuilder()
{
$treeBuilder = new TreeBuilder();
$rootNode = $treeBuilder->root('ez_share_buttons');
$systemNode = $this->generateScopeBaseNode($rootNode);
$this->addCommonSettings($systemNode);
$this->addFacebookLikeSettings($systemNode);
$this->addFacebookRecommendSettings($systemNode);
$this->addGooglePlusSettings($systemNode);
$this->addTwitterSettings($systemNode);
$this->addLinkedinSettings($systemNode);
$this->addXingSettings($systemNode);
return $treeBuilder;
} | {@inheritdoc} | entailment |
protected function parseSize($size)
{
$result = null;
$size = (string) $size;
$matches = null;
if (preg_match('/^\s*(\d+(?:\.\d*)?)\s*(?:([bkmgtpezy])b?)?\s*/i', $size, $matches)) {
$value = (float) $matches[1];
$unit = empty($matches[2]) ? 'b' : strtolower($matches[2]);
if ($unit === 'b') {
$result = (int) $value;
} else {
$result = (int) round($value * pow(1024, strpos('bkmgtpezy', $unit)));
}
}
return $result;
} | @param string|int $size
@return int|null | entailment |
protected function normalizeArgs(array $args)
{
$args += [
'statsFromPackage' => '',
];
$error = $this->app->make('helper/validation/error');
$normalized = [];
try {
/* @var \CommunityTranslation\Service\RateLimit $rateLimitHelper */
list($normalized['rateLimit_maxRequests'], $normalized['rateLimit_timeWindow']) = $this->app->make(RateLimit::class)->fromWidgetHtml('rateLimit', $this->rateLimit_timeWindow ?: 3600);
} catch (UserMessageException $x) {
$error->add($x->getMessage());
}
$normalized['maxFileSize'] = null;
if (isset($args['maxFileSizeValue']) && (is_int($args['maxFileSizeValue']) || (is_string($args['maxFileSizeValue']) && is_numeric($args['maxFileSizeValue'])))) {
$maxFileSizeValue = (int) $args['maxFileSizeValue'];
if ($maxFileSizeValue > 0) {
$maxFileSizeUnit = $this->post('maxFileSizeUnit');
$p = is_string($maxFileSizeUnit) ? array_search($maxFileSizeUnit, ['b', 'KB', 'MB', 'GB'], true) : false;
if ($p === false) {
$error->add(t('Please specify the unit of the max size of uploaded files'));
} else {
$maxFileSize = (int) $maxFileSizeValue * pow(1024, $p);
$postLimit = $this->getPostLimit();
if ($postLimit !== null && $maxFileSize > $postLimit) {
$nh = $this->app->make('helper/number');
$error->add(
t(
'You can\'t set the max file size to %1$s since the current limit imposed by PHP is %2$s',
$nh->formatSize($maxFileSize),
$nh->formatSize($postLimit)
)
);
} else {
$normalized['maxFileSize'] = $maxFileSize;
}
}
}
}
$normalized['maxLocalesCount'] = null;
if (isset($args['maxLocalesCount']) && (is_int($args['maxLocalesCount']) || (is_string($args['maxLocalesCount']) && is_numeric($args['maxLocalesCount'])))) {
$i = (int) $args['maxLocalesCount'];
if ($i > 0) {
$normalized['maxLocalesCount'] = $i;
}
}
$normalized['maxStringsCount'] = null;
if (isset($args['maxStringsCount']) && (is_int($args['maxStringsCount']) || (is_string($args['maxStringsCount']) && is_numeric($args['maxStringsCount'])))) {
$i = (int) $args['maxStringsCount'];
if ($i > 0) {
$normalized['maxStringsCount'] = $i;
}
}
$normalized['statsFromPackage'] = '';
if (is_string($args['statsFromPackage'])) {
$normalized['statsFromPackage'] = trim($args['statsFromPackage']);
if ($normalized['statsFromPackage'] !== '') {
$package = $this->app->make(PackageRepository::class)->findOneBy(['handle' => $normalized['statsFromPackage']]);
if ($package === null) {
$error->add(t('Unable to find a package with handle "%s"', $normalized['statsFromPackage']));
} elseif ($package->getLatestVersion() === null) {
$error->add(t('The package with handle "%s" does not have a latest version', $normalized['statsFromPackage']));
}
}
}
return $error->has() ? $error : $normalized;
} | {@inheritdoc}
@see BlockController::normalizeArgs() | entailment |
private function getPostedFile()
{
$file = $this->request->files->get('file');
if ($file === null) {
throw new UserMessageException(t('Please specify the file to be analyzed'));
}
if (!$file->isValid()) {
throw new UserMessageException($file->getErrorMessage());
}
if ($this->maxFileSize) {
$filesize = @filesize($file->getPathname());
if ($filesize !== false && $filesize > $this->maxFileSize) {
throw new UserMessageException(t('The uploaded file is too big'));
}
}
return $file;
} | @throws UserMessageException
$return \Symfony\Component\HttpFoundation\File\UploadedFile | entailment |
private function getPostedLocales()
{
$localeIDs = [];
$list = $this->post('translatedLocales');
if (is_array($list)) {
$localeIDs = array_merge($localeIDs, $list);
}
$list = $this->post('untranslatedLocales');
if (is_array($list)) {
$localeIDs = array_merge($localeIDs, $list);
}
$repo = $this->app->make(LocaleRepository::class);
$locales = $repo->getApprovedLocales();
$result = [];
foreach ($locales as $locale) {
if (in_array($locale->getID(), $localeIDs, true)) {
$result[] = $locale;
}
}
$count = count($result);
if ($count === 0) {
throw new UserMessageException(t('Please specify the languages of the .po/.mo files to generate'));
}
if ($this->maxLocalesCount && $count > (int) $this->maxLocalesCount) {
throw new UserMessageException(t('Please specify up to %s languages (you requested %2$s languages)', $this->maxLocalesCount, $count));
}
return $result;
} | @throws UserMessageException
$return \CommunityTranslation\Entity\Locale[] | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$eventName = $this->getStopwatchEventName($request);
$this->stopwatch->start($eventName, self::CATEGORY);
return $next($request)->then(function (ResponseInterface $response) use ($eventName) {
$this->stopwatch->stop($eventName, self::CATEGORY);
return $response;
}, function (Exception $exception) use ($eventName) {
$this->stopwatch->stop($eventName, self::CATEGORY);
throw $exception;
});
} | {@inheritdoc} | entailment |
public function getColumnContent($gridField, $record, $columnName) {
if(!$record->canView()) return;
$field = GridField_FormAction::create($gridField, 'ExportSingle'.$record->ID, false,
"exportsingle", array('RecordID' => $record->ID))
->addExtraClass('gridfield-button-export-single no-ajax')
->setAttribute('title', _t('firebrandhq.EXCELEXPORT', "Export"))
->setAttribute('data-icon', 'download-csv');
return $field->Field();
} | Return the button to show at the end of the row
@param GridField $gridField
@param DataObject $record
@param string $columnName
@return string - the HTML for the column | entailment |
public function handleAction(GridField $gridField, $actionName, $arguments, $data) {
if($actionName == 'exportsingle') {
// Get the item
$item = $gridField->getList()->byID($arguments['RecordID']);
if(!$item) {
return;
}
// Make sure th current user is authorised to view the item.
if (!$item->canView()) {
throw new ValidationException(
_t('firebrandhq.EXCELEXPORT', "Can not view record"),0);
}
// Build a filename
$filename = $item->i18n_singular_name() . ' - ID ' . $item->ID;
$title = $item->getTitle();
if ($title) {
$filename .= ' - ' . $title;
}
// Pick Converter
switch ($this->exportType) {
case 'xlsx':
$formater = new ExcelDataFormatter();
break;
case 'xls':
$formater = new OldExcelDataFormatter();
break;
case 'csv':
$formater = new CsvDataFormatter();
break;
default:
user_error(
"GridFieldExcelExportAction expects \$exportType to be either 'xlsx', 'xls' or 'csv'. " .
"'{$this->exportType}' provided",
E_USER_ERROR
);
}
// Set the header that will cause the browser to download and save the file.
$this->setHeader($gridField, $this->exportType, $filename);
// Export our Data Object
$formater->setUseLabelsAsHeaders($this->useLabelsAsHeaders);
$fileData = $formater->convertDataObject($item);
return $fileData;
}
} | Handle the actions and apply any changes to the GridField
@param GridField $gridField
@param string $actionName
@param mixed $arguments
@param array $data - form data
@return void | entailment |
public function setUseLabelsAsHeaders($value)
{
if ($value === null) {
$this->useLabelsAsHeaders = null;
} else {
$this->useLabelsAsHeaders = (bool)$value;
}
return $this;
} | Set the DataFormatter's UseFieldLabelsAsHeaders property
@param bool $value
@return GridFieldExcelExportButton | entailment |
public function createAttributeValueFromRequest()
{
$data = $this->post();
if (!is_array($data)) {
$data = [];
}
$data += [
'operation' => null,
'current-token' => '',
'current-token-hash' => '',
];
switch ($data['operation']) {
case 'keep':
$value = $data['current-token'];
if (!is_string($value)) {
$value = '';
}
if ($value !== '') {
if (sha1($this->getSessionHash(false) . $value) !== $data['current-token-hash']) {
$ok = false;
} else {
$ok = $this->app->make(Token::class)->isGenerated($value);
}
if (!$ok) {
throw new Exception('Hack attempt detected.');
}
}
break;
case 'generate':
$value = $this->app->make(Token::class)->generate();
break;
case 'remove':
$value = '';
break;
default:
throw new Exception('Invalid operation');
}
return $this->createAttributeValue($value);
} | {@inheritdoc}
@see \Concrete\Core\Attribute\Controller::createAttributeValueFromRequest() | entailment |
public function search()
{
$this->set('form', $this->app->make('helper/form'));
$this->set('fieldName', $this->field('value'));
$this->set('fieldValue', $this->request('value'));
} | {@inheritdoc}
@see \Concrete\Core\Attribute\DefaultController::search() | entailment |
protected function normalizeArgs(array $args)
{
$error = $this->app->make('helper/validation/error');
$normalized = [
'askNewTeamCID' => null,
'askNewTeamLink' => '',
];
switch (isset($args['askNewTeamLinkType']) ? $args['askNewTeamLinkType'] : '') {
case 'cid':
if (isset($args['askNewTeamCID']) && ((is_string($args['askNewTeamCID']) && is_numeric($args['askNewTeamCID'])) || is_int($args['askNewTeamCID']))) {
$i = (int) $args['askNewTeamCID'];
if ($i > 0) {
$normalized['askNewTeamCID'] = $i;
}
}
break;
case 'link':
if (isset($args['askNewTeamLink']) && is_string($args['askNewTeamLink'])) {
$normalized['askNewTeamLink'] = trim($args['askNewTeamLink']);
}
break;
}
return $error->has() ? $error : $normalized;
} | {@inheritdoc}
@see BlockController::normalizeArgs() | entailment |
protected function getPackageVersions($obj)
{
$result = [];
if ($obj instanceof PackageVersionEntity) {
$result[] = $obj;
} elseif (is_array($obj)) {
$app = Application::getFacadeApplication();
if (isset($obj['handle']) && isset($obj['version'])) {
$pv = $app->make(PackageVersionRepository::class)->findByHandleAndVersion(
$obj['handle'],
$obj['version']
);
if ($pv === null) {
throw new UserMessageException(t('Invalid translated package specified'));
}
$result[] = $pv;
} elseif (isset($obj[0]) && is_string($obj[1]) && isset($obj[1]) && is_string($obj[1])) {
$pv = $app->make(PackageVersionRepository::class)->findByHandleAndVersion(
$obj[0],
$obj[1]
);
if ($pv === null) {
throw new UserMessageException(t('Invalid translated package specified'));
}
$result[] = $pv;
} else {
foreach ($obj as $item) {
$result = array_merge($result, $this->getPackageVersions($item));
}
}
}
if (empty($result)) {
throw new UserMessageException(t('Invalid translated package specified'));
}
return $result;
} | @param mixed $obj
@return PackageVersionEntity[] | entailment |
protected function getLocales($obj)
{
$result = [];
if ($obj instanceof LocaleEntity) {
$result[] = $obj;
} elseif (is_string($obj)) {
$app = Application::getFacadeApplication();
$l = $app->make(LocaleRepository::class)->findApproved($obj);
if ($l === null) {
throw new UserMessageException(t('Invalid locale specified'));
}
$result[] = $l;
} elseif (is_array($obj)) {
foreach ($obj as $item) {
$result = array_merge($result, $this->getLocales($item));
}
}
if (empty($result)) {
throw new UserMessageException(t('Invalid locale specified'));
}
return $result;
} | @param mixed $obj
@return LocaleEntity[] | entailment |
public function getOne(PackageVersionEntity $packageVersion, LocaleEntity $locale)
{
$array = $this->get($packageVersion, $locale);
return array_shift($array);
} | Get some stats about a package version and a locale.
@param PackageVersionEntity $packageVersion
@param LocaleEntity $locale
@return Stats | entailment |
public function get($wantedPackageVersions, $wantedLocales)
{
$packageVersions = array_values(array_unique($this->getPackageVersions($wantedPackageVersions)));
$locales = array_values(array_unique($this->getLocales($wantedLocales)));
$qb = $this->createQueryBuilder('s');
if (count($packageVersions) === 1) {
$qb->andWhere('s.packageVersion = :packageVersion')->setParameter('packageVersion', $packageVersions[0]);
} else {
$or = $qb->expr()->orX();
foreach ($packageVersions as $i => $pv) {
$or->add("s.packageVersion = :packageVersion$i");
$qb->setParameter("packageVersion$i", $pv);
}
$qb->andWhere($or);
}
if (count($locales) === 1) {
$qb->andWhere('s.locale = :locale');
$qb->setParameter('locale', $locales[0]);
} else {
$or = $qb->expr()->orX();
foreach ($locales as $i => $l) {
$or->add("s.locale = :locale$i");
$qb->setParameter("locale$i", $l);
}
$qb->andWhere($or);
}
$result = $qb->getQuery()->getResult();
/* @var StatsEntity[] $result */
$missingLocalesForPackageVersions = [];
foreach ($packageVersions as $packageVersion) {
foreach ($locales as $locale) {
$found = false;
foreach ($result as $stats) {
if ($stats->getPackageVersion()->getID() === $packageVersion->getID() && $stats->getLocale()->getID() === $locale->getID()) {
$found = true;
break;
}
}
if ($found === false) {
if (!isset($missingLocalesForPackageVersions[$packageVersion->getID()])) {
$missingLocalesForPackageVersions[$packageVersion->getID()] = ['packageVersion' => $packageVersion, 'locales' => []];
}
$missingLocalesForPackageVersions[$packageVersion->getID()]['locales'][] = $locale;
}
}
}
foreach ($missingLocalesForPackageVersions as $missingLocalesForPackageVersion) {
$result = array_merge($result, $this->build($missingLocalesForPackageVersion['packageVersion'], $missingLocalesForPackageVersion['locales']));
}
return array_values($result);
} | Get some stats about one or more package versions and one or more locales.
@param PackageVersionEntity|PackageVersionEntity[]|array|array[array] $wantedPackageVersions
@param LocaleEntity|LocaleEntity[]|string|string[] $wantedLocales
@return StatsEntity[] | entailment |
public function resetForLocaleTranslatables(LocaleEntity $locale, $translatables)
{
$this->resetForLocale($locale);
$translatableIDs = [];
if ($translatables) {
if ($translatables instanceof TranslatableEntity) {
$translatableIDs[] = $translatables->getID();
} elseif (is_int($translatables)) {
$translatableIDs[] = $translatables;
} elseif (is_array($translatables)) {
foreach ($translatables as $translatable) {
if ($translatable instanceof TranslatableEntity) {
$translatableIDs[] = $translatable->getID();
} elseif (is_int($translatable)) {
$translatableIDs[] = $translatable;
} else {
throw new UserMessageException(t('Invalid translatable string specified'));
}
}
}
}
if (empty($translatableIDs)) {
throw new UserMessageException(t('Invalid translatable string specified'));
}
$this->getEntityManager()->getConnection()->executeQuery(
'
delete s.*
from CommunityTranslationStats as s
inner join CommunityTranslationTranslatablePlaces as p on s.packageVersion = p.packageVersion
where s.locale = ?
and (p.translatable = ' . implode(' or p.translatable = ', $translatableIDs) . ')
',
[$locale->getID()]
);
} | @param LocaleEntity $locale
@param TranslatableEntity|int|TranslatableEntity[]|int[] $translatables
@throws UserMessageException | entailment |
protected function build(PackageVersionEntity $packageVersion, array $locales)
{
$result = [];
$app = Application::getFacadeApplication();
try {
$total = (int) $app->make(TranslatablePlaceRepository::class)
->createQueryBuilder('p')
->select('count(p.translatable)')
->where('p.packageVersion = :packageVersion')->setParameter('packageVersion', $packageVersion)
->getQuery()->getSingleScalarResult();
} catch (NoResultException $x) {
$total = 0;
}
foreach ($locales as $locale) {
$result[$locale->getID()] = StatsEntity::create($packageVersion, $locale)->setTotal($total);
}
$em = $this->getEntityManager();
$connection = $em->getConnection();
if ($total > 0) {
$q = [$packageVersion->getID()];
$w = [];
foreach ($locales as $locale) {
$w[] = 't.locale = ?';
$q[] = $locale->getID();
}
$dateTimeFormatString = $connection->getDatabasePlatform()->getDateTimeFormatString();
$rs = $connection->executeQuery(
'
select
t.locale,
count(t.translatable) as translated,
max(t.currentSince) as updated
from
CommunityTranslationTranslatablePlaces as p
inner join CommunityTranslationTranslations as t on p.translatable = t.translatable and 1 = t.current
where
p.packageVersion = ?
and (' . implode(' or ', $w) . ')
group by
t.locale
',
$q
);
while (($row = $rs->fetch()) !== false) {
if (!empty($row['translated'])) {
$result[$row['locale']]
->setTranslated($row['translated'])
->setLastUpdated(DateTime::createFromFormat($dateTimeFormatString, $row['updated']));
}
}
$rs->closeCursor();
}
foreach ($result as $stats) {
$em->persist($stats);
}
$em->flush();
return array_values($result);
} | @param PackageVersionEntity $packageVersion
@param LocaleEntity[] $locales
@return Stats | entailment |
public function getUser($user)
{
$result = null;
if ($user === 'current') {
$u = new \User();
if ($u->isRegistered()) {
$result = $u;
}
} elseif (is_int($user) || (is_string($user) && is_numeric($user))) {
$result = \User::getByUserID($user);
} elseif ($user instanceof UserService) {
$result = $user;
} elseif ($user instanceof UserEntity) {
$result = \User::getByUserID($user->getUserID());
}
return $result;
} | Parse the $user parameter of the functions.
@param int|UserService|UserEntity|'current' $user
@return \User|null | entailment |
public function getUserEntity($user)
{
$result = null;
if ($user instanceof UserEntity) {
$result = $user;
} else {
$u = $this->getUser($user);
if ($u !== null) {
$result = $this->app->make(EntityManager::class)->find(UserEntity::class, $u->getUserID());
}
}
return $result;
} | Parse the $user parameter of the functions.
@param int|UserService|UserEntity|'current' $user
@return UserEntity|null | entailment |
protected function getLocale($locale)
{
$result = null;
if ($locale instanceof LocaleEntity) {
$result = $locale;
} elseif (is_string($locale) && $locale !== '') {
$result = $this->app->make(LocaleRepository::class)->findApproved($locale);
}
return $result;
} | Parse the $locale parameter of the functions.
@param mixed $locale
@return LocaleEntity|null | entailment |
public function getLocaleAccess($locale, $user = 'current')
{
$result = self::NONE;
$user = $this->getUser($user);
if ($user === null) {
$result = self::NOT_LOGGED_IN;
} else {
$result = self::NONE;
if ($user->getUserID() == USER_SUPER_ID) {
$result = self::GLOBAL_ADMIN;
} elseif ($user->inGroup($this->groups->getGlobalAdministrators())) {
$result = self::GLOBAL_ADMIN;
} else {
$locale = $this->getLocale($locale);
if ($locale !== null) {
if ($user->inGroup($this->groups->getAdministrators($locale))) {
$result = self::ADMIN;
} elseif ($user->inGroup($this->groups->getTranslators($locale))) {
$result = self::TRANSLATE;
} elseif ($user->inGroup($this->groups->getAspiringTranslators($locale))) {
$result = self::ASPRIRING;
}
}
}
}
return $result;
} | Get the access level to a specific locale.
@param LocaleEntity|string $locale
@param UserService|int|'current' $user
@return int One of the Access constants | entailment |
public function setLocaleAccess($wantedLocale, $access, $wantedUser = 'current')
{
$user = $this->getUser($wantedUser);
if ($user === null) {
throw new UserMessageException(t('Invalid user'));
}
$locale = $this->getLocale($wantedLocale);
if ($locale === null) {
throw new UserMessageException(t("The locale identifier '%s' is not valid", $locale));
}
if ($user->getUserID() === USER_SUPER_ID) {
return;
}
$access = (int) $access;
if ($access === self::GLOBAL_ADMIN) {
$this->setGlobalAccess(true, $user);
} else {
$oldAccess = $this->getLocaleAccess($locale, $user);
if ($oldAccess === self::GLOBAL_ADMIN && $access !== self::NONE) {
throw new UserMessageException(t('User is a global locale administrator'));
}
switch ($access) {
case self::ADMIN:
$newGroup = $this->groups->getAdministrators($locale);
break;
case self::TRANSLATE:
$newGroup = $this->groups->getTranslators($locale);
break;
case self::ASPRIRING:
$newGroup = $this->groups->getAspiringTranslators($locale);
break;
case self::NONE:
$newGroup = null;
break;
default:
throw new UserMessageException(t('Invalid access level specified'));
}
if ($newGroup !== null) {
$user->enterGroup($newGroup);
}
switch ($oldAccess) {
case self::GLOBAL_ADMIN:
/* @noinspection PhpMissingBreakStatementInspection */
case self::ADMIN:
$g = $this->groups->getAdministrators($locale);
if ($g !== $newGroup && $user->inGroup($g)) {
$user->exitGroup($g);
}
/* @noinspection PhpMissingBreakStatementInspection */
case self::TRANSLATE:
$g = $this->groups->getTranslators($locale);
if ($g !== $newGroup && $user->inGroup($g)) {
$user->exitGroup($g);
}
/* @noinspection PhpMissingBreakStatementInspection */
case self::ASPRIRING:
$g = $this->groups->getAspiringTranslators($locale);
if ($g !== $newGroup && $user->inGroup($g)) {
$user->exitGroup($g);
}
break;
}
}
} | Get the access level to a specific locale.
@param LocaleEntity|string $wantedLocale
@param int $access One of the Access constants
@param UserService|int|'current' $wantedUser
@return int One of the Access constants | entailment |
public function setGlobalAccess($enable, $user = 'current')
{
$user = $this->getUser($user);
if ($user === null) {
throw new UserMessageException(t('Invalid user'));
}
if ($user->getUserID() === USER_SUPER_ID) {
return;
}
$group = $this->groups->getGlobalAdministrators();
if ($enable) {
foreach ($this->app->make(LocaleRepository::class)->getApprovedLocales() as $locale) {
$this->setLocaleAccess($locale, self::NONE, $user);
}
if (!$user->inGroup($group)) {
$user->enterGroup($group);
}
} else {
if ($user->inGroup($group)) {
$user->exitGroup($group);
}
}
} | Set or unset global administration access.
@param bool $enable
@param UserService|int|'current' $user | entailment |
private function decodeOnEncodingHeader($headerName, ResponseInterface $response)
{
if ($response->hasHeader($headerName)) {
$encodings = $response->getHeader($headerName);
$newEncodings = [];
while ($encoding = array_pop($encodings)) {
$stream = $this->decorateStream($encoding, $response->getBody());
if (false === $stream) {
array_unshift($newEncodings, $encoding);
continue;
}
$response = $response->withBody($stream);
}
$response = $response->withHeader($headerName, $newEncodings);
}
return $response;
} | Decode a response on a specific header (content encoding or transfer encoding mainly).
@param string $headerName Name of the header
@param ResponseInterface $response Response
@return ResponseInterface A new instance of the response decoded | entailment |
private function decorateStream($encoding, StreamInterface $stream)
{
if ('chunked' == strtolower($encoding)) {
return new DechunkStream($stream);
}
if ('compress' == strtolower($encoding)) {
return new DecompressStream($stream);
}
if ('deflate' == strtolower($encoding)) {
return new InflateStream($stream);
}
if ('gzip' == strtolower($encoding)) {
return new GzipDecodeStream($stream);
}
return false;
} | Decorate a stream given an encoding.
@param string $encoding
@param StreamInterface $stream
@return StreamInterface|false A new stream interface or false if encoding is not supported | entailment |
public function getSerializedTranslationsFile(PackageVersionEntity $packageVersion, LocaleEntity $locale, TranslationsConverter $format)
{
$fileMTime = null;
$file = $this->getCacheDirectory($packageVersion, $locale, true) . '/data.' . $format->getHandle();
if ($this->fs->isFile($file)) {
$fileMTime = $this->fs->lastModified($file) ?: null;
}
if ($fileMTime === null) {
$refreshCache = true;
} else {
$refreshCache = false;
$stats = $this->app->make(StatsRepository::class)->getOne($packageVersion, $locale);
$lastUpdated = $stats->getLastUpdated();
if ($lastUpdated !== null && $lastUpdated->getTimestamp() > $fileMTime) {
$refreshCache = true;
}
}
if ($refreshCache) {
$translations = $this->app->make(Exporter::class)->forPackage($packageVersion, $locale);
$serializedTranslations = $format->convertTranslationsToString($translations);
unset($translations);
if (@$this->fs->put($file, $serializedTranslations, true) === false) {
throw new UserMessageException(t('Failed to create a cache file'));
}
}
return $file;
} | @param PackageVersionEntity $packageVersion
@param LocaleEntity $locale
@param TranslationsConverter $format
@throws UserMessageException
@return string | entailment |
public function getSerializedTranslations(PackageVersionEntity $packageVersion, LocaleEntity $locale, TranslationsConverter $format)
{
$file = $this->getSerializedTranslationsFile($packageVersion, $locale, $format);
$result = $this->fs->get($file);
if ($result === false) {
throw new UserMessageException(t('Failed to read a cache file'));
}
return $result;
} | @param PackageVersionEntity $packageVersion
@param LocaleEntity $locale
@param TranslationsConverter $format
@throws UserMessageException
@return string | entailment |
protected function getWorktreeDirectory()
{
if ($this->worktreeDirectory === null) {
$config = $this->app->make('community_translation/config');
$dir = $config->get('options.tempDir');
$dir = is_string($dir) ? rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/') : '';
if ($dir === '') {
$fh = $this->app->make('helper/file');
$dir = $fh->getTemporaryDirectory();
$dir = is_string($dir) ? rtrim(str_replace(DIRECTORY_SEPARATOR, '/', $dir), '/') : '';
if ($dir === '') {
throw new UserMessageException(t('Unable to retrieve the temporary directory.'));
}
}
$fs = $this->getFilesystem();
$dir = $dir . '/git-repositories';
if (!@$fs->isDirectory($dir)) {
@$fs->makeDirectory($dir, DIRECTORY_PERMISSIONS_MODE_COMPUTED, true);
if (!@$fs->isDirectory($dir)) {
throw new UserMessageException(t('Unable to create a temporary directory.'));
}
}
$file = $dir . '/index.html';
if (!$fs->isFile($file)) {
if (@$fs->put($file, '') === false) {
throw new UserMessageException(t('Error initializing a temporary directory.'));
}
}
$file = $dir . '/.htaccess';
if (!$fs->isFile($file)) {
if (@$fs->put($file, <<<'EOT'
Order deny,allow
Deny from all
php_flag engine off
EOT
) === false) {
throw new UserMessageException(t('Error initializing a temporary directory.'));
}
}
$handle = strtolower($this->gitRepository->getURL());
$handle = preg_replace('/[^a-z0-9\-_\.]+/', '_', $handle);
$handle = preg_replace('/_+/', '_', $handle);
$dir .= '/' . $handle;
$this->worktreeDirectory = $dir;
}
return $this->worktreeDirectory;
} | Get the working tree directory.
@throws UserMessageException
@return string | entailment |
protected function getGitDirectory()
{
if ($this->gitDirectory === null) {
$this->gitDirectory = $this->getWorktreeDirectory() . '/.git';
}
return $this->gitDirectory;
} | Get the git directory.
@throws UserMessageException
@return string | entailment |
public function getRootDirectory()
{
$dir = $this->getWorktreeDirectory();
$relativeRoot = trim(str_replace(DIRECTORY_SEPARATOR, '/', $this->gitRepository->getDirectoryToParse()), '/');
if ($relativeRoot !== '') {
$dir .= '/' . $relativeRoot;
}
return $dir;
} | Return the directory containing the files to be parsed.
@throws UserMessageException
@return string | entailment |
public function initialize()
{
$directory = $this->getWorktreeDirectory();
$fs = $this->getFilesystem();
if (@$fs->isDirectory($directory)) {
@$fs->cleanDirectory($directory);
if (count($fs->files($directory)) > 0 || count($fs->directories($directory)) > 0) {
throw new UserMessageException(t('Failed to empty directory %s', $directory));
}
} else {
if (@$fs->makeDirectory($directory, DIRECTORY_PERMISSIONS_MODE_COMPUTED) !== true) {
throw new UserMessageException(t('Failed to create directory %s', $directory));
}
}
try {
$cmd = 'clone --quiet --no-checkout --origin origin';
$cmd .= ' ' . escapeshellarg($this->gitRepository->getURL()) . ' ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $directory));
$this->runGit($cmd);
} catch (Exception $x) {
try {
$fs->deleteDirectory($directory);
} catch (Exception $foo) {
}
throw $x;
}
} | Initializes the git repository (if the local directory exists it will be erased).
@throws UserMessageException | entailment |
public function update()
{
$fs = $this->getFilesystem();
if ($fs->isDirectory($this->getGitDirectory())) {
$this->runGit('fetch origin --tags');
} else {
$this->initialize();
}
} | Initializes or update the git repository.
@throws UserMessageException | entailment |
public function getTaggedVersions()
{
$tagFilters = $this->gitRepository->getTagFiltersExpanded();
$taggedVersions = [];
if ($tagFilters !== null) {
$matches = null;
foreach ($this->runGit('tag --list') as $tag) {
$matchResult = @preg_match($this->gitRepository->getTagToVersionRegexp(), $tag, $matches);
if ($matchResult === false) {
throw new UserMessageException(t('Invalid regular expression for git repository %s', $this->gitRepository->getName()));
}
if ($matchResult > 0) {
$version = $matches[1];
$ok = true;
foreach ($tagFilters as $tagFilter) {
if (version_compare($version, $tagFilter['version'], $tagFilter['operator']) === false) {
$ok = false;
break;
}
}
if ($ok) {
$taggedVersions[$tag] = $version;
}
}
}
}
uasort($taggedVersions, 'version_compare');
return $taggedVersions;
} | Returns the list of tags and their associated versions (keys are the tags, values are the versions).
@throws UserMessageException
@return array Keys: tag, values: version | entailment |
private function runGit($cmd, $setDirectories = true)
{
static $execAvailable;
if (!isset($execAvailable)) {
$safeMode = @ini_get('safe_mode');
if (!empty($safeMode)) {
throw new UserMessageException(t("Safe-mode can't be on"));
}
if (!function_exists('exec')) {
throw new UserMessageException(t('exec() function is missing'));
}
if (in_array('exec', array_map('trim', explode(',', strtolower(@ini_get('disable_functions')))))) {
throw new UserMessageException(t('exec() function is disabled'));
}
$execAvailable = true;
}
$line = 'git';
if ($setDirectories) {
$line .= ' -C ' . escapeshellarg(str_replace('/', DIRECTORY_SEPARATOR, $this->getWorktreeDirectory()));
}
$line .= ' ' . $cmd . ' 2>&1';
$rc = 1;
$output = [];
@exec($line, $output, $rc);
if ($rc !== 0) {
throw new UserMessageException(t('Command failed with return code %1$s: %2$s', $rc, implode("\n", $output)));
}
return $output;
} | Execute a git command.
@param string $cmd
@param bool $setDirectories
@throws UserMessageException
@return string[] | entailment |
protected function normalizeArgs(array $args)
{
$args += [
'numTranslators' => '',
'limitToLocale' => '',
];
$valn = $this->app->make(Numbers::class);
$normalized = [
'numTranslators' => $valn->integer($args['numTranslators'], 1) ? (int) $args['numTranslators'] : null,
'allTranslations' => empty($args['allTranslations']) ? 0 : 1,
'limitToLocale' => '',
];
if ($args['limitToLocale'] !== '') {
$locale = $this->app->make(LocaleRepository::class)->findApproved($args['limitToLocale']);
if ($locale !== null) {
$normalized['limitToLocale'] = $locale->getID();
}
}
return $normalized;
} | {@inheritdoc}
@see BlockController::normalizeArgs() | entailment |
public function search($params)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery($params)
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs
@param array $params
@return Input[] array | entailment |
public function getSearchQuery($params)
{
$data['query'] = [];
$data['query']['ands'] = [];
if (isset($params[self::INPUT_CONCEPTS])) {
$data['query']['ands'] = $this->getInputConceptsQuery(
$data['query']['ands'],
$params[self::INPUT_CONCEPTS]
);
}
if (isset($params[self::OUTPUT_CONCEPTS])) {
$data['query']['ands'] = $this->getOutputConceptsQuery(
$data['query']['ands'],
$params[self::OUTPUT_CONCEPTS]
);
}
if (isset($params[self::METADATA])) {
$data['query']['ands'] = $this->getMetadataQuery($data['query']['ands'], $params[self::METADATA]);
}
if (isset($params[self::IMAGES])) {
$data['query']['ands'] = $this->getImagesQuery($data['query']['ands'], $params[self::IMAGES]);
}
if (isset($params[self::REVERSED_IMAGES])) {
$data['query']['ands'] = $this->getReverseImagesQuery(
$data['query']['ands'],
$params[self::REVERSED_IMAGES]
);
}
return $data;
} | @param array $params
@return array | entailment |
public function getInputConceptsQuery($data, $concepts)
{
foreach ($concepts as $concept) {
$data[] = $this->setData(
[
'concepts' => [
[
'name' => $concept->getName(),
'value' => $concept->getValue(),
],
],
],
'input'
);
}
return $data;
} | Generates Input Concept search query and adds it to existing data
@param $data
@param Concept[] $concepts
@return array $data | entailment |
public function getMetadataQuery($data, $metadata)
{
foreach ($metadata as $searchMetadata) {
$data[] = $this->setData(['metadata' => $searchMetadata], 'input');
}
return $data;
} | Generates Metadata search query and adds it to existing data
@param $data
@param array $metadata
@return array $data | entailment |
public function getImagesQuery($data, $inputs)
{
foreach ($inputs as $input) {
$data[] = $this->setData(['image' => ['url' => $input->getImage()]], 'input');
}
return $data;
} | Generates Image search query and adds it to existing data
@param $data
@param Input[] $inputs
@return array $data | entailment |
public function getReverseImagesQuery($data, $inputs)
{
foreach ($inputs as $input) {
$data[] = ['output' => $this->setData(['image' => ['url' => $input->getImage()]], 'input')];
}
return $data;
} | Generates Reverse Image search query and adds it to existing data
@param $data
@param Input[] $inputs
@return array $data | entailment |
public function searchByPredictedConcepts($concepts)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery([self::OUTPUT_CONCEPTS => $concepts])
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs by predicted Concepts
@param Concept[] $concepts
@return Input[] array | entailment |
public function searchByUserSuppliedConcepts($concepts)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery([self::INPUT_CONCEPTS => $concepts])
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs by predicted Concepts
@param Concept[] $concepts
@return Input[] array | entailment |
public function searchByCustomMetadata($metadata)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery([self::METADATA => $metadata])
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs custom Metadata
@param array $metadata
@return Input[] array | entailment |
public function searchByReverseImage($inputs)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery([self::REVERSED_IMAGES => $inputs])
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs custom Metadata
@param Input[] $inputs
@return Input[] array | entailment |
public function searchByMatchUrl($inputs)
{
$searchResult = $this->getRequest()->request(
'POST',
$this->getRequestUrl('searches'),
$this->getSearchQuery([self::IMAGES => $inputs])
);
return $this->getInputsFromSearchResult($searchResult);
} | Searches Inputs custom Metadata
@param Input[] $inputs
@return Input[] array | entailment |
public function getInputsFromSearchResult($searchResult)
{
$input_array = [];
if (!isset($searchResult['hits'])) {
throw new \Exception('Hits Not Found');
}
foreach ($searchResult['hits'] as $hit) {
if (!isset($hit['input'])) {
throw new \Exception('Inputs Not Found');
}
$input = new Input($hit['input']);
$input_array[] = $input;
}
return $input_array;
} | Parses Search Request Result and gets Inputs
@param $searchResult
@return array
@throws \Exception | entailment |
public static function create(Package $package, $version)
{
$result = new static();
$result->package = $package;
$result->version = (string) $version;
$result->createdOn = new DateTime();
$result->updatedOn = new DateTime();
return $result;
} | @param Package $package
@param string $version
@return static | entailment |
public function getDisplayVersion()
{
if ($this->isDevVersion()) {
return t(/*i18n: %s is a version*/'%s development series', substr($this->version, strlen(static::DEV_PREFIX)));
} else {
return $this->version;
}
} | Get the package version display name.
@return string | entailment |
private function getCommentPeopleIDs(TranslatableCommentEntity $comment)
{
$result = [];
$author = $comment->getPostedBy();
if ($author !== null) {
$result[] = $author->getUserID();
}
foreach ($comment->getChildComments() as $childComment) {
$result = array_merge($result, $this->getCommentPeopleIDs($childComment));
}
return $result;
} | @param TranslatableCommentEntity $comment
@return int[] | entailment |
protected function getRecipientIDs(NotificationEntity $notification)
{
$result = [];
$locale = null;
$notificationData = $notification->getNotificationData();
$commentsRepository = $this->app->make(TranslatableCommentRepository::class);
$someComment = false;
// Let's notify also all the people involved in the whole discussions
foreach (array_keys($notificationData['comments']) as $commentID) {
$comment = $commentsRepository->find($commentID);
if ($comment !== null) {
$someComment = true;
$result = array_merge($result, $this->getCommentPeopleIDs($comment->getRootComment()));
}
}
if ($someComment === false) {
throw new Exception(t('No comment found (have they been deleted?)'));
}
if ($notificationData['localeID'] === null) {
// Discussions about source strings (not locale specific): let's notify the global administrators
$ul = new UserList();
$ul->disableAutomaticSorting();
$ul->filterByGroup($this->getGroupsHelper()->getGlobalAdministrators());
$ul->filterByAttribute('notify_translatable_messages', 1);
$result = array_merge($result, $ul->getResultIDs());
} else {
// Locale-specific discussions: let's notify the people involved in that locale
$locale = $this->app->make(LocaleRepository::class)->findApproved($notificationData['localeID']);
if ($locale === null) {
throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID']));
}
$ul = new UserList();
$ul->disableAutomaticSorting();
$ul->filterByGroup($this->getGroupsHelper()->getTranslators($locale));
$ul->filterByAttribute('notify_translatable_messages', 1);
$result = array_merge($result, $ul->getResultIDs());
$ul = new UserList();
$ul->disableAutomaticSorting();
$ul->filterByGroup($this->getGroupsHelper()->getAdministrators($locale));
$ul->filterByAttribute('notify_translatable_messages', 1);
$result = array_merge($result, $ul->getResultIDs());
}
return $result;
} | {@inheritdoc}
@see Category::getRecipientIDs() | entailment |
private function markdownToHtml($md)
{
return nl2br(
$this->app->make('helper/text')->autolink(
htmlspecialchars(
$md,
ENT_QUOTES,
APP_CHARSET,
true
)
)
);
} | @param string $md
@return string | entailment |
public function getMailParameters(NotificationEntity $notification, UserInfo $recipient)
{
$notificationData = $notification->getNotificationData();
$localeRepository = $this->app->make(LocaleRepository::class);
if ($notificationData['localeID'] === null) {
$locale = null;
} else {
$locale = $localeRepository->findApproved($notificationData['localeID']);
if ($locale === null) {
throw new Exception(t('Unable to find the locale with ID %s', $notificationData['localeID']));
}
}
$commentsRepository = $this->app->make(TranslatableCommentRepository::class);
$packageVersionRepository = $this->app->make(PackageVersionRepository::class);
$comments = [];
$config = $this->app->make('community_translation/config');
$onlineTranslationPath = $config->get('options.onlineTranslationPath');
$dh = $this->app->make('date');
foreach ($notificationData['comments'] as $commentID => $commentInfo) {
$comment = $commentsRepository->find($commentID);
if ($comment !== null) {
$packageVersion = $packageVersionRepository->find($commentInfo['packageVersionID']);
if ($packageVersion !== null) {
$localeForLink = $locale;
if ($localeForLink === null) {
$localeForLink = $localeRepository->findApproved($commentInfo['whileTranslatingLocaleID']);
}
if ($localeForLink !== null) {
$comments[] = [
'_dateSort' => $comment->getPostedOn()->getTimestamp(),
'date' => $dh->formatPrettyDateTime($comment->getPostedOn(), true, true, $recipient->getUserTimezone() ?: 'user'),
'author' => $comment->getPostedBy(),
'translatable' => $comment->getTranslatable()->getText(),
'messageHtml' => $this->markdownToHtml($comment->getText()),
'link' => ((string) URL::to($onlineTranslationPath, $packageVersion->getID(), $localeForLink->getID())) . '#tid:' . $comment->getTranslatable()->getID(),
];
}
}
}
}
if (empty($comments)) {
throw new Exception(t('No comment found (have they been deleted?)'));
}
usort($comments, function (array $a, array $b) {
return $a['_dateSort'] - $b['_dateSort'];
});
$comments = array_map(
function (array $comment) {
unset($comment['_dateSort']);
return $comment;
},
$comments
);
return [
'specificForLocale' => ($locale === null) ? null : $locale->getDisplayName(),
'comments' => $comments,
] + $this->getCommonMailParameters($notification, $recipient);
} | {@inheritdoc}
@see Category::getMailParameters() | entailment |
public function getHTMLFragments($gridField)
{
// Set up the split button
$splitButton = new SplitButton('Export', 'Export');
$splitButton->setAttribute('data-icon', 'download-csv');
// XLSX option
$button = new GridField_FormAction(
$gridField,
'xlsxexport',
_t('firebrandhq.EXCELEXPORT', 'Export to Excel (XLSX)'),
'xlsxexport',
null
);
$button->addExtraClass('no-ajax');
$splitButton->push($button);
// XLS option
$button = new GridField_FormAction(
$gridField,
'xlsexport',
_t('firebrandhq.EXCELEXPORT', 'Export to Excel (XLS)'),
'xlsexport',
null
);
$button->addExtraClass('no-ajax');
$splitButton->push($button);
// CSV option
$button = new GridField_FormAction(
$gridField,
'csvexport',
_t('firebrandhq.EXCELEXPORT', 'Export to CSV'),
'csvexport',
null
);
$button->addExtraClass('no-ajax');
$splitButton->push($button);
// Return the fragment
return array(
$this->targetFragment =>
$splitButton->Field()
);
} | @inheritdoc
Create the split button with all the export options.
@param GridField $gridField
@return array | entailment |
protected function genericHandle($dataFormatterClass, $ext, GridField $gridField, $request = null)
{
$items = $this->getItems($gridField);
$this->setHeader($gridField, $ext);
$formater = new $dataFormatterClass();
$formater->setUseLabelsAsHeaders($this->useLabelsAsHeaders);
$fileData = $formater->convertDataObjectSet($items);
return $fileData;
} | Generic Handle request that will return a Spread Sheet in the requested format
@param string $dataFormatterClass
@param string $ext
@param GridField $gridField
@param SS_HTTPRequest $request
@return string | entailment |
protected function setHeader($gridField, $ext)
{
$do = singleton($gridField->getModelClass());
Controller::curr()->getResponse()
->addHeader(
"Content-Disposition",
'attachment; filename="' .
$do->i18n_plural_name() .
'.' . $ext . '"'
);
} | Set the HTTP header to force a download and set the filename.
@param GridField $gridField
@param string $ext Extension to use in the filename. | entailment |
protected function getItems(GridField $gridField)
{
$gridField->getConfig()->removeComponentsByType('GridFieldPaginator');
$items = $gridField->getManipulatedList();
foreach ($gridField->getConfig()->getComponents() as $component) {
if ($component instanceof GridFieldFilterHeader || $component instanceof GridFieldSortableHeader) {
$items = $component->getManipulatedData($gridField, $items);
}
}
$arrayList = new ArrayList();
foreach ($items->limit(null) as $item) {
if (!$item->hasMethod('canView') || $item->canView()) {
$arrayList->add($item);
}
}
return $arrayList;
} | Helper function to extract the item list out of the GridField.
@param GridField $gridField
@return SS_list | entailment |
public function up()
{
Schema::create(\Config::get('registry.table', 'system_registries'), function(Blueprint $table)
{
$table->string('key');
$table->text('value');
$table->primary('key');
});
} | Run the migrations.
@return void | entailment |
public function handleRequest(RequestInterface $request, callable $next, callable $first)
{
$chainIdentifier = spl_object_hash((object) $first);
return $next($request)->then(function (ResponseInterface $response) use ($request, $chainIdentifier) {
if (array_key_exists($chainIdentifier, $this->retryStorage)) {
unset($this->retryStorage[$chainIdentifier]);
}
return $response;
}, function (Exception $exception) use ($request, $next, $first, $chainIdentifier) {
if (!array_key_exists($chainIdentifier, $this->retryStorage)) {
$this->retryStorage[$chainIdentifier] = 0;
}
if ($this->retryStorage[$chainIdentifier] >= $this->retry) {
unset($this->retryStorage[$chainIdentifier]);
throw $exception;
}
++$this->retryStorage[$chainIdentifier];
// Retry in synchrone
$promise = $this->handleRequest($request, $next, $first);
return $promise->wait();
});
} | {@inheritdoc} | entailment |
public function buildFacebookLike()
{
$facebookLikeProvider = new FacebookLikeProvider(array(
'layout' => $this->configResolver->getParameter('facebook_like.layout', 'ez_share_buttons'),
'width' => $this->configResolver->getParameter('facebook_like.width', 'ez_share_buttons'),
'showFaces' => $this->configResolver->getParameter('facebook_like.show_faces', 'ez_share_buttons'),
'share' => $this->configResolver->getParameter('facebook_like.share', 'ez_share_buttons'),
));
return $facebookLikeProvider;
} | Builds Facebook like button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function buildFacebookRecommend()
{
$facebookRecommendProvider = new FacebookRecommendProvider(array(
'layout' => $this->configResolver->getParameter('facebook_recommend.layout', 'ez_share_buttons'),
'width' => $this->configResolver->getParameter('facebook_recommend.width', 'ez_share_buttons'),
'showFaces' => $this->configResolver->getParameter('facebook_recommend.show_faces', 'ez_share_buttons'),
'share' => $this->configResolver->getParameter('facebook_recommend.share', 'ez_share_buttons'),
));
return $facebookRecommendProvider;
} | Builds Facebook recommend button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function buildTwitter()
{
$twitterProvider = new TwitterProvider(array(
'showUsername' => $this->configResolver->getParameter('twitter.show_username', 'ez_share_buttons'),
'largeButton' => $this->configResolver->getParameter('twitter.large_button', 'ez_share_buttons'),
'language' => $this->configResolver->getParameter('twitter.language', 'ez_share_buttons'),
));
return $twitterProvider;
} | Builds Twitter button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function buildLinkedin()
{
$linkedinProvider = new LinkedinProvider(array(
'countMode' => $this->configResolver->getParameter('linkedin.count_mode', 'ez_share_buttons'),
'language' => $this->configResolver->getParameter('linkedin.language', 'ez_share_buttons'),
));
return $linkedinProvider;
} | Builds Linkedin button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function buildGooglePlus()
{
$googlePlusProvider = new GooglePlusProvider(array(
'size' => $this->configResolver->getParameter('google_plus.size', 'ez_share_buttons'),
'annotation' => $this->configResolver->getParameter('google_plus.annotation', 'ez_share_buttons'),
'width' => $this->configResolver->getParameter('google_plus.width', 'ez_share_buttons'),
'language' => $this->configResolver->getParameter('google_plus.language', 'ez_share_buttons'),
));
return $googlePlusProvider;
} | Builds Google Plus button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function buildXing()
{
$xingProvider = new XingProvider(array(
'shape' => $this->configResolver->getParameter('xing.shape', 'ez_share_buttons'),
'counter' => $this->configResolver->getParameter('xing.counter', 'ez_share_buttons'),
'language' => $this->configResolver->getParameter('xing.language', 'ez_share_buttons'),
));
return $xingProvider;
} | Builds Xing button provider.
@return \EzSystems\ShareButtonsBundle\SocialShare\ProviderInterface | entailment |
public function import(RemotePackageEntity $remotePackage)
{
$temp = $this->download($remotePackage);
$rootPath = $this->getRootPath($temp);
$this->translatableImporter->importDirectory($rootPath, $remotePackage->getHandle(), $remotePackage->getVersion(), '');
$package = $this->packageRepo->findOneBy(['handle' => $remotePackage->getHandle()]);
if ($package !== null) {
/* @var \CommunityTranslation\Entity\Package $package */
$persist = false;
if ($remotePackage->getName() !== '' && $remotePackage->getName() !== $package->getName()) {
$package->setName($remotePackage->getName());
$persist = true;
}
if ($remotePackage->getUrl() !== '' && $remotePackage->getUrl() !== $package->getUrl()) {
$package->setUrl($remotePackage->getUrl());
$persist = true;
}
if ($persist) {
$this->em->persist($package);
$this->em->flush($package);
}
}
} | Import a remote package.
@param RemotePackageEntity $remotePackage
@throws UserMessageException | entailment |
private function download(RemotePackageEntity $remotePackage)
{
$temp = $this->app->make(VolatileDirectory::class);
/* @var VolatileDirectory $temp */
$zipFilename = $temp->getPath() . '/downloaded.zip';
$this->httpClient->reset();
$this->httpClient->setOptions([
'storeresponse' => false,
'outputstream' => $zipFilename,
]);
$request = new Request();
if (($header = (string) getenv('CT_REMOTEPACKAGE_HEADER')) &&
$value = (string) getenv('CT_REMOTEPACKAGE_HEADER_VALUE')) {
$request->getHeaders()->addHeaderLine($header, $value);
}
$request->setMethod('GET')->setUri($remotePackage->getArchiveUrl());
$response = $this->httpClient->send($request);
$this->httpClient->reset();
$streamHandle = ($response instanceof \Zend\Http\Response\Stream) ? $response->getStream() : null;
if (is_resource($streamHandle)) {
fclose($streamHandle);
}
if ($response->getStatusCode() != 200) {
$error = t('Failed to download package archive %s v%s: %s (%d)', $remotePackage->getHandle(), $remotePackage->getVersion(), $response->getReasonPhrase(), $response->getStatusCode());
unset($temp);
throw new DownloadException($error, $response->getStatusCode());
}
$contentEncodingHeader = $response->getHeaders()->get('Content-Encoding');
if (!empty($contentEncodingHeader)) {
$contentEncoding = trim((string) $contentEncodingHeader->getFieldValue());
if ($contentEncoding !== '') {
$decodedZipFilename = $temp->getPath() . '/downloaded-decoded.zip';
switch (strtolower($contentEncoding)) {
case 'gzip':
$this->decodeGzip($zipFilename, $decodedZipFilename);
break;
case 'deflate':
$this->decodeDeflate($zipFilename, $decodedZipFilename);
break;
case 'plainbinary':
default:
$decodedZipFilename = '';
break;
}
if ($decodedZipFilename !== '') {
$temp->getFilesystem()->delete([$zipFilename]);
$zipFilename = $decodedZipFilename;
}
}
}
$temp->getFilesystem()->makeDirectory($temp->getPath() . '/unzipped');
$this->zip->unzip($zipFilename, $temp->getPath() . '/unzipped');
$temp->getFilesystem()->delete([$zipFilename]);
return $temp;
} | @param RemotePackageEntity $remotePackage
@throws UserMessageException
@return VolatileDirectory | entailment |
private function decodeGzip($fromFilename, $toFilename)
{
if (!function_exists('gzopen')) {
throw new UserMessageException(t(/*i18n: %s is a compression method, like gzip*/'The PHP zlib extension is required in order to decode "%s" encodings.', 'gzip'));
}
try {
$hFrom = @gzopen($fromFilename, 'rb');
if ($hFrom === false) {
throw new UserMessageException(t('Failed to open the file to be decoded with gzip.'));
}
$hTo = @fopen($toFilename, 'wb');
if ($hTo === false) {
throw new UserMessageException(t('Failed to create the file that contain gzip-decoded data.'));
}
while (!gzeof($hFrom)) {
$data = @gzread($hFrom, 32768);
if (!is_string($data) || $data === '') {
throw new UserMessageException(t('Failed to decode the gzip data.'));
}
if (@fwrite($hTo, $data) === false) {
throw new UserMessageException(t('Failed to write decoded gzip data.'));
}
}
} catch (Exception $x) {
if (isset($hTo) && is_resource($hTo)) {
@fclose($hTo);
}
if (isset($hFrom) && is_resource($hFrom)) {
@gzclose($hFrom);
}
throw $x;
}
fclose($hTo);
gzclose($hFrom);
} | @param string $fromFilename
@param string $toFilename
@throws UserMessageException | entailment |
private function decodeDeflate($fromFilename, $toFilename)
{
if (!function_exists('gzuncompress')) {
throw new UserMessageException(t(/*i18n: %s is a compression method, like gzip*/'The PHP zlib extension is required in order to decode "%s" encodings.', 'deflate'));
}
$compressed = @file_get_contents($fromFilename);
if ($compressed === false) {
throw new UserMessageException(t('Failed to read the file to be decoded with inflate.'));
}
$isGZip = false;
if (isset($compressed[1])) {
$zlibHeader = unpack('n', substr($compressed, 0, 2));
if ($zlibHeader[1] % 31 === 0) {
$isGZip = true;
}
}
if ($isGZip) {
$decompressed = @gzuncompress($compressed);
if ($decompressed === false) {
throw new UserMessageException(t('Failed to decode the ZLIB compressed data.'));
}
} else {
$decompressed = @gzinflate($compressed);
if ($decompressed === false) {
throw new UserMessageException(t('Failed to inflate the deflated data.'));
}
}
if (@file_put_contents($toFilename, $decompressed) === false) {
throw new UserMessageException(t('Failed to decompress the file to be decoded with inflate.'));
}
throw new UserMessageException(t('Failed to write the deflated data.'));
} | @param string $fromFilename
@param string $toFilename
@throws UserMessageException | entailment |
private function getRootPath(VolatileDirectory $temp)
{
$fs = $temp->getFilesystem();
$result = $temp->getPath() . '/unzipped';
for (; ;) {
if (count($fs->files($result)) !== 0) {
break;
}
$dirs = $fs->directories($result);
if (count($dirs) !== 1) {
break;
}
$result = $dirs[0];
}
return $result;
} | @param VolatileDirectory $temp
@return string | entailment |
protected function normalizeArgs(array $args)
{
$args += [
'resultsPerPage' => null,
'allowedDownloadFormats' => null,
];
$normalized = [];
$error = $this->app->make('helper/validation/error');
/* @var \Concrete\Core\Error\ErrorList\ErrorList $error */
$valn = $this->app->make('helper/validation/numbers');
/* @var \Concrete\Core\Utility\Service\Validation\Numbers $valn */
if ($valn->integer($args['resultsPerPage'], 1)) {
$normalized['resultsPerPage'] = (int) $args['resultsPerPage'];
} else {
$error->add(t('Please specify the number of search results per page.'));
}
$allowedDownloadFormats = [];
if (is_array($args['allowedDownloadFormats'])) {
$tcProvider = $this->app->make(TranslationsConverterProvider::class);
foreach (array_unique($args['allowedDownloadFormats']) as $adf) {
if ($tcProvider->isRegistered($adf) === false) {
$error->add(t('Invalid format identifier received'));
} else {
$allowedDownloadFormats[] = $adf;
}
}
}
$normalized['allowedDownloadFormats'] = implode(',', $allowedDownloadFormats);
$normalized['allowedDownloadFor'] = (isset($args['allowedDownloadFor']) && is_string($args['allowedDownloadFor'])) ? $args['allowedDownloadFor'] : '';
if (!array_key_exists($normalized['allowedDownloadFor'], $this->getDownloadAccessLevels())) {
$error->add(t('Please specify who can download the translations'));
}
if (!$error->has()) {
if ($normalized['allowedDownloadFor'] !== static::ALLOWDOWNLOADFOR_NOBODY && $normalized['allowedDownloadFormats'] === '') {
$error->add(t('If you specify that some user can download the translations, you should specify the allowed download formats'));
}
}
return $error->has() ? $error : $normalized;
} | {@inheritdoc}
@see BlockController::normalizeArgs() | entailment |
private function getAllowedDownloadFormats(LocaleEntity $locale, $user = 'current', array $approvedLocales = null)
{
$result = [];
$allowedFormats = [];
if ($this->allowedDownloadFormats) {
$tcProvider = $this->app->make(TranslationsConverterProvider::class);
foreach (explode(',', $this->allowedDownloadFormats) as $adf) {
$converter = $tcProvider->getByHandle($adf);
if ($converter !== null && $converter->canSerializeTranslations()) {
$allowedFormats[$adf] = $converter;
}
}
}
if (!empty($allowedFormats)) {
$userOk = false;
switch ($this->allowedDownloadFor) {
case static::ALLOWDOWNLOADFOR_EVERYBODY:
$userOk = true;
break;
case static::ALLOWDOWNLOADFOR_REGISTEREDUSERS:
if ($user === 'current') {
$user = $this->getAccess()->getUser('current');
}
if ($user !== null) {
$userOk = true;
}
break;
case static::ALLOWDOWNLOADFOR_TRANSLATORS_ALLLOCALES:
if ($approvedLocales === null) {
$approvedLocales = $this->app->make(LocaleRepository::class)->getApprovedLocales();
}
if ($user === 'current') {
$user = $this->getAccess()->getUser('current');
}
foreach ($approvedLocales as $l) {
if ($this->getAccess()->getLocaleAccess($l, $user) >= Access::TRANSLATE) {
$userOk = true;
break;
}
}
break;
case static::ALLOWDOWNLOADFOR_TRANSLATORS_OWNLOCALES:
if ($this->getAccess()->getLocaleAccess($locale, $user) >= Access::TRANSLATE) {
$userOk = true;
}
break;
case static::ALLOWDOWNLOADFOR_LOCALEADMINS_ALLLOCALES:
if ($approvedLocales === null) {
$approvedLocales = $this->app->make(LocaleRepository::class)->getApprovedLocales();
}
if ($user === 'current') {
$user = $this->getAccess()->getUser('current');
}
foreach ($approvedLocales as $l) {
if ($this->getAccess()->getLocaleAccess($l, $user) >= Access::ADMIN) {
$userOk = true;
break;
}
}
break;
case static::ALLOWDOWNLOADFOR_LOCALEADMINS_OWNLOCALES:
if ($this->getAccess()->getLocaleAccess($locale, $user) >= Access::TRANSLATE) {
$userOk = true;
}
break;
case static::ALLOWDOWNLOADFOR_GLOBALADMINS:
if ($this->getAccess()->getLocaleAccess($locale, $user) >= Access::GLOBAL_ADMIN) {
$userOk = true;
}
break;
}
if ($userOk === true) {
$result = $allowedFormats;
}
}
return $result;
} | @param LocaleEntity $locale
@param mixed $user
@param LocaleEntity[]|null $approvedLocales
@return \CommunityTranslation\TranslationsConverter\ConverterInterface[] | entailment |
public function percToProgressbarClass($perc, $translatedThreshold = null)
{
if ($translatedThreshold === null) {
$translatedThreshold = $this->getTranslatedThreshold();
}
if ($perc >= 100) {
$percClass = 'progress-bar-success';
} elseif ($perc >= $translatedThreshold) {
$percClass = 'progress-bar-info';
} elseif ($perc > 0) {
$percClass = 'progress-bar-warning';
} else {
$percClass = 'progress-bar-danger';
}
if ($perc > 0 && $perc < 10) {
$percClass .= ' progress-bar-minwidth1';
} elseif ($perc >= 10 && $perc < 100) {
$percClass .= ' progress-bar-minwidth2';
}
return $percClass;
} | @param int $perc
@param int|null $translatedThreshold
@return string | entailment |
private function getSearchWords($text)
{
$result = [];
if (is_string($text)) {
$text = trim(preg_replace('/[\W_]+/u', ' ', $text));
if ($text !== '') {
$words = explode(' ', mb_strtolower($text));
$words = array_values(array_unique($words));
$duplicates = [];
for ($i = 0; $i < count($words); ++$i) {
for ($j = 0; $j < count($words); ++$j) {
if ($i !== $j && @mb_stripos($words[$i], $words[$j]) === 0) {
$duplicates[] = $words[$j];
}
}
}
if (!empty($duplicates)) {
$words = array_values(array_diff($words, $duplicates));
}
$result = $words;
}
}
return $result;
} | @param string $text
@return string[] | entailment |
private function buildSearchQuery(array $words)
{
$qb = $this->app->make(PackageRepository::class)->createQueryBuilder('p');
$expr = $qb->expr();
$orFields = $expr->orX();
foreach (['p.handle', 'p.name'] as $fieldName) {
$and = $expr->andX();
foreach ($words as $word) {
$and->add($expr->like($fieldName, $expr->literal('%' . $word . '%')));
}
$orFields->add($and);
}
$qb->where($orFields);
if ($this->maximumSearchResults) {
$qb->setMaxResults($this->maximumSearchResults);
}
return $qb;
} | @param string[] $words
@return \Doctrine\ORM\QueryBuilder | entailment |
public function saveTranslationsToFile(Translations $translations, $filename)
{
if (!$this->canSerializeTranslations()) {
throw new UserMessageException(t('The "%s" converter is not able to serialize translations', $this->getName()));
}
$serialized = $this->convertTranslationsToString($translations);
if (@$this->fs->put($filename, $serialized) === false) {
throw new UserMessageException(t('Failed to save translations to file'));
}
} | {@inheritdoc}
@see ConverterInterface::saveTranslationsToFile() | entailment |
public function loadTranslationsFromFile($filename)
{
if (!$this->canSerializeTranslations()) {
throw new UserMessageException(t('The "%s" converter is not able to unserialize translations', $this->getName()));
}
if (!$this->fs->isFile($filename)) {
throw new UserMessageException(t('File not found'));
}
$contents = @$this->fs->get($filename);
if ($contents === false) {
throw new UserMessageException(t('Unable to read a file'));
}
return $this->convertStringToTranslations($contents);
} | {@inheritdoc}
@see ConverterInterface::loadTranslationsFromFile() | entailment |
public function getRequestUser()
{
if ($this->requestUser === null) {
$token = $this->getRequestApiToken();
if ($token === '') {
$this->requestUser = 'no-token';
} else {
$ip = $this->app->make('ip');
if ($ip->isBanned()) {
$this->requestUser = 'banned';
} else {
$requestUser = null;
$list = new UserList();
$list->disableAutomaticSorting();
$list->filterByAttribute('api_token', $token);
$ids = $list->getResultIDs();
if (!empty($ids)) {
$u = \User::getByUserID($ids[0]);
if ($u->isRegistered()) {
$requestUser = $u;
}
}
if ($requestUser === null) {
$this->requestUser == 'invalid-token';
$ip->logSignupRequest();
if ($ip->signupRequestThreshholdReached()) {
$ip->createIPBan();
}
} else {
$this->requestUser = $requestUser;
}
}
}
}
if ($this->requestUser === 'no-token') {
throw AccessDeniedException::create(t('API Access Token required'));
}
if ($this->requestUser === 'banned') {
throw AccessDeniedException::create($this->app->make('ip')->getErrorMessage());
}
if ($this->requestUser === 'invalid-token') {
throw AccessDeniedException::create(t('Bad API Access Token'));
}
return $this->requestUser;
} | @throws AccessDeniedException
@return User | entailment |
public function checkGenericAccess($configKey)
{
$config = $this->app->make('community_translation/config');
$level = $config->get('options.api.access.' . $configKey);
switch ($level) {
case self::ACCESSOPTION_EVERYBODY:
return;
case self::ACCESSOPTION_REGISTEREDUSERS:
$this->getRequestUser();
return;
case self::ACCESSOPTION_TRANSLATORS:
$requiredLevel = Access::TRANSLATE;
break;
case self::ACCESSOPTION_LOCALEADMINS:
$requiredLevel = Access::ADMIN;
break;
case self::ACCESSOPTION_GLOBALADMINS:
$requiredLevel = Access::GLOBAL_ADMIN;
break;
case self::ACCESSOPTION_SITEADMINS:
$user = $this->getRequestUser();
if ($user->getUserID() != USER_SUPER_ID) {
$admins = Group::getByID(ADMIN_GROUP_ID);
if (!$admins || !$user->inGroup($admins)) {
throw AccessDeniedException::create();
}
}
return;
case self::ACCESSOPTION_ROOT:
$user = $this->getRequestUser();
if ($user->getUserID() != USER_SUPER_ID) {
throw AccessDeniedException::create();
}
return;
case self::ACCESSOPTION_NOBODY:
default:
throw AccessDeniedException::create();
}
$user = $this->getRequestUser();
$hasRequiredLevel = false;
foreach ($this->getApprovedLocales() as $locale) {
if ($this->getAccessHelper()->getLocaleAccess($locale, $user) >= $requiredLevel) {
$hasRequiredLevel = true;
break;
} elseif ($requiredLevel >= Access::GLOBAL_ADMIN) {
break;
}
}
if ($hasRequiredLevel !== true) {
throw AccessDeniedException::create();
}
} | @param string $configKey
@throws AccessDeniedException | entailment |
public function checkLocaleAccess($configKey)
{
$config = $this->app->make('community_translation/config');
$level = $config->get('options.api.access.' . $configKey);
switch ($level) {
case self::ACCESSOPTION_EVERYBODY:
return $this->getApprovedLocales();
case self::ACCESSOPTION_REGISTEREDUSERS:
$this->getRequestUser();
return $this->getApprovedLocales();
case self::ACCESSOPTION_TRANSLATORS_ALLLOCALES:
$requiredLevel = Access::TRANSLATE;
$ownLocalesOnly = false;
break;
case self::ACCESSOPTION_TRANSLATORS_OWNLOCALES:
$requiredLevel = Access::TRANSLATE;
$ownLocalesOnly = true;
break;
case self::ACCESSOPTION_LOCALEADMINS_ALLLOCALES:
$requiredLevel = Access::ADMIN;
$ownLocalesOnly = false;
break;
case self::ACCESSOPTION_LOCALEADMINS_OWNLOCALES:
$requiredLevel = Access::ADMIN;
$ownLocalesOnly = true;
break;
case self::ACCESSOPTION_GLOBALADMINS:
$requiredLevel = Access::GLOBAL_ADMIN;
$ownLocalesOnly = false;
break;
case self::ACCESSOPTION_SITEADMINS:
$user = $this->getRequestUser();
if ($user->getUserID() != USER_SUPER_ID) {
$admins = Group::getByID(ADMIN_GROUP_ID);
if (!$admins || !$user->inGroup($admins)) {
throw AccessDeniedException::create();
}
}
return;
case self::ACCESSOPTION_ROOT:
$user = $this->getRequestUser();
if ($user->getUserID() != USER_SUPER_ID) {
throw AccessDeniedException::create();
}
return;
case self::ACCESSOPTION_NOBODY:
default:
throw AccessDeniedException::create();
}
$user = $this->getRequestUser();
$ownLocales = [];
foreach ($this->getApprovedLocales() as $locale) {
if ($this->getAccessHelper()->getLocaleAccess($locale, $user) >= $requiredLevel) {
$ownLocales[] = $locale;
if ($ownLocalesOnly === false) {
break;
}
} elseif ($requiredLevel >= Access::GLOBAL_ADMIN) {
break;
}
}
if (empty($ownLocales)) {
throw AccessDeniedException::create();
}
return $ownLocalesOnly ? $ownLocales : $this->getApprovedLocales();
} | @param string $configKey
@throws AccessDeniedException
@return \CommunityTranslation\Entity\Locale[] | entailment |
public function getRateLimit()
{
$result = null;
$config = $this->app->make('community_translation/config');
$maxRequests = (int) $config->get('options.api.rateLimit.maxRequests');
if ($maxRequests > 0) {
$timeWindow = (int) $config->get('options.api.rateLimit.timeWindow');
if ($timeWindow > 0) {
$result = [$maxRequests, $timeWindow];
}
}
return $result;
} | Returns the defined rate limit (if set).
@return int[]|null First item is the max requests, second limit is the time window. If no rate limit is defined returns null. | entailment |
public function getVisitsCountFromCurrentIP($timeWindow)
{
$timeWindow = (int) $timeWindow;
$ipControlLog = $this->app->make(IPControlLog::class);
return $ipControlLog->countVisits('api', new DateTime("-$timeWindow seconds"));
} | Get the number of visits from the current IP address since a determined number of seconds ago.
@param int $timeWindow
@return int | entailment |
public function checkRateLimit()
{
$rateLimit = $this->getRateLimit();
if ($rateLimit !== null) {
list($maxRequests, $timeWindow) = $rateLimit;
$visits = $this->getVisitsCountFromCurrentIP($timeWindow);
if ($visits >= $maxRequests) {
throw new UserMessageException(t('You reached the API rate limit (%1$s requests every %2$s seconds)', $maxRequests, $timeWindow));
}
$this->app->make(IPControlLog::class)->addVisit('api');
}
} | Check if the API Rate limit has been reached.
@throws UserMessageException | entailment |
public static function create()
{
$result = new static();
$result->devBranches = [];
$result->directoryToParse = '';
$result->directoryForPlaces = '';
$result->detectedVersions = [];
$result->tagToVersionRegexp = '/^(?:v(?:er(?:s(?:ion)?)?)?[.\s]*)?(\d+(?:\.\d+)*)$/';
$result->setTagFilters(null);
return $result;
} | Create a new instance.
@return static | entailment |
public function setDirectoryToParse($value)
{
$this->directoryToParse = trim(str_replace(DIRECTORY_SEPARATOR, '/', trim((string) $value)), '/');
return $this;
} | Set the path to the directory to be parsed.
@param string $value
@return static | entailment |
public function setDirectoryForPlaces($value)
{
$this->directoryForPlaces = trim(str_replace(DIRECTORY_SEPARATOR, '/', trim((string) $value)), '/');
return $this;
} | Set the base directory for places.
@param string $value
@return static | entailment |
public function addDetectedVersion($version, $kind, $repoName)
{
$this->detectedVersions[$version] = [
'kind' => $kind,
'repoName' => $repoName,
];
return $this;
} | Add a repository detected version.
@param string $version
@param string $kind
@param string $repoName
@return static | entailment |
public function getDetectedVersion($version)
{
return isset($this->detectedVersions[$version]) ? $this->detectedVersions[$version] : null;
} | Get the repository tag filters.
@param string $version
@return array|null | entailment |
public function setTagFilters(array $value = null)
{
if ($value === null) {
$this->tagFilters = ['none'];
} elseif (empty($value)) {
$this->tagFilters = ['all'];
} else {
$this->tagFilters = $value;
}
return $this;
} | Set the repository tag filters.
@param string[]|null $value Null for no tags, an array otherwise (empty means all tags)
@return static | entailment |
public function getTagFilters()
{
if ($this->tagFilters === ['none']) {
$result = null;
} elseif ($this->tagFilters === ['all']) {
$result = [];
} else {
$result = $this->tagFilters;
}
return $result;
} | Get the repository tag filters.
@return string[]|null | entailment |
public function getTagFiltersExpanded()
{
$tagFilters = $this->getTagFilters();
if ($tagFilters === null) {
$result = null;
} else {
$result = [];
$m = null;
foreach ($tagFilters as $tagFilter) {
if (preg_match('/^\s*([<>=]+)\s*(\d+(?:\.\d+)?)\s*$/', $tagFilter, $m)) {
switch ($m[1]) {
case '<=':
case '<':
case '=':
case '>=':
case '>':
$result[] = ['operator' => $m[1], 'version' => $m[2]];
break;
}
}
}
}
return $result;
} | Extracts the info for tag filter.
@return null|array(array('operator' => string, 'version' => string)) | entailment |
public function getTagFiltersDisplayName()
{
$expanded = $this->getTagFiltersExpanded();
if ($expanded === null) {
$result = tc('Tags', 'none');
} elseif (count($expanded) === 0) {
$result = tc('Tags', 'all');
} else {
$list = [];
foreach ($expanded as $x) {
switch ($x['operator']) {
case '<=':
$op = '≤';
break;
case '>=':
$op = '≥';
break;
default:
$op = $x['operator'];
break;
}
$list[] = "$op {$x['version']}";
}
$result = implode(' ∧ ', $list);
}
return $result;
} | Get a visual representation of the tag filters.
@return string | entailment |
public static function create(UserEntity $user, Package\Version $packageVersion, $notifyUpdates)
{
$result = new static();
$result->user = $user;
$result->packageVersion = $packageVersion;
$result->notifyUpdates = $notifyUpdates ? true : false;
return $result;
} | @param UserEntity $user User associated to this subscription
@param Package $package package associated to this subscription
@param bool $notifyUpdates Send notifications about updates to this package versions?
@return static | entailment |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.