sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
public function process(MinifyContext $context) { $booleanAttributes = implode('|', (new HtmlBooleanAttributeRepository())->getAttributes()); return $context->setContents(preg_replace_callback( '/ \s # first match a whitespace which is an indication if its an attribute ('.$booleanAttributes.') # match and capture a boolean attribute \s* = \s* ([\'"])? # optional to use a quote (\1|true|false|([\s>"\'])) # match the boolean attribute name again or true|false \2? # match the quote again /xi', function ($match) { if (isset($match[4])) { return ' '.$match[1]; } if ($match[3] == 'false') { return ''; } return ' '.$match[1]; }, $context->getContents())); }
Execute the minification rule. @param \ArjanSchouten\HtmlMinifier\MinifyContext $context @return \ArjanSchouten\HtmlMinifier\MinifyContext
entailment
public function handle() { if ((bool)GeneralUtility::_GP('juSecure')) { $this->forwardJumpUrlSecureFileData($this->url); } else { $this->redirectToJumpUrl($this->url); } }
Custom processing of the current URL. If a valid hash was submitted the user will either be redirected to the given jumpUrl or if it is a secure jumpUrl the file data will be passed to the user. If canHandle() has returned TRUE this method needs to take care of redirecting the user or generating custom output. This hook will be called BEFORE the user is redirected to an external URL configured in the page properties. @see \TYPO3\CMS\Frontend\Controller\TypoScriptFrontendController::processCustomUrlHandlers()
entailment
protected function redirectToJumpUrl($jumpUrl) { $this->validateIfJumpUrlRedirectIsAllowed($jumpUrl); $pageTSconfig = $this->getTypoScriptFrontendController()->getPagesTSconfig(); if (is_array($pageTSconfig['TSFE.'])) { $pageTSconfig = $pageTSconfig['TSFE.']; } else { $pageTSconfig = []; } // Allow sections in links $jumpUrl = str_replace('%23', '#', $jumpUrl); $jumpUrl = $this->addParametersToTransferSession($jumpUrl, $pageTSconfig); $statusCode = $this->getRedirectStatusCode($pageTSconfig); $this->redirect($jumpUrl, $statusCode); }
Redirects the user to the given jump URL if all submitted values are valid @param string $jumpUrl The URL to which the user should be redirected @throws \Exception
entailment
protected function forwardJumpUrlSecureFileData($jumpUrl) { // Set the parameters required for handling a secure jumpUrl link // The locationData GET parameter, containing information about the record that created the URL $locationData = (string)GeneralUtility::_GP('locationData'); // The optional mimeType GET parameter $mimeType = (string)GeneralUtility::_GP('mimeType'); // The jump Url Hash GET parameter $juHash = (string)GeneralUtility::_GP('juHash'); // validate the hash GET parameter against the other parameters if ($juHash !== JumpUrlUtility::calculateHashSecure($jumpUrl, $locationData, $mimeType)) { throw new \Exception('The calculated Jump URL secure hash ("juHash") did not match the submitted "juHash" query parameter.', 1294585196); } if (!$this->isLocationDataValid($locationData)) { throw new \Exception('The calculated secure location data "' . $locationData . '" is not accessible.', 1294585195); } // Allow spaces / special chars in filenames. $jumpUrl = rawurldecode($jumpUrl); // Deny access to files that match TYPO3_CONF_VARS[SYS][fileDenyPattern] and whose parent directory // is typo3conf/ (there could be a backup file in typo3conf/ which does not match against the fileDenyPattern) if (version_compare(TYPO3_version, '8.0', '<')) { $absoluteFileName = GeneralUtility::getFileAbsFileName(GeneralUtility::resolveBackPath($jumpUrl), false); } else { $absoluteFileName = GeneralUtility::getFileAbsFileName(GeneralUtility::resolveBackPath($jumpUrl)); } if ( !GeneralUtility::isAllowedAbsPath($absoluteFileName) || !GeneralUtility::verifyFilenameAgainstDenyPattern($absoluteFileName) || GeneralUtility::isFirstPartOfStr($absoluteFileName, (PATH_site . 'typo3conf')) ) { throw new \Exception('The requested file was not allowed to be accessed through Jump URL. The path or file is not allowed.', 1294585194); } try { $resourceFactory = $this->getResourceFactory(); $file = $resourceFactory->retrieveFileOrFolderObject($absoluteFileName); $this->readFileAndExit($file, $mimeType); } catch (\Exception $e) { throw new \Exception('The requested file "' . $jumpUrl . '" for Jump URL was not found..', 1294585193); } }
If the submitted hash is correct and the user has access to the related content element the contents of the submitted file will be output to the user. @param string $jumpUrl The URL to the file that should be output to the user @throws \Exception
entailment
protected function isLocationDataValid($locationData) { $isValidLocationData = false; list($pageUid, $table, $recordUid) = explode(':', $locationData); $pageRepository = $this->getTypoScriptFrontendController()->sys_page; $timeTracker = $this->getTimeTracker(); if (empty($table) || $pageRepository->checkRecord($table, $recordUid, true)) { // This check means that a record is checked only if the locationData has a value for a // record else than the page. if (!empty($pageRepository->getPage($pageUid))) { $isValidLocationData = true; } else { $timeTracker->setTSlogMessage('LocationData Error: The page pointed to by location data "' . $locationData . '" was not accessible.', 2); } } else { $timeTracker->setTSlogMessage('LocationData Error: Location data "' . $locationData . '" record pointed to was not accessible.', 2); } return $isValidLocationData; }
Checks if the given location data is valid and the connected record is accessible by the current user. @param string $locationData @return bool
entailment
protected function validateIfJumpUrlRedirectIsAllowed($jumpUrl) { $allowRedirect = false; if ($this->isJumpUrlHashValid($jumpUrl)) { $allowRedirect = true; } elseif ( isset($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['jumpurlRedirectHandler']) && is_array($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['jumpurlRedirectHandler']) ) { foreach ($GLOBALS['TYPO3_CONF_VARS']['SC_OPTIONS']['tslib/class.tslib_fe.php']['jumpurlRedirectHandler'] as $className) { $hookObject = GeneralUtility::getUserObj($className); if (method_exists($hookObject, 'jumpurlRedirectHandler')) { $allowRedirect = $hookObject->jumpurlRedirectHandler($jumpUrl, $GLOBALS['TSFE']); } if ($allowRedirect) { break; } } } if (!$allowRedirect) { throw new \Exception('The calculated Jump URL hash ("juHash") did not match the submitted "juHash" query parameter.', 1359987599); } }
This implements a hook, e.g. for direct mail to allow the redirects but only if the handler says it's alright But also checks against the common juHash parameter first @param string $jumpUrl the URL to check @throws \Exception thrown if no redirect is allowed
entailment
protected function readFileAndExit($file, $mimeType) { $file->getStorage()->dumpFileContents($file, true, null, $mimeType); exit; }
Calls the PHP readfile function and exits. @param FileInterface $file The file that should be read. @param string $mimeType Optional mime type override. If empty the automatically detected mime type will be used.
entailment
protected function addParametersToTransferSession($jumpUrl, $pageTSconfig) { // allow to send the current fe_user with the jump URL if (!empty($pageTSconfig['jumpUrl_transferSession'])) { $uParts = parse_url($jumpUrl); /** @noinspection PhpInternalEntityUsedInspection We need access to the current frontend user ID. */ $params = '&FE_SESSION_KEY=' . rawurlencode( $this->getTypoScriptFrontendController()->fe_user->id . '-' . md5( $this->getTypoScriptFrontendController()->fe_user->id . '/' . $GLOBALS['TYPO3_CONF_VARS']['SYS']['encryptionKey'] ) ); // Add the session parameter ... $jumpUrl .= ($uParts['query'] ? '' : '?') . $params; } return $jumpUrl; }
Modified the URL to go to by adding the session key information to it but only if TSFE.jumpUrl_transferSession = 1 is set via pageTSconfig. @param string $jumpUrl the URL to go to @param array $pageTSconfig the TSFE. part of the TS configuration @return string the modified URL
entailment
protected function getRedirectStatusCode($pageTSconfig) { $statusCode = HttpUtility::HTTP_STATUS_303; if (!empty($pageTSconfig['jumpURL_HTTPStatusCode'])) { switch ((int)$pageTSconfig['jumpURL_HTTPStatusCode']) { case 301: $statusCode = HttpUtility::HTTP_STATUS_301; break; case 302: $statusCode = HttpUtility::HTTP_STATUS_302; break; case 307: $statusCode = HttpUtility::HTTP_STATUS_307; break; default: throw new \InvalidArgumentException('The configured jumpURL_HTTPStatusCode option is invalid. Allowed codes are 301, 302 and 307.', 1381768833); } } return $statusCode; }
Returns one of the HTTP_STATUS_* constants of the HttpUtility that matches the configured HTTP status code in TSFE.jumpURL_HTTPStatusCode Page TSconfig. @param array $pageTSconfig @return string @throws \InvalidArgumentException If the configured status code is not valid.
entailment
public function run(Application $app) { $response = call_user_func_array($this->callback, array_merge($this->parameters, [$app])); parent::callAfterCallbacks($app); return $response; }
Run the given event. @param Application $app @return mixed
entailment
public function deauthorize($stripeUserId) { $request = $this->createRequest( self::METHOD_POST, $this->getBaseDeauthorizationUrl(), null, [ 'body' => $this->buildQueryString([ 'stripe_user_id' => $stripeUserId, 'client_id' => $this->clientId, 'client_secret' => $this->clientSecret, ]), ] ); return $this->getParsedResponse($request); }
@param string $stripeUserId stripe account ID @return mixed
entailment
public function process(MinifyContext $context) { Collection::make($this->redundantAttributes)->each(function ($attributes, $element) use (&$context) { Collection::make($attributes)->each(function ($value, $attribute) use ($element, &$context) { $contents = preg_replace_callback( '/ '.$element.' # Match the given element ((?!\s*'.$attribute.'\s*=).)* # Match everything except the given attribute ( \s*'.$attribute.'\s* # Match the attribute =\s* # Match the equals sign (["\']?) # Match the opening quotes \s*'.$value.'\s* # Match the value \3? # Match the captured opening quotes again \s* ) /xis', function ($match) { return $this->removeAttribute($match[0], $match[2]); }, $context->getContents()); $context->setContents($contents); }); }); return $context; }
Minify redundant attributes which are not needed by the browser. @param \ArjanSchouten\HtmlMinifier\MinifyContext $context @return \ArjanSchouten\HtmlMinifier\MinifyContext
entailment
protected function removeAttribute($element, $attribute) { $replacement = Html::hasSurroundingAttributes($attribute) ? ' ' : ''; return str_replace($attribute, $replacement, $element); }
Remove the attribute from the element. @param string $element @param string $attribute @return string
entailment
public function GetCustomFromAddresses($select = 1000, $skip = 0) { $url = sprintf("custom-from-addresses?select=%s&skip=%s", $select, $skip); return new ApiCampaignFromAddressList($this->execute($url)); }
/* ========== custom-from-addresses ==========
entailment
public function GetProgramById(XsInt $programId) { $url = sprintf("programs/%s", $programId); return new ApiProgram($this->execute($url)); }
/* ========== programs and enrolments ==========
entailment
public function PostSegmentsRefresh(XsInt $segmentId) { $url = sprintf("segments/refresh/%s", $segmentId); return new ApiSegmentRefresh($this->execute($url, 'POST')); }
/* ========== segments ==========
entailment
public function PostSmsMessagesSendTo(XsString $telephoneNumber, ApiSms $apiSms) { $this->execute(sprintf("/sms-messages/send-to/%s", $telephoneNumber), 'POST', $apiSms->toJson()); }
/* ========== sms-messages ==========
entailment
public function createReferencePoint($inputSize, $keyname = null) { if ($keyname === null) { $keyname = 'Step: '.(count($this->referencePoints) + 1); } if (!array_key_exists($keyname, $this->referencePoints)) { $this->referencePoints[$keyname] = new ReferencePoint($keyname, $inputSize); } else { $this->referencePoints[$keyname]->addBytes($inputSize); } return $this->referencePoints; }
Add a step and measure the input size. @param int $inputSize @param string $keyname @return \ArjanSchouten\HtmlMinifier\Statistics\ReferencePoint[]
entailment
public function getTotalSavedBytes() { $initialStep = array_first($this->referencePoints); $lastStep = array_last($this->referencePoints); return $initialStep->getBytes() - $lastStep->getBytes(); }
Get the total saved bytes in bytes. @return int
entailment
public function actionRun() { $this->importScheduleFile(); $events = $this->schedule->dueEvents(Yii::$app); foreach ($events as $event) { $this->stdout('Running scheduled command: ' . $event->getSummaryForDisplay() . "\n"); $event->run(Yii::$app); } if (count($events) === 0) { $this->stdout("No scheduled commands are ready to run.\n"); } }
Run scheduled commands
entailment
public function actionList() { $this->importScheduleFile(); $climate = new CLImate(); $data = []; $row = 0; foreach ($this->schedule->getEvents() as $event) { $data[] = [ '#' => ++$row, 'Task' => $event->getSummaryForDisplay(), 'Expression' => $event->getExpression(), 'Command to Run' => is_a($event, CallbackEvent::class) ? $event->getSummaryForDisplay() : $event->command, 'Next run at' => $this->getNextRunDate($event), ]; } $climate->table($data); }
Render list of registered tasks
entailment
protected function importScheduleFile() { $scheduleFile = Yii::getAlias($this->scheduleFile); if (!file_exists($scheduleFile)) { throw new InvalidConfigException("Can not load schedule file {$this->scheduleFile}"); } $schedule = $this->schedule; call_user_func(function () use ($schedule, $scheduleFile) { include $scheduleFile; }); }
Import schedule file @throws InvalidConfigException
entailment
protected function getNextRunDate(Event $event) { $cron = CronExpression::factory($event->getExpression()); $date = Carbon::now(); if ($event->hasTimezone()) { $date->setTimezone($event->getTimezone()); } return $cron->getNextRunDate()->format('Y-m-d H:i:s'); }
Get the next scheduled run date for this event @param Event $event @return string
entailment
public function setImage(\Imagick $image) { $this->originalImage = $image; // set base image dimensions $this->setBaseDimensions( $this->originalImage->getImageWidth(), $this->originalImage->getImageHeight() ); return $this; }
Sets the object Image to be croped @param \Imagick $image @return Crop
entailment
public function resizeAndCrop($targetWidth, $targetHeight) { if ($this->getAutoOrient()) { $this->autoOrient(); } // First get the size that we can use to safely trim down the image without cropping any sides $crop = $this->getSafeResizeOffset($this->originalImage, $targetWidth, $targetHeight); // Resize the image $this->originalImage->resizeImage($crop['width'], $crop['height'], $this->getFilter(), $this->getBlur()); // Get the offset for cropping the image further $offset = $this->getSpecialOffset($this->originalImage, $targetWidth, $targetHeight); // Crop the image $this->originalImage->cropImage($targetWidth, $targetHeight, $offset['x'], $offset['y']); return $this->originalImage; }
Resize and crop the image so it dimensions matches $targetWidth and $targetHeight @param int $targetWidth @param int $targetHeight @return boolean|\Imagick
entailment
protected function getSafeResizeOffset(\Imagick $image, $targetWidth, $targetHeight) { $source = $image->getImageGeometry(); if (0 == $targetHeight || ($source['width'] / $source['height']) < ($targetWidth / $targetHeight)) { $scale = $source['width'] / $targetWidth; } else { $scale = $source['height'] / $targetHeight; } return array('width' => (int) ($source['width'] / $scale), 'height' => (int) ($source['height'] / $scale)); }
Returns width and height for resizing the image, keeping the aspect ratio and allow the image to be larger than either the width or height @param \Imagick $image @param int $targetWidth @param int $targetHeight @return array
entailment
protected function getBaseDimension($key) { if (isset($this->baseDimension)) { return $this->baseDimension[$key]; } elseif ($key == 'width') { return $this->originalImage->getImageWidth(); } else { return $this->originalImage->getImageHeight(); } }
getBaseDimension @param string $key width|height @access protected @return int
entailment
protected function autoOrient() { // apply EXIF orientation to pixel data switch ($this->originalImage->getImageOrientation()) { case \Imagick::ORIENTATION_BOTTOMRIGHT: $this->originalImage->rotateimage('#000', 180); // rotate 180 degrees break; case \Imagick::ORIENTATION_RIGHTTOP: $this->originalImage->rotateimage('#000', 90); // rotate 90 degrees CW break; case \Imagick::ORIENTATION_LEFTBOTTOM: $this->originalImage->rotateimage('#000', -90); // rotate 90 degrees CCW break; } // reset EXIF orientation $this->originalImage->setImageOrientation(\Imagick::ORIENTATION_TOPLEFT); }
Applies EXIF orientation metadata to pixel data and removes the EXIF rotation @access protected
entailment
public function getData() { $data = array(); /** @var eZContentClassAttribute $contentClassAttribute */ $contentClassAttribute = $this->ContentObjectAttribute->contentClassAttribute(); $keywordFieldName = parent::generateAttributeFieldName( $contentClassAttribute, 'lckeyword' ); $textFieldName = parent::generateAttributeFieldName( $contentClassAttribute, 'text' ); $tagIDsFieldName = parent::generateSubattributeFieldName( $contentClassAttribute, 'tag_ids', 'sint' ); $data[$keywordFieldName] = ''; $data[$textFieldName] = ''; $data[$tagIDsFieldName] = array(); if ( !$this->ContentObjectAttribute->hasContent() ) return $data; $objectAttributeContent = $this->ContentObjectAttribute->content(); if ( !$objectAttributeContent instanceof eZTags ) return $data; $tagIDs = array(); $keywords = array(); $this->indexSynonyms = eZINI::instance( 'eztags.ini' )->variable( 'SearchSettings', 'IndexSynonyms' ) === 'enabled'; $indexParentTags = eZINI::instance( 'eztags.ini' )->variable( 'SearchSettings', 'IndexParentTags' ) === 'enabled'; $includeSynonyms = eZINI::instance( 'eztags.ini' )->variable( 'SearchSettings', 'IncludeSynonyms' ) === 'enabled'; $tags = $objectAttributeContent->attribute( 'tags' ); if ( is_array( $tags ) ) { foreach ( $tags as $tag ) { if ( $tag instanceof eZTagsObject ) { $this->processTag( $tag, $tagIDs, $keywords, $indexParentTags, $includeSynonyms ); } } } if ( !empty( $tagIDs ) ) { $data[$keywordFieldName] = implode( ', ', $keywords ); $data[$textFieldName] = implode( ' ', $keywords ); $data[$tagIDsFieldName] = $tagIDs; } $data['ezf_df_tag_ids'] = $tagIDs; $data['ezf_df_tags'] = $keywords; return $data; }
Returns the data from content object attribute which is sent to Solr backend @return array
entailment
static public function getFieldNameList( eZContentClassAttribute $classAttribute, $exclusiveTypeFilter = array() ) { $fieldsList = array(); if ( empty( $exclusiveTypeFilter ) || !in_array( 'lckeyword', $exclusiveTypeFilter ) ) $fieldsList[] = parent::generateAttributeFieldName( $classAttribute, 'lckeyword' ); if ( empty( $exclusiveTypeFilter ) || !in_array( 'text', $exclusiveTypeFilter ) ) $fieldsList[] = parent::generateAttributeFieldName( $classAttribute, 'text' ); if ( empty( $exclusiveTypeFilter ) || !in_array( 'sint', $exclusiveTypeFilter ) ) $fieldsList[] = parent::generateSubattributeFieldName( $classAttribute, 'tag_ids', 'sint' ); return $fieldsList; }
Returns the list of field names this handler sends to Solr backend @static @param eZContentClassAttribute $classAttribute @param array $exclusiveTypeFilter @return array
entailment
private function processTag( eZTagsObject $tag, array &$tagIDs, array &$keywords, $indexParentTags = false, $includeSynonyms = false ) { if ( !$this->indexSynonyms && $tag->isSynonym() ) $tag = $tag->getMainTag(); //get keyword in content's locale $keyword = $tag->getKeyword( $this->ContentObjectAttribute->attribute( 'language_code' ) ); if ( !$keyword ) { //fall back to main language /** @var eZContentLanguage $mainLanguage */ $mainLanguage = eZContentLanguage::fetch( $tag->attribute( 'main_language_id') ); if ( $mainLanguage instanceof eZContentLanguage ) $keyword = $tag->getKeyword( $mainLanguage->attribute( 'locale' ) ); } if ( $keyword ) { $tagIDs[] = (int) $tag->attribute( 'id' ); $keywords[] = $keyword; } if ( $indexParentTags ) { $parentTags = $tag->getPath( true ); foreach ( $parentTags as $parentTag ) { if ( $parentTag instanceof eZTagsObject ) { $this->processTag( $parentTag, $tagIDs, $keywords ); } } } if ( $this->indexSynonyms && $includeSynonyms ) { foreach ( $tag->getSynonyms() as $synonym ) { if ( $synonym instanceof eZTagsObject ) { $this->processTag( $synonym, $tagIDs, $keywords ); } } } }
Extracts data to be indexed from the tag @param eZTagsObject $tag @param array $tagIDs @param array $keywords @param bool $indexParentTags @param bool $includeSynonyms
entailment
private static function isBinaryOperator(TokenInterface $token): bool { return in_array($token->getType(), [ TokenInterface::TYPE_OPERATOR_ASSIGNMENT, TokenInterface::TYPE_OPERATOR_COPY, TokenInterface::TYPE_OPERATOR_MODIFY, TokenInterface::TYPE_OPERATOR_REFERENCE, ]); }
Tests whether a token is a binary operator @param TokenInterface $token @return bool
entailment
private static function isWhitespaceOfLength(TokenInterface $token, int $length): bool { return static::isWhitespace($token) && strlen(trim($token->getValue(), "\n")) == $length; }
Tests whether a token is a whitespace of a given length @param TokenInterface $token @param int $length @return bool
entailment
public function validateConfigurationForm(array &$form, FormStateInterface $form_state) { parent::validateConfigurationForm($form, $form_state); $exploded_mime = explode('/', $form_state->getValue('mimetype')); if ($exploded_mime[0] != "image") { $form_state->setErrorByName( 'mimetype', t('Please enter an image mimetype (e.g. image/jpeg, image/png, etc...)') ); } }
{@inheritdoc}
entailment
public function countIssues(): int { $count = 0; foreach ($this->files as $file) { $count += count($file->getIssues()); } return $count; }
Returns the number of issues for the entire report. @return int The number of issues for the entire report.
entailment
public function countIssuesBySeverity(string $severity): int { $count = 0; foreach ($this->files as $file) { $count += count($file->getIssuesBySeverity($severity)); } return $count; }
Returns the number of issues with a given severity for the entire report @param string $severity The severity. Should be one of the Issue class' SEVERITY_* constants @return int The number of issues for the entire report.
entailment
public function onResponse(FilterResponseEvent $event) { $response = $event->getResponse(); $node = $this->getObject($response, 'node'); if ($node === FALSE) { return; } $links = array_merge( $this->generateEntityReferenceLinks($node), $this->generateRelatedMediaLinks($node), $this->generateRestLinks($node) ); // Add the link headers to the response. if (empty($links)) { return; } $response->headers->set('Link', $links, FALSE); }
Adds node-specific link headers to appropriate responses. @param \Symfony\Component\HttpKernel\Event\FilterResponseEvent $event Event containing the response.
entailment
protected function generateRelatedMediaLinks(NodeInterface $node) { $links = []; foreach ($this->utils->getMedia($node) as $media) { $url = $media->url('canonical', ['absolute' => TRUE]); foreach ($media->referencedEntities() as $term) { if ($term->getEntityTypeId() == 'taxonomy_term' && $term->hasField('field_external_uri')) { $field = $term->get('field_external_uri'); if (!$field->isEmpty()) { $link = $field->first()->getValue(); $uri = $link['uri']; if (strpos($uri, 'http://pcdm.org/use#') === 0) { $title = $term->label(); $links[] = "<$url>; rel=\"related\"; title=\"$title\""; } } } } } return $links; }
Generates link headers for media associated with a node.
entailment
public function buildConfigurationForm(array $form, FormStateInterface $form_state) { if (isset($this->configuration['uri']) && !empty($this->configuration['uri'])) { $default = $this->utils->getTermForUri($this->configuration['uri']); } else { $default = NULL; } $form['term'] = [ '#type' => 'entity_autocomplete', '#title' => $this->t('Term'), '#tags' => TRUE, '#default_value' => $default, '#target_type' => 'taxonomy_term', ]; return parent::buildConfigurationForm($form, $form_state); }
{@inheritdoc}
entailment
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) { // Set URI for term if possible. $this->configuration['uri'] = NULL; $value = $form_state->getValue('term'); if (!empty($value)) { $tid = $value[0]['target_id']; $term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid); $uri = $this->utils->getUriForTerm($term); if ($uri) { $this->configuration['uri'] = $uri; } } parent::submitConfigurationForm($form, $form_state); }
{@inheritdoc}
entailment
public function evaluate() { if (empty($this->configuration['uri']) && !$this->isNegated()) { return TRUE; } $node = $this->getContextValue('node'); if (!$node) { return FALSE; } return $this->evaluateEntity($node); }
{@inheritdoc}
entailment
protected function evaluateEntity(EntityInterface $entity) { foreach ($entity->referencedEntities() as $referenced_entity) { if ($referenced_entity->getEntityTypeId() == 'taxonomy_term' && $referenced_entity->hasField(IslandoraUtils::EXTERNAL_URI_FIELD)) { $field = $referenced_entity->get(IslandoraUtils::EXTERNAL_URI_FIELD); if (!$field->isEmpty()) { $link = $field->first()->getValue(); if ($link['uri'] == $this->configuration['uri']) { return $this->isNegated() ? FALSE : TRUE; } } } } return $this->isNegated() ? TRUE : FALSE; }
Evaluates if an entity has the specified term(s). @param \Drupal\Core\Entity\EntityInterface $entity The entity to evalute. @return bool TRUE if entity has all the specified term(s), otherwise FALSE.
entailment
public function getParentNode(MediaInterface $media) { if (!$media->hasField(self::MEDIA_OF_FIELD)) { return NULL; } $field = $media->get(self::MEDIA_OF_FIELD); if ($field->isEmpty()) { return NULL; } $parent = $field->first() ->get('entity') ->getTarget(); if (!is_null($parent)) { return $parent->getValue(); } return NULL; }
Gets nodes that a media belongs to. @param \Drupal\media\MediaInterface $media The Media whose node you are searching for. @return \Drupal\node\NodeInterface Parent node. @throws \Drupal\Core\TypedData\Exception\MissingDataException Method $field->first() throws if data structure is unset and no item can be created.
entailment
public function getMedia(NodeInterface $node) { if (!$this->entityTypeManager->getStorage('field_storage_config')->load('media.' . self::MEDIA_OF_FIELD)) { return []; } $mids = $this->entityQuery->get('media')->condition(self::MEDIA_OF_FIELD, $node->id())->execute(); if (empty($mids)) { return []; } return $this->entityTypeManager->getStorage('media')->loadMultiple($mids); }
Gets media that belong to a node. @param \Drupal\node\NodeInterface $node The parent node. @return \Drupal\media\MediaInterface[] The children Media. @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException Calling getStorage() throws if the entity type doesn't exist. @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException Calling getStorage() throws if the storage handler couldn't be loaded.
entailment
public function getMediaWithTerm(NodeInterface $node, TermInterface $term) { $mids = $this->getMediaReferencingNodeAndTerm($node, $term); if (empty($mids)) { return NULL; } return $this->entityTypeManager->getStorage('media')->load(reset($mids)); }
Gets media that belong to a node with the specified term. @param \Drupal\node\NodeInterface $node The parent node. @param \Drupal\taxonomy\TermInterface $term Taxonomy term. @return \Drupal\media\MediaInterface The child Media. @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException Calling getStorage() throws if the entity type doesn't exist. @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException Calling getStorage() throws if the storage handler couldn't be loaded.
entailment
public function getReferencingMedia($fid) { // Get media fields that reference files. $fields = $this->getReferencingFields('media', 'file'); // Process field names, stripping off 'media.' and appending 'target_id'. $conditions = array_map( function ($field) { return ltrim($field, 'media.') . '.target_id'; }, $fields ); // Query for media that reference this file. $query = $this->entityQuery->get('media', 'OR'); foreach ($conditions as $condition) { $query->condition($condition, $fid); } return $this->entityTypeManager->getStorage('media')->loadMultiple($query->execute()); }
Gets Media that reference a File. @param int $fid File id. @return \Drupal\media\MediaInterface[] Array of media. @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException Calling getStorage() throws if the entity type doesn't exist. @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException Calling getStorage() throws if the storage handler couldn't be loaded.
entailment
public function getTermForUri($uri) { $results = $this->entityQuery->get('taxonomy_term') ->condition(self::EXTERNAL_URI_FIELD . '.uri', $uri) ->execute(); if (empty($results)) { return NULL; } return $this->entityTypeManager->getStorage('taxonomy_term')->load(reset($results)); }
Gets the taxonomy term associated with an external uri. @param string $uri External uri. @return \Drupal\taxonomy\TermInterface|null Term or NULL if not found. @throws \Drupal\Component\Plugin\Exception\PluginNotFoundException Calling getStorage() throws if the entity type doesn't exist. @throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException Calling getStorage() throws if the storage handler couldn't be loaded.
entailment
public function getUriForTerm(TermInterface $term) { if ($term && $term->hasField(self::EXTERNAL_URI_FIELD)) { $field = $term->get(self::EXTERNAL_URI_FIELD); if (!$field->isEmpty()) { $link = $field->first()->getValue(); return $link['uri']; } } return NULL; }
Gets the taxonomy term associated with an external uri. @param \Drupal\taxonomy\TermInterface $term Taxonomy term. @return string|null URI or NULL if not found. @throws \Drupal\Core\TypedData\Exception\MissingDataException Method $field->first() throws if data structure is unset and no item can be created.
entailment
public function executeNodeReactions($reaction_type, NodeInterface $node) { $provider = new NodeContextProvider($node); $provided = $provider->getRuntimeContexts([]); $this->contextManager->evaluateContexts($provided); // Fire off index reactions. foreach ($this->contextManager->getActiveReactions($reaction_type) as $reaction) { $reaction->execute($node); } }
Executes context reactions for a Node. @param string $reaction_type Reaction type. @param \Drupal\node\NodeInterface $node Node to evaluate contexts and pass to reaction.
entailment
public function executeMediaReactions($reaction_type, MediaInterface $media) { $provider = new MediaContextProvider($media); $provided = $provider->getRuntimeContexts([]); $this->contextManager->evaluateContexts($provided); // Fire off index reactions. foreach ($this->contextManager->getActiveReactions($reaction_type) as $reaction) { $reaction->execute($media); } }
Executes context reactions for a Media. @param string $reaction_type Reaction type. @param \Drupal\media\MediaInterface $media Media to evaluate contexts and pass to reaction.
entailment
public function executeFileReactions($reaction_type, FileInterface $file) { $provider = new FileContextProvider($file); $provided = $provider->getRuntimeContexts([]); $this->contextManager->evaluateContexts($provided); // Fire off index reactions. foreach ($this->contextManager->getActiveReactions($reaction_type) as $reaction) { $reaction->execute($file); } }
Executes context reactions for a File. @param string $reaction_type Reaction type. @param \Drupal\file\FileInterface $file File to evaluate contexts and pass to reaction.
entailment
public function executeTermReactions($reaction_type, TermInterface $term) { $provider = new TermContextProvider($term); $provided = $provider->getRuntimeContexts([]); $this->contextManager->evaluateContexts($provided); // Fire off index reactions. foreach ($this->contextManager->getActiveReactions($reaction_type) as $reaction) { $reaction->execute($term); } }
Executes context reactions for a File. @param string $reaction_type Reaction type. @param \Drupal\taxonomy\TermInterface $term Term to evaluate contexts and pass to reaction.
entailment
public function executeDerivativeReactions($reaction_type, NodeInterface $node, MediaInterface $media) { $provider = new MediaContextProvider($media); $provided = $provider->getRuntimeContexts([]); $this->contextManager->evaluateContexts($provided); // Fire off index reactions. foreach ($this->contextManager->getActiveReactions($reaction_type) as $reaction) { $reaction->execute($node); } }
Executes derivative reactions for a Media and Node. @param string $reaction_type Reaction type. @param \Drupal\node\NodeInterface $node Node to pass to reaction. @param \Drupal\media\MediaInterface $media Media to evaluate contexts.
entailment
public function haveFieldsChanged(ContentEntityInterface $entity, ContentEntityInterface $original) { $field_definitions = $this->entityFieldManager->getFieldDefinitions($entity->getEntityTypeId(), $entity->bundle()); $ignore_list = ['vid' => 1, 'changed' => 1, 'path' => 1]; $field_definitions = array_diff_key($field_definitions, $ignore_list); foreach ($field_definitions as $field_name => $field_definition) { $langcodes = array_keys($entity->getTranslationLanguages()); if ($langcodes !== array_keys($original->getTranslationLanguages())) { // If the list of langcodes has changed, we need to save. return TRUE; } foreach ($langcodes as $langcode) { $items = $entity ->getTranslation($langcode) ->get($field_name) ->filterEmptyItems(); $original_items = $original ->getTranslation($langcode) ->get($field_name) ->filterEmptyItems(); // If the field items are not equal, we need to save. if (!$items->equals($original_items)) { return TRUE; } } } return FALSE; }
Evaluates if fields have changed between two instances of a ContentEntity. @param \Drupal\Core\Entity\ContentEntityInterface $entity The updated entity. @param \Drupal\Core\Entity\ContentEntityInterface $original The original entity. @return bool TRUE if the fields have changed.
entailment
public function getFilesystemSchemes() { $schemes = ['public']; if (!empty(Settings::get('file_private_path'))) { $schemes[] = 'private'; } return array_merge($schemes, $this->flysystemFactory->getSchemes()); }
Returns a list of all available filesystem schemes. @return String[] List of all available filesystem schemes.
entailment
public function getMediaReferencingNodeAndTerm(NodeInterface $node, TermInterface $term) { $term_fields = $this->getReferencingFields('media', 'taxonomy_term'); if (count($term_fields) <= 0) { \Drupal::logger("No media fields reference a taxonomy term"); return NULL; } $node_fields = $this->getReferencingFields('media', 'node'); if (count($node_fields) <= 0) { \Drupal::logger("No media fields reference a node."); return NULL; } $remove_entity = function (&$o) { $o = substr($o, strpos($o, '.') + 1); }; array_walk($term_fields, $remove_entity); array_walk($node_fields, $remove_entity); $query = $this->entityQuery->get('media'); $taxon_condition = $this->getEntityQueryOrCondition($query, $term_fields, $term->id()); $query->condition($taxon_condition); $node_condition = $this->getEntityQueryOrCondition($query, $node_fields, $node->id()); $query->condition($node_condition); // Does the tags field exist? try { $mids = $query->execute(); } catch (QueryException $e) { $mids = []; } return $mids; }
Get array of media ids that have fields that reference $node and $term. @param \Drupal\node\NodeInterface $node The node to reference. @param \Drupal\taxonomy\TermInterface $term The term to reference. @return array|int|null Array of media IDs or NULL.
entailment
public function getReferencingFields($entity_type, $target_type) { $fields = $this->entityQuery->get('field_storage_config') ->condition('entity_type', $entity_type) ->condition('settings.target_type', $target_type) ->execute(); if (!is_array($fields)) { $fields = [$fields]; } return $fields; }
Get the fields on an entity of $entity_type that reference a $target_type. @param string $entity_type Type of entity to search for. @param string $target_type Type of entity the field references. @return array Array of fields.
entailment
private function getEntityQueryOrCondition(QueryInterface $query, array $fields, $value) { $condition = $query->orConditionGroup(); foreach ($fields as $field) { $condition->condition($field, $value); } return $condition; }
Make an OR condition for an array of fields and a value. @param \Drupal\Core\Entity\Query\QueryInterface $query The QueryInterface for the query. @param array $fields The array of field names. @param string $value The value to search the fields for. @return \Drupal\Core\Entity\Query\ConditionInterface The OR condition to add to your query.
entailment
public function createAndFilterSqlParts( $params ) { $returnArray = array( 'tables' => '', 'joins' => '', 'columns' => '' ); if ( !isset( $params['tag_id'] ) ) return $returnArray; if ( is_array( $params['tag_id'] ) ) { $tagIDsArray = $params['tag_id']; } else if ( (int) $params['tag_id'] > 0 ) { $tagIDsArray = array( (int) $params['tag_id'] ); } else { return $returnArray; } if ( !isset( $params['include_synonyms'] ) || ( isset( $params['include_synonyms'] ) && (bool) $params['include_synonyms'] == true ) ) { /** @var eZTagsObject[] $tags */ $tags = eZTagsObject::fetchList( array( 'main_tag_id' => array( $tagIDsArray ) ) ); if ( is_array( $tags ) ) { foreach ( $tags as $tag ) { $tagIDsArray[] = $tag->attribute( 'id' ); } } } $returnArray['tables'] = " INNER JOIN eztags_attribute_link i1 ON (i1.object_id = ezcontentobject.id AND i1.objectattribute_version = ezcontentobject.current_version) INNER JOIN eztags i2 ON (i1.keyword_id = i2.id) INNER JOIN eztags_keyword i3 ON (i2.id = i3.keyword_id)"; $dbStrings = array(); foreach ( $tagIDsArray as $tagID ) { if ( is_numeric( $tagID ) ) { $dbStrings[] = "EXISTS ( SELECT 1 FROM eztags_attribute_link j1, ezcontentobject j2 WHERE j1.keyword_id = " . (int) $tagID . " AND j1.object_id = j2.id AND j2.id = ezcontentobject.id AND j1.objectattribute_version = j2.current_version )"; } } $dbString = implode( " AND ", $dbStrings ); if ( isset( $params['language'] ) ) { $language = $params['language']; if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $returnArray['joins'] = " $dbString AND " . eZContentLanguage::languagesSQLFilter( 'i2' ) . " AND " . eZContentLanguage::sqlFilter( 'i3', 'i2' ) . " AND "; if ( isset( $params['language'] ) ) eZContentLanguage::clearPrioritizedLanguages(); return $returnArray; }
Creates and returns SQL parts used in fetch functions @param array $params @return array
entailment
public function createAndMultipleFilterSqlParts( $params ) { $returnArray = array( 'tables' => '', 'joins' => '', 'columns' => '' ); if ( !isset( $params['tag_id'] ) ) return $returnArray; if ( is_array( $params['tag_id'] ) ) { $tagIDsArray = $params['tag_id']; } else { return $returnArray; } $returnArray['tables'] = " INNER JOIN eztags_attribute_link i1 ON (i1.object_id = ezcontentobject.id AND i1.objectattribute_version = ezcontentobject.current_version) INNER JOIN eztags i2 ON (i1.keyword_id = i2.id) INNER JOIN eztags_keyword i3 ON (i2.id = i3.keyword_id)"; $dbStrings = array(); $db = eZDB::instance(); foreach ( $tagIDsArray as $tagIDGroup ) { $tagIDGroup = (array) $tagIDGroup; if ( !isset( $params['include_synonyms'] ) || ( isset( $params['include_synonyms'] ) && (bool) $params['include_synonyms'] == true ) ) { /** @var eZTagsObject[] $tags */ $tags = eZTagsObject::fetchList( array( 'main_tag_id' => array( $tagIDGroup ) ) ); if ( is_array( $tags ) ) { foreach ( $tags as $tag ) { $tagIDGroup[] = $tag->attribute( 'id' ); } } } $dbStrings[] = "EXISTS ( SELECT 1 FROM eztags_attribute_link j1, ezcontentobject j2 WHERE " . $db->generateSQLINStatement( $tagIDGroup, 'j1.keyword_id', false, true, 'int' ) . " AND j1.object_id = j2.id AND j2.id = ezcontentobject.id AND j1.objectattribute_version = j2.current_version )"; } $dbString = implode( " AND ", $dbStrings ); if ( isset( $params['language'] ) ) { $language = $params['language']; if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $returnArray['joins'] = " $dbString AND " . eZContentLanguage::languagesSQLFilter( 'i2' ) . " AND " . eZContentLanguage::sqlFilter( 'i3', 'i2' ) . " AND "; if ( isset( $params['language'] ) ) eZContentLanguage::clearPrioritizedLanguages(); return $returnArray; }
Creates and returns SQL parts used in fetch functions @param array $params where 'tag_id' is an array of arrays; at least one tag ID from each array must match @return array
entailment
protected function alterRoutes(RouteCollection $collection) { if ($route = $collection->get('view.media_of.page_1')) { $route->setOption('_admin_route', 'TRUE'); } if ($route = $collection->get('view.manage_members.page_1')) { $route->setOption('_admin_route', 'TRUE'); } }
{@inheritdoc}
entailment
public function getPath() { $this->checkPathIndexNeeded(); if(empty($this->jsonValues) && empty($this->jsonText)) { throw new \Exception('JSON values must be given to the object\'s constructor.'); } return rawurlencode($this->options['index']).'/field/'; }
{@inheritdoc}
entailment
public function addQuery(Search $query, $modeManualAction = null) { if($modeManualAction && $this->data['mode'] != 'manual') { throw new \InvalidArgumentException('Query mode must be set to "manual" before using a batchAction for queries.'); } //add query data $queryArray = json_decode($query->getData(), true); //add batchAction if any if($modeManualAction) { $queryArray['batchAction'] = $modeManualAction; } //add template if any $template = $query->getTemplate(); if(!empty($template)) { $queryArray['template'] = $template; $suffix = 'Template'; } else { $suffix = ''; } //add type of query $type = get_class($query); switch($type) { case 'OpenSearchServer\Search\Field\Search': $queryArray['type'] = 'SearchField'.$suffix; break; case 'OpenSearchServer\Search\Pattern\Search': $queryArray['type'] = 'SearchPattern'.$suffix; break; } $this->data['queries'][] = $queryArray; }
Add one query to the batch @param Search $query @param String $modeManualAction Batch action to use for the query, if mode is "manual"
entailment
public function addQueries(array $queries = array()) { foreach($queries as $queryInfo) { $batchAction = (isset($queryInfo[1])) ? $queryInfo[1] : null; $this->addQuery($queryInfo[0], $batchAction); } }
Call query() for each item in the array @param array $queries An array of array: each sub array contains one required item, the query, and a second optionnal item, the batchAction to use for this query if mode is "manual"
entailment
public function defaultConfiguration() { $config = parent::defaultConfiguration(); $config['path'] = '[date:custom:Y]-[date:custom:m]/[node:nid]-[term:name].mp3'; $config['mimetype'] = 'audio/mpeg'; $config['queue'] = 'islandora-connector-homarus'; $config['destination_media_type'] = 'audio'; $config['args'] = '-codec:a libmp3lame -q:a 5'; return $config; }
{@inheritdoc}
entailment
public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form = parent::buildConfigurationForm($form, $form_state); $form['mimetype']['#description'] = t('Mimetype to convert to (e.g. audio/mpeg, audio/m4a, etc...)'); $form['args']['#description'] = t('Additional command line parameters for FFMpeg'); return $form; }
{@inheritdoc}
entailment
public function load($resource, $type = null): array { try { $path = $this->locator->locate($resource); $file = $this->filesystem->openFile($path); $configValues = $this->yamlParser->parse($file->getContents()); return $configValues; } catch (FileLocatorFileNotFoundException $error) { return []; } }
Loads a resource. @param mixed $resource The resource @param string $type The resource type @return array @suppress PhanUndeclaredClassCatch
entailment
public function supports($resource, $type = null): bool { return is_string($resource) && in_array(pathinfo($resource, PATHINFO_EXTENSION), ['yml', 'yaml']); }
Returns true if this class supports the given resource. @param mixed $resource A resource @param string $type The resource type @return bool true if this class supports the given resource, false otherwise
entailment
static public function fetchTag( $tagID, $language = false ) { if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $result = false; if ( is_numeric( $tagID ) ) { $result = eZTagsObject::fetch( $tagID ); } else if ( is_array( $tagID ) && !empty( $tagID ) ) { $result = eZTagsObject::fetchList( array( 'id' => array( $tagID ) ) ); } if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); if ( $result instanceof eZTagsObject || ( is_array( $result ) && !empty( $result ) ) ) return array( 'result' => $result ); return array( 'result' => false ); }
Fetches eZTagsObject object for the provided tag ID @static @param int $tagID @param mixed $language @return array
entailment
static public function fetchTagsByKeyword( $keyword, $language = false ) { if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } if ( strpos( $keyword, '*' ) !== false ) { $keyword = preg_replace( array( '#%#m', '#(?<!\\\\)\\*#m', '#(?<!\\\\)\\\\\\*#m', '#\\\\\\\\#m' ), array( '\\%', '%', '*', '\\\\' ), $keyword ); $keyword = array( 'like', $keyword ); } $result = eZTagsObject::fetchByKeyword( $keyword ); if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); if ( is_array( $result ) && !empty( $result ) ) return array( 'result' => $result ); return array( 'result' => false ); }
Fetches all tags named with provided keyword @static @param string $keyword @param mixed $language @return array
entailment
static public function fetchTagByRemoteID( $remoteID, $language = false ) { if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $result = eZTagsObject::fetchByRemoteID( $remoteID ); if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); if ( $result instanceof eZTagsObject ) return array( 'result' => $result ); return array( 'result' => false ); }
Fetches tag identified with provided remote ID @static @param string $remoteID @param mixed $language @return array
entailment
static public function fetchTagByUrl( $url, $language = false ) { if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $result = eZTagsObject::fetchByUrl( $url ); if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); if ( $result instanceof eZTagsObject ) return array( 'result' => $result ); return array( 'result' => false ); }
Fetches tag identified with provided URL @static @param string $url @param mixed $language @return array
entailment
static public function fetchTagTree( $parentTagID, $sortBy, $offset, $limit, $depth, $depthOperator, $includeSynonyms, $language = false ) { if ( !is_numeric( $parentTagID ) || (int) $parentTagID < 0 ) return array( 'result' => false ); $params = array( 'SortBy' => $sortBy, 'Offset' => $offset, 'Limit' => $limit, 'IncludeSynonyms' => $includeSynonyms ); if ( $depth !== false ) { $params['Depth'] = $depth; $params['DepthOperator'] = $depthOperator; } if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $tags = eZTagsObject::subTreeByTagID( $params, $parentTagID ); if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); return array( 'result' => $tags ); }
Fetches subtree of tags by specified parameters @static @param int $parentTagID @param array $sortBy @param int $offset @param int $limit @param int $depth @param string $depthOperator @param bool $includeSynonyms @param mixed $language @return array
entailment
static public function fetchTagTreeCount( $parentTagID, $depth, $depthOperator, $includeSynonyms, $language = false ) { if ( !is_numeric( $parentTagID ) || (int) $parentTagID < 0 ) return array( 'result' => 0 ); $params = array( 'IncludeSynonyms' => $includeSynonyms ); if ( $depth !== false ) { $params['Depth'] = $depth; $params['DepthOperator'] = $depthOperator; } if ( $language ) { if ( !is_array( $language ) ) $language = array( $language ); eZContentLanguage::setPrioritizedLanguages( $language ); } $tagsCount = eZTagsObject::subTreeCountByTagID( $params, $parentTagID ); if ( $language ) eZContentLanguage::clearPrioritizedLanguages(); return array( 'result' => $tagsCount ); }
Fetches subtree tag count by specified parameters @static @param int $parentTagID @param int $depth @param string $depthOperator @param bool $includeSynonyms @param mixed $language @return array
entailment
public function getRuntimeContexts(array $unqualified_context_ids) { $context_definition = new ContextDefinition('entity:file', NULL, FALSE); $value = NULL; // Hack the file out of the route. $route_object = $this->routeMatch->getRouteObject(); if ($route_object) { $route_contexts = $route_object->getOption('parameters'); if ($route_contexts && isset($route_contexts['file'])) { $file = $this->routeMatch->getParameter('file'); if ($file) { $value = $file; } } } $cacheability = new CacheableMetadata(); $cacheability->setCacheContexts(['route']); $context = new Context($context_definition, $value); $context->addCacheableDependency($cacheability); return ['file' => $context]; }
{@inheritdoc}
entailment
public function getBodyAttribute($value){ $value = str_replace(':)', '<div class="smiley smile"></div>', $value); $value = str_replace(':-)', '<div class="smiley smile"></div>', $value); $value = str_replace('(angry)', '<div class="smiley angry"></div>', $value); $value = str_replace(':(', '<div class="smiley sad"></div>', $value); $value = str_replace(':-(', '<div class="smiley sad"></div>', $value); $value = str_replace(':o', '<div class="smiley surprised"></div>', $value); $value = str_replace(':-o', '<div class="smiley surprised"></div>', $value); $value = str_replace(':s', '<div class="smiley confused"></div>', $value); $value = str_replace(':-s', '<div class="smiley confused"></div>', $value); $value = str_replace(':D', '<div class="smiley laugh"></div>', $value); $value = str_replace(':-D', '<div class="smiley laugh"></div>', $value); $value = str_replace(';)', '<div class="smiley wink"></div>', $value); $value = str_replace(';-)', '<div class="smiley wink"></div>', $value); $value = str_replace(':|', '<div class="smiley speechless"></div>', $value); $value = str_replace(':-|', '<div class="smiley speechless"></div>', $value); return $value; }
mutator for message body that replaces smiley codes with smiley images @param $value @return string
entailment
public function verify(Payload $payload) { $response = $this->service->call($payload); $string = $response->getBody(); $pattern = sprintf('/(%s|%s)/', self::IPN_VERIFIED, self::IPN_INVALID); if (!preg_match($pattern, $string)) { throw new UnexpectedValueException( sprintf('Unexpected verification status encountered: %s', $string) ); } return $response; }
Send HTTP Request to PayPal & verfify payload. @param Payload $payload @return mixed
entailment
public function createLogger(string $outputFormat, OutputInterface $reportOutput, OutputInterface $consoleOutput): LinterLoggerInterface { $errorOutput = ($consoleOutput instanceof ConsoleOutputInterface) ? $consoleOutput->getErrorOutput() : $consoleOutput; switch ($outputFormat) { case 'checkstyle': case 'xml': return new CompactConsoleLogger(new CheckstyleReportPrinter($reportOutput), $errorOutput); case 'txt': case 'text': return new VerboseConsoleLogger(new ConsoleReportPrinter($reportOutput), $consoleOutput); case 'compact': return new CompactConsoleLogger(new ConsoleReportPrinter($reportOutput), $consoleOutput); default: throw new \InvalidArgumentException('Invalid report printer "' . $outputFormat . '"!'); } }
Builds a suitable logger for logging lint progress and results. @param string $outputFormat The desired output format, as specified by the user, e.g. via command-line parameter @param OutputInterface $reportOutput Output stream for the result report (usually STDOUT or a file) @param OutputInterface $consoleOutput Output stream for console data (usually STDOUT) @return LinterLoggerInterface The printer matching the user's specifications.
entailment
public function buildForm(array $form, FormStateInterface $form_state) { $config = $this->config(self::CONFIG_NAME); $form[self::BROKER_URL] = [ '#type' => 'textfield', '#title' => $this->t('Broker URL'), '#default_value' => $config->get(self::BROKER_URL) ? $config->get(self::BROKER_URL) : 'tcp://localhost:61613', ]; $form[self::JWT_EXPIRY] = [ '#type' => 'textfield', '#title' => $this->t('JWT Expiry'), '#default_value' => $config->get(self::JWT_EXPIRY) ? $config->get(self::JWT_EXPIRY) : '+2 hour', ]; $form[self::GEMINI_URL] = [ '#type' => 'textfield', '#title' => $this->t('Gemini URL'), '#default_value' => $config->get(self::GEMINI_URL) ? $config->get(self::GEMINI_URL) : '', ]; $selected_bundles = $config->get(self::GEMINI_PSEUDO) ? $config->get(self::GEMINI_PSEUDO) : []; $options = []; foreach (['node', 'media', 'taxonomy_term'] as $content_entity) { $bundles = $this->entityTypeBundleInfo->getBundleInfo($content_entity); foreach ($bundles as $bundle => $bundle_properties) { $options["{$bundle}:{$content_entity}"] = $this->t('@label (@type)', [ '@label' => $bundle_properties['label'], '@type' => $content_entity, ]); } } $form['bundle_container'] = [ '#type' => 'details', '#title' => $this->t('Bundles with Gemini URI Pseudo field'), '#description' => $this->t('The selected bundles can display the pseudo-field showing the Gemini linked URI. Configured in the field display.'), '#open' => TRUE, self::GEMINI_PSEUDO => [ '#type' => 'checkboxes', '#options' => $options, '#default_value' => $selected_bundles, ], ]; return parent::buildForm($form, $form_state); }
{@inheritdoc}
entailment
public function validateForm(array &$form, FormStateInterface $form_state) { // Validate broker url by actually connecting with a stomp client. $brokerUrl = $form_state->getValue(self::BROKER_URL); // Attempt to subscribe to a dummy queue. try { $stomp = new StatefulStomp( new Client( $brokerUrl ) ); $stomp->subscribe('dummy-queue-for-validation'); $stomp->unsubscribe(); } // Invalidate the form if there's an issue. catch (StompException $e) { $form_state->setErrorByName( self::BROKER_URL, $this->t( 'Cannot connect to message broker at @broker_url', ['@broker_url' => $brokerUrl] ) ); } // Validate jwt expiry as a valid time string. $expiry = $form_state->getValue(self::JWT_EXPIRY); if (strtotime($expiry) === FALSE) { $form_state->setErrorByName( self::JWT_EXPIRY, $this->t( '"@expiry" is not a valid time or interval expression.', ['@expiry' => $expiry] ) ); } // Needed for the elseif below. $pseudo_types = array_filter($form_state->getValue(self::GEMINI_PSEUDO)); // Validate Gemini URL by validating the URL. $geminiUrlValue = trim($form_state->getValue(self::GEMINI_URL)); if (!empty($geminiUrlValue)) { try { $geminiUrl = Url::fromUri($geminiUrlValue); $client = GeminiClient::create($geminiUrlValue, $this->logger('islandora')); $client->findByUri('http://example.org'); } // Uri is invalid. catch (\InvalidArgumentException $e) { $form_state->setErrorByName( self::GEMINI_URL, $this->t( 'Cannot parse URL @url', ['@url' => $geminiUrlValue] ) ); } // Uri is not available. catch (ConnectException $e) { $form_state->setErrorByName( self::GEMINI_URL, $this->t( 'Cannot connect to URL @url', ['@url' => $geminiUrlValue] ) ); } } elseif (count($pseudo_types) > 0) { $form_state->setErrorByName( self::GEMINI_URL, $this->t('Must enter Gemini URL before selecting bundles to display a pseudo field on.') ); } }
{@inheritdoc}
entailment
public function submitForm(array &$form, FormStateInterface $form_state) { $config = $this->configFactory->getEditable(self::CONFIG_NAME); $pseudo_types = array_filter($form_state->getValue(self::GEMINI_PSEUDO)); $config ->set(self::BROKER_URL, $form_state->getValue(self::BROKER_URL)) ->set(self::JWT_EXPIRY, $form_state->getValue(self::JWT_EXPIRY)) ->set(self::GEMINI_URL, $form_state->getValue(self::GEMINI_URL)) ->set(self::GEMINI_PSEUDO, $pseudo_types) ->save(); parent::submitForm($form, $form_state); }
{@inheritdoc}
entailment
public function addDocument($document) { if(is_array($document)) { $this->addDocumentArray($document); } elseif ($document instanceof Document) { $this->addDocumentObject($document); } }
Add a document in list of documents to push to index @param array|string|OpenSearchServer\Document\Document $document
entailment
public function loadConfiguration(array $possibleConfigurationFiles = [], LinterConfiguration $configuration = null): LinterConfiguration { $configs = [$this->loader->load('typoscript-lint.dist.yml')]; foreach ($possibleConfigurationFiles as $configurationFile) { $loadedConfig = $this->loader->load($configurationFile); // Simple mechanism to detect tslint config files ("ts" as in "TypeScript", not "Typoscript") // and excluding them from being loaded. if (isset($loadedConfig["extends"]) || isset($loadedConfig["rulesDirectory"]) || isset($loadedConfig["rules"])) { continue; } $configs[] = $loadedConfig; } $configuration = $configuration ?? new LinterConfiguration(); $processedConfiguration = $this->processor->processConfiguration( $configuration, $configs ); $configuration->setConfiguration($processedConfiguration); return $configuration; }
Loads the linter configuration. @param string[] $possibleConfigurationFiles A list of possible configuration files to load from. These files will be searched in the current working directory and in the typoscript-lint root directory. Contents from these files will also be merged with the typoscript-lint.dist.yml file in the typoscript-lint root directory. @param LinterConfiguration|null $configuration The configuration on which to set the loaded configuration values. @return LinterConfiguration The linter configuration from the given configuration file.
entailment
static public function fetchByTagID( $tagID ) { $objects = parent::fetchObjectList( self::definition(), null, array( 'keyword_id' => $tagID ) ); if ( is_array( $objects ) ) return $objects; return array(); }
Fetches the array of eZTagsAttributeLinkObject objects based on provided tag ID @static @param int $tagID @return eZTagsAttributeLinkObject[]
entailment
static public function fetchByObjectAttributeAndKeywordID( $objectAttributeID, $objectAttributeVersion, $objectID, $keywordID ) { $objects = parent::fetchObjectList( self::definition(), null, array( 'objectattribute_id' => $objectAttributeID, 'objectattribute_version' => $objectAttributeVersion, 'object_id' => $objectID, 'keyword_id' => $keywordID ) ); if ( is_array( $objects ) && !empty( $objects ) ) return $objects[0]; return false; }
Fetches the eZTagsAttributeLinkObject object based on provided content object params and keyword ID @static @param int $objectAttributeID @param int $objectAttributeVersion @param int $objectID @param int $keywordID @return eZTagsAttributeLinkObject if found, false otherwise
entailment
static public function removeByAttribute( $objectAttributeID, $objectAttributeVersion = null ) { if ( !is_numeric( $objectAttributeID ) ) return; $conditions = array( 'objectattribute_id' => (int) $objectAttributeID ); if ( is_numeric( $objectAttributeVersion ) ) $conditions['objectattribute_version'] = (int) $objectAttributeVersion; parent::removeObject( self::definition(), $conditions ); }
Removes the objects from persistence which are related to content object attribute defined by attribute ID and attribute version @static @param int $objectAttributeID @param int|null $objectAttributeVersion
entailment
public function getPath() { $this->checkPathIndexNeeded(); if(empty($this->options['template'])) { throw new \Exception('Method "template($name)" must be called before submitting request.'); } return rawurlencode($this->options['index']).'/spellcheck/'.rawurlencode($this->options['template']); }
{@inheritdoc}
entailment
public function writeReport(Report $report): void { $count = 0; $this->output->writeln(''); $this->output->writeln('<comment>CHECKSTYLE REPORT</comment>'); $styleMap = [ Issue::SEVERITY_ERROR => 'error', Issue::SEVERITY_WARNING => 'comment', Issue::SEVERITY_INFO => 'info', ]; foreach ($report->getFiles() as $file) { $this->output->writeln("=> <comment>{$file->getFilename()}</comment>."); foreach ($file->getIssues() as $issue) { $count++; $style = $styleMap[$issue->getSeverity()]; $this->output->writeln( sprintf( '<comment>%4d <%s>%s</%s></comment>', $issue->getLine() ?? 0, $style, $issue->getMessage(), $style ) ); } } $summary = []; foreach ($styleMap as $severity => $style) { $severityCount = $report->countIssuesBySeverity($severity); if ($severityCount > 0) { $summary[] = "<comment>$severityCount</comment> {$severity}s"; } } $this->output->writeln(""); $this->output->writeln('<comment>SUMMARY</comment>'); $this->output->write("<info><comment>$count</comment> issues in total.</info>"); if ($count > 0) { $this->output->writeln(" (" . implode(', ', $summary) . ")"); } }
Writes a report in human-readable table form. @param Report $report The report to print. @return void
entailment
public function execute() { // Return the mode name by itself. $config = $this->getConfiguration(); $exploded = explode('.', $config[self::MODE]); return $exploded[1]; }
{@inheritdoc}
entailment
public function getVersion() { $current = dirname(__FILE__); while($current !== '/') { if (file_exists($current . '/composer.lock')) { $contents = file_get_contents($current . '/composer.lock'); if ($contents === false) { continue; } $data = json_decode($contents); $packages = array_values(array_filter($data->packages, function($package) { return $package->name === "helmich/typo3-typoscript-lint"; })); if (count($packages) > 0) { return $packages[0]->version; } } $current = dirname($current); } return parent::getVersion(); }
Gets the currently installed version number. In contrast to the overridden parent method, this variant is Composer-aware and will its own version from the first-best composer.lock file that it can find. @see https://github.com/martin-helmich/typo3-typoscript-lint/issues/35 @return string
entailment
public static function create(ConfigFactoryInterface $config, LoggerInterface $logger) { // Get broker url from config. $settings = $config->get(IslandoraSettingsForm::CONFIG_NAME); $geminiUrl = $settings->get(IslandoraSettingsForm::GEMINI_URL); // Only attempt if there is one. if (!empty($geminiUrl)) { return GeminiClient::create($geminiUrl, $logger); } else { $logger->notice("Attempted to create Gemini client without a Gemini URL defined."); throw new PreconditionFailedHttpException("Unable to instantiate GeminiClient, missing Gemini URI in Islandora setting."); } }
Factory function. @param \Drupal\Core\Config\ConfigFactoryInterface $config Config. @param \Psr\Log\LoggerInterface $logger The logger channel. @return \Islandora\Crayfish\Commons\Client\GeminiClient Return GeminiClient @throws \Exception If there is no URL to connect to.
entailment
public function execute($entity = NULL) { // Include a token for later authentication in the message. $token = $this->auth->generateToken(); if (empty($token)) { // JWT isn't properly configured. Log and notify user. \Drupal::logger('islandora')->error( t('Error getting JWT token for message. Check JWT Configuration.') ); drupal_set_message( t('Error getting JWT token for message. Check JWT Configuration.'), 'error' ); return; } // Generate event as stomp message. try { $user = $this->entityTypeManager->getStorage('user')->load($this->account->id()); $data = $this->generateData($entity); $message = new Message( $this->eventGenerator->generateEvent($entity, $user, $data), ['Authorization' => "Bearer $token"] ); } catch (\RuntimeException $e) { // Notify the user the event couldn't be generated and abort. \Drupal::logger('islandora')->error( t('Error generating event: @msg', ['@msg' => $e->getMessage()]) ); drupal_set_message( t('Error generating event: @msg', ['@msg' => $e->getMessage()]), 'error' ); return; } // Send the message. try { $this->stomp->begin(); $this->stomp->send($this->configuration['queue'], $message); $this->stomp->commit(); } catch (StompException $e) { // Log it. \Drupal::logger('islandora')->error( 'Error publishing message: @msg', ['@msg' => $e->getMessage()] ); // Notify user. drupal_set_message( t('Error publishing message: @msg', ['@msg' => $e->getMessage()] ), 'error' ); } }
{@inheritdoc}
entailment
public function buildConfigurationForm(array $form, FormStateInterface $form_state) { $form['queue'] = [ '#type' => 'textfield', '#title' => t('Queue'), '#default_value' => $this->configuration['queue'], '#required' => TRUE, '#rows' => '8', '#description' => t('Name of queue to which event is published'), ]; $form['event'] = [ '#type' => 'select', '#title' => t('Event type'), '#default_value' => $this->configuration['event'], '#description' => t('Type of event to emit'), '#options' => [ 'Create' => t('Create'), 'Update' => t('Update'), 'Delete' => t('Delete'), 'Generate Derivative' => t('Generate Derivative'), ], ]; return $form; }
{@inheritdoc}
entailment
public function access($object, AccountInterface $account = NULL, $return_as_object = FALSE) { $result = AccessResult::allowed(); return $return_as_object ? $result : $result->isAllowed(); }
{@inheritdoc}
entailment
protected function getSpecialOffset(\Imagick $original, $targetWidth, $targetHeight) { return $this->getCenterOffset($original, $targetWidth, $targetHeight); }
get special offset for class @param \Imagick $original @param int $targetWidth @param int $targetHeight @return array
entailment
protected function getCenterOffset(\Imagick $image, $targetWidth, $targetHeight) { $size = $image->getImageGeometry(); $originalWidth = $size['width']; $originalHeight = $size['height']; $goalX = (int) (($originalWidth-$targetWidth)/2); $goalY = (int) (($originalHeight-$targetHeight)/2); return array('x' => $goalX, 'y' => $goalY); }
Get the cropping offset for the image based on the center of the image @param \Imagick $image @param int $targetWidth @param int $targetHeight @return array
entailment
protected function execute(InputInterface $input, OutputInterface $output): void { $filename = $input->getArgument('filename'); '@phan-var string $filename'; $output->writeln("Parsing input file <comment>{$filename}</comment>."); $tokens = $this->tokenizer->tokenizeStream($filename); $output->write($this->tokenPrinter->printTokenStream($tokens)); }
Executes this command. @param InputInterface $input Input options. @param OutputInterface $output Output stream. @return void
entailment
public function initializeClassAttribute( $classAttribute ) { if ( $classAttribute->attribute( self::SUBTREE_LIMIT_FIELD ) === null ) $classAttribute->setAttribute( self::SUBTREE_LIMIT_FIELD, 0 ); if ( $classAttribute->attribute( self::HIDE_ROOT_TAG_FIELD ) === null ) $classAttribute->setAttribute( self::HIDE_ROOT_TAG_FIELD, 0 ); if ( $classAttribute->attribute( self::MAX_TAGS_FIELD ) === null ) $classAttribute->setAttribute( self::MAX_TAGS_FIELD, 0 ); if ( $classAttribute->attribute( self::EDIT_VIEW_FIELD ) === null ) $classAttribute->setAttribute( self::EDIT_VIEW_FIELD, self::EDIT_VIEW_DEFAULT_VALUE ); $classAttribute->store(); }
Initializes the content class attribute @param eZContentClassAttribute $classAttribute
entailment
public function initializeObjectAttribute( $contentObjectAttribute, $currentVersion, $originalContentObjectAttribute ) { if ( $currentVersion != false ) { $eZTags = eZTags::createFromAttribute( $originalContentObjectAttribute, $contentObjectAttribute->attribute( 'language_code' ) ); $eZTags->store( $contentObjectAttribute ); } }
Initializes content object attribute based on another attribute @param eZContentObjectAttribute $contentObjectAttribute @param eZContentObjectVersion $currentVersion @param eZContentObjectAttribute $originalContentObjectAttribute
entailment
private function validateObjectAttribute( $contentObjectAttribute, $idString, $keywordString, $parentString, $localeString ) { $classAttribute = $contentObjectAttribute->contentClassAttribute(); // we cannot use empty() here as there can be cases where $parentString or $idString can be "0", // which evaluates to false with empty(), which is wrong for our use case if ( strlen( $keywordString ) == 0 && strlen( $parentString ) == 0 && strlen( $idString ) == 0 && strlen( $localeString ) == 0 ) { if ( $contentObjectAttribute->validateIsRequired() ) { $contentObjectAttribute->setValidationError( ezpI18n::tr( 'extension/eztags/datatypes', 'At least one tag is required to be added.' ) ); return eZInputValidator::STATE_INVALID; } } // see comment above else if ( strlen( $keywordString ) == 0 || strlen( $parentString ) == 0 || strlen( $idString ) == 0 || strlen( $localeString ) == 0 ) { $contentObjectAttribute->setValidationError( ezpI18n::tr( 'extension/eztags/datatypes', 'Attribute contains invalid data.' ) ); return eZInputValidator::STATE_INVALID; } else { $idArray = explode( '|#', $idString ); $keywordArray = explode( '|#', $keywordString ); $parentArray = explode( '|#', $parentString ); $localeArray = explode( '|#', $localeString ); if ( count( $keywordArray ) != count( $idArray ) || count( $parentArray ) != count( $idArray ) || count( $localeArray ) != count( $idArray ) ) { $contentObjectAttribute->setValidationError( ezpI18n::tr( 'extension/eztags/datatypes', 'Attribute contains invalid data.' ) ); return eZInputValidator::STATE_INVALID; } $maxTags = (int) $classAttribute->attribute( self::MAX_TAGS_FIELD ); if ( $maxTags > 0 && ( count( $idArray ) > $maxTags || count( $keywordArray ) > $maxTags || count( $parentArray ) > $maxTags || count( $localeArray ) > $maxTags ) ) { $contentObjectAttribute->setValidationError( ezpI18n::tr( 'extension/eztags/datatypes', 'Up to %1 tags are allowed to be added.', null, array( '%1' => $maxTags ) ) ); return eZInputValidator::STATE_INVALID; } } return eZInputValidator::STATE_ACCEPTED; }
Validates the data structure and returns true if it is valid for this datatype @param eZContentObjectAttribute $contentObjectAttribute @param string $idString @param string $keywordString @param string $parentString @param string $localeString @return bool
entailment