/**
  * Create a token for a user, and return its value.
  *
  * @param string $token
  *   The refresh token.
  *
  * @throws BadRequestException
  *
  * @return RestfulTokenAuth
  *   The new access token.
  */
 public function refreshToken($token)
 {
     // Check if there is a token that did not expire yet.
     /* @var \Drupal\restful\Plugin\resource\DataProvider\DataProviderEntityInterface $data_provider */
     $data_provider = $this->getDataProvider();
     $query = $data_provider->EFQObject();
     $results = $query->entityCondition('entity_type', $this->entityType)->entityCondition('bundle', 'refresh_token')->propertyCondition('token', $token)->range(0, 1)->execute();
     if (empty($results['restful_token_auth'])) {
         throw new BadRequestException('Invalid refresh token.');
     }
     // Remove the refresh token once used.
     $refresh_token = entity_load_single('restful_token_auth', key($results['restful_token_auth']));
     $uid = $refresh_token->uid;
     // Get the access token linked to this refresh token then do some cleanup.
     $access_token_query = new EntityFieldQuery();
     $access_token_reference = $access_token_query->entityCondition('entity_type', 'restful_token_auth')->entityCondition('bundle', 'access_token')->fieldCondition('refresh_token_reference', 'target_id', $refresh_token->id)->range(0, 1)->execute();
     if (!empty($access_token_reference['restful_token_auth'])) {
         $access_token = key($access_token_reference['restful_token_auth']);
         entity_delete('restful_token_auth', $access_token);
     }
     $refresh_token->delete();
     // Create the new access token and return it.
     /* @var \Drupal\restful_token_auth\Entity\RestfulTokenAuthController $controller */
     $controller = entity_get_controller($this->getEntityType());
     $token = $controller->generateAccessToken($uid);
     return $this->view($token->id);
 }
 /**
  * Test node creation by editor.
  *
  * 1. Editor creates Draft node
  * 2. Editor set status from Draft to Final Draft
  * 3. The node appears in the users's overview screen.
  */
 public function testCreateNode()
 {
     $this->drupalGet('node/add/news');
     $this->assertRaw('Current: Draft');
     $this->assertRaw('Final Draft');
     $this->assertNoRaw('Rejected');
     $this->assertNoRaw('Approved');
     $this->assertNoRaw('To Be Reviewed');
     $this->assertNoRaw('To Be Approved');
     $this->assertNoRaw('Ready To Publish');
     $this->assertNoRaw('Published');
     // Create a node in Draft state.
     $options = array('title_field[und][0][value]' => $this->nodeTitle1);
     $this->drupalPost('node/add/news', $options, t('Save'));
     $node = $this->drupalGetNodeByTitle($this->nodeTitle1);
     $nid = $node->nid;
     $this->assertEquals('draft', $node->workbench_moderation['current']->state);
     // Moderate to Final Draft.
     $options = array('title_field[en][0][value]' => $this->nodeTitle1, 'workbench_moderation_state_new' => 'final_draft');
     $this->drupalPost("node/{$nid}/edit", $options, t('Save'));
     // Reset the cache sice we are using node_load().
     entity_get_controller('node')->resetCache(array($node->nid));
     $node = node_load($nid);
     $this->assertEquals('final_draft', $node->workbench_moderation['current']->state);
     // Test the node appears in user's overview screen.
     $this->drupalGet('admin/workbench');
     $this->assertText($this->nodeTitle1);
 }
 /**
  * Create a token for a user, and return its value.
  */
 public function getOrCreateToken()
 {
     $entity_type = $this->getEntityType();
     $account = $this->getAccount();
     // Check if there is a token that did not expire yet.
     /* @var DataProviderEntityInterface $data_provider */
     $data_provider = $this->getDataProvider();
     $query = $data_provider->EFQObject();
     $result = $query->entityCondition('entity_type', $entity_type)->entityCondition('bundle', 'access_token')->propertyCondition('uid', $account->uid)->range(0, 1)->execute();
     $token_exists = FALSE;
     if (!empty($result[$entity_type])) {
         $id = key($result[$entity_type]);
         $access_token = entity_load_single($entity_type, $id);
         $token_exists = TRUE;
         if (!empty($access_token->expire) && $access_token->expire < REQUEST_TIME) {
             if (variable_get('restful_token_auth_delete_expired_tokens', TRUE)) {
                 // Token has expired, so we can delete this token.
                 $access_token->delete();
             }
             $token_exists = FALSE;
         }
     }
     if (!$token_exists) {
         /* @var \Drupal\restful_token_auth\Entity\RestfulTokenAuthController $controller */
         $controller = entity_get_controller($this->getEntityType());
         $access_token = $controller->generateAccessToken($account->uid);
         $id = $access_token->id;
     }
     $output = $this->view($id);
     return $output;
 }
 /**
  * Test node creation by editor.
  *
  * 1. Editor creates Draft node
  * 2. Editor set status from Draft to Final Draft
  * 3. The node appears in the users's overview screen.
  */
 public function testModerateToBeApproved()
 {
     $this->loginAs('editor1');
     $node = $this->drupalCreateNode(array('language' => 'en', 'title' => $this->nodeTitle1, 'type' => 'news', 'workbench_access' => 1007));
     workbench_moderation_moderate($node, 'final_draft');
     $this->loginAs('review_manager1');
     // Set node status To Be Reviewed.
     $options = array('title_field[en][0][value]' => $this->nodeTitle1, 'workbench_moderation_state_new' => 'needs_review');
     $this->drupalPost("node/{$node->nid}/edit", $options, t('Save'));
     entity_get_controller('node')->resetCache(array($node->nid));
     $node = node_load($node->nid);
     $this->assertEquals('needs_review', $node->workbench_moderation['current']->state);
     // Set the reviewer to project_manager1
     $pm1 = user_load_by_name('project_manager1');
     $options = array('project_manager' => $pm1->uid);
     $this->drupalPost("node/{$node->nid}/review", $options, t('Change'));
     $this->drupalGet("node/{$node->nid}/review");
     $this->assertText('project_manager1');
     // Define the list of approvers.
     // Cannot use drupalPost here.
     $ap1 = user_load_by_name('approver1');
     $ap2 = user_load_by_name('approver2 ');
     $form_state = array('node' => $node, 'values' => array('rows' => array($ap1->uid => array('weight' => -10), $ap2->uid => array('weight' => -11))));
     module_load_include('inc', 'osha_workflow', 'osha_workflow.admin');
     drupal_form_submit('osha_workflow_node_approval_form', $form_state, $node);
     $this->drupalGet("node/{$node->nid}/approve");
     $this->assertText($ap1->name);
     $this->assertText($ap2->name);
     $this->loginAs('project_manager1');
     $options = array('workbench_moderation_state_new' => 'to_be_approved');
     $this->drupalPost("node/{$node->nid}/edit", $options, t('Save'));
     entity_get_controller('node')->resetCache(array($node->nid));
     $node = node_load($node->nid);
     $this->assertEquals('to_be_approved', $node->workbench_moderation['current']->state);
 }
 function setUp()
 {
     $this->entityTypeId = 'user';
     $this->testLanguageSelector = FALSE;
     $this->name = $this->randomName();
     parent::setUp();
     entity_get_controller('user')->resetCache();
 }
 /**
  * Get Drupal 7 entity controller
  *
  * @return \DrupalEntityControllerInterface
  */
 protected final function getController()
 {
     if (!$this->controller) {
         $this->controller = entity_get_controller($this->entityType);
         if (!$this->controller) {
             throw new \InvalidArgumentException(sprintf("%s: entity type does not exist", $this->entityType));
         }
     }
     return $this->controller;
 }
Example #7
0
 /**
  * Assert that a field has the expected values in an entity.
  *
  * This function only checks a single column in the field values.
  *
  * @param EntityInterface $entity
  *   The entity to test.
  * @param $field_name
  *   The name of the field to test
  * @param $expected_values
  *   The array of expected values.
  * @param $langcode
  *   (Optional) The language code for the values. Defaults to
  *   \Drupal\Core\Language\LanguageInterface::LANGCODE_NOT_SPECIFIED.
  * @param $column
  *   (Optional) The name of the column to check. Defaults to 'value'.
  */
 function assertFieldValues(EntityInterface $entity, $field_name, $expected_values, $langcode = LanguageInterface::LANGCODE_NOT_SPECIFIED, $column = 'value')
 {
     // Re-load the entity to make sure we have the latest changes.
     entity_get_controller($entity->getEntityTypeId())->resetCache(array($entity->id()));
     $e = entity_load($entity->getEntityTypeId(), $entity->id());
     $field = $values = $e->getTranslation($langcode)->{$field_name};
     // Filter out empty values so that they don't mess with the assertions.
     $field->filterEmptyItems();
     $values = $field->getValue();
     $this->assertEqual(count($values), count($expected_values), 'Expected number of values were saved.');
     foreach ($expected_values as $key => $value) {
         $this->assertEqual($values[$key][$column], $value, format_string('Value @value was saved correctly.', array('@value' => $value)));
     }
 }
 /**
  * Test node creation by editor.
  *
  * 1. Editor creates Draft node
  * 2. Editor set status from Draft to Final Draft
  * 3. The node appears in the users's overview screen.
  */
 public function testModerateToNeedsReview()
 {
     $this->loginAs('editor1');
     $this->drupalGet('node/add/news');
     $this->assertRaw('Current: Draft');
     $this->assertRaw('Final Draft');
     $this->assertNoRaw('Rejected');
     $this->assertNoRaw('Approved');
     $this->assertNoRaw('To Be Reviewed');
     $this->assertNoRaw('To Be Approved');
     $this->assertNoRaw('Ready To Publish');
     $this->assertNoRaw('Published');
     // Create a node1, node2 in Final draft state.
     $options = array('title_field[und][0][value]' => $this->nodeTitle1, 'workbench_moderation_state_new' => 'final_draft');
     $this->drupalPost('node/add/news', $options, t('Save'));
     $node1 = $this->drupalGetNodeByTitle($this->nodeTitle1);
     $this->assertEquals('final_draft', $node1->workbench_moderation['current']->state);
     $options = array('title_field[und][0][value]' => $this->nodeTitle2, 'workbench_moderation_state_new' => 'final_draft');
     $this->drupalPost('node/add/news', $options, t('Save'));
     $node2 = $this->drupalGetNodeByTitle($this->nodeTitle2);
     $this->assertEquals('final_draft', $node1->workbench_moderation['current']->state);
     $this->loginAs('review_manager1');
     // Moderate node1 to Needs Review.
     $nid1 = $node1->nid;
     $options = array('title_field[en][0][value]' => $this->nodeTitle1, 'workbench_moderation_state_new' => 'needs_review');
     $this->drupalPost("node/{$nid1}/edit", $options, t('Save'));
     // Moderate node2 to Draft.
     $nid2 = $node2->nid;
     $options = array('title_field[en][0][value]' => $this->nodeTitle2, 'workbench_moderation_state_new' => 'draft');
     $this->drupalPost("node/{$nid2}/edit", $options, t('Save'));
     // Reset the cache sice we are using node_load().
     entity_get_controller('node')->resetCache(array($node1->nid, $node2->nid));
     $node1 = node_load($nid1);
     $node2 = node_load($nid2);
     $this->assertEquals('needs_review', $node1->workbench_moderation['current']->state);
     $this->assertEquals('draft', $node2->workbench_moderation['current']->state);
     // Test the node appears in user's needs review.
     $this->drupalGet('admin/workbench');
     $this->assertText($this->nodeTitle1);
     $this->assertText($this->nodeTitle2);
 }
  /**
   * Create a token for a user, and return its value.
   *
   * @param string $token
   *   The refresh token.
   *
   * @throws RestfulBadRequestException
   *
   * @return \RestfulTokenAuth
   *   The new access token.
   */
  public function refreshToken($token) {
    // Check if there is a token that did not expire yet.
    $query = new EntityFieldQuery();
    $results = $query
      ->entityCondition('entity_type', $this->entityType)
      ->entityCondition('bundle', 'refresh_token')
      ->propertyCondition('token', $token)
      ->range(0, 1)
      ->execute();

    if (empty($results['restful_token_auth'])) {
      throw new \RestfulBadRequestException('Invalid refresh token.');
    }

    // Remove the refresh token once used.
    $refresh_token = entity_load_single('restful_token_auth', key($results['restful_token_auth']));
    $uid = $refresh_token->uid;

    // Get the access token linked to this refresh token then do some cleanup.
    $access_token_query = new EntityFieldQuery();
    $access_token_reference = $access_token_query
      ->entityCondition('entity_type', $this->getEntityType())
      ->entityCondition('bundle', $this->getBundle())
      ->fieldCondition('refresh_token_reference', 'target_id', $refresh_token->id)
      ->range(0, 1)
      ->execute();

    if (!empty($access_token_reference['restful_token_auth'])) {
      $access_token_id = key($access_token_reference['restful_token_auth']);
      entity_delete('restful_token_auth', $access_token_id);
    }

    $refresh_token->delete();

    // Create the new access token and return it.
    $controller = entity_get_controller($this->getEntityType());
    $token = $controller->generateAccessToken($uid);
    return $this->viewEntity($token->id);
  }
 /**
  * Makes sure that every simple queue has a subqueue.
  */
 protected function ensureSubqueue()
 {
     global $user;
     static $queues = array();
     if (!isset($queues[$this->queue->name])) {
         $queues[$this->queue->name] = TRUE;
         $transaction = db_transaction();
         $query = new EntityFieldQuery();
         $query->entityCondition('entity_type', 'entityqueue_subqueue')->entityCondition('bundle', $this->queue->name);
         $result = $query->execute();
         // If we don't have a subqueue already, create one now.
         if (empty($result['entityqueue_subqueue'])) {
             $subqueue = entityqueue_subqueue_create();
             $subqueue->queue = $this->queue->name;
             $subqueue->name = $this->queue->name;
             $subqueue->label = $this->getSubqueueLabel($subqueue);
             $subqueue->module = 'entityqueue';
             $subqueue->uid = $user->uid;
             entity_get_controller('entityqueue_subqueue')->save($subqueue, $transaction);
         }
     }
 }
  /**
   * Create a token for a user, and return its value.
   *
   * @param string $token
   *   The refresh token.
   *
   * @throws RestfulBadRequestException
   *
   * @return \RestfulTokenAuth
   *   The new access token.
   */
  public function refreshToken($token) {
    $account = $this->getAccount();
    // Check if there is a token that did not expire yet.
    $query = new EntityFieldQuery();
    $results = $query
      ->entityCondition('entity_type', $this->entityType)
      ->entityCondition('bundle', 'refresh_token')
      ->propertyCondition('token', $token)
      ->range(0, 1)
      ->execute();

    if (empty($results['restful_token_auth'])) {
      throw new \RestfulBadRequestException('Invalid refresh token.');
    }

    // Remove the refresh token once used.
    $refresh_token = entity_load_single('restful_token_auth', key($results['restful_token_auth']));
    $refresh_token->delete();

    // Create the new access token and return it.
    $controller = entity_get_controller($this->getEntityType());
    $token = $controller->generateAccessToken($account->uid);
    return $this->viewEntity($token->id);
  }
 public function delete($fpids)
 {
     $transaction = db_transaction();
     if (!empty($fpids)) {
         $entities = fieldable_panels_panes_load_multiple($fpids, array());
         try {
             foreach ($entities as $fpid => $entity) {
                 // Call the entity-specific callback (if any):
                 module_invoke_all('entity_delete', $entity, 'fieldable_panels_pane');
                 field_attach_delete('fieldable_panels_pane', $entity);
             }
             // Delete after calling hooks so that they can query entity tables as needed.
             db_delete('fieldable_panels_panes')->condition('fpid', $fpids, 'IN')->execute();
             db_delete('fieldable_panels_panes_revision')->condition('fpid', $fpids, 'IN')->execute();
         } catch (Exception $e) {
             $transaction->rollback();
             watchdog_exception('fieldable_panels_pane', $e);
             throw $e;
         }
         // Clear the page and block and entity_load_multiple caches.
         entity_get_controller('fieldable_panels_pane')->resetCache();
     }
 }
 /**
  * Deletes one address.
  *
  * @param int $type
  *   Type of the argument given, can be the address id (BY_AID) or the address nickname (BY_NAME).
  * @param mixed $arg
  *   Either the address id or the address nickname.
  *
  * @access private
  * @return boolean
  *   TRUE if the address was deleted.
  *   FALSE otherwise.
  * @throws UcAddressesDbException
  */
 private function deleteOne($type, $arg)
 {
     // Reasons to skip out early
     if (!$this->isOwned()) {
         return FALSE;
     }
     // We can't delete an address that is a default address, so
     // we'll need to make sure this address is loaded.
     $this->loadOne($type, $arg);
     if ($type == self::BY_AID) {
         $address = $this->getAddressById($arg);
     }
     if ($type == self::BY_NAME) {
         $address = $this->getAddressByName($arg);
     }
     if (!$address) {
         return FALSE;
     }
     if ($address->isDefault('shipping') || $address->isDefault('billing')) {
         return FALSE;
     }
     // Delete the address from the database only if it is not new (else it won't exist in the db).
     if (!$address->isNew()) {
         db_delete('uc_addresses')->condition('aid', $address->getId())->execute();
     }
     // Remove from address book object.
     $this->removeAddressFromAddressBook($address);
     // Give other modules a chance to react on this.
     module_invoke_all('uc_addresses_address_delete', $address);
     entity_get_controller('uc_addresses')->invoke('delete', $address);
     return TRUE;
 }
Example #14
0
 /**
  * Deletes the entity from database. This is copied from the entity_delete()
  * function since entity module may not be installed.
  */
 public function deleteProgrammatically()
 {
     $entity_class = "RedTest\\core\\entities\\" . Utils::makeTitleCase($this->entity_type);
     $info = entity_get_info($this->entity_type);
     if (isset($info['deletion callback'])) {
         $info['deletion callback']($this->getId());
         return TRUE;
     } elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
         entity_get_controller($this->entity_type)->delete(array($this->getId()));
         return TRUE;
     } else {
         return FALSE;
     }
 }
Example #15
0
 /**
  * Purge all data from a field instance.
  *
  * @param array $instance
  *   The field instance definition. This may be deleted or inactive.
  */
 public static function purgeInstanceData(array $instance)
 {
     $field = static::readFieldByID($instance['field_id']);
     $data_table = _field_sql_storage_tablename($field);
     // Ensure the entity caches are cleared for the changed entities.
     if ($ids = db_query("SELECT entity_id FROM {$data_table} WHERE entity_type = :type AND bundle = :bundle", array(':type' => $instance['entity_type'], ':bundle' => $instance['bundle']))->fetchCol()) {
         entity_get_controller($instance['entity_type'])->resetCache($ids);
         db_delete($data_table)->condition('entity_type', $instance['entity_type'])->condition('bundle', $instance['bundle'])->execute();
     }
     $revision_table = _field_sql_storage_revision_tablename($field);
     if (db_table_exists($revision_table)) {
         db_delete($revision_table)->condition('entity_type', $instance['entity_type'])->condition('bundle', $instance['bundle'])->execute();
     }
     watchdog('helper', "Purged data for field instance ID {$instance['id']}.");
 }
 /**
  * Renders a entity_test and sets the output in the internal browser.
  *
  * @param int $id
  *   The entity_test ID to render.
  * @param string $view_mode
  *   (optional) The view mode to use for rendering. Defaults to 'full'.
  * @param bool $reset
  *   (optional) Whether to reset the entity_test controller cache. Defaults to
  *   TRUE to simplify testing.
  */
 protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE)
 {
     if ($reset) {
         entity_get_controller('entity_test')->resetCache(array($id));
     }
     $entity = entity_load('entity_test', $id);
     $display = EntityViewDisplay::collectRenderDisplay($entity, $view_mode);
     $build = $display->build($entity);
     $output = drupal_render($build);
     $this->drupalSetContent($output);
     $this->verbose($output);
 }
Example #17
0
 /**
  * Tests hiding a field in a form.
  */
 function testHiddenField()
 {
     $entity_type = 'entity_test_rev';
     $field_storage = $this->fieldStorageSingle;
     $field_storage['entity_type'] = $entity_type;
     $field_name = $field_storage['name'];
     $this->instance['field_name'] = $field_name;
     $this->instance['default_value'] = array(0 => array('value' => 99));
     $this->instance['entity_type'] = $entity_type;
     $this->instance['bundle'] = $entity_type;
     entity_create('field_storage_config', $field_storage)->save();
     $this->instance = entity_create('field_instance_config', $this->instance);
     $this->instance->save();
     // We explicitly do not assign a widget in a form display, so the field
     // stays hidden in forms.
     // Display the entity creation form.
     $this->drupalGet($entity_type . '/add');
     // Create an entity and test that the default value is assigned correctly to
     // the field that uses the hidden widget.
     $this->assertNoField("{$field_name}[0][value]", 'The field does not appear in the form');
     $this->drupalPostForm(NULL, array('user_id' => 1, 'name' => $this->randomMachineName()), t('Save'));
     preg_match('|' . $entity_type . '/manage/(\\d+)|', $this->url, $match);
     $id = $match[1];
     $this->assertText(t('entity_test_rev @id has been created.', array('@id' => $id)), 'Entity was created');
     $entity = entity_load($entity_type, $id);
     $this->assertEqual($entity->{$field_name}->value, 99, 'Default value was saved');
     // Update the instance to remove the default value and switch to the
     // default widget.
     $this->instance->default_value = NULL;
     $this->instance->save();
     entity_get_form_display($entity_type, $this->instance->bundle, 'default')->setComponent($this->instance->getName(), array('type' => 'test_field_widget'))->save();
     // Display edit form.
     $this->drupalGet($entity_type . '/manage/' . $id);
     $this->assertFieldByName("{$field_name}[0][value]", 99, 'Widget is displayed with the correct default value');
     // Update the entity.
     $value = mt_rand(1, 127);
     $edit = array("{$field_name}[0][value]" => $value);
     $this->drupalPostForm(NULL, $edit, t('Save'));
     $this->assertText(t('entity_test_rev @id has been updated.', array('@id' => $id)), 'Entity was updated');
     entity_get_controller($entity_type)->resetCache(array($id));
     $entity = entity_load($entity_type, $id);
     $this->assertEqual($entity->{$field_name}->value, $value, 'Field value was updated');
     // Set the field back to hidden.
     entity_get_form_display($entity_type, $this->instance->bundle, 'default')->removeComponent($this->instance->getName())->save();
     // Create a new revision.
     $edit = array('revision' => TRUE);
     $this->drupalPostForm($entity_type . '/manage/' . $id, $edit, t('Save'));
     // Check that the expected value has been carried over to the new revision.
     entity_get_controller($entity_type)->resetCache(array($id));
     $entity = entity_load($entity_type, $id);
     $this->assertEqual($entity->{$field_name}->value, $value, 'New revision has the expected value for the field with the Hidden widget');
 }
Example #18
0
/**
 * Loads UI controller and generates view pages for Tincan Statements
 *
 * @param integer id
 *
 * @return string content
 */
function tincan_lrs_statement_view($id)
{
    $content = "";
    $entity = entity_load('tincan_statement', array($id));
    if (!empty($entity)) {
        $controller = entity_get_controller('tincan_statement');
        $content = $controller->view($entity);
    } else {
        $content = '<p>No statement found for drupal id: ' . $id . '</p>';
    }
    drupal_set_title($entity[$id]->label());
    return $content;
}
 /**
  * {@inheritdoc}
  */
 public function set($value)
 {
     /* @var CacheFragmentController $controller */
     $controller = entity_get_controller('cache_fragment');
     if (!$controller->createCacheFragments($this->cacheFragments)) {
         return;
     }
     $this->cacheObject->set($this->generateCacheId(), $value);
 }
 /**
  * Execute a transition (change state of a node).
  *
  * @param bool $force
  *   If set to TRUE, workflow permissions will be ignored.
  *
  * @return int
  *   New state ID. If execution failed, old state ID is returned,
  *
  * deprecated workflow_execute_transition() --> WorkflowTransition::execute().
  */
 public function execute($force = FALSE)
 {
     $user = $this->getUser();
     $old_sid = $this->old_sid;
     $new_sid = $this->new_sid;
     // Load the entity, if not already loaded.
     // This also sets the (empty) $revision_id in Scheduled Transitions.
     $entity = $this->getEntity();
     // Only after getEntity(), the following are surely set.
     $entity_type = $this->entity_type;
     $entity_id = $this->entity_id;
     $field_name = $this->field_name;
     // Make sure $force is set in the transition, too.
     if ($force) {
         $this->force($force);
     }
     // Store the transition, so it can be easily fetched later on.
     // Store in an array, to prepare for multiple workflow_fields per entity.
     // This is a.o. used in hook_entity_update to trigger 'transition post'.
     $entity->workflow_transitions[$field_name] = $this;
     // Prepare an array of arguments for error messages.
     $args = array('%user' => isset($user->name) ? $user->name : '', '%old' => $old_sid, '%new' => $new_sid);
     if (!$this->getOldState()) {
         drupal_set_message($message = t('You tried to set a Workflow State, but
     the entity is not relevant. Please contact your system administrator.'), 'error');
         $message = 'Setting a non-relevant Entity from state %old to %new';
         $uri = entity_uri($entity_type, $entity);
         watchdog('workflow', $message, $args, WATCHDOG_ERROR, l('view', $uri['path']));
         return $old_sid;
     }
     // Check if the state has changed.
     $state_changed = $old_sid != $new_sid;
     // If so, check the permissions.
     if ($state_changed) {
         // State has changed. Do some checks upfront.
         if (!$force) {
             // Make sure this transition is allowed by workflow module Admin UI.
             $roles = array_keys($user->roles);
             $roles = array_merge(array(WORKFLOW_ROLE_AUTHOR_RID), $roles);
             if (!$this->isAllowed($roles, $user, $force)) {
                 watchdog('workflow', 'User %user not allowed to go from state %old to %new', $args, WATCHDOG_NOTICE);
                 // If incorrect, quit.
                 return $old_sid;
             }
         }
         if (!$force) {
             // Make sure this transition is allowed by custom module.
             // @todo D8: remove, or replace by 'transition pre'. See WorkflowState::getOptions().
             // @todo D8: replace all parameters that are included in $transition.
             $permitted = module_invoke_all('workflow', 'transition permitted', $old_sid, $new_sid, $entity, $force, $entity_type, $field_name, $this, $user);
             // Stop if a module says so.
             if (in_array(FALSE, $permitted, TRUE)) {
                 watchdog('workflow', 'Transition vetoed by module.');
                 return $old_sid;
             }
         }
         // Make sure this transition is valid and allowed for the current user.
         // Invoke a callback indicating a transition is about to occur.
         // Modules may veto the transition by returning FALSE.
         // (Even if $force is TRUE, but they shouldn't do that.)
         $permitted = module_invoke_all('workflow', 'transition pre', $old_sid, $new_sid, $entity, $force, $entity_type, $field_name, $this);
         // Stop if a module says so.
         if (in_array(FALSE, $permitted, TRUE)) {
             watchdog('workflow', 'Transition vetoed by module.');
             return $old_sid;
         }
     } elseif ($this->comment) {
         // No need to ask permission for adding comments.
         // Since you should not add actions to a 'transition pre' event, there is
         // no need to invoke the event.
     } else {
         // There is no state change, and no comment.
         // We may need to clean up something.
     }
     // The transition is allowed. Let other modules modify the comment.
     // @todo D8: remove all but last items from $context.
     $context = array('node' => $entity, 'sid' => $new_sid, 'old_sid' => $old_sid, 'uid' => $user->uid, 'transition' => $this);
     drupal_alter('workflow_comment', $this->comment, $context);
     // Now, change the database.
     // Log the new state in {workflow_node}.
     if (!$field_name) {
         if ($state_changed || $this->comment) {
             // If the node does not have an existing 'workflow' property,
             // save the $old_sid there, so it can be logged.
             if (!isset($entity->workflow)) {
                 // This is a workflow_node sid.
                 $entity->workflow = $old_sid;
                 // This is a workflow_node sid.
             }
             // Change the state for {workflow_node}.
             // The equivalent for Field API is in WorkflowDefaultWidget::submit.
             $data = array('nid' => $entity_id, 'sid' => $new_sid, 'uid' => isset($entity->workflow_uid) ? $entity->workflow_uid : $user->uid, 'stamp' => REQUEST_TIME);
             workflow_update_workflow_node($data);
             $entity->workflow = $new_sid;
             // This is a workflow_node sid.
         }
     } else {
         // This is a Workflow Field.
         // Until now, adding code here (instead of in workflow_execute_transition() )
         // doesn't work, creating an endless loop.
         /*
              if ($state_changed || $this->comment) {
                // Do a separate update to update the field (Workflow Field API)
                // This will call hook_field_update() and WorkflowFieldDefaultWidget::submit().
                // $entity->{$field_name}[$this->language] = array();
                // $entity->{$field_name}[$this->language][0]['workflow']['workflow_sid'] = $new_sid;
                // $entity->{$field_name}[$this->language][0]['workflow']['workflow_comment'] = $this->comment;
                $entity->{$field_name}[$this->language][0]['transition'] = $this;
         
                // Save the entity, but not through entity_save(),
                // since this will check permissions again and trigger rules.
                // @TODO: replace below by a workflow_field setter callback.
                // The transition was successfully executed, or else a message was raised.
         //        entity_save($entity_type, $entity);
                // or
         //        field_attach_update($entity_type, $entity);
         
                // Reset the entity cache after update.
                entity_get_controller($entity_type)->resetCache(array($entity_id));
         
                $new_sid = workflow_node_current_state($entity, $entity_type, $field_name);
              }
         */
     }
     $this->is_executed = TRUE;
     if ($state_changed || $this->comment) {
         // Log the transition in {workflow_node_history}.
         $this->save();
         // Register state change with watchdog.
         if ($state_changed) {
             $workflow = $this->getWorkflow();
             // Get the workflow_settings, unified for workflow_node and workflow_field.
             // @todo D8: move settings back to Workflow (like workflownode currently is).
             // @todo D8: to move settings back, grep for "workflow->options" and "field['settings']".
             $field = _workflow_info_field($field_name, $workflow);
             if (($new_state = $this->getNewState()) && !empty($field['settings']['watchdog_log'])) {
                 $entity_type_info = entity_get_info($entity_type);
                 $message = $this->isScheduled() ? 'Scheduled state change of @type %label to %state_name executed' : 'State of @type %label set to %state_name';
                 $args = array('@type' => $entity_type_info['label'], '%label' => entity_label($entity_type, $entity), '%state_name' => check_plain(t($new_state->label())));
                 $uri = entity_uri($entity_type, $entity);
                 watchdog('workflow', $message, $args, WATCHDOG_NOTICE, l('view', $uri['path']));
             }
         }
         // Remove any scheduled state transitions.
         foreach (WorkflowScheduledTransition::load($entity_type, $entity_id, $field_name) as $scheduled_transition) {
             /* @var $scheduled_transition WorkflowScheduledTransition */
             $scheduled_transition->delete();
         }
         // Notify modules that transition has occurred.
         // Action triggers should take place in response to this callback, not the 'transaction pre'.
         if (!$field_name) {
             // Now that workflow data is saved, reset stuff to avoid problems
             // when Rules etc want to resave the data.
             // Remember, this is only for nodes, and node_save() is not necessarily performed.
             unset($entity->workflow_comment);
             module_invoke_all('workflow', 'transition post', $old_sid, $new_sid, $entity, $force, $entity_type, $field_name, $this);
             entity_get_controller('node')->resetCache(array($entity->nid));
             // from entity_load(), node_save();
         } else {
             // module_invoke_all('workflow', 'transition post', $old_sid, $new_sid, $entity, $force, $entity_type, $field_name, $this);
             // We have a problem here with Rules, Trigger, etc. when invoking
             // 'transition post': the entity has not been saved, yet. we are still
             // IN the transition, not AFTER. Alternatives:
             // 1. Save the field here explicitly, using field_attach_save;
             // 2. Move the invoke to another place: hook_entity_insert(), hook_entity_update();
             // 3. Rely on the entity hooks. This works for Rules, not for Trigger.
             // --> We choose option 2:
             // - First, $entity->workflow_transitions[] is set for easy re-fetching.
             // - Then, post_execute() is invoked via workflowfield_entity_insert(), _update().
         }
     }
     return $new_sid;
 }
Example #21
0
 /**
  * Calls the entity controller to do the saving, then copies resulting field
  * values back to the incoming entity.
  *
  * @return int|bool
  */
 public function save()
 {
     $saved = entity_get_controller('developer_app')->save($this);
     if ($saved) {
         $app = \DeveloperAppController::getLastApp();
         foreach ($app as $key => $value) {
             $this->{$key} = $value;
         }
     }
     return $saved;
 }
Example #22
0
function api_node_save($node)
{
    $transaction = db_transaction();
    try {
        // Load the stored entity, if any.
        if (!empty($node->nid) && !isset($node->original)) {
            $node->original = entity_load_unchanged('node', $node->nid);
        }
        field_attach_presave('node', $node);
        global $user;
        // Determine if we will be inserting a new node.
        if (!isset($node->is_new)) {
            $node->is_new = empty($node->nid);
        }
        /*
            // Set the timestamp fields.
            if (empty($node->created)) {
              $node->created = REQUEST_TIME;
            }
            // The changed timestamp is always updated for bookkeeping purposes,
            // for example: revisions, searching, etc.
            $node->changed = REQUEST_TIME;
        
            $node->timestamp = REQUEST_TIME;
        */
        $update_node = TRUE;
        // Let modules modify the node before it is saved to the database.
        module_invoke_all('node_presave', $node);
        module_invoke_all('entity_presave', $node, 'node');
        if ($node->is_new || !empty($node->revision)) {
            // When inserting either a new node or a new node revision, $node->log
            // must be set because {node_revision}.log is a text column and therefore
            // cannot have a default value. However, it might not be set at this
            // point (for example, if the user submitting a node form does not have
            // permission to create revisions), so we ensure that it is at least an
            // empty string in that case.
            // @todo: Make the {node_revision}.log column nullable so that we can
            // remove this check.
            if (!isset($node->log)) {
                $node->log = '';
            }
        } elseif (!isset($node->log) || $node->log === '') {
            // If we are updating an existing node without adding a new revision, we
            // need to make sure $node->log is unset whenever it is empty. As long as
            // $node->log is unset, drupal_write_record() will not attempt to update
            // the existing database column when re-saving the revision; therefore,
            // this code allows us to avoid clobbering an existing log entry with an
            // empty one.
            unset($node->log);
        }
        // When saving a new node revision, unset any existing $node->vid so as to
        // ensure that a new revision will actually be created, then store the old
        // revision ID in a separate property for use by node hook implementations.
        if (!$node->is_new && !empty($node->revision) && $node->vid) {
            $node->old_vid = $node->vid;
            unset($node->vid);
        }
        // Save the node and node revision.
        if ($node->is_new) {
            // For new nodes, save new records for both the node itself and the node
            // revision.
            drupal_write_record('node', $node);
            _node_save_revision($node, $user->uid);
            $op = 'insert';
        } else {
            // For existing nodes, update the node record which matches the value of
            // $node->nid.
            drupal_write_record('node', $node, 'nid');
            // Then, if a new node revision was requested, save a new record for
            // that; otherwise, update the node revision record which matches the
            // value of $node->vid.
            if (!empty($node->revision)) {
                _node_save_revision($node, $user->uid);
            } else {
                _node_save_revision($node, $user->uid, 'vid');
                $update_node = FALSE;
            }
            $op = 'update';
        }
        if ($update_node) {
            db_update('node')->fields(array('vid' => $node->vid))->condition('nid', $node->nid)->execute();
        }
        // Call the node specific callback (if any). This can be
        // node_invoke($node, 'insert') or
        // node_invoke($node, 'update').
        node_invoke($node, $op);
        // Save fields.
        $function = "field_attach_{$op}";
        $function('node', $node);
        module_invoke_all('node_' . $op, $node);
        module_invoke_all('entity_' . $op, $node, 'node');
        // Update the node access table for this node.
        node_access_acquire_grants($node);
        // Clear internal properties.
        unset($node->is_new);
        unset($node->original);
        // Clear the static loading cache.
        entity_get_controller('node')->resetCache(array($node->nid));
        // Ignore slave server temporarily to give time for the
        // saved node to be propagated to the slave.
        db_ignore_slave();
    } catch (Exception $e) {
        $transaction->rollback();
        watchdog_exception('node', $e);
        throw $e;
    }
}
  /**
   * Renders a test_entity and sets the output in the internal browser.
   *
   * @param int $id
   *   The test_entity ID to render.
   * @param string $view_mode
   *   (optional) The view mode to use for rendering.
   * @param bool $reset
   *   (optional) Whether to reset the test_entity controller cache. Defaults to
   *   TRUE to simplify testing.
   */
  protected function renderTestEntity($id, $view_mode = 'full', $reset = TRUE) {
    if ($reset) {
      entity_get_controller('test_entity')->resetCache(array($id));
    }
    $entity = field_test_entity_test_load($id);
    field_attach_prepare_view('test_entity', array($entity->id() => $entity), $view_mode);
    $entity->content = field_attach_view('test_entity', $entity, $view_mode);

    $output = drupal_render($entity->content);
    $this->drupalSetContent($output);
    $this->verbose($output);
  }
 /**
  * Reset panelizers associated with the entity to the appropriate default.
  *
  * @param object $entity
  *   The entity.
  * @param $view_mode
  *   The view mode to delete. If not specified, all view modes will be
  *   deleted.
  */
 function reset_entity_panelizer($entity, $view_mode = NULL)
 {
     list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity);
     // Load all of the defaults for this entity bundle.
     $panelizers = $this->get_default_panelizer_objects($bundle);
     // Work out which view modes to use.
     if (!empty($view_mode)) {
         $view_modes = array($view_mode);
     } else {
         $entity_info = entity_get_info($this->entity_type);
         $view_modes = array_keys($entity_info['view modes']);
     }
     // Locate all displays associated with the entity.
     $dids = db_select('panelizer_entity', 'p')->fields('p', array('did'))->condition('entity_type', $this->entity_type)->condition('entity_id', $entity_id)->condition('revision_id', $revision_id)->condition('view_mode', $view_modes, 'IN')->condition('did', '0', '>')->execute()->fetchCol();
     // Loop over each view mode that is being reset.
     foreach ($view_modes as $view_mode) {
         // The default display to be used if nothing found.
         $default_name = implode(':', array($this->entity_type, $bundle, 'default'));
         $variable_name = 'panelizer_' . $this->entity_type . ':' . $bundle . ':' . $view_mode . '_selection';
         if ($view_mode != 'page_manager') {
             $default_name .= ':' . $view_mode;
         }
         // If this has not been set previously, use the 'default' as the default
         // selection.
         $default_value = variable_get($variable_name, FALSE);
         if ($default_value === FALSE) {
             $default_value = $default_name;
         }
         // Update the panelizer_entity record.
         $panelizer = $panelizers[$default_value];
         $panelizer->entity_type = $this->entity_type;
         $panelizer->entity_id = $entity_id;
         $panelizer->revision_id = (int) $revision_id;
         $panelizer->view_mode = $view_mode;
         $panelizer->did = NULL;
         $update = array('entity_type', 'entity_id', 'revision_id', 'view_mode');
         drupal_write_record('panelizer_entity', $panelizer, $update);
     }
     // Delete the dids if they are not still in use.
     foreach (array_unique($dids) as $did) {
         $in_use = db_select('panelizer_entity', 'p')->fields('p', array('did'))->condition('did', $did)->execute()->fetchCol();
         // Only delete the display if another revision was not using it.
         if (empty($in_use)) {
             panels_delete_display($did);
         }
     }
     // Reset the entity's cache. If the EntityCache module is enabled, this also
     // resets its permanent cache.
     entity_get_controller($this->entity_type)->resetCache(array($entity_id));
 }
<?php

// Get all nodes of 'ereference' and 'databases' type, populate the proxy field with a value of '1' if there is no field currently.
$eresource = db_query("SELECT nid, vid, type FROM {node} WHERE type = 'ereference' OR type = 'databases'")->fetchAllAssoc('nid');
foreach ($eresource as $nid => $values) {
    $key = array('entity_id' => $values->nid);
    // fields based on existing nodes
    $fields = array('entity_type' => 'node', 'bundle' => $values->type, 'deleted' => 0, 'entity_id' => $values->nid, 'revision_id' => $values->vid, 'language' => 'und', 'delta' => 0, 'field_proxy_value' => '1');
    // only insert missing fields, don't update existing fields.
    db_merge('field_data_field_proxy')->key($key)->insertFields($fields)->execute();
    db_merge('field_revision_field_proxy')->key($key)->insertFields($fields)->execute();
    // Save fields, use actual node object
    $node = node_load($values->nid);
    field_attach_presave('node', $node);
    field_attach_update('node', $node);
    entity_get_controller('node')->resetCache($key);
}
 /**
  * {@inheritdoc}
  */
 public function save($queue = TRUE)
 {
     $this->init(TRUE);
     if ($queue) {
         $this->queue();
     }
     /** @var EntityController $controller */
     $controller = entity_get_controller($this->entityType);
     return $controller->save($this);
 }
Example #27
0
 /**
  * {@inheritdoc}
  */
 public function getEntityController($entityType)
 {
     $this->initialize();
     return entity_get_controller($entityType);
 }
Example #28
0
 /**
  * Delete entities. This is a copy of entity_delete_multiple() function in
  * entity.module since entity module may not be present.
  *
  * @param string $entity_type
  *   Entity type.
  * @param int $min_entity_id
  *  Minimum entity id over which all entities will be deleted.
  *
  * @return bool
  *   TRUE if entities got deleted and FALSE otherwise.
  */
 public static function deleteEntities($entity_type, $min_entity_id)
 {
     $query = new \EntityFieldQuery();
     $results = $query->entityCondition('entity_type', $entity_type)->entityCondition('entity_id', $min_entity_id, '>')->execute();
     if (isset($results[$entity_type])) {
         $entity_ids = array_keys($results[$entity_type]);
         $info = entity_get_info($entity_type);
         if (isset($info['deletion callback'])) {
             foreach ($entity_ids as $id) {
                 $info['deletion callback']($id);
             }
         } elseif (in_array('EntityAPIControllerInterface', class_implements($info['controller class']))) {
             entity_get_controller($entity_type)->delete($entity_ids);
         } else {
             if ($entity_type == 'node') {
                 node_delete_multiple($entity_ids);
             } elseif ($entity_type == 'user') {
                 user_delete_multiple($entity_ids);
             } elseif ($entity_type == 'taxonomy_term') {
                 foreach ($entity_ids as $entity_id) {
                     taxonomy_term_delete($entity_id);
                 }
             } elseif ($entity_type == 'comment') {
                 foreach ($entity_ids as $entity_id) {
                     comment_delete($entity_id);
                 }
             }
             return FALSE;
         }
     }
 }
 /**
  * Reset panelizers associated with the entity to the appropriate default.
  *
  * @param object $entity
  *   The entity.
  * @param $view_mode
  *   The view mode to delete. If not specified, all view modes will be
  *   deleted.
  */
 function reset_entity_panelizer($entity, $view_mode = NULL)
 {
     // Only proceed if the view mode was customized for this entity.
     if (empty($entity->panelizer[$view_mode])) {
         drupal_set_message(t('Unable to reset this view mode'));
     } else {
         // Identify this entity's bundle.
         list($entity_id, , $bundle) = entity_extract_ids($this->entity_type, $entity);
         // Update the panelizer_entity record.
         $entity->panelizer[$view_mode]->did = NULL;
         $entity->panelizer[$view_mode]->name = $this->get_default_display_name($bundle, $view_mode);
         // Update the entity.
         $this->entity_save($entity);
         // If a new revision was not created, delete any unused displays.
         if ($this->supports_revisions && empty($entity->revision)) {
             // Get the IDs for this revision.
             list(, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity);
             // Work out which view modes to use.
             if (!empty($view_mode)) {
                 $view_modes = array($view_mode);
             } else {
                 $entity_info = entity_get_info($this->entity_type);
                 $view_modes = array_keys($entity_info['view modes']);
             }
             // Locate all displays associated with the entity.
             $dids = db_select('panelizer_entity', 'p')->fields('p', array('did'))->condition('entity_type', $this->entity_type)->condition('entity_id', $entity_id)->condition('revision_id', $revision_id)->condition('view_mode', $view_modes, 'IN')->condition('did', '0', '>')->execute()->fetchCol();
             // Delete the display records if they are not still in use.
             foreach (array_unique($dids) as $did) {
                 $in_use = db_select('panelizer_entity', 'p')->fields('p', array('did'))->condition('did', $did)->execute()->fetchCol();
                 // Only delete the display if another revision was not using it.
                 if (empty($in_use)) {
                     panels_delete_display($did);
                 }
             }
         }
         // Reset the entity's cache. If the EntityCache module is enabled, this
         // also resets its permanent cache.
         entity_get_controller($this->entity_type)->resetCache(array($entity_id));
     }
 }
 /**
  * Saves address if address is marked as 'dirty'.
  *
  * @access public
  * @return void
  * @throws UcAddressesDbException
  * @throws UcAddressesUnownedException
  */
 public function save()
 {
     if (!$this->isOwned()) {
         throw new UcAddressesUnownedException(t('The address can not be saved because it is not owned by an user.'));
     }
     if ($this->isDirty()) {
         // Allow other modules to alter the address before saving.
         module_invoke_all('uc_addresses_address_presave', $this);
         entity_get_controller('uc_addresses')->invoke('presave', $this);
         $address = $this->getSchemaAddress();
         $address->modified = REQUEST_TIME;
         $address->uid = $this->getUserId();
         if ($address->aid < 0) {
             unset($address->aid);
             $address->created = REQUEST_TIME;
             $result = drupal_write_record('uc_addresses', $address);
             $hook = 'insert';
             // Tell address book the address now has a definitive ID.
             $this->addressBook->updateAddress($this);
         } else {
             $result = drupal_write_record('uc_addresses', $address, array('aid'));
             $hook = 'update';
         }
         if ($result === FALSE) {
             throw new UcAddressesDbException(t('Failed to write address with id = %aid', array('%aid' => $address->aid)));
         }
         // Address is saved and no longer 'dirty'.
         $this->clearDirty();
         // If this a default address, ensure no other addresses are marked as
         // default in the database.
         if (function_exists('uc_addresses_address_types')) {
             // During installation the function 'uc_addresses_address_types()'
             // may not be available yet.
             $default_types = uc_addresses_address_types();
         } else {
             $default_types = array('shipping', 'billing');
         }
         foreach ($default_types as $default_type) {
             if ($this->isDefault($default_type)) {
                 // Mark all addresses of the address owner as non-default except
                 // the current address.
                 db_update('uc_addresses')->fields(array('default_' . $default_type => 0))->condition('uid', $address->uid)->condition('aid', $address->aid, '!=')->execute();
             }
         }
         // Notify other modules that an address has been saved.
         module_invoke_all('uc_addresses_address_' . $hook, $this);
         entity_get_controller('uc_addresses')->invoke($hook, $this);
     }
 }