/** * @Route("/{entity_type}/{entity}", name="entity_view", defaults={"view_mode" = "full", "langcode" = null, "page" = null}) * @Method("GET") * @ParamConverter("entity", converter="drupal.entity") * @Template */ public function viewAction(Request $request, $entity_type, $entity) { $view_mode = $request->get('view_mode'); $langcode = $request->get('langcode'); $page = $request->get('page'); list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity); $entities = entity_view($entity_type, array($id => $entity), $view_mode, $langcode, $page); return array('label' => entity_label($entity_type, $entity), 'uri' => entity_uri($entity_type, $entity), 'entity_type' => $entity_type, 'id' => $id, 'vid' => $vid, 'bundle' => $bundle, 'entity' => $entity, 'content' => reset($entities[$entity_type])); }
/** * Determine if the entity allows revisions. */ public function entity_allows_revisions($entity) { $retval = array(); list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity); $node_options = variable_get('node_options_' . $bundle, array('status', 'promote')); $retval[0] = in_array('revision', $node_options); $retval[1] = user_access('administer nodes'); return $retval; }
/** * Constructor * * @param string $eventName * @param string $entityType * @param EntityInterface $entity * @param int $userId * @param array $arguments */ public function __construct($eventName, $entityType, EntityInterface $entity, $userId = null, array $arguments = []) { $this->setEventName($eventName); $this->setEntityType($entityType); $this->setUserId($userId); list($id, , $bundle) = entity_extract_ids($entityType, $entity); // Keeping the 'uid' in arguments allows compatibility with the // makinacorpus/apubsub API, using subject too parent::__construct($entity, $arguments + ['uid' => $userId, 'id' => $id, 'bundle' => $bundle]); }
/** * Implements EditMetadataGeneratorInterface::generate(). */ public function generate($entity_type, $entity, array $instance, $langcode, $view_mode) { $field_name = $instance['field_name']; // Early-return if user does not have access. $access = $this->accessChecker->accessEditEntityField($entity_type, $entity, $field_name); if (!$access) { return array('access' => FALSE); } // Early-return if no editor is available. if (!_edit_is_extra_field($entity_type, $field_name)) { $display = field_get_display($instance, $view_mode, $entity); $formatter_type = field_info_formatter_types($display['type']); $items = field_get_items($entity_type, $entity, $field_name, $langcode); $items = $items === FALSE ? array() : $items; $editor_id = $this->editorSelector->getEditor($formatter_type, $instance, $items); } else { // @see hook_edit_extra_fields_info() $extra = edit_extra_field_info($entity_type, $field_name); if (isset($extra['view mode dependent editor'][$view_mode])) { $editor_id = $extra['view mode dependent editor'][$view_mode]; } else { $editor_id = $extra['default editor']; } } if (!isset($editor_id)) { return array('access' => FALSE); } // Gather metadata, allow the editor to add additional metadata of its own. if (!_edit_is_extra_field($entity_type, $field_name)) { $label = $instance['label']; } else { $label = edit_extra_field_info($entity_type, $field_name, 'label'); } list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity); $metadata = array('label' => check_plain($label), 'access' => TRUE, 'editor' => $editor_id, 'aria' => t('Entity @type @id, field @field', array('@type' => $entity_type, '@id' => $id, '@field' => $label))); if (!_edit_is_extra_field($entity_type, $field_name)) { $editor = edit_editor_get($editor_id); if (!empty($editor['metadata callback'])) { if ($editor['file']) { require_once $editor['file path'] . '/' . $editor['file']; } if (function_exists($editor['metadata callback'])) { $custom_metadata = $editor['metadata callback']($instance, $items); if (count($custom_metadata)) { $metadata['custom'] = $custom_metadata; } } } // Allow the metadata to be altered. $context = array('entity_type' => $entity_type, 'entity' => $entity, 'field' => $instance, 'items' => $items); drupal_alter('edit_editor_metadata', $metadata, $editor_id, $context); } return $metadata; }
/** * Act on Linked Field settings * * This hook is invoked from linked_field_field_attach_view_alter() when linking * a field. It allows you to override all settings. * * @param $settings * An associative array of Linked Field settings. * @param $context * An associative array containing: * - entity_type: The type of $entity; for example, 'node' or 'user'. * - entity: The entity with fields to render. * - view_mode: View mode; for example, 'full' or 'teaser'. * - display: Either a view mode string or an array of display settings. If * this hook is being invoked from field_attach_view(), the 'display' * element is set to the view mode string. If this hook is being invoked * from field_view_field(), this element is set to the $display argument * and the view_mode element is set to '_custom'. See field_view_field() * for more information on what its $display argument contains. * - language: The language code used for rendering. */ function hook_linked_field_settings_alter(&$settings, $context) { $entity_type = $context['entity_type']; $entity = $context['entity']; list(, , $bundle) = entity_extract_ids($entity_type, $entity); $view_mode = $context['view_mode']; // Add custom attribute for the link. if ($entity_type == 'node' && $bundle == 'article' && $view_mode == 'default') { $settings['options']['attributes']['data-id'] = $entity->nid; } }
/** * Determine if the entity allows revisions. */ public function entity_allows_revisions($entity) { $retval = array(); list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity); $node_options = variable_get('node_options_' . $bundle, array('status', 'promote')); // Whether or not the entity supports revisions. $retval[0] = TRUE; // Whether or not the user can control if a revision is created. $retval[1] = user_access('administer nodes'); // Whether or not the revision is created by default. $retval[2] = in_array('revision', $node_options); return $retval; }
/** * Prepare internal bundle and id list cache */ private function buildListCache() { if (null !== $this->idList) { return; } foreach ($this->subject as $entity) { list($id, , $bundle) = entity_extract_ids($this->getEntityType(), $entity); $this->idList[] = $id; $this->bundleList[$id] = $bundle; $this->bundleList = $bundle; $this->bundleList = array_unique($this->bundleList); } }
/** * Overrides EntityInlineEntityFormController::entityFormSubmit(). * * Fixes some of the custom entity values, similar to * fieldable_panels_panes_entity_edit_form_submit(). */ public function entityFormSubmit(&$entity_form, &$form_state) { $info = entity_get_info($this->entityType); list(, , $bundle) = entity_extract_ids($this->entityType, $entity_form['#entity']); $entity = $entity_form['#entity']; $entity_values = drupal_array_get_nested_value($form_state['values'], $entity_form['#parents']); // Some additional adjustments necessary for FPP to save correctly. if (!empty($entity_values['link']['path'])) { $entity_values['path'] = $entity_values['link']['path']; } if (isset($entity_values['link']['link'])) { $entity_values['link'] = $entity_values['link']['link']; } else { $entity_values['link'] = 0; } // The 'reusable' option contains several sub fields. if (isset($entity_values['reusable']['reusable'])) { $reusable = $entity_values['reusable']; $entity_values['reusable'] = FALSE; $entity_values['category'] = ''; $entity_values['admin_title'] = ''; $entity_values['admin_description'] = ''; foreach (array('reusable', 'category', 'admin_title', 'admin_description') as $field) { if (isset($reusable[$field])) { $entity_values[$field] = $reusable[$field]; } } } // Only fix the revision log if a revision is being saved. $entity_values['log'] = ''; if (isset($entity_values['revision']['revision'])) { if (isset($entity_values['revision']['log'])) { $entity_values['log'] = $entity_values['revision']['log']; } $entity_values['revision'] = $entity_values['revision']['revision']; } else { $entity_values['revision'] = 0; } // Copy top-level form values that are not for fields to entity properties, // without changing existing entity properties that are not being edited by // this form. Copying field values must be done using field_attach_submit(). $values_excluding_fields = $info['fieldable'] ? array_diff_key($entity_values, field_info_instances($this->entityType, $bundle)) : $entity_values; foreach ($values_excluding_fields as $key => $value) { $entity->{$key} = $value; } if ($info['fieldable']) { field_attach_submit($this->entityType, $entity, $entity_form, $form_state); } }
/** * Implements EntityReference_BehaviorHandler_Abstract::load(). */ public function load($entity_type, $entities, $field, $instances, $langcode, &$items) { // Get the OG memberships from the field. $field_name = $field['field_name']; $target_type = $field['settings']['target_type']; foreach ($entities as $entity) { list($id) = entity_extract_ids($entity_type, $entity); $items[$id] = array(); $gids = og_get_entity_groups($entity_type, $entity, array(), $field_name); if (empty($gids[$target_type])) { continue; } foreach ($gids[$target_type] as $gid) { $items[$id][] = array('target_id' => $gid); } } }
/** * * Do the actual update - passes the update to the plugin's process functions */ function update() { if (function_exists($this->plugin['process'])) { $this->plugin['process']($this); } // Are there any form errors? if ($errors = form_get_errors()) { foreach ($errors as $error) { // Form errors will apply for all entities foreach ($this->entities as $entity) { list($id) = entity_extract_ids($this->entity_type, $entity); $this->set_error($id, $error); } } } return $this->get_result(); }
/** * Overrides EntityInlineEntityFormController::entityForm(). * * Copied from fieldable_panels_panes_entity_edit_form(). */ public function entityForm($entity_form, &$form_state) { // Make the other form items dependent upon it. ctools_include('dependent'); ctools_add_js('dependent'); $entity = $entity_form['#entity']; $entity_type = 'fieldable_panels_pane'; list(, , $bundle) = entity_extract_ids($entity_type, $entity); // Map these properties for entity translations. $entity_form['#entity_type'] = array('#type' => 'value', '#value' => $entity->bundle); $form_state['fieldable_panels_pane'] = $entity_form['#entity']; $entity_form['title'] = array('#type' => 'textfield', '#title' => t('Title'), '#default_value' => $entity->title, '#weight' => -10); $entity_form['language'] = array('#type' => 'value', '#value' => $entity->language); $entity_form['link'] = array('#weight' => -10); $entity_form['link']['link'] = array('#title' => t('Make title a link'), '#type' => 'checkbox', '#default_value' => $entity->link, '#description' => t('Check here to make the title link to another page.'), '#id' => 'edit-link'); $entity_form['link']['path'] = array('#type' => 'textfield', '#title' => t('Path'), '#description' => t('The path for this link. This can be an internal Drupal path such as %add-node or an external URL such as %drupal. Enter %front to link to the front page.', array('%front' => '<front>', '%add-node' => 'node/add', '%drupal' => 'http://drupal.org')), '#dependency' => array('edit-link' => array(1)), '#default_value' => $entity->path); $entity_form['reusable'] = array('#weight' => 10); $entity_form['revision'] = array('#weight' => 11); if (empty($entity->fpid)) { $entity_form['revision']['#access'] = FALSE; } $entity_form['reusable']['reusable'] = array('#type' => 'checkbox', '#title' => t('Make this entity reusable'), '#default_value' => $entity->reusable, '#id' => 'edit-reusable'); $entity_form['reusable']['category'] = array('#type' => 'textfield', '#title' => t('Category'), '#description' => t('The category this content will appear in the "Add content" modal. If left blank the category will be "Miscellaneous".'), '#dependency' => array('edit-reusable' => array(1)), '#default_value' => $entity->category); $entity_form['reusable']['admin_title'] = array('#type' => 'textfield', '#title' => t('Administrative title'), '#description' => t('The name this content will appear in the "Add content" modal.'), '#dependency' => array('edit-reusable' => array(1)), '#default_value' => $entity->admin_title); $entity_form['reusable']['admin_description'] = array('#type' => 'textarea', '#title' => t('Administrative description'), '#description' => t('A description of what this content is, does or is for, for administrative use.'), '#dependency' => array('edit-reusable' => array(1)), '#default_value' => $entity->admin_description); $entity_form['revision']['revision'] = array('#type' => 'checkbox', '#title' => t('Create new revision'), '#default_value' => 1, '#id' => 'edit-revision'); if (!user_access('administer fieldable panels panes') || empty($entity->fpid) || $entity->vid != $entity->current_vid) { $form['revision']['revision']['#disabled'] = TRUE; $form['revision']['revision']['#value'] = TRUE; } $entity_form['revision']['log'] = array('#type' => 'textarea', '#title' => t('Log message'), '#description' => t('Provide an explanation of the changes you are making. This will help other authors understand your motivations.'), '#dependency' => array('edit-revision' => array(1)), '#default_value' => ''); $langcode = entity_language('fieldable_panels_pane', $entity); field_attach_form('fieldable_panels_pane', $entity, $entity_form, $form_state, $langcode); // _field_extra_fields_pre_render() doesn't execute properly, so manually // set the weights. $extra_fields = field_info_extra_fields($entity_type, $bundle, 'form'); foreach ($extra_fields as $name => $settings) { if (isset($entity_form[$name])) { $entity_form[$name]['#weight'] = $settings['weight']; } } return $entity_form; }
/** * Overrides RestfulEntityBase::getList(). */ public function getList() { $entity_type = $this->entityType; $result = $this ->getQueryForList() ->execute(); if (empty($result[$entity_type])) { return; } $account = $this->getAccount(); $request = $this->getRequest(); $ids = array_keys($result[$entity_type]); // Pre-load all entities. $entities = entity_load($entity_type, $ids); $return = array(); $handlers = array(); $resources_info = $this->getBundles(); foreach ($entities as $entity) { // Call each handler by its registered bundle. list($id,, $bundle) = entity_extract_ids($this->getEntityType(), $entity); if (empty($handlers[$bundle])) { $version = $this->getVersion(); $handlers[$bundle] = restful_get_restful_handler($resources_info[$bundle], $version['major'], $version['minor']); } $bundle_handler = $handlers[$bundle]; $bundle_handler->setAccount($account); $bundle_handler->setRequest($request); $return[] = $bundle_handler->viewEntity($id); } return $return; }
/** * Implements EntityReferenceHandler::getReferencableEntities(). */ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { global $user; // For admin users, use the standard plugin behavior. if (user_access('assign content ownership')) { return parent::getReferencableEntities($match, $match_operator, $limit); } $options = array(); if (empty($user->uid)) { return $options; } $uids = array($user->uid); if (function_exists('yaffle_delegation_get_delegate_uids')) { $uids += yaffle_delegation_get_delegate_uids($user->uid); } $entities = entity_load($entity_type, array_keys($results[$entity_type])); foreach ($entities as $entity_id => $entity) { list(, , $bundle) = entity_extract_ids($entity_type, $entity); $options[$bundle][$entity_id] = check_plain($this->getLabel($entity)); } // $uids = array($user->uid); // $options = array(); // $entity_type = $this->field['settings']['target_type']; // $query = $this->buildEntityFieldQuery($match, $match_operator); // if ($limit > 0) { // $query->range(0, $limit); // } // $results = $query->execute(); // if (!empty($results[$entity_type])) { // $entities = entity_load($entity_type, array_keys($results[$entity_type])); // foreach ($entities as $entity_id => $entity) { // list(,, $bundle) = entity_extract_ids($entity_type, $entity); // $options[$bundle][$entity_id] = check_plain($this->getLabel($entity)); // } // } return $options; }
/** * Implements hook_form_alter(). * * Use this hook to alter the form on a Node Form, Comment Form (Edit page). */ function hook_form_alter(&$form, $form_state, $form_id) { // Get the Entity. $entity = $form['#entity']; $entity_type = $form['#entity_type']; // Use the complicated form, which is suited for all Entity Types. list(, , $entity_bundle) = entity_extract_ids($entity_type, $entity); // Discover if this is the correct form. // ... // Get the current state and act upon it. // .. copy code from the hook above. }
/** * Remove field storage information when field data is purged. * * Called from field_purge_data() to allow the field storage * module to delete field data information. * * @param $entity_type * The type of $entity; for example, 'node' or 'user'. * @param $entity * The pseudo-entity whose field data to delete. * @param $field * The (possibly deleted) field whose data is being purged. * @param $instance * The deleted field instance whose data is being purged. */ function hook_field_storage_purge($entity_type, $entity, $field, $instance) { list($id, $vid, $bundle) = entity_extract_ids($entity_type, $entity); $table_name = _field_sql_storage_tablename($field); $revision_name = _field_sql_storage_revision_tablename($field); db_delete($table_name)->condition('entity_type', $entity_type)->condition('entity_id', $id)->execute(); db_delete($revision_name)->condition('entity_type', $entity_type)->condition('entity_id', $id)->execute(); }
/** * Act on entities when deleted. * * @param $entity * The entity object. * @param $type * The type of entity being deleted (i.e. node, user, comment). */ function hook_entity_delete($entity, $type) { // Delete the entity's entry from a fictional table of all entities. $info = entity_get_info($type); list($id) = entity_extract_ids($type, $entity); db_delete('example_entity')->condition('type', $type)->condition('id', $id)->execute(); }
/** * Implements EntityReference_BehaviorHandler_Abstract::validate(). * * Re-build $errors array to be keyed correctly by "default" and "admin" field * modes. * * @todo: Try to get the correct delta so we can highlight the invalid * reference. * * @see entityreference_field_validate(). */ public function validate($entity_type, $entity, $field, $instance, $langcode, $items, &$errors) { $new_errors = array(); $values = array('default' => array(), 'admin' => array()); foreach ($items as $item) { $values[$item['field_mode']][] = $item['target_id']; } list(, , $bundle) = entity_extract_ids($entity_type, $entity); $field_name = $field['field_name']; foreach ($values as $field_mode => $ids) { if (!$ids) { continue; } if ($field_mode == 'admin' && !user_access('administer group')) { // No need to validate the admin, as the user has no access to it. continue; } $instance['field_mode'] = $field_mode; $valid_ids = entityreference_get_selection_handler($field, $instance, $entity_type, $entity)->validateReferencableEntities($ids); if ($invalid_entities = array_diff($ids, $valid_ids)) { foreach ($invalid_entities as $id) { $new_errors[$field_mode][] = array('error' => 'og_invalid_entity', 'message' => t('The referenced group (@type: @id) is invalid.', array('@type' => $field['settings']['target_type'], '@id' => $id))); } } } if ($new_errors) { og_field_widget_register_errors($field_name, $new_errors); } $errors = array(); }
/** * Implements hook_field_attach_submit(). */ public function hook_field_attach_submit($entity, &$form, &$form_state) { // Call parent. parent::hook_field_attach_submit($entity, $form, $form_state); // Save paragraph item panelizer settings. if (!empty($form_state['panelizer has choice'])) { list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity); foreach ($this->plugin['view modes'] as $view_mode => $view_mode_info) { if (isset($form['#parents']) && drupal_array_nested_key_exists($form_state['values'], $form['#parents'])) { $values = drupal_array_get_nested_value($form_state['values'], $form['#parents']); if (isset($values['panelizer'][$view_mode]['name'])) { $entity->panelizer[$view_mode] = clone $this->get_default_panelizer_object($bundle . '.' . $view_mode, $values['panelizer'][$view_mode]['name']); if (!empty($entity->panelizer[$view_mode])) { $entity->panelizer[$view_mode]->did = NULL; // Ensure original values are maintained, if they exist. if (isset($form['panelizer'][$view_mode]['name'])) { $entity->panelizer[$view_mode]->entity_id = $form['panelizer'][$view_mode]['name']['#entity_id']; $entity->panelizer[$view_mode]->revision_id = $form['panelizer'][$view_mode]['name']['#revision_id']; } } } } } } }
/** * Gets called after an entity has been deleted from database. * * @param $entity * An entity object * @param string $entity * An string containing entity type name * * @see hook_entity_postsave() * @see hook_entity_postinsert() * @see hook_entity_postupdate() * @ingroup entity_api_hooks */ function hook_entity_postdelete($entity, $entity_type) { list($id) = entity_extract_ids($entity_type, $entity); watchdog('hook_post_action_test', "The deleted entity {$entity_type} id is {$id} from " . __FUNCTION__); }
/** * Overrides theme_date_display_combination(). */ function favrskovtheme_date_display_combination($variables) { static $repeating_ids = array(); $entity_type = $variables['entity_type']; $entity = $variables['entity']; $field = $variables['field']; $instance = $variables['instance']; $langcode = $variables['langcode']; $item = $variables['item']; $delta = $variables['delta']; $display = $variables['display']; $field_name = $field['field_name']; $formatter = $display['type']; $options = $display['settings']; $dates = $variables['dates']; $attributes = $variables['attributes']; $rdf_mapping = $variables['rdf_mapping']; $add_rdf = $variables['add_rdf']; $precision = date_granularity_precision($field['settings']['granularity']); $output = ''; // If date_id is set for this field and delta doesn't match, don't display it. if (!empty($entity->date_id)) { foreach ((array) $entity->date_id as $key => $id) { list($module, $nid, $field_name, $item_delta, $other) = explode('.', $id . '.'); if ($field_name == $field['field_name'] && isset($delta) && $item_delta != $delta) { return $output; } } } // Check the formatter settings to see if the repeat rule should be displayed. // Show it only with the first multiple value date. list($id) = entity_extract_ids($entity_type, $entity); if (!in_array($id, $repeating_ids) && module_exists('date_repeat_field') && !empty($item['rrule']) && $options['show_repeat_rule'] == 'show') { $repeat_vars = array('field' => $field, 'item' => $item, 'entity_type' => $entity_type, 'entity' => $entity); $output .= theme('date_repeat_display', $repeat_vars); $repeating_ids[] = $id; } // If this is a full node or a pseudo node created by grouping multiple // values, see exactly which values are supposed to be visible. if (isset($entity->{$field_name})) { $entity = date_prepare_entity($formatter, $entity_type, $entity, $field, $instance, $langcode, $item, $display); // Did the current value get removed by formatter settings? if (empty($entity->{$field_name}[$langcode][$delta])) { return $output; } // Adjust the $element values to match the changes. $element['#entity'] = $entity; } switch ($options['fromto']) { case 'value': $date1 = $dates['value']['formatted']; $date2 = $date1; break; case 'value2': $date2 = $dates['value2']['formatted']; $date1 = $date2; break; default: $date1 = $dates['value']['formatted']; $date2 = $dates['value2']['formatted']; break; } // Pull the timezone, if any, out of the formatted result and tack it back on // at the end, if it is in the current formatted date. $timezone = $dates['value']['formatted_timezone']; if ($timezone) { $timezone = ' ' . $timezone; } $date1 = str_replace($timezone, '', $date1); $date2 = str_replace($timezone, '', $date2); $time1 = preg_replace('`^([\\(\\[])`', '', $dates['value']['formatted_time']); $time1 = preg_replace('([\\)\\]]$)', '', $time1); $time2 = preg_replace('`^([\\(\\[])`', '', $dates['value2']['formatted_time']); $time2 = preg_replace('([\\)\\]]$)', '', $time2); // A date with a granularity of 'hour' has a time string that is an integer // value. We can't use that to replace time strings in formatted dates. $has_time_string = date_has_time($field['settings']['granularity']); if ($precision == 'hour') { $has_time_string = FALSE; } // No date values, display nothing. if (empty($date1) && empty($date2)) { $output .= ''; } elseif ($date1 == $date2 || empty($date2)) { $output .= theme('date_display_single', array('date' => $date1, 'timezone' => $timezone, 'attributes' => $attributes, 'rdf_mapping' => $rdf_mapping, 'add_rdf' => $add_rdf, 'dates' => $dates)); } else { $output .= theme('date_display_range', array('date1' => $date1, 'date2' => $date2, 'timezone' => $timezone, 'attributes' => $attributes, 'rdf_mapping' => $rdf_mapping, 'add_rdf' => $add_rdf, 'dates' => $dates)); } return $output; }
/** * Update votes in database from API response. */ public function updateVotes($response) { $votes = array(); if (!empty($response['response']['items'])) { foreach ($response['response']['items'] as $item) { $entity_type = ''; $entity_id = ''; $field_id = ''; $field_index = 0; // Parse identifier. if (strstr($item['identifier'], '_field_')) { // Item is a field. preg_match("/^(.*)_(\\d+)_field_(\\d+)(?:_index_(\\d+))?\$/", $item['identifier'], $identifier_parts); if (!empty($identifier_parts[1])) { $entity_type = $identifier_parts[1]; } else { continue; } if (!empty($identifier_parts[2])) { $entity_id = $identifier_parts[2]; } else { continue; } if (!empty($identifier_parts[3])) { $field_id = $identifier_parts[3]; } else { continue; } if (!empty($identifier_parts[4])) { $field_index = $identifier_parts[4]; } } else { // Item is an entity. preg_match("/^(.*)_(\\d+)\$/", $item['identifier'], $identifier_parts); if (!empty($identifier_parts[1])) { $entity_type = $identifier_parts[1]; } else { continue; } if (!empty($identifier_parts[2])) { $entity_id = $identifier_parts[2]; } else { continue; } } $vote_source = LIKEBTN_VOTING_VOTE_SOURCE; if ($field_id) { $vote_source = 'field_' . $field_id . '_index_' . $field_index; } $likes = 0; if (!empty($item['likes'])) { $likes = $item['likes']; } $dislikes = 0; if (!empty($item['dislikes'])) { $dislikes = $item['dislikes']; } // If vote for this entity/field has been already stored - continue. foreach ($votes as $vote) { if ($vote['entity_type'] == $entity_type && $vote['entity_id'] == $entity_id && $vote['vote_source'] == $vote_source) { continue 2; } } // Get entity info. try { $entity_type_info = entity_get_info($entity_type); if (empty($entity_type_info['controller class'])) { continue; } } catch (Exception $e) { continue; } // Likes and Disliked stored in Voting API. $votes[] = array('entity_type' => $entity_type, 'entity_id' => $entity_id, 'value_type' => 'points', 'value' => $likes, 'tag' => LIKEBTN_VOTING_TAG, 'uid' => 0, 'vote_source' => $vote_source); $votes[] = array('entity_type' => $entity_type, 'entity_id' => $entity_id, 'value_type' => 'points', 'value' => $dislikes * -1, 'tag' => LIKEBTN_VOTING_TAG, 'uid' => 0, 'vote_source' => $vote_source); // Remove (backup) votes cast on this entity by other modules. /*$remove_old_votes_fields = array( 'entity_type' => $entity_type . '_backup', ); try { db_update('votingapi_vote') ->fields($remove_old_votes_fields) ->condition('entity_type', $entity_type) ->condition('vote_source', array('like', 'dislike'), 'NOT IN') ->execute(); } catch (Exception $e) {} */ // Remove votes cast on this entity by the previous version // of the plugin, when vote_source was '' /*try { db_delete('votingapi_vote') ->condition('entity_type', $entity_type) ->condition('entity_id', $entity_id) ->condition('tag', 'vote') ->condition('vote_source', '') ->execute(); } catch (Exception $e) { } */ // Update LikeBtn fields. if ($vote_source) { $entities = entity_load($entity_type, array($entity_id)); if (empty($entities[$entity_id])) { continue; } $entity = $entities[$entity_id]; list($tmp_entity_id, $entity_revision_id, $bundle) = entity_extract_ids($entity_type, $entity); // Get entity LikeBtn fields. $entity_fields = field_info_instances($entity_type, $bundle); // Set field value. $likes_minus_dislikes = $likes - $dislikes; foreach ($entity_fields as $field_name => $field_info) { if ($field_info['widget']['module'] != 'likebtn') { continue; } $field_fields_data = array('entity_type' => $entity_type, 'bundle' => $bundle, 'entity_id' => $entity_id, 'revision_id' => $entity_id, 'delta' => $field_index, 'language' => isset($entity->language) ? $entity->language : LANGUAGE_NONE); $field_fields_data[$field_name . '_likebtn_likes'] = $likes; $field_fields_data[$field_name . '_likebtn_dislikes'] = $dislikes; $field_fields_data[$field_name . '_likebtn_likes_minus_dislikes'] = $likes_minus_dislikes; try { // Insert value. db_insert('field_data_' . $field_name)->fields($field_fields_data)->execute(); } catch (Exception $e) { // Update value. try { db_update('field_data_' . $field_name)->fields($field_fields_data)->condition('entity_type', $entity_type)->condition('bundle', $bundle)->condition('entity_id', $entity_id)->execute(); } catch (Exception $e) { } } } } } if ($votes) { // Prepare criteria for removing previous vote values. $criteria = array(); foreach ($votes as $vote) { $criteria[] = array('entity_type' => $vote['entity_type'], 'entity_id' => $vote['entity_id'], 'value_type' => $vote['value_type'], 'tag' => $vote['tag'], 'uid' => $vote['uid'], 'vote_source' => $vote['vote_source']); } // Votes must be saved altogether. votingapi_set_votes($votes, $criteria); return TRUE; } return FALSE; } }
/** * Loads a RestWS Schema object. * * @param int $id * The original entity ID. * * @return stdClass * An object matching the requested RestWS Schema object structure. */ protected function objectLoad($id) { $object = new stdClass(); // Get original entity. $original_wrapper = $this->originalWrapper($id); // If the wrapped entity is not of the correct bundle, bail now. if ($original_wrapper->getBundle() !== $this->bundleName) { return $object; } $original_properties = $original_wrapper->getPropertyInfo(); // Add to our object according to our defined API property info. if ($map = $this->apiMap[$this->resource()]) { foreach (array_keys($this->propertyInfo) as $property) { if (array_key_exists($map[$property], $original_properties)) { $value = $original_wrapper->{$map[$property]}->value(array('sanitize' => TRUE)); // Do some specific things for fields. if ($field = field_info_field($map[$property])) { // We assume the first column is the primary value column. This is // how Views gets the $real_field. // @see field_views_field_default_views_data() $column = key($field['columns']); } // For now make a quick check for references, and build an array of // reference objects. // @todo Abstract this by creating our own format handler, using // hook_restws_format_info_alter(), which extends RestWSFormatJSON, // and overrides RestWSBaseFormat::getResourceReferenceValue. if ($field && $field['type'] == 'entityreference' && ($type = $field['settings']['target_type'])) { // Return an array of values, regardless of field cardinality. $value = !is_array($value) ? array($value) : $value; $values = array(); foreach ($value as $item) { list($id, , $target_bundle) = entity_extract_ids($type, $item); $target_resource = NULL; // Get target resource from map. foreach ($this->apiMap as $r => $i) { if ($i['entity'] == $type && $i['bundle'] == $target_bundle) { $target_resource = $r; break; } } $values[] = (object) array('uri' => restws_resource_uri($target_resource, $id), 'resource' => $target_resource, 'id' => $id); } $value = $values; } elseif ($field && $field['type'] == 'image') { $values = array(); foreach ($value as $key => $item) { $values[$key] = array('alt' => $item['alt'], 'title' => $item['title'], 'mime' => $item['filemime']); $values[$key]['sizes']['original'] = array('uri' => file_uri_target($item['uri']), 'height' => $item['height'], 'width' => $item['width']); foreach (image_styles() as $style_name => $style) { $values[$key]['sizes'][$style_name] = array('uri' => image_style_url($style_name, $item['uri']), 'height' => $style['effects'][0]['data']['height'], 'width' => $style['effects'][0]['data']['width']); } } $value = $values; } elseif ($field && is_array($value)) { try { $value = $original_wrapper->{$map[$property]}->{$column}->value(array('decode' => TRUE)); } catch (EntityMetadataWrapperException $e) { } } $object->{$property} = $value; } } } return $object; }
function epf_preprocess_node(&$variables) { $node = $variables['node']; list(, , $bundle) = entity_extract_ids('node', $node); $output = ''; // $variables['ins']=$variables['content']['links']; foreach (field_info_instances('node', $bundle) as $instance) { if ($instance['field_name'] == 'authorname') { if (!empty($node->{$instance['field_name']})) { $variables['paper_authors'] = $node->{$instance['field_name']}['und'][0]['value']; } } if ($instance['field_name'] == 'field_reviewer') { if (!empty($node->{$instance['field_name']})) { $variables['reviewer'] = $node->{$instance['field_name']}['und'][0]['value']; } } if ($instance['field_name'] == 'datebegin') { if (!empty($node->{$instance['field_name']})) { $variables['datebegin'] = substr($node->{$instance['field_name']}['und'][0]['value'], 0, 10); } } if ($instance['field_name'] == 'dateend') { if (!empty($node->{$instance['field_name']})) { $variables['dateend'] = substr($node->{$instance['field_name']}['und'][0]['value'], 0, 10); } } if ($instance['field_name'] == 'city') { if (!empty($node->{$instance['field_name']})) { $variables['city'] = $node->{$instance['field_name']}['und'][0]['value']; } } if ($instance['field_name'] == 'website') { if (!empty($node->{$instance['field_name']})) { $variables['website'] = $node->{$instance['field_name']}['und'][0]['value']; } } if ($instance['widget']['module'] == 'arxiv') { if (!empty($node->{$instance['field_name']})) { $variables['paper_authors'] = $node->{$instance['field_name']}['und'][0]['authors']; } if (!empty($node->{$instance['field_name']}) && $node->{$instance['field_name']}['und'][0]['pdfUrl'] != '') { $output .= '<a href="' . url('/paper/download/' . $node->nid . '/pdf') . '" >pdf </a>'; } if (!empty($node->{$instance['field_name']}) && $node->{$instance['field_name']}['und'][0]['psUrl'] != '') { $output .= '<a href="' . url('/paper/download/' . $node->nid . '/ps') . '" >ps </a>'; } if (!empty($node->{$instance['field_name']}) && $node->{$instance['field_name']}['und'][0]['otherUrl'] != '') { $output .= '<a href="' . url('/paper/download/' . $node->nid . '/other') . '" >other </a>'; } } if ($instance['field_name'] == 'field_author') { if (!empty($node->{$instance['field_name']})) { $variables['paper_authors'] = $node->{$instance['field_name']}['und'][0]['value']; } } if ($instance['field_name'] == 'field_upload') { if (!empty($node->{$instance['field_name']}) && $node->{$instance['field_name']}['und'][0]['filename'] != '') { $url = file_create_url($node->{$instance['field_name']}['und'][0]['uri']); $output .= '<a href="' . url('/paper/download/' . $node->nid) . '" >download </a>'; } } if ($instance['field_name'] == 'field_prefix') { if (!empty($node->{$instance['field_name']})) { $variables['news_prefix'] = $node->{$instance['field_name']}['und'][0]['value']; } } } if (substr($node->type, 0, 5) == 'paper') { $statistics = statistics_get($node->nid); $obj = db_select('arxiv_downNo', 'm')->fields('m', array('downloadNo'))->condition('m.nid', $node->nid)->execute()->fetchAll(); if ($obj) { $variables['download'] = $output . ' (' . (empty($statistics['totalcount']) ? 0 : $statistics['totalcount']) . ' views, ' . $obj[0]->downloadNo . ' download, ' . $node->comment_count . ' comments)'; } else { $variables['download'] = $output . ' (' . (empty($statistics['totalcount']) ? 0 : $statistics['totalcount']) . ' views, 0 download, ' . $node->comment_count . ' comments)'; } } if ($variables['page']) { $variables['submitted'] = t('posted on !datetime', array('!datetime' => $variables['date'])); } else { $variables['submitted'] = t('posted by !username, !datetime', array('!username' => $variables['name'], '!datetime' => $variables['date'])); } }
/** * Implements EntityReferenceHandler::getReferencableEntities(). */ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { $display_name = $this->field['settings']['handler_settings']['view']['display_name']; $args = $this->field['settings']['handler_settings']['view']['args']; $result = array(); if ($this->initializeView($match, $match_operator, $limit)) { // Get the results. $result = $this->view->execute_display($display_name, $args); } $return = array(); if ($result) { $target_type = $this->field['settings']['target_type']; $entities = entity_load($target_type, array_keys($result)); foreach ($entities as $entity) { list($id, , $bundle) = entity_extract_ids($target_type, $entity); $return[$bundle][$id] = $result[$id]; } } return $return; }
/** * Determine if an entity is valid, and accessible. * * @param string $op * The operation to perform on the entity (view, update, delete). * @param int $entity_id * The entity ID. * * @return bool * TRUE if entity is valid, and user can access it. * * @throws UnprocessableEntityException * @throws InaccessibleRecordException */ protected function isValidEntity($op, $entity_id) { $entity_type = $this->entityType; if (!ctype_digit((string) $entity_id) || !($entity = entity_load_single($entity_type, $entity_id))) { // We need to check if the entity ID is numeric since if this is a uuid // that starts by the number 4, and there is an entity with ID 4 that // entity will be loaded incorrectly. throw new UnprocessableEntityException(sprintf('The entity ID %s does not exist.', $entity_id)); } list(, , $bundle) = entity_extract_ids($entity_type, $entity); if (!empty($this->bundles) && !in_array($bundle, $this->bundles)) { return FALSE; } if ($this->checkEntityAccess($op, $entity_type, $entity) === FALSE) { if ($op == 'view' && !$this->getResourcePath()) { // Just return FALSE, without an exception, for example when a list of // entities is requested, and we don't want to fail all the list because // of a single item without access. // Add the inaccessible item to the metadata to fix the record count in // the formatter. $inaccessible_records = $this->getMetadata()->get('inaccessible_records'); $inaccessible_records[] = array('resource' => $this->pluginId, 'id' => $entity_id); $this->getMetadata()->set('inaccessible_records', $inaccessible_records); return FALSE; } // Entity was explicitly requested so we need to throw an exception. throw new InaccessibleRecordException(sprintf('You do not have access to entity ID %s.', $entity_id)); } return TRUE; }
/** * Helper debugging function to easily show the contents fo a transition. */ public function dpm($function = '') { $transition = $this; $entity = $transition->getEntity(); $entity_type = $transition->entity_type; list($entity_id, , $entity_bundle) = $entity ? entity_extract_ids($entity_type, $entity) : array('', '', ''); $time = $transition->getTimestampFormatted(); // Do this extensive $user_name lines, for some troubles with Action. $user = $transition->getUser(); $user_name = $user ? $user->name : 'unknown username'; $t_string = get_class($this) . ' ' . (isset($this->hid) ? $this->hid : '') . ' ' . ($function ? "in function '{$function}'" : ''); $output[] = 'Entity = ' . (!$entity ? 'NULL' : $entity_type . '/' . $entity_bundle . '/' . $entity_id); $output[] = 'Field = ' . $transition->getFieldName(); $output[] = 'From/To = ' . $transition->old_sid . ' > ' . $transition->new_sid . ' @ ' . $time; $output[] = 'Comment = ' . $user_name . ' says: ' . $transition->getComment(); $output[] = 'Forced = ' . ($transition->isForced() ? 'yes' : 'no'); if (function_exists('dpm')) { dpm($output, $t_string); } }
/** * Preprocess the entity view mode template. */ public function preprocess_panelizer_view_mode(&$vars, $entity, $element, $panelizer, $info) { $vars['classes_array'][] = drupal_html_class($this->entity_type); $vars['classes_array'][] = drupal_html_class($this->entity_type . '-' . $element['#view_mode']); $vars['classes_array'][] = drupal_html_class($this->entity_type . '-' . $element['#panelizer_bundle']); $vars['classes_array'][] = drupal_html_class($this->entity_type . '-' . $element['#panelizer_entity_id']); if (!empty($entity->preview)) { $vars['classes_array'][] = drupal_html_class($this->entity_type . '-preview'); } if (!empty($panelizer->title_element)) { $vars['title_element'] = $panelizer->title_element; } else { $vars['title_element'] = 'h2'; } $vars['content'] = $info['content']; if (!empty($info['title'])) { $vars['title'] = $info['title']; } if (!empty($info['classes_array'])) { $vars['classes_array'] = array_merge($vars['classes_array'], $info['classes_array']); } if (!empty($panelizer->link_to_entity)) { list($entity_id, $revision_id, $bundle) = entity_extract_ids($this->entity_type, $entity); $bits = explode('/', $this->plugin['entity path']); foreach ($bits as $count => $bit) { if (strpos($bit, '%') === 0) { $bits[$count] = $entity_id; } } $vars['entity_url'] = url(implode('/', $bits)); } }
/** * Returns information about field instance. * * @param Entity $entityObject * Entity for which the field instance is to be returned. * @param string $field_name * Field name. * * @return array|null * An array of field instance information if the instance exists. NULL if * the field instance does not exist. */ public static function getFieldInstance(Entity $entityObject, $field_name) { list(, , $bundle) = entity_extract_ids($entityObject->getEntityType(), $entityObject->getEntity()); $instance = field_info_instance($entityObject->getEntityType(), $field_name, $bundle); return $instance; }
/** * Implements EntityReferenceHandler::getReferencableEntities(). */ public function getReferencableEntities($match = NULL, $match_operator = 'CONTAINS', $limit = 0) { $options = array(); $entity_type = $this->field['settings']['target_type']; $query = $this->buildEntityFieldQuery($match, $match_operator); if ($limit > 0) { $query->range(0, $limit); } $results = $query->execute(); if (!empty($results[$entity_type])) { $entities = entity_load($entity_type, array_keys($results[$entity_type])); foreach ($entities as $entity_id => $entity) { list(, , $bundle) = entity_extract_ids($entity_type, $entity); $options[$bundle][$entity_id] = check_plain($this->getLabel($entity)); } } return $options; }
public function getFieldInstances() { list(, , $bundle) = entity_extract_ids($this->entity_type, $this->entity); return field_info_instances($this->entity_type, $bundle); }