sentence1
stringlengths 52
3.87M
| sentence2
stringlengths 1
47.2k
| label
stringclasses 1
value |
---|---|---|
public function getSourceFile(MediaInterface $media) {
// Get the source field for the media type.
$source_field = $this->getSourceFieldName($media->bundle());
if (empty($source_field)) {
throw new NotFoundHttpException("Source field not set for {$media->bundle()} media");
}
// Get the file from the media.
$files = $media->get($source_field)->referencedEntities();
$file = reset($files);
return $file;
} | Gets the value of a source field for a Media.
@param \Drupal\media\MediaInterface $media
Media whose source field you are searching for.
@return \Drupal\file\FileInterface
File if it exists
@throws \Symfony\Component\HttpKernel\Exception\NotFoundHttpException | entailment |
public function updateSourceField(
MediaInterface $media,
$resource,
$mimetype
) {
$source_field = $this->getSourceFieldName($media->bundle());
$file = $this->getSourceFile($media);
// Update it.
$this->updateFile($file, $resource, $mimetype);
$file->save();
// Set fields provided by type plugin and mapped in bundle configuration
// for the media.
foreach ($media->bundle->entity->getFieldMap() as $source => $destination) {
if ($media->hasField($destination) && $value = $media->getSource()->getMetadata($media, $source)) {
$media->set($destination, $value);
}
// Ensure width and height are updated on File reference when it's an
// image. Otherwise you run into scaling problems when updating images
// with different sizes.
if ($source == 'width' || $source == 'height') {
$media->get($source_field)->first()->set($source, $value);
}
}
$media->save();
} | Updates a media's source field with the supplied resource.
@param \Drupal\media\MediaInterface $media
The media to update.
@param resource $resource
New file contents as a resource.
@param string $mimetype
New mimetype of contents.
@throws HttpException | entailment |
protected function updateFile(FileInterface $file, $resource, $mimetype = NULL) {
$uri = $file->getFileUri();
$destination = fopen($uri, 'wb');
if (!$destination) {
throw new HttpException(500, "File $uri could not be opened to write.");
}
$content_length = stream_copy_to_stream($resource, $destination);
fclose($destination);
if ($content_length === FALSE) {
throw new HttpException(500, "Request body could not be copied to $uri");
}
if ($content_length === 0) {
// Clean up the newly created, empty file.
unlink($uri);
throw new HttpException(400, "No bytes were copied to $uri");
}
if (!empty($mimetype)) {
$file->setMimeType($mimetype);
}
// Flush the image cache for the image so thumbnails get regenerated.
image_path_flush($uri);
} | Updates a File's binary contents on disk.
@param \Drupal\file\FileInterface $file
File to update.
@param resource $resource
Stream holding the new contents.
@param string $mimetype
Mimetype of new contents. | entailment |
public function putToNode(
NodeInterface $node,
MediaTypeInterface $media_type,
TermInterface $taxonomy_term,
$resource,
$mimetype,
$content_location
) {
$existing = $this->islandoraUtils->getMediaReferencingNodeAndTerm($node, $taxonomy_term);
if (!empty($existing)) {
// Just update already existing media.
$media = $this->entityTypeManager->getStorage('media')->load(reset($existing));
$this->updateSourceField(
$media,
$resource,
$mimetype
);
return FALSE;
}
else {
// Otherwise, the media doesn't exist yet.
// So make everything by hand.
// Get the source field for the media type.
$bundle = $media_type->id();
$source_field = $this->getSourceFieldName($bundle);
if (empty($source_field)) {
throw new NotFoundHttpException("Source field not set for $bundle media");
}
// Construct the File.
$file = $this->entityTypeManager->getStorage('file')->create([
'uid' => $this->account->id(),
'uri' => $content_location,
'filename' => $this->fileSystem->basename($content_location),
'filemime' => $mimetype,
'status' => FILE_STATUS_PERMANENT,
]);
// Validate file extension.
$source_field_config = $this->entityTypeManager->getStorage('field_config')->load("media.$bundle.$source_field");
$valid_extensions = $source_field_config->getSetting('file_extensions');
$errors = file_validate_extensions($file, $valid_extensions);
if (!empty($errors)) {
throw new BadRequestHttpException("Invalid file extension. Valid types are $valid_extensions");
}
$directory = $this->fileSystem->dirname($content_location);
if (!file_prepare_directory($directory, FILE_CREATE_DIRECTORY | FILE_MODIFY_PERMISSIONS)) {
throw new HttpException(500, "The destination directory does not exist, could not be created, or is not writable");
}
// Copy over the file content.
$this->updateFile($file, $resource, $mimetype);
$file->save();
// Construct the Media.
$media_struct = [
'bundle' => $bundle,
'uid' => $this->account->id(),
'name' => $file->getFilename(),
'langcode' => $this->languageManager->getDefaultLanguage()->getId(),
"$source_field" => [
'target_id' => $file->id(),
],
IslandoraUtils::MEDIA_OF_FIELD => [
'target_id' => $node->id(),
],
IslandoraUtils::MEDIA_USAGE_FIELD => [
'target_id' => $taxonomy_term->id(),
],
];
// Set alt text.
if ($source_field_config->getSetting('alt_field') && $source_field_config->getSetting('alt_field_required')) {
$media_struct[$source_field]['alt'] = $file->getFilename;
}
$media = $this->entityTypeManager->getStorage('media')->create($media_struct);
$media->save();
return $media;
}
} | Creates a new Media using the provided resource, adding it to a Node.
@param \Drupal\node\NodeInterface $node
The node to reference the newly created Media.
@param \Drupal\media\MediaTypeInterface $media_type
Media type for new media.
@param \Drupal\taxonomy\TermInterface $taxonomy_term
Term from the 'Behavior' vocabulary to give to new media.
@param resource $resource
New file contents as a resource.
@param string $mimetype
New mimetype of contents.
@param string $content_location
Drupal/PHP stream wrapper for where to upload the binary.
@throws HttpException | entailment |
protected function generateTypeList($entity_type, $bundle_type, $entity_add_form, $bundle_add_form, NodeInterface $node, $field) {
$type_definition = $this->entityTypeManager->getDefinition($bundle_type);
$build = [
'#theme' => 'entity_add_list',
'#bundles' => [],
'#cache' => ['tags' => $type_definition->getListCacheTags()],
];
$bundles = $this->entityTypeManager->getStorage($bundle_type)->loadMultiple();
$access_control_handler = $this->entityTypeManager->getAccessControlHandler($entity_type);
foreach (array_keys($bundles) as $bundle_id) {
$bundle = $bundles[$bundle_id];
// Skip bundles that don't have the specified field.
$fields = $this->entityFieldManager->getFieldDefinitions($entity_type, $bundle_id);
if (!isset($fields[$field])) {
continue;
}
$build['#bundles'][$bundle_id] = [
'label' => $bundle->label(),
'description' => $bundle->getDescription(),
'add_link' => Link::createFromRoute(
$bundle->label(),
$entity_add_form,
[$bundle_type => $bundle->id()],
['query' => ["edit[$field][widget][0][target_id]" => $node->id()]]
),
];
}
// Filter out bundles the user can't create.
foreach (array_keys($bundles) as $bundle_id) {
$access = $access_control_handler->createAccess($bundle_id, NULL, [], TRUE);
if (!$access->isAllowed()) {
unset($build['#bundles'][$bundle_id]);
}
$this->renderer->addCacheableDependency($build, $access);
}
// Build the message shown when there are no bundles.
$type_label = $type_definition->getLowercaseLabel();
$link_text = $this->t('Add a new @entity_type.', ['@entity_type' => $type_label]);
$build['#add_bundle_message'] = $this->t('There is no @entity_type yet. @add_link', [
'@entity_type' => $type_label,
'@add_link' => Link::createFromRoute($link_text, $bundle_add_form)->toString(),
]);
return $build;
} | Renders a list of content types to add as members. | entailment |
protected function getFaceList()
{
if (!function_exists('face_detect')) {
$msg = 'PHP Facedetect extension must be installed.
See http://www.xarg.org/project/php-facedetect/ for more details';
throw new \Exception($msg);
}
if ($this->maxExecutionTime) {
$timeBefore = microtime(true);
}
$faceList = $this->getFaceListFromClassifier(self::CLASSIFIER_FACE);
if ($this->maxExecutionTime) {
$timeSpent = microtime(true) - $timeBefore;
}
if (!$this->maxExecutionTime || $timeSpent < ($this->maxExecutionTime / 2)) {
$profileList = $this->getFaceListFromClassifier(self::CLASSIFIER_PROFILE);
$faceList = array_merge($faceList, $profileList);
}
return $faceList;
} | getFaceList get faces positions and sizes
@access protected
@return array | entailment |
protected function getFaceListFromClassifier($classifier)
{
$faceList = face_detect($this->imagePath, __DIR__ . $classifier);
if (!$faceList) {
$faceList = array();
}
return $faceList;
} | getFaceListFromClassifier
@param string $classifier
@access protected
@return array | entailment |
protected function getSafeZoneList()
{
if (!isset($this->safeZoneList)) {
$this->safeZoneList = array();
}
// the local key is the current image width-height
$key = $this->originalImage->getImageWidth() . '-' . $this->originalImage->getImageHeight();
if (!isset($this->safeZoneList[$key])) {
$faceList = $this->getFaceList();
// getFaceList works on the main image, so we use a ratio between main/current image
$xRatio = $this->getBaseDimension('width') / $this->originalImage->getImageWidth();
$yRatio = $this->getBaseDimension('height') / $this->originalImage->getImageHeight();
$safeZoneList = array();
foreach ($faceList as $face) {
$hw = ceil($face['w'] / 2);
$hh = ceil($face['h'] / 2);
$safeZone = array(
'left' => $face['x'] - $hw,
'right' => $face['x'] + $face['w'] + $hw,
'top' => $face['y'] - $hh,
'bottom' => $face['y'] + $face['h'] + $hh
);
$safeZoneList[] = array(
'left' => round($safeZone['left'] / $xRatio),
'right' => round($safeZone['right'] / $xRatio),
'top' => round($safeZone['top'] / $yRatio),
'bottom' => round($safeZone['bottom'] / $yRatio),
);
}
$this->safeZoneList[$key] = $safeZoneList;
}
return $this->safeZoneList[$key];
} | getSafeZoneList
@access private
@return array | entailment |
public function read($path) {
$meta = $this->readStream($path);
if (!$meta) {
return FALSE;
}
if (isset($meta['stream'])) {
$meta['contents'] = stream_get_contents($meta['stream']);
fclose($meta['stream']);
unset($meta['stream']);
}
return $meta;
} | {@inheritdoc} | entailment |
public function readStream($path) {
$response = $this->fedora->getResource($path);
if ($response->getStatusCode() != 200) {
return FALSE;
}
$meta = $this->getMetadataFromHeaders($response);
$meta['path'] = $path;
if ($meta['type'] == 'file') {
$meta['stream'] = StreamWrapper::getResource($response->getBody());
}
return $meta;
} | {@inheritdoc} | entailment |
public function getMetadata($path) {
$response = $this->fedora->getResourceHeaders($path);
if ($response->getStatusCode() != 200) {
return FALSE;
}
$meta = $this->getMetadataFromHeaders($response);
$meta['path'] = $path;
return $meta;
} | {@inheritdoc} | entailment |
protected function getMetadataFromHeaders(Response $response) {
$last_modified = \DateTime::createFromFormat(
\DateTime::RFC1123,
$response->getHeader('Last-Modified')[0]
);
// NonRDFSource's are considered files. Everything else is a
// directory.
$type = 'dir';
$links = Psr7\parse_header($response->getHeader('Link'));
foreach ($links as $link) {
if ($link['rel'] == 'type' && $link[0] == '<http://www.w3.org/ns/ldp#NonRDFSource>') {
$type = 'file';
break;
}
}
$meta = [
'type' => $type,
'timestamp' => $last_modified->getTimestamp(),
];
if ($type == 'file') {
$meta['size'] = $response->getHeader('Content-Length')[0];
$meta['mimetype'] = $response->getHeader('Content-Type')[0];
}
return $meta;
} | Gets metadata from response headers.
@param \GuzzleHttp\Psr7\Response $response
Response. | entailment |
public function listContents($directory = '', $recursive = FALSE) {
// Strip leading and trailing whitespace and /'s.
$normalized = trim($directory, ' \t\n\r\0\x0B/');
// Exit early if it's a file.
$meta = $this->getMetadata($normalized);
if ($meta['type'] == 'file') {
return [];
}
// Get the resource from Fedora.
$response = $this->fedora->getResource($normalized, ['Accept' => 'application/ld+json']);
$jsonld = (string) $response->getBody();
$graph = json_decode($jsonld, TRUE);
$uri = $this->fedora->getBaseUri() . $normalized;
// Hack it out of the graph.
// There may be more than one resource returned.
$resource = [];
foreach ($graph as $elem) {
if (isset($elem['@id']) && $elem['@id'] == $uri) {
$resource = $elem;
break;
}
}
// Exit early if resource doesn't contain other resources.
if (!isset($resource['http://www.w3.org/ns/ldp#contains'])) {
return [];
}
// Collapse uris to a single array.
$contained = array_map(
function ($elem) {
return $elem['@id'];
},
$resource['http://www.w3.org/ns/ldp#contains']
);
// Exit early if not recursive.
if (!$recursive) {
// Transform results to their flysystem metadata.
return array_map(
[$this, 'transformToMetadata'],
$contained
);
}
// Recursively get containment for ancestors.
$ancestors = [];
foreach ($contained as $child_uri) {
$child_directory = explode($this->fedora->getBaseUri(), $child_uri)[1];
$ancestors = array_merge($this->listContents($child_directory, $recursive), $ancestors);
}
// // Transform results to their flysystem metadata.
return array_map(
[$this, 'transformToMetadata'],
array_merge($ancestors, $contained)
);
} | {@inheritdoc} | entailment |
protected function transformToMetadata($uri) {
if (is_array($uri)) {
return $uri;
}
$exploded = explode($this->fedora->getBaseUri(), $uri);
return $this->getMetadata($exploded[1]);
} | Normalizes data for listContents().
@param string $uri
Uri. | entailment |
public function write($path, $contents, Config $config) {
$headers = [
'Content-Type' => $this->mimeTypeGuesser->guess($path),
];
$response = $this->fedora->saveResource(
$path,
$contents,
$headers
);
$code = $response->getStatusCode();
if (!in_array($code, [201, 204])) {
return FALSE;
}
return $this->getMetadata($path);
} | {@inheritdoc} | entailment |
public function writeStream($path, $contents, Config $config) {
return $this->write($path, $contents, $config);
} | {@inheritdoc} | entailment |
public function updateStream($path, $contents, Config $config) {
return $this->write($path, $contents, $config);
} | {@inheritdoc} | entailment |
public function delete($path) {
$response = $this->fedora->deleteResource($path);
$code = $response->getStatusCode();
if ($code == 204) {
// Deleted so check for a tombstone as well.
$tomb_code = $this->deleteTombstone($path);
if (!is_null($tomb_code)) {
return $tomb_code;
}
}
return in_array($code, [204, 404]);
} | {@inheritdoc} | entailment |
public function createDir($dirname, Config $config) {
$response = $this->fedora->saveResource(
$dirname
);
$code = $response->getStatusCode();
if (!in_array($code, [201, 204])) {
return FALSE;
}
return $this->getMetadata($dirname);
} | {@inheritdoc} | entailment |
private function deleteTombstone($path) {
$response = $this->fedora->getResourceHeaders($path);
$return = NULL;
if ($response->getStatusCode() == 410) {
$return = FALSE;
$link_headers = Psr7\parse_header($response->getHeader('Link'));
if ($link_headers) {
$tombstones = array_filter($link_headers, function ($o) {
return (isset($o['rel']) && $o['rel'] == 'hasTombstone');
});
foreach ($tombstones as $tombstone) {
// Trim <> from URL.
$url = rtrim(ltrim($tombstone[0], '<'), '>');
$response = $this->fedora->deleteResource($url);
if ($response->getStatusCode() == 204) {
$return = TRUE;
}
}
}
}
return $return;
} | Delete a tombstone for a path if it exists.
@param string $path
The original deleted resource path.
@return bool|null
NULL if no tombstone, TRUE if tombstone deleted, FALSE otherwise. | entailment |
public function put(MediaInterface $media, Request $request) {
$content_type = $request->headers->get('Content-Type', "");
if (empty($content_type)) {
throw new BadRequestHttpException("Missing Content-Type header");
}
// Since we update both the Media and its File, do this in a transaction.
$transaction = $this->database->startTransaction();
try {
$this->service->updateSourceField(
$media,
$request->getContent(TRUE),
$content_type
);
return new Response("", 204);
}
catch (HttpException $e) {
$transaction->rollBack();
throw $e;
}
catch (\Exception $e) {
$transaction->rollBack();
throw new HttpException(500, $e->getMessage());
}
} | Updates a source file for a Media.
@param \Drupal\media\MediaInterface $media
The media whose source file you want to update.
@param \Symfony\Component\HttpFoundation\Request $request
The request object.
@return \Symfony\Component\HttpFoundation\Response
204 on success.
@throws \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
public function putToNode(
NodeInterface $node,
MediaTypeInterface $media_type,
TermInterface $taxonomy_term,
Request $request
) {
$content_type = $request->headers->get('Content-Type', "");
if (empty($content_type)) {
throw new BadRequestHttpException("Missing Content-Type header");
}
$content_location = $request->headers->get('Content-Location', "");
// Since we create both a Media and its File,
// start a transaction.
$transaction = $this->database->startTransaction();
try {
$media = $this->service->putToNode(
$node,
$media_type,
$taxonomy_term,
$request->getContent(TRUE),
$content_type,
$content_location
);
// We return the media if it was newly created.
if ($media) {
$response = new Response("", 201);
$response->headers->set("Location", $media->url('canonical', ['absolute' => TRUE]));
}
else {
$response = new Response("", 204);
}
return $response;
}
catch (HttpException $e) {
$transaction->rollBack();
throw $e;
}
catch (\Exception $e) {
$transaction->rollBack();
throw new HttpException(500, $e->getMessage());
}
} | Adds a Media to a Node using the specified field.
@param \Drupal\node\NodeInterface $node
The Node to which you want to add a Media.
@param \Drupal\media\MediaTypeInterface $media_type
Media type for new media.
@param \Drupal\taxonomy\TermInterface $taxonomy_term
Term from the 'Behavior' vocabulary to give to new media.
@param \Symfony\Component\HttpFoundation\Request $request
The request object.
@return \Symfony\Component\HttpFoundation\Response
201 on success with a Location link header.
@throws \Symfony\Component\HttpKernel\Exception\HttpException | entailment |
public function putToNodeAccess(AccountInterface $account, RouteMatch $route_match) {
// We'd have 404'd already if node didn't exist, so no need to check.
// Just hack it out of the route match.
$node = $route_match->getParameter('node');
return AccessResult::allowedIf($node->access('update', $account) && $account->hasPermission('create media'));
} | Checks for permissions to update a node and create media.
@param \Drupal\Core\Session\AccountInterface $account
Account for user making the request.
@param \Drupal\Core\Routing\RouteMatch $route_match
Route match to get Node from url params.
@return \Drupal\Core\Access\AccessResultInterface
Access result. | entailment |
public static function create(ContainerInterface $container, array $configuration, $plugin_id, $plugin_definition) {
// Construct guzzle client to middleware that adds JWT.
$stack = HandlerStack::create();
$stack->push(static::addJwt($container->get('jwt.authentication.jwt')));
$client = new Client([
'handler' => $stack,
'base_uri' => $configuration['root'],
]);
$fedora = new FedoraApi($client);
// Return it.
return new static(
$fedora,
$container->get('file.mime_type.guesser')
);
} | {@inheritdoc} | entailment |
public static function addJwt(JwtAuth $jwt) {
return function (callable $handler) use ($jwt) {
return function (
RequestInterface $request,
array $options
) use (
$handler,
$jwt
) {
$request = $request->withHeader('Authorization', 'Bearer ' . $jwt->generateToken());
return $handler($request, $options);
};
};
} | Guzzle middleware to add a header to outgoing requests.
@param \Drupal\jwt\Authentication\Provider\JwtAuth $jwt
JWT. | entailment |
public function ensure($force = FALSE) {
// Check fedora root for sanity.
$response = $this->fedora->getResourceHeaders('');
if ($response->getStatusCode() != 200) {
return [[
'severity' => RfcLogLevel::ERROR,
'message' => '%url returned %status',
'context' => [
'%url' => $this->fedora->getBaseUri(),
'%status' => $response->getStatusCode(),
],
],
];
}
return [];
} | {@inheritdoc} | entailment |
protected function generateData(EntityInterface $entity) {
$data = parent::generateData($entity);
// Find media belonging to node that has the source term, and set its file
// url in the data array.
$source_term = $this->utils->getTermForUri($this->configuration['source_term_uri']);
if (!$source_term) {
throw new \RuntimeException("Could not locate source term with uri" . $this->configuration['source_term_uri'], 500);
}
$source_media = $this->utils->getMediaWithTerm($entity, $source_term);
if (!$source_media) {
throw new \RuntimeException("Could not locate source media", 500);
}
$source_file = $this->mediaSource->getSourceFile($source_media);
if (!$source_file) {
throw new \RuntimeException("Could not locate source file for media {$source_media->id()}", 500);
}
$data['source_uri'] = $source_file->url('canonical', ['absolute' => TRUE]);
// Find the term for the derivative and use it to set the destination url
// in the data array.
$derivative_term = $this->utils->getTermForUri($this->configuration['derivative_term_uri']);
if (!$source_term) {
throw new \RuntimeException("Could not locate derivative term with uri" . $this->configuration['derivative_term_uri'], 500);
}
$route_params = [
'node' => $entity->id(),
'media_type' => $this->configuration['destination_media_type'],
'taxonomy_term' => $derivative_term->id(),
];
$data['destination_uri'] = Url::fromRoute('islandora.media_source_put_to_node', $route_params)
->setAbsolute()
->toString();
$token_data = [
'node' => $entity,
'media' => $source_media,
'term' => $derivative_term,
];
$path = $this->token->replace($data['path'], $token_data);
$data['file_upload_uri'] = $data['scheme'] . '://' . $path;
// Get rid of some config so we just pass along
// what the camel route and microservice need.
unset($data['source_term_uri']);
unset($data['derivative_term_uri']);
unset($data['path']);
unset($data['scheme']);
unset($data['destination_media_type']);
return $data;
} | Override this to return arbitrary data as an array to be json encoded. | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$schemes = $this->utils->getFilesystemSchemes();
$scheme_options = array_combine($schemes, $schemes);
$form = parent::buildConfigurationForm($form, $form_state);
$form['event']['#disabled'] = 'disabled';
$form['source_term'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'taxonomy_term',
'#title' => t('Source term'),
'#default_value' => $this->utils->getTermForUri($this->configuration['source_term_uri']),
'#required' => TRUE,
'#description' => t('Term indicating the source media'),
];
$form['derivative_term'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'taxonomy_term',
'#title' => t('Derivative term'),
'#default_value' => $this->utils->getTermForUri($this->configuration['derivative_term_uri']),
'#required' => TRUE,
'#description' => t('Term indicating the derivative media'),
];
$form['destination_media_type'] = [
'#type' => 'entity_autocomplete',
'#target_type' => 'media_type',
'#title' => t('Derivative media type'),
'#default_value' => $this->getEntityById($this->configuration['destination_media_type']),
'#required' => TRUE,
'#description' => t('The Drupal media type to create with this derivative, can be different than the source'),
];
$form['mimetype'] = [
'#type' => 'textfield',
'#title' => t('Mimetype'),
'#default_value' => $this->configuration['mimetype'],
'#required' => TRUE,
'#rows' => '8',
'#description' => t('Mimetype to convert to (e.g. image/jpeg, video/mp4, etc...)'),
];
$form['args'] = [
'#type' => 'textfield',
'#title' => t('Additional arguments'),
'#default_value' => $this->configuration['args'],
'#rows' => '8',
'#description' => t('Additional command line arguments'),
];
$form['scheme'] = [
'#type' => 'select',
'#title' => t('File system'),
'#options' => $scheme_options,
'#default_value' => $this->configuration['scheme'],
'#required' => TRUE,
];
$form['path'] = [
'#type' => 'textfield',
'#title' => t('File path'),
'#default_value' => $this->configuration['path'],
'#description' => t('Path within the upload destination where files will be stored. Includes the filename and optional extension.'),
];
$form['queue'] = [
'#type' => 'textfield',
'#title' => t('Queue name'),
'#default_value' => $this->configuration['queue'],
'#description' => t('Queue name to send along to help routing events, CHANGE WITH CARE. Defaults to :queue', [
':queue' => $this->defaultConfiguration()['queue'],
]),
];
return $form;
} | {@inheritdoc} | entailment |
public function submitConfigurationForm(array &$form, FormStateInterface $form_state) {
parent::submitConfigurationForm($form, $form_state);
$tid = $form_state->getValue('source_term');
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
$this->configuration['source_term_uri'] = $this->utils->getUriForTerm($term);
$tid = $form_state->getValue('derivative_term');
$term = $this->entityTypeManager->getStorage('taxonomy_term')->load($tid);
$this->configuration['derivative_term_uri'] = $this->utils->getUriForTerm($term);
$this->configuration['mimetype'] = $form_state->getValue('mimetype');
$this->configuration['args'] = $form_state->getValue('args');
$this->configuration['scheme'] = $form_state->getValue('scheme');
$this->configuration['path'] = trim($form_state->getValue('path'), '\\/');
$this->configuration['destination_media_type'] = $form_state->getValue('destination_media_type');
} | {@inheritdoc} | entailment |
protected function getEntityById($entity_id) {
$entity_ids = $this->entityTypeManager->getStorage('media_type')
->getQuery()->condition('id', $entity_id)->execute();
$id = reset($entity_ids);
if ($id !== FALSE) {
return $this->entityTypeManager->getStorage('media_type')->load($id);
}
return '';
} | Find a media_type by id and return it or nothing.
@param string $entity_id
The media type.
@return \Drupal\Core\Entity\EntityInterface|string
Return the loaded entity or nothing.
@throws \Drupal\Component\Plugin\Exception\PluginNotFoundException
Thrown by getStorage() if the entity type doesn't exist.
@throws \Drupal\Component\Plugin\Exception\InvalidPluginDefinitionException
Thrown by getStorage() if the storage handler couldn't be loaded. | entailment |
public function register()
{
$this->app->singleton('pushover', function($app)
{
return new Pushover($app['config']);
});
$this->app->booting(function()
{
$loader = AliasLoader::getInstance();
$loader->alias('Pushover', 'Dyaa\Pushover\Facades\Pushover');
});
$this->app->singleton('pushover.send', function ()
{
return new Commands\PushoverCommand($this->app['pushover']);
});
$this->commands(
'pushover.send'
);
} | Register the service provider.
@return void | entailment |
static public function definition()
{
return array( 'fields' => array( 'id' => array( 'name' => 'ID',
'datatype' => 'integer',
'default' => 0,
'required' => true ),
'parent_id' => array( 'name' => 'ParentID',
'datatype' => 'integer',
'default' => null,
'required' => false ),
'main_tag_id' => array( 'name' => 'MainTagID',
'datatype' => 'integer',
'default' => null,
'required' => false ),
'keyword' => array( 'name' => 'Keyword',
'datatype' => 'string',
'default' => '',
'required' => false ),
'depth' => array( 'name' => 'Depth',
'datatype' => 'integer',
'default' => 1,
'required' => false ),
'path_string' => array( 'name' => 'PathString',
'datatype' => 'string',
'default' => '',
'required' => false ),
'modified' => array( 'name' => 'Modified',
'datatype' => 'integer',
'default' => 0,
'required' => false ),
'remote_id' => array( 'name' => 'RemoteID',
'datatype' => 'string',
'default' => '',
'required' => true ),
'main_language_id' => array( 'name' => 'MainLanguageID',
'datatype' => 'integer',
'default' => 0,
'required' => false ),
'language_mask' => array( 'name' => 'LanguageMask',
'datatype' => 'integer',
'default' => 0,
'required' => false ) ),
'function_attributes' => array( 'parent' => 'getParent',
'children' => 'getChildren',
'children_count' => 'getChildrenCount',
'related_objects' => 'getRelatedObjects',
'related_objects_count' => 'getRelatedObjectsCount',
'subtree_limitations' => 'getSubTreeLimitations',
'subtree_limitations_count' => 'getSubTreeLimitationsCount',
'main_tag' => 'getMainTag',
'synonyms' => 'getSynonyms',
'synonyms_count' => 'getSynonymsCount',
'is_synonym' => 'isSynonym',
'icon' => 'getIcon',
'url' => 'getUrl',
'clean_url' => 'getCleanUrl',
'path' => 'getPath',
'path_count' => 'getPathCount',
'keyword' => 'getKeyword',
'available_languages' => 'getAvailableLanguages',
'current_language' => 'getCurrentLanguage',
'language_name_array' => 'languageNameArray',
'main_translation' => 'getMainTranslation',
'translations' => 'getTranslations',
'translations_count' => 'getTranslationsCount',
'always_available' => 'isAlwaysAvailable' ),
'keys' => array( 'id' ),
'increment_key' => 'id',
'class_name' => 'eZTagsObject',
'name' => 'eztags' );
} | Returns the definition array for eZTagsObject
@return array | entailment |
public function updatePathString()
{
$parentTag = $this->getParent( true );
$pathStringPrefix = $parentTag instanceof self ? $parentTag->attribute( 'path_string' ) : '/';
$this->setAttribute( 'path_string', $pathStringPrefix . $this->attribute( 'id' ) . '/' );
$this->store();
foreach ( $this->getSynonyms( true ) as $s )
{
$s->setAttribute( 'path_string', $pathStringPrefix . $s->attribute( 'id' ) . '/' );
$s->store();
}
foreach ( $this->getChildren( 0, null, true ) as $c )
{
$c->updatePathString();
}
} | Updates path string of the tag and all of it's children and synonyms. | entailment |
public function updateDepth()
{
$parentTag = $this->getParent( true );
$depth = $parentTag instanceof self ? $parentTag->attribute( 'depth' ) + 1 : 1;
$this->setAttribute( 'depth', $depth );
$this->store();
foreach ( $this->getSynonyms( true ) as $s )
{
$s->setAttribute( 'depth', $depth );
$s->store();
}
foreach ( $this->getChildren( 0, null, true ) as $c )
{
$c->updateDepth();
}
} | Updates depth of the tag and all of it's children and synonyms. | entailment |
public function getParent( $mainTranslation = false )
{
if ( $mainTranslation )
return self::fetchWithMainTranslation( $this->attribute( 'parent_id' ) );
return self::fetch( $this->attribute( 'parent_id' ) );
} | Returns tag parent
@param bool $mainTranslation
@return eZTagsObject | entailment |
public function getChildren( $offset = 0, $limit = null, $mainTranslation = false )
{
return self::fetchByParentID( $this->attribute( 'id' ), $offset, $limit, $mainTranslation );
} | Returns first level children tags
@param bool $mainTranslation
@param int $offset
@param int $limit
@return eZTagsObject[] | entailment |
public function getRelatedObjects()
{
// Not an easy task to fetch published objects with API and take care of current_version, status
// and attribute version, so just use SQL to fetch all related object ids in one go
$tagID = (int) $this->attribute( 'id' );
$db = eZDB::instance();
$result = $db->arrayQuery( "SELECT DISTINCT(o.id) AS object_id FROM eztags_attribute_link l
INNER JOIN ezcontentobject o ON l.object_id = o.id
AND l.objectattribute_version = o.current_version
AND o.status = " . eZContentObject::STATUS_PUBLISHED . "
WHERE l.keyword_id = $tagID" );
if ( !is_array( $result ) || empty( $result ) )
return array();
$objectIDArray = array();
foreach ( $result as $r )
{
$objectIDArray[] = $r['object_id'];
}
return eZContentObject::fetchIDArray( $objectIDArray );
} | Returns objects related to this tag
@return eZContentObject[] | entailment |
public function getRelatedObjectsCount()
{
// Not an easy task to fetch published objects with API and take care of current_version, status
// and attribute version, so just use SQL to fetch the object count in one go
$tagID = (int) $this->attribute( 'id' );
$db = eZDB::instance();
$result = $db->arrayQuery( "SELECT COUNT(DISTINCT o.id) AS count FROM eztags_attribute_link l
INNER JOIN ezcontentobject o ON l.object_id = o.id
AND l.objectattribute_version = o.current_version
AND o.status = " . eZContentObject::STATUS_PUBLISHED . "
WHERE l.keyword_id = $tagID" );
if ( is_array( $result ) && !empty( $result ) )
return (int) $result[0]['count'];
return 0;
} | Returns the count of objects related to this tag
@return int | entailment |
public function getSubTreeLimitations()
{
if ( $this->attribute( 'main_tag_id' ) != 0 )
return array();
return parent::fetchObjectList( eZContentClassAttribute::definition(), null,
array( 'data_type_string' => 'eztags',
eZTagsType::SUBTREE_LIMIT_FIELD => $this->attribute( 'id' ),
'version' => eZContentClass::VERSION_STATUS_DEFINED ) );
} | Returns list of eZContentClassAttribute objects (represented as subtree limitations)
@return eZContentClassAttribute[] | entailment |
public function getSubTreeLimitationsCount()
{
if ( $this->attribute( 'main_tag_id' ) != 0 )
return 0;
return parent::count( eZContentClassAttribute::definition(),
array( 'data_type_string' => 'eztags',
eZTagsType::SUBTREE_LIMIT_FIELD => $this->attribute( 'id' ),
'version' => eZContentClass::VERSION_STATUS_DEFINED ) );
} | Returns count of eZContentClassAttribute objects (represented as subtree limitation count)
@return int | entailment |
public function isInsideSubTreeLimit()
{
/** @var eZTagsObject[] $path */
$path = $this->getPath( true, true );
if ( is_array( $path ) && !empty( $path ) )
{
foreach ( $path as $tag )
{
if ( $tag->getSubTreeLimitationsCount() > 0 )
return true;
}
}
return false;
} | Checks if any of the parents have subtree limits defined
@return bool | entailment |
public function getMainTag( $mainTranslation = false )
{
if ( $mainTranslation )
return self::fetchWithMainTranslation( $this->attribute( 'main_tag_id' ) );
return self::fetch( $this->attribute( 'main_tag_id' ) );
} | Returns the main tag for synonym
@param bool $mainTranslation
@return eZTagsObject | entailment |
public function getIcon()
{
$ini = eZINI::instance( 'eztags.ini' );
/** @var array $iconMap */
$iconMap = $ini->variable( 'Icons', 'IconMap' );
$defaultIcon = $ini->variable( 'Icons', 'Default' );
if ( $this->attribute( 'main_tag_id' ) > 0 )
$tag = $this->getMainTag( true );
else
$tag = $this;
$tagID = $tag->attribute( 'id' );
if ( array_key_exists( $tagID, $iconMap ) && !empty( $iconMap[$tagID] ) )
return $iconMap[$tagID];
/** @var eZTagsObject[] $path */
$path = $tag->getPath( true, true );
if ( is_array( $path ) && !empty( $path ) )
{
foreach ( $path as $pathElement )
{
$pathElementID = $pathElement->attribute( 'id' );
if ( array_key_exists( $pathElementID, $iconMap ) && !empty( $iconMap[$pathElementID] ) )
return $iconMap[$pathElementID];
}
}
return $defaultIcon;
} | Returns icon associated with the tag, while respecting hierarchy structure
@return string | entailment |
public function getUrl( $clean = false )
{
/** @var eZTagsObject[] $path */
$path = $this->getPath();
$fullPathCount = $this->getPathCount( true );
$urlPrefix = trim( eZINI::instance( 'eztags.ini' )->variable( 'GeneralSettings', 'URLPrefix' ) );
$urlPrefix = trim( $urlPrefix, '/' );
$keywordArray = array();
if ( is_array( $path ) )
{
if ( count( $path ) != $fullPathCount )
{
return 'tags/id/' . $this->attribute( 'id' );
}
else
{
foreach ( $path as $tag )
{
$keywordArray[] = $clean ? $tag->attribute( 'keyword' ) : urlencode( $tag->attribute( 'keyword' ) );
}
$keywordArray[] = $clean ? $this->attribute( 'keyword' ) : urlencode( $this->attribute( 'keyword' ) );
return $clean ? implode( '/', $keywordArray ) : $urlPrefix . '/' . implode( '/', $keywordArray );
}
}
return $clean ? $this->attribute( 'keyword' ) : $urlPrefix . '/' . urlencode( $this->attribute( 'keyword' ) );
} | Returns the URL of the tag, to be used in tags/view
@param bool $clean
@return string | entailment |
public function getPath( $reverseSort = false, $mainTranslation = false )
{
$pathArray = explode( '/', trim( $this->attribute( 'path_string' ), '/' ) );
if ( !is_array( $pathArray ) || empty( $pathArray ) || count( $pathArray ) == 1 )
return array();
$pathArray = array_slice( $pathArray, 0, count( $pathArray ) - 1 );
return self::fetchList( array( 'id' => array( $pathArray ) ),
null,
array( 'path_string' => $reverseSort != false ? 'desc' : 'asc' ),
$mainTranslation );
} | Returns the array of eZTagsObject objects which are parents of this tag
@param bool $reverseSort
@param bool $mainTranslation
@return eZTagsObject[] | entailment |
public function getPathCount( $mainTranslation = false )
{
$pathArray = explode( '/', trim( $this->attribute( 'path_string' ), '/' ) );
if ( !is_array( $pathArray ) || empty( $pathArray ) || count( $pathArray ) == 1 )
return 0;
$pathArray = array_slice( $pathArray, 0, count( $pathArray ) - 1 );
return self::fetchListCount( array( 'id' => array( $pathArray ) ), $mainTranslation );
} | Returns the count of eZTagsObject objects which are parents of this tag
@param bool $mainTranslation
@return int | entailment |
public function getParentString()
{
$keywordsArray = array();
/** @var eZTagsObject[] $path */
$path = $this->getPath( false, true );
if ( is_array( $path ) && !empty( $path ) )
{
foreach ( $path as $tag )
{
$synonymsCount = $tag->getSynonymsCount( true );
$keywordsArray[] = $synonymsCount > 0 ? $tag->attribute( 'keyword' ) . ' (+' . $synonymsCount . ')' : $tag->attribute( 'keyword' );
}
}
$synonymsCount = $this->getSynonymsCount( true );
$keywordsArray[] = $synonymsCount > 0 ? $this->attribute( 'keyword' ) . ' (+' . $synonymsCount . ')' : $this->attribute( 'keyword' );
return implode( ' / ', $keywordsArray );
} | Returns the parent string of the tag
@return string | entailment |
public function updateModified()
{
$pathArray = explode( '/', trim( $this->attribute( 'path_string' ), '/' ) );
if ( $this->attribute( 'main_tag_id' ) > 0 )
array_push( $pathArray, $this->attribute( 'main_tag_id' ) );
if ( !empty( $pathArray ) )
{
$db = eZDB::instance();
$db->query( "UPDATE eztags SET modified = " . time() .
" WHERE " . $db->generateSQLINStatement( $pathArray, 'id', false, true, 'int' ) );
}
} | Updates modified timestamp on current tag and all of its parents
Expensive to run through API, so SQL takes care of it | entailment |
public function registerSearchObjects($relatedObjects = null)
{
$eZTagsINI = eZINI::instance( 'eztags.ini' );
if ( eZINI::instance( 'site.ini' )->variable( 'SearchSettings', 'DelayedIndexing' ) !== 'disabled'
|| $eZTagsINI->variable( 'SearchSettings', 'ReindexWhenDelayedIndexingDisabled' ) == 'enabled' )
{
if ($relatedObjects === null) {
$relatedObjects = $this->getRelatedObjects();
}
foreach ( $relatedObjects as $relatedObject )
{
eZContentOperationCollection::registerSearchObject( $relatedObject->attribute( 'id' ), $relatedObject->attribute( 'current_version' ) );
}
return;
}
eZHTTPTool::instance()->setSessionVariable( 'eZTagsShowReindexMessage', 1 );
} | Registers all objects related to this tag to search engine for processing
@param array|null $relatedObjects when not null, we assume that these are the objects related to the tag, instead
of fetching them. Useful when deleting tags. | entailment |
static public function fetch( $id, $locale = false )
{
if ( is_string( $locale ) )
$tags = self::fetchList( array( 'id' => $id ), null, null, false, $locale );
else
$tags = self::fetchList( array( 'id' => $id ) );
if ( is_array( $tags ) && !empty( $tags ) )
return $tags[0];
return false;
} | Returns eZTagsObject for given ID
@static
@param int $id
@param mixed $locale
@return eZTagsObject | entailment |
static public function fetchWithMainTranslation( $id )
{
$tags = self::fetchList( array( 'id' => $id ), null, null, true );
if ( is_array( $tags ) && !empty( $tags ) )
return $tags[0];
return false;
} | Returns eZTagsObject for given ID, using the main translation of the tag
@static
@param int $id
@return eZTagsObject | entailment |
static public function fetchList( $params, $limits = null, $sorts = null, $mainTranslation = false, $locale = false )
{
$customConds = self::fetchCustomCondsSQL( $params, $mainTranslation, $locale );
if ( is_array( $params ) )
{
$newParams = array();
foreach ( $params as $key => $value )
{
if ( $key != 'keyword' )
$newParams[$key] = $value;
else
$newParams['eztags_keyword.keyword'] = $value;
}
$params = $newParams;
}
if ( is_array( $sorts ) )
{
$newSorts = array();
foreach ( $sorts as $key => $value )
{
if ( $key != 'keyword' )
$newSorts[$key] = $value;
else
$newSorts['eztags_keyword.keyword'] = $value;
}
$sorts = $newSorts;
}
else if ( $sorts == null )
{
$sorts = array( 'eztags_keyword.keyword' => 'asc' );
}
$tagsList = parent::fetchObjectList( self::definition(), array(), $params,
$sorts, $limits, true, false,
array( 'DISTINCT eztags.*',
array( 'operation' => 'eztags_keyword.keyword',
'name' => 'keyword' ),
array( 'operation' => 'eztags_keyword.locale',
'name' => 'locale' ) ),
array( 'eztags_keyword' ), $customConds );
return $tagsList;
} | Returns array of eZTagsObject objects for given params
@static
@param array $params
@param array $limits
@param array $sorts
@param bool $mainTranslation
@param mixed $locale
@return eZTagsObject[] | entailment |
static public function fetchListCount( $params, $mainTranslation = false, $locale = false )
{
$customConds = self::fetchCustomCondsSQL( $params, $mainTranslation, $locale );
if ( is_array( $params ) )
{
$newParams = array();
foreach ( $params as $key => $value )
{
if ( $key != 'keyword' )
$newParams[$key] = $value;
else
$newParams['eztags_keyword.keyword'] = $value;
}
$params = $newParams;
}
$tagsList = parent::fetchObjectList( self::definition(), array(), $params,
array(), null, false, false,
array( array( 'operation' => 'COUNT( * )',
'name' => 'row_count' ) ),
array( 'eztags_keyword' ), $customConds );
return $tagsList[0]['row_count'];
} | Returns count of eZTagsObject objects for given params
@static
@param mixed $params
@param bool $mainTranslation
@param mixed $locale
@return int | entailment |
static public function fetchCustomCondsSQL( $params, $mainTranslation = false, $locale = false )
{
$customConds = is_array( $params ) && !empty( $params ) ? " AND " : " WHERE ";
$customConds .= " eztags.id = eztags_keyword.keyword_id ";
if ( $mainTranslation !== false )
{
$customConds .= " AND eztags.main_language_id + MOD( eztags.language_mask, 2 ) = eztags_keyword.language_id ";
}
else if ( is_string( $locale ) )
{
$db = eZDB::instance();
$customConds .= " AND " . eZContentLanguage::languagesSQLFilter( 'eztags' ) . " ";
$customConds .= " AND eztags_keyword.locale = '" . $db->escapeString( $locale ) . "' ";
}
else
{
$customConds .= " AND " . eZContentLanguage::languagesSQLFilter( 'eztags' ) . " ";
$customConds .= " AND " . eZContentLanguage::sqlFilter( 'eztags_keyword', 'eztags' ) . " ";
}
return $customConds;
} | Returns the SQL for custom fetching of tags with eZPersistentObject
@static
@param mixed $params
@param bool $mainTranslation
@param mixed $locale
@return string | entailment |
static public function fetchLimitations()
{
/** @var eZTagsObject[] $tags */
$tags = self::fetchList( array( 'parent_id' => 0, 'main_tag_id' => 0 ), null, null, true );
if ( !is_array( $tags ) )
return array();
$returnArray = array();
foreach ( $tags as $tag )
{
$returnArray[] = array( 'name' => $tag->attribute( 'keyword' ), 'id' => $tag->attribute( 'id' ) );
}
return $returnArray;
} | Returns the list of limitations that eZ Tags support
@static
@return array | entailment |
static public function fetchByParentID( $parentID, $offset = 0, $limit = null, $mainTranslation = false )
{
if ( $offset === 0 && $limit === null )
{
$limits = null;
}
else
{
$limits = array( 'offset' => $offset, 'limit' => $limit );
}
return self::fetchList(
array( 'parent_id' => $parentID, 'main_tag_id' => 0 ),
$limits,
null,
$mainTranslation
);
} | Returns array of eZTagsObject objects for given parent ID
@static
@param int $parentID
@param bool $mainTranslation
@param int $offset
@param int $limit
@return eZTagsObject[] | entailment |
static public function fetchSynonyms( $mainTagID, $mainTranslation = false )
{
return self::fetchList( array( 'main_tag_id' => $mainTagID ), null, null, $mainTranslation );
} | Returns array of eZTagsObject objects that are synonyms of provided tag ID
@static
@param int $mainTagID
@param bool $mainTranslation
@return eZTagsObject[] | entailment |
static public function fetchByKeyword( $keyword, $mainTranslation = false )
{
return self::fetchList( array( 'keyword' => $keyword ), null, null, $mainTranslation );
} | Returns array of eZTagsObject objects for given keyword
@static
@param mixed $keyword
@param bool $mainTranslation
@return eZTagsObject[] | entailment |
static public function fetchByPathString( $pathString, $mainTranslation = false )
{
return self::fetchList( array( 'path_string' => array( 'like', $pathString . '%' ),
'main_tag_id' => 0 ), null, null, $mainTranslation );
} | Returns the array of eZTagsObject objects for given path string
@static
@param string $pathString
@param bool $mainTranslation
@return eZTagsObject[] | entailment |
static public function fetchByRemoteID( $remoteID, $mainTranslation = false )
{
$tagsList = self::fetchList( array( 'remote_id' => $remoteID ), null, null, $mainTranslation );
if ( is_array( $tagsList ) && !empty( $tagsList ) )
return $tagsList[0];
return null;
} | Fetches tag by remote ID
@static
@param string $remoteID
@param bool $mainTranslation
@return eZTagsObject|null | entailment |
static public function fetchByUrl( $url, $mainTranslation = false )
{
$urlArray = is_array( $url ) ? $url : explode( '/', ltrim( $url, '/' ) );
if ( !is_array( $urlArray ) || empty( $urlArray ) )
return null;
$parentID = 0;
for ( $i = 0; $i < count( $urlArray ) - 1; $i++ )
{
/** @var eZTagsObject[] $tags */
$tags = self::fetchList(
array(
'parent_id' => $parentID,
'main_tag_id' => 0,
'keyword' => urldecode( trim( $urlArray[$i] ) )
),
null,
null,
$mainTranslation
);
if ( !is_array( $tags ) || empty( $tags ) )
return null;
$parentID = $tags[0]->attribute( 'id' );
}
$tags = self::fetchList(
array(
'parent_id' => $parentID,
'keyword' => urldecode( trim( $urlArray[count( $urlArray ) - 1] ) )
),
null,
null,
$mainTranslation
);
if ( !is_array( $tags ) || empty( $tags ) )
return null;
return $tags[0];
} | Fetches tag by URL
@static
@param string $url
@param bool $mainTranslation
@return eZTagsObject|null | entailment |
public function recursivelyDeleteTag()
{
foreach ( $this->getChildren( 0, null, true ) as $child )
{
$child->recursivelyDeleteTag();
}
$relatedObjects = $this->getRelatedObjects();
foreach ( $this->getSynonyms( true ) as $synonym )
{
$synonym->remove();
}
$this->remove();
$this->registerSearchObjects($relatedObjects);
} | Recursively deletes all tags below this tag, including self | entailment |
public function moveChildrenBelowAnotherTag( eZTagsObject $targetTag )
{
$currentTime = time();
$children = $this->getChildren( 0, null, true );
foreach ( $children as $child )
{
$childSynonyms = $child->getSynonyms( true );
foreach ( $childSynonyms as $childSynonym )
{
$childSynonym->setAttribute( 'parent_id', $targetTag->attribute( 'id' ) );
$childSynonym->store();
}
$child->setAttribute( 'parent_id', $targetTag->attribute( 'id' ) );
$child->setAttribute( 'modified', $currentTime );
$child->store();
$child->updatePathString( $targetTag );
$child->updateDepth( $targetTag );
}
} | Moves all children of this tag below another tag
@param eZTagsObject $targetTag | entailment |
public function transferObjectsToAnotherTag( $destination )
{
if ( !$destination instanceof self )
{
$destination = self::fetchWithMainTranslation( (int) $destination );
if ( !$destination instanceof self )
return;
}
foreach ( $this->getTagAttributeLinks() as $tagAttributeLink )
{
$link = eZTagsAttributeLinkObject::fetchByObjectAttributeAndKeywordID(
$tagAttributeLink->attribute( 'objectattribute_id' ),
$tagAttributeLink->attribute( 'objectattribute_version' ),
$tagAttributeLink->attribute( 'object_id' ),
$destination->attribute( 'id' ) );
if ( !$link instanceof eZTagsAttributeLinkObject )
{
$tagAttributeLink->setAttribute( 'keyword_id', $destination->attribute( 'id' ) );
$tagAttributeLink->store();
}
else
{
$tagAttributeLink->remove();
}
}
} | Transfers all objects related to this tag, to another tag
@param eZTagsObject|int $destination | entailment |
public function remove( $conditions = null, $extraConditions = null )
{
foreach ( $this->getTagAttributeLinks() as $tagAttributeLink )
{
$tagAttributeLink->remove();
}
foreach ( $this->getTranslations() as $translation )
{
$translation->remove();
}
parent::remove( $conditions, $extraConditions );
} | Removes self, while also removing related translations and links to objects
@param mixed $conditions
@param mixed $extraConditions | entailment |
static public function exists( $tagID, $keyword, $parentID )
{
$db = eZDB::instance();
$sql = "SELECT COUNT(*) AS row_count FROM eztags, eztags_keyword
WHERE eztags.id = eztags_keyword.keyword_id AND
eztags.parent_id = " . (int) $parentID . " AND
eztags.id <> " . (int) $tagID . " AND
eztags_keyword.keyword LIKE '" . $db->escapeString( $keyword ) . "'";
$result = $db->arrayQuery( $sql );
if ( is_array( $result ) && !empty( $result ) )
{
if ( (int) $result[0]['row_count'] > 0 )
return true;
}
return false;
} | Returns if tag with provided keyword and parent ID already exists, not counting tag with provided tag ID
@static
@param int $tagID
@param string $keyword
@param int $parentID
@return bool | entailment |
static public function subTreeByTagID( $params = array(), $tagID = 0 )
{
if ( !is_numeric( $tagID ) || (int) $tagID < 0 )
return false;
$tag = self::fetch( (int) $tagID );
if ( (int) $tagID > 0 && !$tag instanceof self )
return false;
if ( $tag instanceof self && $tag->attribute( 'main_tag_id' ) != 0 )
return false;
if ( !is_array( $params ) )
$params = array();
$offset = ( isset( $params['Offset'] ) && (int) $params['Offset'] > 0 ) ? (int) $params['Offset'] : 0;
$limit = ( isset( $params['Limit'] ) && (int) $params['Limit'] > 0 ) ? (int) $params['Limit'] : 0;
$sortBy = ( isset( $params['SortBy'] ) && is_array( $params['SortBy'] ) ) ? $params['SortBy'] : array();
$depth = ( isset( $params['Depth'] ) ) ? $params['Depth'] : false;
$depthOperator = ( isset( $params['DepthOperator'] ) ) ? $params['DepthOperator'] : false;
$includeSynonyms = ( isset( $params['IncludeSynonyms'] ) ) ? (bool) $params['IncludeSynonyms'] : false;
$fetchParams = array();
if ( (int) $tagID > 0 )
{
$fetchParams['path_string'] = array( 'like', '%/' . (string) ( (int) $tagID ) . '/%' );
$fetchParams['id'] = array( '!=', (int) $tagID );
}
if ( !$includeSynonyms )
$fetchParams['main_tag_id'] = 0;
if ( $depth !== false && (int) $depth > 0 )
{
$tagDepth = 0;
if ( $tag instanceof self )
$tagDepth = (int) $tag->attribute( 'depth' );
$depth = (int) $depth + $tagDepth;
$sqlDepthOperator = '<=';
if ( $depthOperator == 'lt' )
$sqlDepthOperator = '<';
else if ( $depthOperator == 'gt' )
$sqlDepthOperator = '>';
else if ( $depthOperator == 'le' )
$sqlDepthOperator = '<=';
else if ( $depthOperator == 'ge' )
$sqlDepthOperator = '>=';
else if ( $depthOperator == 'eq' )
$sqlDepthOperator = '=';
$fetchParams['depth'] = array( $sqlDepthOperator, $depth );
}
$limits = null;
if ( $limit > 0 )
{
$limits = array(
'offset' => $offset,
'limit' => $limit,
);
}
$sorts = array();
if ( !empty( $sortBy ) )
{
$columnArray = array( 'id', 'parent_id', 'main_tag_id', 'keyword', 'depth', 'path_string', 'modified' );
$orderArray = array( 'asc', 'desc' );
if ( count( $sortBy ) == 2 && !is_array( $sortBy[0] ) && !is_array( $sortBy[1] ) )
{
$sortBy = array( $sortBy );
}
foreach ( $sortBy as $sortCond )
{
if ( is_array( $sortCond ) && count( $sortCond ) == 2 )
{
if ( in_array( strtolower( trim( $sortCond[0] ) ), $columnArray ) )
{
$sortCond[0] = trim( strtolower( $sortCond[0] ) );
if( in_array( strtolower( trim( $sortCond[1] ) ), $orderArray ) )
$sortCond[1] = trim( strtolower( $sortCond[1] ) );
else
$sortCond[1] = 'asc';
if ( !array_key_exists( $sortCond[0], $sorts ) )
$sorts[$sortCond[0]] = $sortCond[1];
}
}
}
}
if ( empty( $sorts ) )
$sorts = null;
$fetchResults = self::fetchList( $fetchParams, $limits, $sorts );
if ( is_array( $fetchResults ) && !empty( $fetchResults ) )
return $fetchResults;
return false;
} | Fetches subtree of tags by specified parameters
@static
@param array $params
@param int $tagID
@return eZTagsObject[] | entailment |
static public function subTreeCountByTagID( $params = array(), $tagID = 0 )
{
if ( !is_numeric( $tagID ) || (int) $tagID < 0 )
return 0;
$tag = self::fetch( (int) $tagID );
if ( (int) $tagID > 0 && !$tag instanceof self )
return 0;
if ( $tag instanceof self && $tag->attribute( 'main_tag_id' ) != 0 )
return 0;
if ( !is_array( $params ) )
$params = array();
$depth = ( isset( $params['Depth'] ) ) ? $params['Depth'] : false;
$depthOperator = ( isset( $params['DepthOperator'] ) ) ? $params['DepthOperator'] : false;
$includeSynonyms = ( isset( $params['IncludeSynonyms'] ) ) ? (bool) $params['IncludeSynonyms'] : false;
$fetchParams = array();
if ( (int) $tagID > 0 )
{
$fetchParams['path_string'] = array( 'like', '%/' . (string) ( (int) $tagID ) . '/%' );
$fetchParams['id'] = array( '!=', (int) $tagID );
}
if ( !$includeSynonyms )
$fetchParams['main_tag_id'] = 0;
if ( $depth !== false && (int) $depth > 0 )
{
$tagDepth = 0;
if ( $tag instanceof self )
$tagDepth = (int) $tag->attribute( 'depth' );
$depth = (int) $depth + $tagDepth;
$sqlDepthOperator = '<=';
if ( $depthOperator == 'lt' )
$sqlDepthOperator = '<';
else if ( $depthOperator == 'gt' )
$sqlDepthOperator = '>';
else if ( $depthOperator == 'le' )
$sqlDepthOperator = '<=';
else if ( $depthOperator == 'ge' )
$sqlDepthOperator = '>=';
else if ( $depthOperator == 'eq' )
$sqlDepthOperator = '=';
$fetchParams['depth'] = array( $sqlDepthOperator, $depth );
}
$count = self::fetchListCount( $fetchParams );
if ( is_numeric( $count ) )
return $count;
return 0;
} | Fetches subtree tag count by specified parameters
@static
@param array $params
@param int $tagID
@return int | entailment |
static public function generateModuleResultPath( $tag = false, $urlToGenerate = null, $textPart = false, $mainTranslation = true )
{
$moduleResultPath = array();
if ( is_string( $textPart ) )
{
$moduleResultPath[] = array( 'text' => $textPart,
'url' => false );
}
if ( $tag instanceof self )
{
/** @var eZTagsObject $tag */
$moduleResultPath[] = array( 'tag_id' => $tag->attribute( 'id' ),
'text' => $tag->attribute( 'keyword' ),
'url' => false );
/** @var eZTagsObject[] $path */
$path = $tag->getPath( true, $mainTranslation );
if ( is_array( $path ) && !empty( $path ) )
{
foreach ( $path as $pathElement )
{
// if $urlToGenerate === null, generate no urls
$url = false;
if ( $urlToGenerate !== null )
{
// if true generate nice urls
if ( $urlToGenerate )
$url = $pathElement->getUrl();
// else generate urls with ID
else
$url = 'tags/id/' . $pathElement->attribute( 'id' );
}
$moduleResultPath[] = array( 'tag_id' => $pathElement->attribute( 'id' ),
'text' => $pathElement->attribute( 'keyword' ),
'url' => $url );
}
}
}
return array_reverse( $moduleResultPath );
} | Generates module result path for this tag, used in all module views
@static
@param mixed $tag
@param mixed $urlToGenerate
@param mixed $textPart
@param bool $mainTranslation
@return array | entailment |
public function getMainTranslation()
{
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetch( $this->attribute( 'main_language_id' ) );
if ( $language instanceof eZContentLanguage )
return $this->translationByLocale( $language->attribute( 'locale' ) );
return false;
} | Returns the main translation of this tag
@return eZTagsKeyword | entailment |
public function translationByLanguageID( $languageID )
{
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetch( $languageID );
if ( $language instanceof eZContentLanguage )
return $this->translationByLocale( $language->attribute( 'locale' ) );
return false;
} | Returns translation of the tag for provided language ID
@param int $languageID
@return eZTagsKeyword | entailment |
public function getKeyword( $locale = false )
{
if ( $this->attribute( 'id' ) == null )
return $this->Keyword;
$translation = $this->translationByLocale( $locale === false ? $this->CurrentLanguage : $locale );
if ( $translation instanceof eZTagsKeyword )
return $translation->attribute( 'keyword' );
return '';
} | Returns the tag keyword, locale aware
@param mixed $locale
@return string | entailment |
public function languageNameArray()
{
$languageNameArray = array();
$translations = $this->getTranslations();
foreach ( $translations as $translation )
{
$languageName = $translation->languageName();
if ( is_array( $languageName ) )
$languageNameArray[$languageName['locale']] = $languageName['name'];
}
return $languageNameArray;
} | Returns the array of eZTagsKeyword->languageName() arrays, for every translation of the tag
@return array | entailment |
public function updateMainTranslation( $locale )
{
$trans = $this->translationByLocale( $locale );
/** @var eZContentLanguage $language */
$language = eZContentLanguage::fetchByLocale( $locale );
if ( !$trans instanceof eZTagsKeyword || !$language instanceof eZContentLanguage )
return false;
$this->setAttribute( 'main_language_id', $language->attribute( 'id' ) );
$keyword = $this->getKeyword( $locale );
$this->setAttribute( 'keyword', $keyword );
$this->store();
$isAlwaysAvailable = $this->isAlwaysAvailable();
foreach ( $this->getTranslations() as $translation )
{
if ( !$isAlwaysAvailable )
$languageID = (int) $translation->attribute( 'language_id' ) & ~1;
else
{
if ( $translation->attribute( 'locale' ) != $language->attribute( 'locale' ) )
$languageID = (int) $translation->attribute( 'language_id' ) & ~1;
else
$languageID = (int) $translation->attribute( 'language_id' ) | 1;
}
$translation->setAttribute( 'language_id', $languageID );
$translation->store();
}
return true;
} | Sets the main translation of the tag to provided locale
@param string $locale
@return bool | entailment |
public function updateLanguageMask( $mask = false )
{
if ( $mask === false )
{
$locales = array();
foreach ( $this->getTranslations() as $translation )
{
$locales[] = $translation->attribute( 'locale' );
}
$mask = eZContentLanguage::maskByLocale( $locales, $this->isAlwaysAvailable() );
}
$this->setAttribute( 'language_mask', $mask );
$this->store();
} | Updates language mask of the tag based on current translations or provided language mask
@param mixed $mask | entailment |
public function setAlwaysAvailable( $alwaysAvailable )
{
$languageMask = (int) $this->attribute( 'language_mask' ) & ~1;
$zerothBit = $alwaysAvailable ? 1 : 0;
$this->setAttribute( 'language_mask', $languageMask | $zerothBit );
$this->store();
$mainTranslation = $this->getMainTranslation();
if ( $mainTranslation instanceof eZTagsKeyword )
{
foreach ( $this->getTranslations() as $translation )
{
if ( !$alwaysAvailable )
$languageID = (int) $translation->attribute( 'language_id' ) & ~1;
else
{
if ( $translation->attribute( 'locale' ) != $mainTranslation->attribute( 'locale' ) )
$languageID = (int) $translation->attribute( 'language_id' ) & ~1;
else
$languageID = (int) $translation->attribute( 'language_id' ) | 1;
}
$translation->setAttribute( 'language_id', $languageID );
$translation->store();
}
}
} | Sets/unsets always available flag for this tag
@param bool $alwaysAvailable | entailment |
public function lookup(EntityInterface $entity) {
if ($entity->id() != NULL) {
$drupal_uri = $entity->toUrl()->setAbsolute()->toString();
$drupal_uri .= '?_format=jsonld';
$token = "Bearer " . $this->jwtProvider->generateToken();
$linked_uri = $this->geminiClient->findByUri($drupal_uri, $token);
if (!is_null($linked_uri)) {
if (is_array($linked_uri)) {
$linked_uri = reset($linked_uri);
}
return $linked_uri;
}
}
// Return null if we weren't in a saved entity or we didn't find a uri.
return NULL;
} | Lookup this entity's URI in the Gemini db and return the other URI.
@param \Drupal\Core\Entity\EntityInterface $entity
The entity to look for.
@return string|null
Return the URI or null
@throws \Drupal\Core\Entity\EntityMalformedException
If the entity cannot be converted to a URL. | entailment |
static public function autocomplete( $args )
{
$http = eZHTTPTool::instance();
$searchString = trim( $http->postVariable( 'search_string' ), '' );
$autoCompleteType = eZINI::instance( 'eztags.ini' )->variable( 'GeneralSettings', 'AutoCompleteType' );
if ( empty( $searchString ) )
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
// Initialize transformation system
$trans = eZCharTransform::instance();
$searchString = $trans->transformByGroup( $http->postVariable( 'search_string' ), 'lowercase' );
$searchString = $searchString . '%';
if ( $autoCompleteType === 'any' )
{
$searchString = '%' . $searchString;
}
return self::generateOutput(
array( 'LOWER( eztags_keyword.keyword )' => array( 'like', $searchString ) ),
$http->postVariable( 'subtree_limit', 0 ),
$http->postVariable( 'hide_root_tag', '0' ),
$http->postVariable( 'locale', '' )
);
} | Provides auto complete results when adding tags to object
@static
@param array $args
@return array | entailment |
static public function suggest( $args )
{
$http = eZHTTPTool::instance();
$searchEngine = eZINI::instance()->variable( 'SearchSettings', 'SearchEngine' );
if ( !class_exists( 'eZSolr' ) || $searchEngine != 'ezsolr' )
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
$tagIDs = $http->postVariable( 'tag_ids', '' );
if ( empty( $tagIDs ) )
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
if ( is_array( $tagIDs ) ) {
$tagIDs = implode( '|#', $tagIDs );
}
$tagIDs = array_values( array_unique( explode( '|#', $tagIDs ) ) );
$solrSearch = new eZSolr();
$params = array(
'SearchOffset' => 0,
'SearchLimit' => 0,
'Facet' => array(
array(
'field' => 'ezf_df_tag_ids',
'limit' => 5 + count( $tagIDs ),
'mincount' => 1
)
),
'Filter' => array(
'ezf_df_tag_ids' => implode( ' OR ', $tagIDs )
),
'QueryHandler' => 'ezpublish',
'AsObjects' => false
);
$searchResult = $solrSearch->search( '', $params );
if ( !isset( $searchResult['SearchExtras'] ) || !$searchResult['SearchExtras'] instanceof ezfSearchResultInfo )
{
eZDebug::writeWarning( 'There was an error fetching tag suggestions from Solr. Maybe server is not running or using unpatched schema?', __METHOD__ );
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
}
$facetResult = $searchResult['SearchExtras']->attribute( 'facet_fields' );
if ( !is_array( $facetResult ) || !is_array( $facetResult[0]['nameList'] ) )
{
eZDebug::writeWarning( 'There was an error fetching tag suggestions from Solr. Maybe server is not running or using unpatched schema?', __METHOD__ );
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
}
$facetResult = array_values( $facetResult[0]['nameList'] );
$tagsToSuggest = array();
foreach ( $facetResult as $result )
{
if ( !in_array( $result, $tagIDs ) )
$tagsToSuggest[] = $result;
}
if ( empty( $tagsToSuggest ) )
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
return self::generateOutput(
array( 'id' => array( $tagsToSuggest ) ),
$http->postVariable( 'subtree_limit', 0 ),
false,
$http->postVariable( 'locale', '' )
);
} | Provides suggestion results when adding tags to object
@static
@param array $args
@return array | entailment |
static public function children( $args )
{
$ezTagsINI = eZINI::instance( 'eztags.ini' );
$params = array();
// Missing: a limit parameter; generateOutput would need to pass it to eZTagsObject::fetchList
return self::generateOutput(
$params,
$args[0],
$args[1],
$args[2]
);
} | Provides children in a specific tree
@static
@param array $args
@return array | entailment |
static public function tagtranslations( $args )
{
$returnArray = array(
'status' => 'success',
'message' => '',
'translations' => false
);
$http = eZHTTPTool::instance();
$tagID = (int) $http->postVariable( 'tag_id', 0 );
$tag = eZTagsObject::fetchWithMainTranslation( $tagID );
if ( !$tag instanceof eZTagsObject )
return $returnArray;
$returnArray['translations'] = array();
/** @var eZTagsKeyword[] $tagTranslations */
$tagTranslations = $tag->getTranslations();
if ( !is_array( $tagTranslations ) || empty( $tagTranslations ) )
return $returnArray;
foreach ( $tagTranslations as $translation )
{
$returnArray['translations'][] = array(
'locale' => $translation->attribute( 'locale' ),
'translation' => $translation->attribute( 'keyword' )
);
}
return $returnArray;
} | Returns requested tag translations
@static
@param array $args
@return array | entailment |
static public function treeConfig( $args )
{
$returnArray = array(
'status' => 'success',
'message' => '',
'config' => array(
'hideRootTag' => false,
'rootTag' => array()
)
);
if ( !isset( $args[1] ) )
{
return $returnArray;
}
$attributeID = (int)$args[0];
$version = (int)$args[1];
$contentAttribute = eZContentObjectAttribute::fetch( $attributeID, $version );
if ( !$contentAttribute instanceof eZContentObjectAttribute || $contentAttribute->attribute( 'data_type_string' ) !== 'eztags' )
{
return $returnArray;
}
$tagsIni = eZINI::instance( 'eztags.ini' );
$classAttribute = $contentAttribute->attribute( 'contentclass_attribute' );
$rootTagID = (int)$classAttribute->attribute( 'data_int1' );
if ( $rootTagID > 0 )
{
$rootTag = eZTagsObject::fetch( $rootTagID );
if ( !$rootTag instanceof eZTagsObject )
{
return $returnArray;
}
$returnArray['config']['rootTag'] = array(
'id' => (int) $rootTag->attribute( 'id' ),
'parent' => '#',
'text' => $rootTag->attribute( 'keyword' ),
'icon' => eZTagsTemplateFunctions::getTagIcon( $rootTag->getIcon() ),
'children' => $rootTag->getChildrenCount() > 0 ? true : false,
'a_attr' => array(
'data-id' => (int) $rootTag->attribute( 'id' ),
'data-name' => $rootTag->attribute( 'keyword' ),
'data-parent_id' => (int) $rootTag->attribute( 'parent_id' ),
'data-locale' => $rootTag->attribute( 'current_language' )
),
'state' => array(
'opened' => true,
'selected' => false
)
);
}
else
{
$returnArray['config']['rootTag'] = array(
'id' => 0,
'parent' => '#',
'text' => ezpI18n::tr( 'extension/eztags/tags/treemenu', 'Top level tags' ),
'icon' => eZTagsTemplateFunctions::getTagIcon( $tagsIni->variable( 'Icons', 'Default' ) ),
'children' => true,
'state' => array(
'opened' => true,
'disabled' => true,
'selected' => false
)
);
}
$returnArray['config']['hideRootTag'] = (int)$classAttribute->attribute( 'data_int3' ) > 0;
return $returnArray;
} | Returns config for tree view plugin
@static
@param array $args
@return array | entailment |
static public function tree( $args )
{
$returnArray = array(
'status' => 'success',
'message' => '',
'children' => array()
);
$tagID = 0;
if ( isset( $args[0] ) && is_numeric( $args[0] ) )
{
$tagID = (int)$args[0];
}
$children = eZTagsObject::fetchList(
array(
'parent_id' => $tagID,
'main_tag_id' => 0
)
);
if ( empty( $children ) )
{
return $returnArray;
}
foreach ( $children as $child )
{
$returnArray['children'][] = array(
'id' => (int) $child->attribute( 'id' ),
'parent' => (int) $child->attribute( 'parent_id' ),
'text' => $child->attribute( 'keyword' ),
'icon' => eZTagsTemplateFunctions::getTagIcon( $child->getIcon() ),
'children' => $child->getChildrenCount() > 0 ? true : false,
'state' => array(
'opened' => false,
'selected' => false
),
'a_attr' => array(
'data-id' => (int) $child->attribute( 'id' ),
'data-name' => $child->attribute( 'keyword' ),
'data-parent_id' => (int) $child->attribute( 'parent_id' ),
'data-locale' => $child->attribute( 'current_language' )
)
);
}
return $returnArray;
} | Returns children tags formatted for tree view plugin
@static
@param array $args
@return array | entailment |
static protected function generateOutput( array $params, $subTreeLimit, $hideRootTag, $locale )
{
$subTreeLimit = (int) $subTreeLimit;
$hideRootTag = (bool) $hideRootTag;
$locale = (string) $locale;
if ( empty( $locale ) )
return array( 'status' => 'success', 'message' => '', 'tags' => array() );
// @TODO Fix synonyms not showing up in autocomplete
// when subtree limit is defined in class attribute
if ( $subTreeLimit > 0 )
{
if ( $hideRootTag )
$params['id'] = array( '<>', $subTreeLimit );
$params['path_string'] = array( 'like', '%/' . $subTreeLimit . '/%' );
}
// first fetch tags that exist in selected locale
/** @var eZTagsObject[] $tags */
$tags = eZTagsObject::fetchList( $params, null, null, false, $locale );
if ( !is_array( $tags ) )
$tags = array();
$tagsIDsToExclude = array_map(
function ( $tag )
{
/** @var eZTagsObject $tag */
return (int) $tag->attribute( 'id' );
},
$tags
);
// then fetch the rest of tags, but exclude already fetched ones
// fetch with main translation to be consistent with eztags attribute content
$customConds = eZTagsObject::fetchCustomCondsSQL( $params, true );
if ( !empty( $tagsIDsToExclude ) )
$customConds .= " AND " . eZDB::instance()->generateSQLINStatement( $tagsIDsToExclude, 'eztags.id', true, true, 'int' ) . " ";
$tagsRest = eZPersistentObject::fetchObjectList(
eZTagsObject::definition(), array(), $params,
null, null, true, false,
array(
'DISTINCT eztags.*',
array(
'operation' => 'eztags_keyword.keyword',
'name' => 'keyword'
),
array(
'operation' => 'eztags_keyword.locale',
'name' => 'locale'
)
),
array( 'eztags_keyword' ),
$customConds
);
if ( !is_array( $tagsRest ) )
$tagsRest = array();
// finally, return both set of tags as one list
$tags = array_merge( $tags, $tagsRest );
$returnArray = array(
'status' => 'success',
'message' => '',
'tags' => array()
);
foreach ( $tags as $tag )
{
$returnArrayChild = array();
$returnArrayChild['parent_id'] = $tag->attribute( 'parent_id' );
$returnArrayChild['parent_name'] = $tag->hasParent( true ) ? $tag->getParent( true )->attribute( 'keyword' ) : '';
$returnArrayChild['name'] = $tag->attribute( 'keyword' );
$returnArrayChild['id'] = $tag->attribute( 'id' );
$returnArrayChild['main_tag_id'] = $tag->attribute( 'main_tag_id' );
$returnArrayChild['locale'] = $tag->attribute( 'current_language' );
$returnArray['tags'][] = $returnArrayChild;
}
return $returnArray;
} | Generates output for use with autocomplete and suggest methods
@static
@param array $params
@param int $subTreeLimit
@param bool $hideRootTag
@param string $locale
@return array | entailment |
public function fire()
{
$title = $this->argument('title');
$msg = $this->argument('msg');
$url = $this->option('url');
$urltitle = $this->option('urltitle');
$debug = $this->option('debug');
$sound = $this->option('sound');
$device = $this->option('device');
$priority = $this->option('priority');
$retry = $this->option('retry');
$expire = $this->option('expire');
$html = $this->option('html');
if (!isset($retry)) {
$retry = 60;
}
if (!isset($expire)) {
$expire = 365;
}
if(!isset($html)) {
$html = 1;
}
if (!isset($urltitle)) {
$urltitle = $url;
}
// Check if Debug mode is turned on
if ($debug) {
$this->push->debug(true);
}
// if sound var is set
if ($sound) {
$this->push->sound($sound);
}
if ($html) {
$this->push->html($html);
}
// if device var is set
if ($device) {
$this->push->device($device);
}
// if url var is set
if ($url) {
$this->push->url($url, $urltitle);
}
// if priority var is set
if ($priority) {
$this->push->priority($priority, $retry, $expire);
}
$this->push->push($title, $msg);
if ($debug) {
$this->info($this->push->send());
} else if ($this->push->send()) {
$this->info("Your message has been sent.");
} else {
$this->error('Something went wrong!');
}
} | Execute the console command.
@return mixed | entailment |
protected function getOptions()
{
return [
['url', null, InputOption::VALUE_OPTIONAL, 'URL to send.', null],
['urltitle', null, InputOption::VALUE_OPTIONAL, 'URL Title to send.', null],
['sound', null, InputOption::VALUE_OPTIONAL, 'Set notification Sound.', null],
['device', null, InputOption::VALUE_OPTIONAL, 'Set a Device.', null],
['priority', null, InputOption::VALUE_OPTIONAL, 'Set a Priority Message.', null],
['retry', null, InputOption::VALUE_OPTIONAL, 'Set a Retry for the Priority.', null],
['expire', null, InputOption::VALUE_OPTIONAL, 'Set an expire for the Priority.', null],
['html', null, InputOption::VALUE_OPTIONAL, 'Sets if message should be sent as HTML.', null],
['debug', null, InputOption::VALUE_NONE, 'Turn the Debug Mode.', null],
];
} | Get the console command options.
@return array | entailment |
public function modify( $tpl, $operatorName, $operatorParameters, $rootNamespace, $currentNamespace, &$operatorValue, $namedParameters )
{
switch ( $operatorName )
{
case 'eztags_parent_string':
{
$operatorValue = self::generateParentString( $namedParameters['tag_id'] );
} break;
case 'latest_tags':
{
$operatorValue = self::fetchLatestTags( $namedParameters['limit'] );
} break;
case 'user_limitations':
{
$operatorValue = self::getSimplifiedUserAccess( $namedParameters['module'], $namedParameters['function'] );
} break;
case 'tag_icon':
{
if ( $operatorValue === null )
$operatorValue = self::getTagIcon( $namedParameters['first'], $namedParameters['second'] );
else
{
$operatorValue = self::getTagIcon(
$operatorValue,
empty( $namedParameters['first'] ) ? 'small' : $namedParameters['first']
);
}
} break;
}
} | Executes the PHP function for the operator cleanup and modifies $operatorValue.
@param eZTemplate $tpl
@param string $operatorName
@param array $operatorParameters
@param string $rootNamespace
@param string $currentNamespace
@param mixed $operatorValue
@param array $namedParameters | entailment |
static public function generateParentString( $tagID )
{
$tag = eZTagsObject::fetchWithMainTranslation( $tagID );
if ( !$tag instanceof eZTagsObject )
return '(' . ezpI18n::tr( 'extension/eztags/tags/edit', 'no parent' ) . ')';
return $tag->getParentString();
} | Generates tag hierarchy string for given tag ID
@static
@param int $tagID
@return string | entailment |
static public function getSimplifiedUserAccess( $module, $function )
{
$user = eZUser::currentUser();
$userAccess = $user->hasAccessTo( $module, $function );
$userAccess['simplifiedLimitations'] = array();
if ( $userAccess['accessWord'] != 'limited' )
return $userAccess;
foreach ( $userAccess['policies'] as $policy )
{
foreach ( $policy as $limitationName => $limitationList )
{
foreach ( $limitationList as $limitationValue )
{
$userAccess['simplifiedLimitations'][$limitationName][] = $limitationValue;
}
$userAccess['simplifiedLimitations'][$limitationName] = array_unique( $userAccess['simplifiedLimitations'][$limitationName] );
}
}
return $userAccess;
} | Shorthand method to check user access policy limitations for a given module/policy function.
Returns the same array as eZUser::hasAccessTo(), with "simplifiedLimitations".
'simplifiedLimitations' array holds all the limitations names as defined in module.php.
If your limitation name is not defined as a key, then your user has full access to this limitation
@static
@param string $module Name of the module
@param string $function Name of the policy function ( $FunctionList element in module.php )
@return array | entailment |
static public function tagsChildren( $args )
{
$http = eZHTTPTool::instance();
$filter = urldecode( trim( $http->getVariable( 'filter', '' ) ) );
if ( !isset( $args[0] ) || !is_numeric( $args[0] ) )
return array( 'count' => 0, 'offset' => false, 'filter' => $filter, 'data' => array() );
$offset = false;
$limits = null;
if ( $http->hasGetVariable( 'offset' ) )
{
$offset = (int) $http->getVariable( 'offset' );
if ( $http->hasGetVariable( 'limit' ) )
$limit = (int) $http->getVariable( 'limit' );
else
$limit = 10;
$limits = array( 'offset' => $offset, 'limit' => $limit );
}
$sorts = null;
if ( $http->hasGetVariable( 'sortby' ) )
{
$sortBy = trim( $http->getVariable( 'sortby' ) );
$sortDirection = 'asc';
if ( $http->hasGetVariable( 'sortdirection' ) && trim( $http->getVariable( 'sortdirection' ) ) == 'desc' )
$sortDirection = 'desc';
$sorts = array( $sortBy => $sortDirection );
}
$fetchParams = array( 'parent_id' => (int) $args[0], 'main_tag_id' => 0 );
if ( !empty( $filter ) )
$fetchParams['keyword'] = array( 'like', '%' . $filter . '%' );
/** @var eZTagsObject[] $children */
$children = eZTagsObject::fetchList( $fetchParams, $limits, $sorts );
$childrenCount = eZTagsObject::fetchListCount( $fetchParams );
if ( !is_array( $children ) || empty( $children ) )
return array( 'count' => 0, 'offset' => false, 'filter' => $filter, 'data' => array() );
$dataArray = array();
foreach ( $children as $child )
{
$tagArray = array();
$tagArray['id'] = $child->attribute( 'id' );
$tagArray['keyword'] = htmlspecialchars( $child->attribute( 'keyword' ), ENT_QUOTES );
$tagArray['modified'] = $child->attribute( 'modified' );
$tagArray['translations'] = array();
foreach ( $child->getTranslations() as $translation )
{
$tagArray['translations'][] = htmlspecialchars( $translation->attribute( 'locale' ), ENT_QUOTES );
}
$dataArray[] = $tagArray;
}
return array(
'count' => $childrenCount,
'offset' => $offset,
'filter' => $filter,
'data' => $dataArray
);
} | Returns the JSON encoded string of children tags for supplied GET params
Used in YUI version of children tags list in admin interface
@static
@param array $args
@return string | entailment |
public function buildConfigurationForm(array $form, FormStateInterface $form_state) {
$options = [];
foreach (['node', 'media', 'taxonomy_term'] as $content_entity) {
$bundles = \Drupal::service('entity_type.bundle.info')->getBundleInfo($content_entity);
foreach ($bundles as $bundle => $bundle_properties) {
$options[$bundle] = $this->t('@bundle (@type)', [
'@bundle' => $bundle_properties['label'],
'@type' => $content_entity,
]);
}
}
$form['bundles'] = [
'#title' => $this->t('Bundles'),
'#type' => 'checkboxes',
'#options' => $options,
'#default_value' => $this->configuration['bundles'],
];
return parent::buildConfigurationForm($form, $form_state);;
} | {@inheritdoc} | entailment |
public function evaluate() {
foreach ($this->getContexts() as $context) {
if ($context->hasContextValue()) {
$entity = $context->getContextValue();
if (!empty($this->configuration['bundles'][$entity->bundle()])) {
return !$this->isNegated();
}
}
}
return $this->isNegated();
} | {@inheritdoc} | entailment |
public function summary() {
if (empty($this->configuration['bundles'])) {
return $this->t('No bundles are selected.');
}
return $this->t(
'Entity bundle in the list: @bundles',
[
'@bundles' => implode(', ', $this->configuration['field']),
]
);
} | {@inheritdoc} | entailment |
public function createSqlParts( $params )
{
$returnArray = array( 'tables' => '', 'joins' => '', 'columns' => '' );
if ( !isset( $params['parent_tag_id'] ) )
{
return $returnArray;
}
if ( is_array( $params['parent_tag_id'] ) )
{
$parentTagIDsArray = $params['parent_tag_id'];
}
else if ( (int) $params['parent_tag_id'] > 0 )
{
$parentTagIDsArray = array( (int) $params['parent_tag_id'] );
}
else
{
return $returnArray;
}
$suffix = '/%';
if ( isset( $params['exclude_parent'] ) && $params['exclude_parent'] )
{
$suffix = '/%/%';
}
$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)";
$db = eZDB::instance();
$dbStrings = array();
if ( isset( $params['type'] ) && strtolower( $params['type'] ) == 'and' )
{
foreach ( $parentTagIDsArray as $parentTagID )
{
$dbStrings[] = "EXISTS (
SELECT 1
FROM
eztags_attribute_link j1,
ezcontentobject j2,
eztags j3
WHERE j3.path_string LIKE \"%/" . $db->escapeString( $parentTagID . $suffix ) . "
AND j1.object_id = j2.id
AND j2.id = ezcontentobject.id
AND j1.objectattribute_version = j2.current_version
AND j3.id = j1.keyword_id
)";
}
$dbString = implode( ' AND ', $dbStrings );
}
else
{
foreach ( $parentTagIDsArray as $parentTagID )
{
$dbStrings[] = ' i2.path_string LIKE "%/' . $db->escapeString( $parentTagID . $suffix ) . '"';
}
$dbString = implode( ' OR ', $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 |
protected function getSpecialOffset(\Imagick $original, $targetWidth, $targetHeight)
{
return $this->getRandomEdgeOffset($original, $targetWidth, $targetHeight);
} | get special offset for class
@param \Imagick $original
@param int $targetWidth
@param int $targetHeight
@return array | entailment |
protected function getHighestEnergyPoint(\Imagick $image)
{
$size = $image->getImageGeometry();
// It's more performant doing random pixel uplook via GD
$im = imagecreatefromstring($image->getImageBlob());
if ($im === false) {
$msg = 'GD failed to create image from string';
throw new \Exception($msg);
}
$xcenter = 0;
$ycenter = 0;
$sum = 0;
// Only sample 1/50 of all the pixels in the image
$sampleSize = round($size['height']*$size['width'])/50;
for ($k=0; $k<$sampleSize; $k++) {
$i = mt_rand(0, $size['width']-1);
$j = mt_rand(0, $size['height']-1);
$rgb = imagecolorat($im, $i, $j);
$r = ($rgb >> 16) & 0xFF;
$g = ($rgb >> 8) & 0xFF;
$b = $rgb & 0xFF;
$val = $this->rgb2bw($r, $g, $b);
$sum += $val;
$xcenter += ($i+1)*$val;
$ycenter += ($j+1)*$val;
}
if ($sum) {
$xcenter /= $sum;
$ycenter /= $sum;
}
$point = array('x' => $xcenter, 'y' => $ycenter, 'sum' => $sum/round($size['height']*$size['width']));
return $point;
} | By doing random sampling from the image, find the most energetic point on the passed in
image
@param \Imagick $image
@return array | entailment |
public static function getSubscribedEvents() {
$events[JwtAuthEvents::VALIDATE][] = ['validate'];
$events[JwtAuthEvents::VALID][] = ['loadUser'];
$events[JwtAuthEvents::GENERATE][] = ['setIslandoraClaims'];
return $events;
} | {@inheritdoc} | entailment |
public function setIslandoraClaims(JwtAuthGenerateEvent $event) {
global $base_secure_url;
// Standard claims, validated at JWT validation time.
$event->addClaim('iat', time());
$expiry_setting = \Drupal::config(IslandoraSettingsForm::CONFIG_NAME)
->get(IslandoraSettingsForm::JWT_EXPIRY);
$expiry = $expiry_setting ? $expiry_setting : '+2 hour';
$event->addClaim('exp', strtotime($expiry));
$event->addClaim('webid', $this->currentUser->id());
$event->addClaim('iss', $base_secure_url);
// Islandora claims we need to validate.
$event->addClaim('sub', $this->currentUser->getAccountName());
$event->addClaim('roles', $this->currentUser->getRoles(FALSE));
} | Sets claims for a Islandora consumer on the JWT.
@param \Drupal\jwt\Authentication\Event\JwtAuthGenerateEvent $event
The event. | entailment |
public function validate(JwtAuthValidateEvent $event) {
$token = $event->getToken();
$uid = $token->getClaim('webid');
$name = $token->getClaim('sub');
$roles = $token->getClaim('roles');
$url = $token->getClaim('iss');
if ($uid === NULL || $name === NULL || $roles === NULL || $url === NULL) {
$event->invalidate("Expected data missing from payload.");
return;
}
$user = $this->userStorage->load($uid);
if ($user === NULL) {
$event->invalidate("Specified UID does not exist.");
}
elseif ($user->getAccountName() !== $name) {
$event->invalidate("Account name does not match.");
}
} | Validates that the Islandora data is present in the JWT.
@param \Drupal\jwt\Authentication\Event\JwtAuthValidateEvent $event
A JwtAuth event. | entailment |
public function loadUser(JwtAuthValidEvent $event) {
$token = $event->getToken();
$uid = $token->getClaim('webid');
$user = $this->userStorage->load($uid);
$event->setUser($user);
} | Load and set a Drupal user to be authentication based on the JWT's uid.
@param \Drupal\jwt\Authentication\Event\JwtAuthValidEvent $event
A JwtAuth event. | entailment |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.