示例#1
0
 public static function handlesEntity(Entity $entity)
 {
     if ($entity->type() == 'user') {
         return true;
     }
     return false;
 }
示例#2
0
 public function handlesEntity(Entity $entity)
 {
     if ($entity->type() == 'file') {
         return true;
     }
     return false;
 }
示例#3
0
 public function unresolveDependencies($subset = false, $subtype = false)
 {
     // Create a clone of the definition so we don't muck up the entity cache.
     $this->unresolved_definition = $subset === false ? $this->entity->definition : $subset;
     if (!is_object($this->unresolved_definition)) {
         $this->unresolved_definition = (object) $this->unresolved_definition;
     }
     // Generate the list of handlers for each of the fields.
     $handlers = DefinitionHandlerRegistry::getFieldHandlers($this->entity, $this->unresolved_definition, $subtype);
     foreach ($handlers as $field_name => $handler) {
         if (!isset($this->unresolved_definition->{$field_name})) {
             continue;
         }
         foreach ($handler['handlers'] as $single_handler) {
             if (!$single_handler instanceof DefinitionHandlerBase) {
                 continue;
             }
             try {
                 $single_handler->entity =& $this->entity;
                 $single_handler->unresolved_definition =& $this->unresolved_definition;
                 $single_handler->unhandleField($this->entity->type(), $handler['type'], $field_name, $this->unresolved_definition->{$field_name});
             } catch (\Exception $ex) {
                 $message = t('Error processing field "@fieldName" - "@message"', array('@fieldName' => $field_name, '@message' => $ex->getMessage()));
                 \watchdog('publisher', $message, array(), WATCHDOG_WARNING);
                 $this->errors[] = $ex;
             }
         }
     }
 }
示例#4
0
 public function handlesEntity(Entity $entity)
 {
     if (!module_exists('redirect') || !module_exists('redirect_uuid')) {
         return false;
     }
     return redirect_entity_type_supports_redirects($entity->type());
 }
示例#5
0
 public function handlesEntity(Entity $entity)
 {
     if (!module_exists('xmlsitemap')) {
         return false;
     }
     $info = entity_get_info($entity->type());
     return array_key_exists('xmlsitemap', $info) && is_array($info['xmlsitemap']);
 }
 public function handlesEntity(Entity $entity)
 {
     if (!module_exists('webform_validation')) {
         return false;
     }
     if ($entity->type() != 'node') {
         return false;
     }
     if (!in_array($entity->bundle(), webform_node_types())) {
         return false;
     }
     return true;
 }
示例#7
0
 public function unhandleField($entity_type, $field_type, $field_name, &$value)
 {
     if (!is_array($value)) {
         return;
     }
     if (!array_key_exists('url', $value)) {
         return;
     }
     if (!array_key_exists('original_path', $value)) {
         return;
     }
     if (!array_key_exists('uuid', $value)) {
         return;
     }
     if (!array_key_exists('uid', $value)) {
         return;
     }
     // Make sure a file doesn't already exist with that UUID.
     $entity = Entity::loadByUUID($value['uuid'], 'file');
     if ($entity) {
         $definition = $entity->definition;
     } else {
         // Make sure a file doesn't already exist with that URI.
         $query = db_select('file_managed', 'f');
         $query->addField('f', 'fid');
         $query->condition('f.uri', $value['original_path']);
         $query->range(0, 1);
         $result = $query->execute()->fetch();
         if ($result) {
             $entity = Entity::load($result->fid, 'file');
             if ($entity) {
                 $definition = $entity->definition;
             }
         }
     }
     // If we haven't found the file yet, upload it.
     if (!isset($definition)) {
         // Decode the contents of the file.
         $contents = file_get_contents($value['url']);
         if ($contents === false) {
             throw new FileHandlerException('There was an error fetching the contents of the file.');
         }
         // Save the file.
         $file = file_save_data($contents, $value['original_path']);
         if (!$file || !$file->fid) {
             throw new FileHandlerException('There was an error saving the file to the database.');
         }
         $file->uuid = $value['uuid'];
         $file->uid = $value['uid'];
         file_save($file);
         $definition = $file;
     }
     // Don't completely reset the entity.
     foreach ((array) $definition as $key => $val) {
         $this->unresolved_definition->{$key} = $val;
     }
 }
示例#8
0
 public function execute($selected_entity_uuid, $selected_entity_type, &$context)
 {
     // Load the entity.
     $entity = Entity::loadByUUID($selected_entity_uuid, $selected_entity_type);
     if (!$entity) {
         drupal_set_message(t('An invalid entity was found.'), 'error');
         $this->updateContextMessages(null, $context);
         return;
     }
     // Get the transaction session, and fail if we don't have it.
     $transaction_session = TransactionSession::getFromSession();
     if (!$transaction_session) {
         $current_set =& _batch_current_set();
         $current_set['success'] = false;
         drupal_set_message(t('We lost the transaction session.'), 'error');
         $this->updateContextMessages($entity, $context);
         return;
     }
     // Prepare to send the entity over to the receiving server.
     $entities = array();
     $transaction_entities = $transaction_session->getAllEntities();
     // Make sure the transaction entity exists.
     if (array_key_exists($entity->uuid(), $transaction_entities)) {
         $transaction_entity = $transaction_entities[$entity->uuid()];
     } else {
         drupal_set_message(t('An invalid entity was found.'), 'error');
         $this->updateContextMessages($entity, $context);
         return;
     }
     // Get the relationships for the entity.
     $relationships = array();
     foreach ($transaction_session->getRelationships() as $relationship) {
         if ($relationship['source_uuid'] == $entity->uuid() && (!$entity->supportsRevisions() || $relationship['source_vuuid'] == $entity->vuuid())) {
             $relationships[] = $relationship;
         }
     }
     // Send the entity revisions.
     $entities[] = array('entity_type' => $entity->type(), 'uuid' => $entity->uuid(), 'vuuid' => $entity->vuuid(), 'revisions' => $transaction_entity['revisions_payload'], 'relationships' => $relationships);
     $payload = array('entities' => $entities, 'metadata' => $transaction_session->getMetadata($entity->uuid()));
     // Send the request.
     $transaction = new Transaction($transaction_session->getRemote());
     $response = $transaction->send('import', $payload);
     if (!$response['success']) {
         $message = "There was an error sending the <strong>{$entity->type()}</strong> <code>{$entity->id()}</code> to the remote. Look at the recent log messages for more details.";
         drupal_set_message($message, 'error');
         watchdog('publisher', $message, array(), WATCHDOG_WARNING);
         Debug::wd($response);
     } elseif (empty($response['messages'])) {
         drupal_set_message('The operation was successful, but nothing was done on the remote. This probably means there weren\'t any updates to move.');
     }
     // Mark the entity as synced if the response was successful.
     if ($response['success']) {
         publisher_entity_tracking_mark_as_synced($entity, $transaction_session->getRemote());
     }
     $this->updateContextMessages($entity, $context);
 }
 protected function handleIndividualValue($entity_type, $field_type, $field_name, &$value, $delta)
 {
     if (!is_array($value)) {
         return;
     }
     if (!array_key_exists('fid', $value)) {
         throw new ImageCropFieldHandlerException('The field ' . $field_name . ' does not have a file ID.');
     }
     $entity = Entity::load($value['fid'], 'file');
     if (!$entity) {
         throw new FileReferenceHandlerException('The field ' . $field_name . ' has no value.');
     }
     $value['fid'] = self::createReferenceDefinition($entity);
     $this->addDependency($entity);
     // Get the original image and store it.
     $source_file = _imagefield_crop_file_to_crop($value['fid']);
     if (!$source_file) {
         throw new ImageCropFieldHandlerException('The field ' . $field_name . ' does not have a valid source file ID.');
     }
     $source_file_entity = Entity::load($source_file->fid, 'file');
     if (!$source_file_entity) {
         throw new ImageCropFieldHandlerException('The field ' . $field_name . ' has no source image.');
     }
     $value['source_fid'] = self::createReferenceDefinition($source_file_entity);
     $this->addDependency($source_file_entity);
     // Handle the UID now.
     if (array_key_exists('uid', $value)) {
         $entity = Entity::load($value['uid'], 'user');
         if (!$entity) {
             throw new FileReferenceHandlerException('The field ' . $field_name . ' is associated with a user that doesn\'t exist.');
         }
         $value['uid'] = self::createReferenceDefinition($entity);
         $this->addDependency($entity);
     }
     // Make sure the dimensions of the cropbox are always set.
     if (isset($this->entity->definition->{$field_name})) {
         $original_entity_definition_language = reset($this->entity->definition->{$field_name});
         // First language.
         if (array_key_exists($delta, $original_entity_definition_language)) {
             $original_entity_definition = $original_entity_definition_language[$delta];
             if (!array_key_exists('cropbox_x', $value)) {
                 $value['cropbox_x'] = array_key_exists('cropbox_x', $original_entity_definition) ? $original_entity_definition['cropbox_x'] : 0;
             }
             if (!array_key_exists('cropbox_y', $value)) {
                 $value['cropbox_y'] = array_key_exists('cropbox_y', $original_entity_definition) ? $original_entity_definition['cropbox_y'] : 0;
             }
             if (!array_key_exists('cropbox_width', $value)) {
                 $value['cropbox_width'] = array_key_exists('cropbox_width', $original_entity_definition) ? $original_entity_definition['cropbox_width'] : 0;
             }
             if (!array_key_exists('cropbox_height', $value)) {
                 $value['cropbox_height'] = array_key_exists('cropbox_height', $original_entity_definition) ? $original_entity_definition['cropbox_height'] : 0;
             }
         }
     }
 }
示例#10
0
 protected function satisfyDependencies($dependencies)
 {
     $required = array();
     foreach ($dependencies as $dependency) {
         $entity = Entity::loadByUUID($dependency['uuid'], $dependency['entity_type']);
         if (!$entity || array_key_exists('force', $dependency) && $dependency['force'] === true) {
             $dependency['need revision'] = $dependency['vuuid'];
             $dependency['have revision'] = '';
             $dependency['have your revision'] = '';
             $dependency['required_from_remote'] = true;
             $required[] = $dependency;
         } else {
             // Check the entity tracking table.
             $status = publisher_entity_tracking_get_status($entity->uuid(), $entity->type(), $this->remote->name);
             $dependency['required'] = false;
             $dependency['need revision'] = $dependency['vuuid'];
             $dependency['have revision'] = $entity->vuuid();
             // Get the revision from their end that we have.
             $dependency['have your revision'] = false;
             if ($entity->supportsRevisions() && is_array($dependency['revisions'])) {
                 $dependency['have your revision'] = self::findMatchingRevision($dependency['revisions'], $entity);
             }
             if (!$status) {
                 // If the revision information we have matches, create an entry
                 // in the tracking table and skip it.
                 if (!$this->compareRevisions($dependency['have revision'], $dependency['need revision'])) {
                     // Get the last time the entity was modified.
                     $entity->setRevision($dependency['have revision']);
                     $date = $this->getModificationDate($dependency['have revision']);
                     if (!$date) {
                         if ($entity->supportsRevisions()) {
                             $entity->setRevision(Entity::getLatestRevisionID($entity->id(), $entity->type()));
                         }
                         $date = $entity->getModified();
                     }
                     publisher_entity_tracking_create_status($entity, $this->remote, array('date_synced' => REQUEST_TIME, 'changed' => $date));
                     continue;
                 }
                 // Assume that we don't require the latest version by default.
                 $dependency['required_from_remote'] = array_key_exists('requires_latest', $dependency) ? $dependency['requires_latest'] : false;
                 $required[] = $dependency;
             } else {
                 if (!$status->date_synced || $this->compareRevisions($status->vuuid, $dependency['need revision']) && $dependency['have your revision'] != $dependency['need revision'] || array_key_exists('source_required', $dependency) && $dependency['source_required']) {
                     // If the entity has an entry in the entity tracking table, but changes have
                     // been made to it since the last sync, mark it as changed.
                     $dependency['required_from_remote'] = array_key_exists('requires_latest', $dependency) ? $dependency['requires_latest'] : false;
                     $required[] = $dependency;
                 }
             }
         }
     }
     return $required;
 }
 public function execute(\EntityDrupalWrapper $entity_raw, $remote_raw, $force)
 {
     $remote = publisher_remote_load($remote_raw);
     if (!$remote) {
         return false;
     }
     $entity = Entity::load($entity_raw->getIdentifier(), $entity_raw->type());
     if (!$entity) {
         return false;
     }
     publisher_send_entity($entity, $remote, array('force' => $force));
     return true;
 }
示例#12
0
 public function unhandleEntity(array $metadata = array())
 {
     // Update the weight of the sibling links if the entity supports
     // it.
     if (array_key_exists('sibling_link_weights', $metadata) && is_array($metadata['sibling_link_weights'])) {
         foreach ($metadata['sibling_link_weights'] as $uuid => $weight) {
             if ($uuid != $this->original_entity->uuid()) {
                 $menu_link = Entity::loadByUUID($uuid, 'menu_link');
                 $menu_link->definition->weight = $weight;
                 $menu_link->save();
             }
         }
     }
 }
 protected function handleIndividualValue($entity_type, $field_type, $field_name, &$value, $delta)
 {
     // Try to load the entity.
     if (!array_key_exists('tid', $value)) {
         throw new TaxonomyReferenceHandlerException('The term identifier did not exist on the entity.');
     }
     $entity = Entity::load($value['tid'], 'taxonomy_term');
     if (!$entity) {
         throw new TaxonomyReferenceHandlerException('The entity ' . $value['tid'] . ' does not exist.');
     }
     // Set the reference definition for the field.
     $value['tid'] = self::createReferenceDefinition($entity);
     $this->addDependency($entity, true);
     $this->addRelationship($this->original_entity, $entity, $field_name, $delta);
 }
 protected function handleIndividualValue($entity_type, $field_type, $field_name, &$value, $delta)
 {
     // Get the information for the specific field.
     $target_type = $this->getTargetType($field_name);
     if (!array_key_exists('target_id', $value)) {
         throw new EntityReferenceHandlerException('The field ' . $field_name . ' does not have a target ID.');
     }
     $entity = Entity::load($value['target_id'], $target_type);
     if (!$entity) {
         throw new EntityReferenceHandlerException('The field ' . $field_name . ' has no value.');
     }
     $value['target_id'] = self::createReferenceDefinition($entity);
     $this->addDependency($entity, true);
     $this->addRelationship($this->original_entity, $entity, $field_name, $delta);
 }
示例#15
0
 public function handleField($entity_type, $field_type, $field_name, &$value)
 {
     if ($entity_type == 'user' && ($value === 0 || $value === '0')) {
         return;
     }
     // We should be getting a number for the value.
     if (!is_numeric($value)) {
         throw new IDHandlerException('The field of type ' . $field_type . ' does not have a numeric value.');
     }
     // Load the entity.
     $entity = Entity::load($value, $entity_type);
     if (!$entity) {
         throw new IDHandlerException('The entity ' . $value . ' does not exist.');
     }
     // Update the value.
     $value = self::createReferenceDefinition($entity);
 }
 public static function getFieldHandlers(Entity $entity, $definition = null, $subtype = false)
 {
     $instances = \field_info_instances($entity->type(), $entity->bundle());
     $handlers = array();
     $handled = array();
     foreach ($instances as $field_name => $instance) {
         $handled[] = $field_name;
         if ($handler = self::getFieldHandler($entity->type(), $field_name, $subtype)) {
             $handlers[$field_name] = $handler;
         }
     }
     // Check special fields on the entity.
     $keys = \entity_get_info($entity->type());
     if (array_key_exists('entity keys', $keys)) {
         foreach ($keys['entity keys'] as $standard => $key) {
             $handled[] = $key;
             if ($handler = self::getTypeHandler($entity->type(), $standard, $subtype)) {
                 $handlers[$key] = $handler;
             }
         }
     }
     // Various other fields.
     foreach ($entity->definition as $key => $value) {
         if (array_search($key, $handled) !== false) {
             continue;
         }
         if ($handler = self::getTypeHandler($entity->type(), $key, $subtype)) {
             $handlers[$key] = $handler;
         }
     }
     // Get other fields on the definition.
     if (is_object($definition) || is_array($definition)) {
         foreach ($definition as $key => $value) {
             if (array_search($key, $handled) !== false) {
                 continue;
             }
             if ($handler = self::getTypeHandler($entity->type(), $key, $subtype)) {
                 $handlers[$key] = $handler;
             }
         }
     }
     return $handlers;
 }
示例#17
0
function action_feedback()
{
    $transaction = TransactionSession::getFromSession();
    if (!$transaction) {
        return t('There was an error processing the entities.');
    }
    // Before marking the transaction session as complete, set the title.
    action_feedback_title();
    // Set the forced flag based on if any of the root entites were forced.
    $forced = false;
    $root_entity_ids = array();
    foreach ($transaction->getRootEntities() as $uuid => $root_entity) {
        $root_entity_ids[] = $uuid;
        if (array_key_exists('force', $root_entity['options']) && $root_entity['options']['force']) {
            $forced = true;
            break;
        }
    }
    // Add each of the entities to the list for the form.
    $form_entities = array();
    foreach ($transaction->getAllEntities() as $dependency) {
        if (!array_key_exists('original_dependency', $dependency)) {
            continue;
        }
        $original_dependency = $dependency['original_dependency'];
        $form_entity = array();
        $entity = \Drupal\publisher\Entity::loadByUUID($dependency['entity_uuid'], $dependency['entity_type']);
        $entity_uri = entity_uri($entity->type(), $entity->definition);
        $entity_path = ltrim($entity_uri['path'], '/');
        $form_entity['label'] = l(entity_label($entity->type(), $entity->definition), $entity_path) . ' [<strong>' . $entity->type() . '</strong> <code>' . $entity->id() . '</code>]';
        $form_entity['required'] = $original_dependency['required'];
        $form_entity['required_if'] = $original_dependency['required_if'];
        $form_entity['entity_type'] = $dependency['entity_type'];
        $form_entity['root_entity'] = in_array($dependency['entity_uuid'], $root_entity_ids);
        $form_entities[$dependency['entity_uuid']] = $form_entity;
    }
    // If there are no entities to move, complete the session.
    if (count($form_entities) <= 0) {
        $transaction->complete();
    }
    // Output each of the entities to the page with their status.
    $form = drupal_get_form('publisher_select_entities_form', $form_entities, 'publisher_action_feedback_entities_selected', $forced, $transaction->getRemote());
    return $form;
}
示例#18
0
 public function handleField($entity_type, $field_type, $field_name, &$value)
 {
     if ($value === 0 || $value === '0') {
         return;
     }
     // Ignore anonymous user.
     // We should be getting a number for the value.
     if (!is_numeric($value)) {
         throw new UserHandlerException('The field of type ' . $field_type . ' does not have a numeric value.');
     }
     // Load the user entity.
     $entity = Entity::load($value, 'user');
     if (!$entity) {
         throw new UserHandlerException('The user ' . $value . ' does not exist.');
     }
     // Update the value.
     $value = self::createReferenceDefinition($entity);
     $this->addDependency($entity);
 }
示例#19
0
 public function resolve($recurse = true)
 {
     // Get all revisions for the entity.
     $diff = new EntityDiff($this->entity);
     $revisions = $diff->getRevisionHistory();
     if (is_array($revisions)) {
         // Make it so that we process the latest revision last.
         $revisions = array_reverse($revisions);
         foreach ($revisions as $revision_id) {
             $entity = Entity::load($this->base_entity->id(), $this->base_entity->type());
             $entity->setRevision($revision_id);
             $this->entity = $entity;
             $this->base_entity = clone $entity;
             $this->resolveDependencies($recurse, $entity->definition);
         }
     } else {
         $this->resolveDependencies($recurse);
     }
 }
示例#20
0
 protected function handleIndividualValue($entity_type, $field_type, $field_name, &$value, $delta)
 {
     global $base_url;
     if (!is_array($value)) {
         throw new FileReferenceHandlerException('The field ' . $field_name . ' has an invalid value.');
     }
     if (!array_key_exists('fid', $value)) {
         throw new FileReferenceHandlerException('The field ' . $field_name . ' does not have a file ID.');
     }
     $entity = Entity::load($value['fid'], 'file');
     if (!$entity) {
         throw new FileReferenceHandlerException('The field ' . $field_name . ' has no value.');
     }
     if (!file_exists(str_replace($base_url, DRUPAL_ROOT, urldecode(file_create_url($entity->definition->uri))))) {
         drupal_set_message(t('The file in the field !field does not exist. Setting the value to <code>NULL</code>', array('!field' => $field_name)), 'warning');
         $value = null;
         return;
     }
     $value['fid'] = self::createReferenceDefinition($entity);
     $this->addDependency($entity, true);
     $this->addRelationship($this->original_entity, $entity, $field_name, $delta, array('alt' => !empty($value['alt']) ? $value['alt'] : '', 'title' => !empty($value['title']) ? $value['title'] : '', 'display' => !empty($value['display']) ? $value['display'] : true, 'description' => !empty($value['description']) ? $value['description'] : ''));
 }
示例#21
0
 protected function handleSingle($mlid, $field_type)
 {
     if (!is_numeric($mlid)) {
         throw new MenuLinkHandlerException('The link ID ' . $mlid . ' is not numeric.');
     }
     $entity = Entity::load($mlid, 'menu_link');
     if (!$entity) {
         throw new MenuLinkHandlerException('The entity ' . $mlid . ' does not exist.');
     }
     if ($entity->uuid() == $this->entity->uuid()) {
         return 'self';
     }
     if ($field_type == 'menu_links') {
         // If the menu item is associated with the node, make the menu item
         // depend on the node, not the other way around.
         $sources = array($entity->uuid());
         $this->addDependency($this->original_entity, $sources);
     }
     // Don't create a source of the node if the type is menu links.
     $this->addDependency($entity, $field_type !== 'menu_links');
     return self::createReferenceDefinition($entity);
 }
示例#22
0
 public function getRevisionHistory($start_revision = false, $end_revision = false)
 {
     // Make sure we have a revisions table.
     if (!$this->revisions_table) {
         return false;
     }
     // Get the keys we need.
     if (array_key_exists('id', $this->entity_keys)) {
         $id_key = $this->entity_keys['id'];
     } else {
         return false;
     }
     if (array_key_exists('revision', $this->entity_keys)) {
         $revision_key = $this->entity_keys['revision'];
     } else {
         return false;
     }
     // Reset the start revision if it has a false value.
     if (!$start_revision) {
         $start_revision = -1;
     }
     // Query the database between the start revision and end revision.
     $query = \db_select($this->revisions_table, 'revision');
     $query->addField('revision', $revision_key, 'revision');
     $query->orderBy('revision.' . $revision_key);
     $query->condition('revision.' . $revision_key, $start_revision, '>');
     if ($end_revision !== false) {
         $query->condition('revision.' . $revision_key, $end_revision, '<=');
     }
     $query->condition('revision.' . $id_key, $this->entity->id());
     $result = $query->execute()->fetchAll();
     $revisions = array();
     foreach ($result as $row) {
         $revisions[] = $row->revision;
     }
     return $revisions;
 }
示例#23
0
 public function receive($endpoint, $payload = array())
 {
     if (!array_key_exists('entities', $payload)) {
         throw new MalformedRequestException('The payload must contain entities to delete, but it does not.');
     }
     $deleted[] = array();
     foreach ($payload['entities'] as $to_delete) {
         if (Entity::exists($to_delete['entity_uuid'], $to_delete['entity_type'])) {
             publisher_set_flag('publisher_deleting');
             $entity_ids = entity_get_id_by_uuid($to_delete['entity_type'], array($to_delete['entity_uuid']));
             $entity_id = count($entity_ids) > 0 ? reset($entity_ids) : false;
             if ($entity_id === false) {
                 continue;
             }
             entity_delete($to_delete['entity_type'], $entity_id);
             drupal_set_message(t('<strong>:type</strong> @title deleted successfully.', array(':type' => $to_delete['entity_type'], '@title' => $to_delete['entity_title'])));
             $deleted[] = $to_delete;
         } else {
             drupal_set_message(t('<strong>:type</strong> @title did not exist.', array(':type' => $to_delete['entity_type'], '@title' => $to_delete['entity_title'])));
             $deleted[] = $to_delete;
         }
     }
     return array('deleted' => $deleted);
 }
示例#24
0
 public static function entityFromReferenceDefinition(array $definition, Entity $current_entity = null)
 {
     // Verify the reference definition.
     if (($message = self::verifyReferenceDefinition($definition)) !== true) {
         throw new InvalidReferenceDefinitionException($message);
     }
     // Make sure the current entity ID and the reference definition ID are different.
     if ($current_entity && $definition['uuid'] == $current_entity->uuid()) {
         return null;
     }
     // Try to load the entity.
     $entity = Entity::loadByUUID($definition['uuid'], $definition['entity_type']);
     if (!$entity) {
         throw new InvalidReferenceDefinitionException(t('The @type @uuid does not exist.', array('@type' => $definition['entity_type'], '@uuid' => $definition['uuid'])));
     }
     return $entity;
 }
示例#25
0
 /**
  * Given an entity reference definition, gets the original entity ID.
  *
  * @param array  $definition     The entity reference definition.
  * @param Entity $current_entity The current entity (optional).
  *
  * @return bool|Entity|null
  * @throws InvalidReferenceDefinitionException
  */
 public static function entityFromReferenceDefinition(array $definition, Entity $current_entity = null)
 {
     // Verify the reference definition.
     if (($message = HandlerBase::verifyReferenceDefinition($definition)) !== true) {
         throw new InvalidReferenceDefinitionException($message);
     }
     // Make sure the current entity ID and the reference definition ID are different.
     if ($current_entity && $definition['uuid'] == $current_entity->uuid()) {
         return null;
     }
     // Try to load the entity.
     $entity = Entity::loadByUUID($definition['uuid'], $definition['entity_type']);
     if (!$entity) {
         // Check to see if there is a relationship for the entity.
         if ($current_entity) {
             $count = db_select('publisher_pending_relationships', 'r')->condition('source_type', $current_entity->type())->condition('source_uuid', $current_entity->uuid())->condition('destination_type', $definition['entity_type'])->condition('destination_uuid', $definition['uuid'])->countQuery()->execute()->fetchField();
             if ($count > 0) {
                 return false;
             }
         }
         throw new InvalidReferenceDefinitionException(t('The @type @uuid does not exist.', array('@type' => $definition['entity_type'], '@uuid' => $definition['uuid'])));
     }
     return $entity;
 }
示例#26
0
 public function execute(Entity $entity, Remote $remote, array $options, &$context)
 {
     // Get the transaction from the session.
     $transaction_session = TransactionSession::getFromSession();
     if (!$transaction_session) {
         return;
     }
     // Prepare the list of entities.
     $entities = array();
     // Get the dependencies from the entity.
     try {
         if ($entity->supportsRevisions()) {
             $revision = $entity->revision();
             $resolver = new RevisionResolver($entity);
         } else {
             $resolver = new Resolver($entity);
         }
         $dependencies = $resolver->dependencies();
         if (!empty($revision)) {
             $entity->setRevision($revision);
         }
     } catch (ResolverException $ex) {
         $message = t('There was an error processing the dependencies for the <strong>:type</strong> <code>:id</code> to the remote. Skipping.', array(':type' => $entity->type(), ':id' => $entity->id()));
         drupal_set_message($message, 'error');
         watchdog('publisher', $message, array(), WATCHDOG_WARNING);
         $this->updateContextMessages($entity, $context);
         return;
     }
     // Optionally mark the item as forced based on the entity type.
     $force = array_key_exists('force', $options) ? $options['force'] : false;
     drupal_alter('publisher_force_entity', $force, $entity);
     // Loop through each of the dependencies and mark them as forced if the options specify.
     if ($force) {
         foreach ($dependencies as $key => $dependency) {
             $dependencies[$key]['force'] = true;
             $dependencies[$key]['required'] = true;
         }
     }
     // Mark the root dependency as required if it has a status update.
     if (array_key_exists($entity->uuid(), $dependencies)) {
         $dependencies[$entity->uuid()]['source_required'] = false;
         $status = publisher_entity_tracking_get_status($entity->uuid(), $entity->type(), $remote->name);
         if (!$status->date_synced) {
             $dependencies[$entity->uuid()]['source_required'] = true;
         }
     }
     // Add the relationships to the transaction session.
     if ($resolver->relationships()) {
         $relationships = $transaction_session->getRelationships();
         foreach ($resolver->relationships() as $relationship) {
             $relationships[] = $relationship;
         }
         $transaction_session->setRelationships($relationships);
     }
     // Add the metadata to the transaction session.
     if ($metadata = $resolver->metadata()) {
         $transaction_session->setMetadata($metadata);
     }
     // Prepare the post data.
     $post_data = array('dependencies' => $dependencies);
     // Start the transaction.
     $transaction = new Transaction($remote);
     $response = $transaction->send('begin', $post_data);
     if (!$response['success']) {
         $message = t('There was an error sending the <strong>:type</strong> <code>:id</code> to the remote. See recent log messages for more details.', array(':type' => $entity->type(), ':id' => $entity->id()));
         drupal_set_message($message, 'error');
         watchdog('publisher', $message, array(), WATCHDOG_WARNING);
         Debug::wd($response);
     }
     $needs = array();
     if (array_key_exists('dependencies', $response)) {
         $needs = $response['dependencies'];
     }
     // Check to see if the receiving server didn't need anything.
     if (count($needs) <= 0) {
         $message = t('The remote <strong>:remote</strong> already has the latest version of the <strong>:type</strong> <code>:id</code>', array(':remote' => $remote->label, ':type' => $entity->type(), ':id' => $entity->id()));
         drupal_set_message($message);
         watchdog('publisher', $message);
         $this->updateContextMessages($entity, $context);
         return;
     }
     // Make sure each of the needs is valid before adding them to the transaction
     // session.
     foreach ($needs as $need) {
         if (!array_key_exists('uuid', $need) || !array_key_exists('entity_type', $need) || !array_key_exists('need revision', $need) || !array_key_exists('have revision', $need)) {
             continue;
         }
         // Check to see if the entity exists and prepare its payload.
         $entity_need = Entity::loadByUUID($need['uuid'], $need['entity_type']);
         if (!$entity_need) {
             $message = t('One of the entities the destination server needs could not be found. Please check the development log for more details.');
             drupal_set_message($message, 'error');
             watchdog('publisher', $message, array(), WATCHDOG_WARNING);
             Debug::wd($need);
             continue;
         }
         // Generate the payload for the entity.
         $entity_need_payload = publisher_compare_revision_uuid($entity_need, $need['have your revision'], $need['need revision']);
         if ($entity_need_payload === false) {
             $message = t('One or more revisions did not exist for the <strong>:type</strong> <code>:id</code>', array(':type' => $entity_need->type(), ':id' => $entity_need->id()));
             drupal_set_message($message, 'error');
             watchdog('publisher', $message, array(), WATCHDOG_WARNING);
             continue;
         }
         // Add the entity to the entities list in the transaction session.
         $entities[$entity_need->uuid()] = array('entity_type' => $entity_need->type(), 'entity_uuid' => $entity_need->uuid(), 'entity_id' => $entity_need->id(), 'entity_vuuid' => $entity_need->vuuid(), 'have_revision' => $need['have revision'], 'have_your_revision' => $need['have your revision'], 'need_revision' => $need['need revision'], 'required_from_remote' => $need['required_from_remote'], 'original_dependency' => $dependencies[$entity_need->uuid()], 'revisions_payload' => $entity_need_payload);
     }
     // Add the entities to the transaction session.
     $transaction_session->addEntities($entity->uuid(), $entities);
     $transaction_session->storeToSession();
     // Finally, record the context messages.
     $this->updateContextMessages($entity, $context);
 }
示例#27
0
 protected function deleteRevision(Entity $entity, $revision_id)
 {
     // First, delete the revision using the entity API.
     entity_revision_delete($entity->type(), $revision_id);
     // Now, if workbench moderation is installed, remove the node history for the specific revision.
     if (module_exists('workbench_moderation') && $entity->type() == 'node') {
         db_delete('workbench_moderation_node_history')->condition('nid', $entity->id())->condition('vid', $revision_id)->execute();
     }
 }
 public function handlesEntity(Entity $entity)
 {
     return module_exists('redirect') && module_exists('redirect_uuid') && $entity->type() == 'redirect';
 }
示例#29
0
 public function resolveDependencies($recurse = true, $subset = false, $child = false, $subtype = false)
 {
     // Check to see if the resolved definition already exists in the cached list.
     $cached_resolutions =& drupal_static('publisher_cached_resolutions', array());
     $key = $this->base_entity->uuid() . '|' . $this->base_entity->type();
     if ($this->base_entity->supportsRevisions()) {
         $key .= '|' . $this->base_entity->vuuid();
     }
     $key .= $recurse ? '|recurse' : '';
     if (array_key_exists($key, $cached_resolutions) && $child === false && $subset === false) {
         $this->dependencies = array_replace_recursive($this->dependencies, $cached_resolutions[$key]['dependencies']);
         $this->relationships = array_merge($this->relationships, $cached_resolutions[$key]['relationships']);
         $this->resolved_definition = $cached_resolutions[$key]['resolved_definition'];
         return;
     }
     if (count($cached_resolutions) > 200) {
         // For memory consumption purposes.
         drupal_static_reset('publisher_cached_resolutions');
     }
     // Create a clone of the definition so we don't muck up the entity cache.
     $this->resolved_definition = $subset !== false ? $subset : clone $this->entity->definition;
     if (!is_object($this->resolved_definition)) {
         $this->resolved_definition = (object) $this->resolved_definition;
     }
     // Generate the list of handlers for each of the fields.
     $handlers = DefinitionHandlerRegistry::getFieldHandlers($this->entity, $this->resolved_definition, $subtype);
     foreach ($handlers as $field_name => $handler) {
         if (!isset($this->resolved_definition->{$field_name})) {
             continue;
         }
         foreach ($handler['handlers'] as $single_handler) {
             if (!$single_handler instanceof DefinitionHandlerBase) {
                 continue;
             }
             try {
                 $single_handler->dependencies =& $this->dependencies;
                 $single_handler->entity =& $this->entity;
                 $single_handler->original_entity = $this->base_entity;
                 if (property_exists($single_handler, 'relationships')) {
                     $single_handler->relationships =& $this->relationships;
                 }
                 $single_handler->handleField($this->entity->type(), $handler['type'], $field_name, $this->resolved_definition->{$field_name});
             } catch (\Exception $ex) {
                 $message = t('Error processing field "@fieldName" - "@message"', array('@fieldName' => $field_name, '@message' => $ex->getMessage()));
                 \watchdog('publisher', $message, array(), WATCHDOG_WARNING);
                 $this->errors[] = $ex;
             }
         }
     }
     // Now, recursion.
     if ($recurse) {
         foreach ($this->dependencies as $identifier => $dependency) {
             // If the dependency has already been handled, skip it.
             if (array_key_exists($identifier, self::$handled_dependencies)) {
                 continue;
             }
             // Add the dependency to the list of handled ones.
             self::$handled_dependencies[$identifier] = $dependency;
             // Load the entity and get its dependencies.
             $entity = Entity::loadByUUID($dependency['uuid'], $dependency['entity_type']);
             // If for some reason the entity fails, we need to just skip it.
             if (!$entity) {
                 continue;
             }
             // Make sure the entity is not the current entity to prevent infinite loop.
             if ($entity->uuid() == $this->entity->uuid()) {
                 continue;
             }
             $resolver = new self($entity, false, $this->dependencies);
             $resolver->relationships =& $this->relationships;
             $resolver->metadata =& $this->metadata;
             $resolver->resolveDependencies(true, false, true);
             $this->dependencies = $resolver->dependencies();
         }
     }
     // Add a dependency for the entity itself if it doesn't already exist.
     if (!array_key_exists($this->base_entity->uuid(), $this->dependencies) || $this->base_entity->supportsRevisions() && !empty($this->dependencies[$this->base_entity->uuid()]['original_revision']) && $this->base_entity->revision() > $this->dependencies[$this->base_entity->uuid()]['original_revision']) {
         $this->dependencies[$this->base_entity->uuid()] = HandlerBase::createReferenceDefinition($this->base_entity);
     }
     // Pass the entity through the entity handlers.
     if (!array_key_exists($this->base_entity->uuid(), $this->metadata) && $recurse) {
         $this->metadata[$this->base_entity->uuid()] = array();
         foreach (EntityHandlerRegistry::getEntityHandlers($this->base_entity) as $handler) {
             if (!$handler instanceof EntityHandlerBase) {
                 continue;
             }
             $handler->entity =& $this->entity;
             $handler->original_entity = $this->base_entity;
             $handler->dependencies =& $this->dependencies;
             $handler->handleEntity($this->metadata[$this->base_entity->uuid()]);
         }
     }
     // Update the cache record.
     $cached_resolutions[$key] = array('dependencies' => $this->dependencies, 'relationships' => $this->relationships, 'resolved_definition' => $this->resolved_definition);
     if (!$child) {
         $dependency_dependencies =& drupal_static('publisher_dependency_dependencies', array());
         foreach ($dependency_dependencies as $source => $dependencies) {
             if (array_key_exists($source, $this->dependencies)) {
                 if (!array_key_exists('dependencies', $this->dependencies[$source]) || !is_array($this->dependencies[$source]['dependencies'])) {
                     $this->dependencies[$source]['dependencies'] = array();
                 }
                 $this->dependencies[$source]['dependencies'] = array_replace_recursive($this->dependencies[$source]['dependencies'], $dependencies);
                 $this->dependencies[$source]['dependencies'] = array_unique($this->dependencies[$source]['dependencies']);
             }
         }
         // Update the relationships.
         $this->updateRelationships();
         // Loop through all the dependencies and perform cleanup tasks.
         foreach ($this->dependencies as $dependency_key => &$dependency) {
             // Cleanup the sources.
             if (array_key_exists('sources', $dependency) && is_array($dependency['sources'])) {
                 $dependency['sources'] = array_unique($dependency['sources']);
             }
         }
         // Loop through again for the required stuff.
         foreach ($this->dependencies as $dependency_key => &$dependency) {
             // Create the 'required' key.
             if (array_key_exists('has_relationship', $dependency) && $dependency['has_relationship']) {
                 $dependency['required'] = false;
                 continue;
             }
             $this->dependencies[$dependency_key]['required'] = true;
             if (array_key_exists('sources', $this->dependencies[$dependency_key]) && is_array($this->dependencies[$dependency_key]['sources']) && count($this->dependencies[$dependency_key]['sources']) > 0) {
                 // Mark dependencies as not required only if all of their parent paths
                 // are marked as having relationships.
                 $sources = array();
                 foreach ($this->dependencies[$dependency_key]['sources'] as $source_uuid) {
                     $sources[] = $this->dependencies[$source_uuid];
                 }
                 $paths = $this->getAllParentTrails($sources);
                 $paths_with_notrequired = 0;
                 foreach ($paths as $path) {
                     foreach ($path as $item) {
                         if (!array_key_exists('required', $this->dependencies[$item]) || !$this->dependencies[$item]['required']) {
                             $paths_with_notrequired++;
                             break;
                         }
                     }
                 }
                 if ($paths_with_notrequired == count($paths)) {
                     $this->dependencies[$dependency_key]['required'] = false;
                 }
             } else {
                 // If the dependency doesn't have any sources, it is not
                 // required.
                 $this->dependencies[$dependency_key]['required'] = false;
             }
         }
         // Now, loop through the dependencies again and fill in their
         // 'required_if' values. If a dependency is marked as not required,
         // go through its trails and find the lowest parent that is marked
         // as having a relationship and add it to the 'required_if' list
         // if it isn't already there.
         foreach ($this->dependencies as $dependency_key => &$dependency) {
             $dependency['required_if'] = array();
             // If the dependency is marked as required already, is a relationship,
             // or doesn't have any sources, skip it.
             if ($dependency['required']) {
                 continue;
             }
             if (!array_key_exists('sources', $dependency) || !is_array($dependency['sources'])) {
                 continue;
             }
             // Loop through its parent trails to find the non-required items.
             $required_if = array();
             $sources = array();
             foreach ($dependency['sources'] as $source_uuid) {
                 // If the source UUID is the owner of the relationship, don't add it.
                 $skip = false;
                 foreach ($this->relationships as $relationship) {
                     if ($relationship['source_uuid'] == $source_uuid && $relationship['destination_uuid'] == $dependency['uuid']) {
                         $skip = true;
                         break;
                     }
                 }
                 if ($skip) {
                     continue;
                 }
                 $sources[] = $this->dependencies[$source_uuid];
             }
             $paths = $this->getAllParentTrails($sources);
             foreach ($paths as $path) {
                 $found = false;
                 foreach ($path as $index => $item) {
                     if (array_key_exists('has_relationship', $this->dependencies[$item]) && $this->dependencies[$item]['has_relationship']) {
                         $found = true;
                         $required_if[] = array_slice($path, 0, $index + 1);
                         break;
                     }
                 }
                 if (!$found) {
                     if (count($path) === 1) {
                         $required_if[] = $path;
                     } else {
                         for ($i = 1; $i < count($path); $i++) {
                             $required_if[] = array_slice($path, 0, $i);
                         }
                     }
                 }
             }
             // Add it to the dependency.
             $required_if_entities = array();
             foreach ($required_if as $path) {
                 $required_if_entities[] = end($path);
             }
             $dependency['required_if'] = array_unique($required_if_entities);
         }
         // Reset the dependency dependencies cache.
         drupal_static_reset('publisher_dependency_dependencies');
         // Finally, perform the topological sort on the dependencies.
         $this->topologicalSortDependencies();
     }
 }
示例#30
0
 public function submit($form, &$form_state)
 {
     // Get the remote.
     $remote = $this->getRemote($form_state);
     $statuses_to_send = array();
     if ($form_state['values']['op'] == $form_state['values']['send_all']) {
         $statuses_to_send = array_keys($form_state['values']['statuses']);
     } elseif ($form_state['values']['op'] == $form_state['values']['submit']) {
         $statuses_to_send = array_filter(array_values($form_state['values']['statuses']));
     }
     $entities_to_send = array();
     foreach ($statuses_to_send as $status_to_send) {
         list($uuid, $type) = explode('|', $status_to_send);
         $entities_to_send[] = Entity::loadByUUID($uuid, $type);
     }
     publisher_send_entities($entities_to_send, $remote);
 }