/**
  * Get the token string from the token entity.
  *
  * @param int $token_id
  *   The restful_token_auth entity.
  *
  * @return string
  *   The token string.
  */
 public static function getTokenFromEntity($token_id)
 {
     if ($token = entity_load_single('restful_token_auth', $token_id)) {
         return $token->token;
     }
     return NULL;
 }
 /**
  * Overrides EntityReferenceHandler::getLabel().
  */
 public function getLabel($entity) {
   $target_type = $this->field['settings']['target_type'];
   $field = $entity->{OG_AUDIENCE_FIELD};
   $gid = $field[LANGUAGE_NONE][0]['target_id'];
   $group = entity_load_single('node', $gid);
   return entity_label($target_type, $entity).' ('.entity_label('node', $group).')';
 }
 /**
  * {@inheritdoc}
  */
 public function authenticate(RequestInterface $request)
 {
     // Access token may be on the request, or in the headers.
     if (!($token = $this->extractToken($request))) {
         return NULL;
     }
     // Check if there is a token that has not expired yet.
     $query = new \EntityFieldQuery();
     $result = $query->entityCondition('entity_type', 'restful_token_auth')->entityCondition('bundle', 'access_token')->propertyCondition('token', $token)->range(0, 1)->execute();
     if (empty($result['restful_token_auth'])) {
         // No token exists.
         return NULL;
     }
     $id = key($result['restful_token_auth']);
     $auth_token = entity_load_single('restful_token_auth', $id);
     if (!empty($auth_token->expire) && $auth_token->expire < REQUEST_TIME) {
         // Token is expired.
         if (variable_get('restful_token_auth_delete_expired_tokens', TRUE)) {
             // Token has expired, so we can delete this token.
             $auth_token->delete();
         }
         return NULL;
     }
     return user_load($auth_token->uid);
 }
 /**
  * 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);
 }
 /**
  * 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;
 }
 /**
  * Get the difference in group audience for a saved field.
  *
  * @return
  *   Array with all the differences, or an empty array if none found.
  */
 public function groupAudiencegetDiff($entity_type, $entity, $field, $instance, $langcode, $items)
 {
     $return = FALSE;
     $field_name = $field['field_name'];
     $wrapper = entity_metadata_wrapper($entity_type, $entity);
     $og_memberships = $wrapper->{$field_name . '__og_membership'}->value();
     $new_memberships = array();
     foreach ($items as $item) {
         $new_memberships[$item['target_id']] = TRUE;
     }
     foreach ($og_memberships as $og_membership) {
         $gid = $og_membership->gid;
         if (empty($new_memberships[$gid])) {
             // Membership was deleted.
             if ($og_membership->entity_type == 'user') {
                 // Make sure this is not the group manager, if exists.
                 $group = entity_load_single($og_membership->group_type, $og_membership->gid);
                 if (!empty($group->uid) && $group->uid == $og_membership->etid) {
                     continue;
                 }
             }
             $return['delete'][] = $og_membership->id;
             unset($new_memberships[$gid]);
         } else {
             // Existing membership.
             unset($new_memberships[$gid]);
         }
     }
     if ($new_memberships) {
         // New memberships.
         $return['insert'] = array_keys($new_memberships);
     }
     return $return;
 }
 /**
  * Returns the user's billing cycle with the provided start time.
  *
  * If an existing billing cycle matches the expected start and end, it will
  * be returned. Otherwise, a new one will be created.
  *
  * @param $uid
  *   The uid of the user.
  * @param $start
  *   The unix timestamp when the billing cycle needs to start.
  * @param $save
  *   Whether to save the created billing cycle entity.
  *   Passing FALSE allows an unsaved billing cycle entity to be returned
  *   for estimation purposes.
  *
  * @return
  *   A cl_billing_cycle entity.
  */
 public function getBillingCycle($uid, $start = REQUEST_TIME, $save = TRUE)
 {
     // Make the billing cycle exactly 30 days long, so that it can be divided
     // predictably for prorating.
     // The 1 is substracted to make sure that the billing cycle ends 1s before
     // the next one starts
     $end = $start + 2592000 - 1;
     // Try to find an existing billing cycle matching our parameters.
     $query = new EntityFieldQuery();
     $query->entityCondition('entity_type', 'cl_billing_cycle')->entityCondition('bundle', $this->name)->propertyCondition('status', 1)->propertyCondition('uid', $uid);
     if ($start != REQUEST_TIME) {
         // In case of a custom start, make sure to match the exact billing cycle.
         // Ensures that new orders get the previous billing cycle created at the
         // start of testing, while getNextBillingCycle returns the expected result.
         $query->propertyCondition('start', $start);
     }
     $result = $query->execute();
     if ($result) {
         $billing_cycle_id = key($result['cl_billing_cycle']);
         $billing_cycle = entity_load_single('cl_billing_cycle', $billing_cycle_id);
     } else {
         // No existing billing cycle found. Create a new one.
         $billing_cycle = entity_create('cl_billing_cycle', array('type' => $this->name));
         $billing_cycle->uid = $uid;
         $billing_cycle->start = $start;
         $billing_cycle->end = $end;
         $billing_cycle->status = 1;
         if ($save) {
             $billing_cycle->save();
         }
     }
     return $billing_cycle;
 }
 /**
  * {@inheritdoc}
  */
 public function validate(&$value)
 {
     if (!empty($value['entity_type']) && !empty($value['entity_id'])) {
         $entity = entity_load_single($value['entity_type'], $value['entity_id']);
         if (!$entity) {
             $entity_types = $this->getEntityTypeOptions();
             return array(t('@entity_type with id @entity_id does not exist.', array('@entity_type' => $entity_types[$value['entity_type']], '@entity_id' => $value['entity_id'])));
         }
         $wrapper = entity_metadata_wrapper($value['entity_type'], $value['entity_id']);
         return parent::validate($wrapper);
     }
 }
Пример #9
0
 public function fetchSingle()
 {
     $query = $this->getEntityFieldQuery();
     $result = $query->execute();
     if (empty($result[$this->entityType])) {
         return null;
     } else {
         $keys = array_keys($result[$this->entityType]);
         $id = array_shift($keys);
         return entity_load_single($this->entityType, $id);
     }
 }
Пример #10
0
 /**
  * Sends the context messages back to Drupal's messaging system using
  * drupal_set_message.
  *
  * Please note that this is meant to be called before using drupal_goto()
  * to redirect the user to a result page.
  *
  * @param array $results The context from the batch operation.
  */
 public static function exportContextResults(array $results)
 {
     foreach ($results as $result) {
         if ($result['entity_id'] && $result['entity_type']) {
             $message = ':label [<strong>:type</strong> <code>:id</code>] !message';
             $arguments = array(':label' => entity_label($result['entity_type'], entity_load_single($result['entity_type'], $result['entity_id'])), ':type' => $result['entity_type'], ':id' => $result['entity_id'], '!message' => $result['message']);
         } else {
             $message = '!message';
             $arguments = array('!message' => $result['message']);
         }
         drupal_set_message(t($message, $arguments), $result['type']);
     }
 }
 /**
  * Implements FeedsEntityProcessorPropertyInterface::validate().
  */
 public function validate(&$value)
 {
     $info = $this->getPropertInfo();
     $entity_type = $info['type'];
     if ($value) {
         $entity = entity_load_single($entity_type, $value);
         if (!$entity) {
             $entity_info = entity_get_info();
             $entity_type_label = $entity_info[$entity_type]['label'];
             return array(t('@entity_type with id @entity_id does not exist.', array('@entity_type' => $entity_type_label, '@entity_id' => $value)));
         }
         $wrapper = entity_metadata_wrapper($entity_type, $value);
         return parent::validate($wrapper);
     }
 }
 /**
  * Displays the bean.
  */
 public function view($bean, $content, $view_mode = 'default', $langcode = NULL)
 {
     // Retrieve the terms from the loaded entity.
     $active_entity = bean_tax_active_entity_array();
     // Check for cached content on this block.
     $cache_name = 'bean_tax:listing:' . $bean->delta . ':' . $active_entity['type'] . ':' . $active_entity['ids'][0];
     if ($cache = cache_get($cache_name)) {
         $content = $cache->data;
     } else {
         // We need to make sure that the bean is configured correctly.
         if ($active_entity['type'] != 'bean' && !empty($bean->filters['vocabulary']) && (isset($active_entity['terms']) && count($active_entity['terms']))) {
             // Reformat vocabulary list from machine names to vocabulary vids.
             $vids = array();
             foreach ($bean->filters['vocabulary'] as $vm) {
                 $query = new EntityFieldQuery();
                 $result = $query->entityCondition('entity_type', 'taxonomy_vocabulary');
                 $query->propertyCondition('machine_name', $vm);
                 global $language;
                 if ($language->language != NULL && db_field_exists('taxonomy_vocabulary', 'language')) {
                     $query->propertyCondition('language', $language->language);
                 }
                 $result = $query->execute();
                 foreach ($result['taxonomy_vocabulary'] as $vocabulary) {
                     $vids[$vocabulary->vid] = $vocabulary->vid;
                 }
             }
             $i = 0;
             $content['terms'] = array();
             // Parse terms from correct vocabularies, limit list to X results.
             foreach ($active_entity['terms'] as $term) {
                 $term = entity_load_single('taxonomy_term', $term->tid);
                 if (in_array($term->vid, $vids) && $i < $bean->settings['records_shown']) {
                     $content['terms'][$term->tid] = entity_view('taxonomy_term', array($term->tid => $term), $bean->settings['term_view_mode']);
                     $i++;
                 }
             }
             cache_set($cache_name, $content, 'cache', time() + 60 * $bean->settings['cache_duration']);
         } elseif (isset($active_entity['type']) && $active_entity['type'] == 'bean' && $bean->bid === $active_entity['object']->bid) {
             $content['#markup'] = '';
         } elseif ($bean->settings['hide_empty'] || !$active_entity['object']) {
             return;
         } else {
             $content['#markup'] = t('No terms.');
         }
     }
     return $content;
 }
  /**
   * 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);
  }
  /**
   * {@inheritdoc}
   */
  public function authenticate(array $request = array(), $method = \RestfulInterface::GET) {
    $options = $this->getPluginKey('options');
    $key_name = !empty($options['param_name']) ? $options['param_name'] : 'access_token';
    $token = !empty($request['__application'][$key_name]) ? $request['__application'][$key_name] : $request[$key_name];

    // Check if there is a token that did not expire yet.

    $query = new EntityFieldQuery();
    $result = $query
      ->entityCondition('entity_type', 'restful_token_auth')
      ->entityCondition('bundle', 'access_token')
      ->propertyCondition('token', $token)
      ->range(0, 1)
      ->execute();


    if (empty($result['restful_token_auth'])) {
      // No token exists.
      return;
    }

    $id = key($result['restful_token_auth']);
    $auth_token = entity_load_single('restful_token_auth', $id);

    if (!empty($auth_token->expire) && $auth_token->expire < REQUEST_TIME) {
      // Token is expired.

      if (variable_get('restful_token_auth_delete_expired_tokens', TRUE)) {
        // Token has expired, so we can delete this token.
        $auth_token->delete();
      }

      return;
    }

    return user_load($auth_token->uid);
  }
  /**
   * 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);
  }
<?php

/**
 * @file
 * This template is used to print a single field in a view.
 *
 * It is not actually used in default Views, as this is registered as a theme
 * function which has better performance. For single overrides, the template is
 * perfectly okay.
 *
 * Variables available:
 * - $view: The view object
 * - $field: The field handler object that can process the input
 * - $row: The raw SQL result that can be used
 * - $output: The processed output that will normally be used.
 *
 * When fetching output from the $row, this construct should be used:
 * $data = $row->{$field->field_alias}
 *
 * The above will guarantee that you'll always get the correct data,
 * regardless of any changes in the aliasing that might happen if
 * the view is modified.
 */
$node = entity_load_single('node', $output);
$wrapper = entity_metadata_wrapper('node', $node);
$commerce_price_data = $wrapper->field_product_store[0]->commerce_price->value();
$commerce_price = commerce_currency_format($commerce_price_data['amount'], $commerce_price_data['currency_code']);
print $commerce_price;
Пример #17
0
 /**
  * Implements Drupal\configuration\Config\Configuration::saveToActiveStore().
  */
 public function saveToActiveStore(ConfigIteratorSettings &$settings)
 {
     $entity = $this->getData();
     $entity_type = $this->getComponent();
     if ($original = entity_load_single($entity_type, $this->getIdentifier())) {
         $entity->id = $original->id;
         unset($entity->is_new);
     }
     $entity->save();
     $settings->addInfo('imported', $this->getUniqueId());
 }
Пример #18
0
 * @see template_preprocess_entity()
 * @see template_process()
 */
?>
<div class="<?php 
print $classes;
?>
 clearfix"<?php 
print $attributes;
?>
>

  <?php 
$publisher_link = '#';
if ($ckan_dataset->publisher_id) {
    $publisher = entity_load_single('ckan_publisher', $ckan_dataset->publisher_id);
    $publisher_link = l($publisher->title, 'ckan_publisher/' . $ckan_dataset->publisher_id);
}
$author = user_load($ckan_dataset->uid);
print 'id: ' . $ckan_dataset->id . '<br />';
print 'ckan_id: ' . $ckan_dataset->ckan_id . '<br />';
print 'name: ' . $ckan_dataset->name . '<br />';
if ($author) {
    print 'published by: ' . l($author->name, 'user/' . $author->uid) . '<br />';
}
print 'publisher: ' . $publisher_link . '<br />';
print 'inventory: ' . $ckan_dataset->inventory . '<br />';
print 'notes: <br />' . $ckan_dataset->notes . '<br />';
?>

</div>
 /**
  * @see LdapAuthorizationConsumerAbstract::normalizeMappings
  */
 public function normalizeMappings($mappings)
 {
     $new_mappings = array();
     if ($this->ogVersion == 2) {
         $group_entity_types = og_get_all_group_bundle();
         foreach ($mappings as $i => $mapping) {
             $from = $mapping[0];
             $to = $mapping[1];
             $to_parts = explode('(raw: ', $to);
             $user_entered = $to_parts[0];
             $new_mapping = array('from' => $from, 'user_entered' => $user_entered, 'valid' => TRUE, 'error_message' => '');
             if (count($to_parts) == 2) {
                 // has simplified and normalized part in (). update normalized part as validation
                 $to_normalized = trim($to_parts[1], ')');
                 /**
                  * users (node:35:1)
                  * node:students (node:21:1)
                  * faculty (node:33:2)
                  * node:35:1 (node:35:1)
                  * node:35 (node:35:1)
                  */
                 $to_simplified = $to_parts[0];
                 $to_simplified_parts = explode(':', trim($to_simplified));
                 $entity_type = count($to_simplified_parts) == 1 ? 'node' : $to_simplified_parts[0];
                 $role = count($to_simplified_parts) < 3 ? OG_AUTHENTICATED_ROLE : $to_simplified_parts[2];
                 $group_name = count($to_simplified_parts) == 1 ? $to_simplified_parts[0] : $to_simplified_parts[1];
                 list($group_entity, $group_entity_id) = ldap_authorization_og2_get_group_from_name($entity_type, $group_name);
                 $to_simplified = join(':', array($entity_type, $group_name));
             } else {
                 // may be simplified or normalized, but not both
                 /**
                  * users
                  * node:students
                  * faculty
                  * node:35:1
                  * node:35
                  */
                 $to_parts = explode(':', trim($to));
                 $entity_type = count($to_parts) == 1 ? 'node' : $to_parts[0];
                 $role = count($to_parts) < 3 ? OG_AUTHENTICATED_ROLE : $to_parts[2];
                 $group_name_or_entity_id = count($to_parts) == 1 ? $to_parts[0] : $to_parts[1];
                 list($group_entity, $group_entity_id) = ldap_authorization_og2_get_group_from_name($entity_type, $group_name_or_entity_id);
                 if ($group_entity) {
                     // if load by name works, $group_name_or_entity_id is group title
                     $to_simplified = join(':', array($entity_type, $group_name_or_entity_id));
                 } else {
                     $to_simplified = FALSE;
                 }
                 $simplified = (bool) $group_entity;
                 if (!$group_entity && ($group_entity = @entity_load_single($entity_type, $group_name_or_entity_id))) {
                     $group_entity_id = $group_name_or_entity_id;
                 }
             }
             if (!$group_entity) {
                 $new_mapping['normalized'] = FALSE;
                 $new_mapping['simplified'] = FALSE;
                 $new_mapping['valid'] = FALSE;
                 $new_mapping['error_message'] = t("cannot find matching group: !to", array('!to' => $to));
             } else {
                 $role_id = is_numeric($role) ? $role : ldap_authorization_og2_rid_from_role_name($entity_type, $group_entity->type, $group_entity_id, $role);
                 $roles = og_roles($entity_type, isset($group_entity->type) ? $group_entity->type : NULL, 0, FALSE, TRUE);
                 $role_name = is_numeric($role) ? $roles[$role] : $role;
                 $to_normalized = join(':', array($entity_type, $group_entity_id, $role_id));
                 $to_simplified = $to_simplified ? $to_simplified . ':' . $role_name : $to_normalized;
                 $new_mapping['normalized'] = $to_normalized;
                 $new_mapping['simplified'] = $to_simplified;
                 if ($to == $to_normalized) {
                     /**  if not using simplified notation, do not convert to simplified.
                            this would create a situation where an og group
                            can change its title and the authorizations change when the
                            admin specified the group by entity id
                          */
                     $new_mapping['user_entered'] = $to;
                 } else {
                     $new_mapping['user_entered'] = $to_simplified . ' (raw: ' . $to_normalized . ')';
                 }
             }
             $new_mappings[] = $new_mapping;
         }
     } else {
         // og 1
         foreach ($mappings as $i => $mapping) {
             $new_mapping = array('from' => $mapping[0], 'user_entered' => $mapping[1], 'normalized' => NULL, 'simplified' => NULL, 'valid' => TRUE, 'error_message' => '');
             $gid = NULL;
             $rid = NULL;
             $correct_syntax = "gid=43,rid=2 or group-name=students,role-name=member or node.title=students,role-name=member";
             $incorrect_syntax = t('Incorrect mapping syntax.  Correct examples are:') . $correct_syntax;
             $targets = explode(',', $mapping[1]);
             if (count($targets) != 2) {
                 $new_mapping['valid'] = FALSE;
                 $new_mapping['error_message'] = $incorrect_syntax;
                 continue;
             }
             $group_target_and_value = explode('=', $targets[0]);
             if (count($group_target_and_value) != 2) {
                 $new_mapping['valid'] = FALSE;
                 $new_mapping['error_message'] = $incorrect_syntax;
                 continue;
             }
             list($group_target, $group_target_value) = $group_target_and_value;
             $role_target_and_value = explode('=', $targets[1]);
             if (count($role_target_and_value) != 2) {
                 $new_mapping['valid'] = FALSE;
                 $new_mapping['error_message'] = $incorrect_syntax;
                 continue;
             }
             list($role_target, $role_target_value) = $role_target_and_value;
             $og_group = FALSE;
             if ($group_target == 'gid') {
                 $gid = $group_target_value;
             } elseif ($group_target == 'group-name') {
                 list($og_group, $og_node) = ldap_authorization_og1_get_group($group_target_value, 'group_name', 'object');
                 if (is_object($og_group) && property_exists($og_group, 'gid') && $og_group->gid) {
                     $gid = $og_group->gid;
                 }
             } else {
                 $entity_type_and_field = explode('.', $group_target);
                 if (count($entity_type_and_field) != 2) {
                     $new_mapping['valid'] = FALSE;
                     $new_mapping['error_message'] = $incorrect_syntax;
                     continue;
                 }
                 list($entity_type, $field) = $entity_type_and_field;
                 $query = new EntityFieldQuery();
                 $query->entityCondition('entity_type', $entity_type)->fieldCondition($field, 'value', $group_target_value, '=')->addMetaData('account', user_load(1));
                 // run the query as user 1
                 $result = $query->execute();
                 if (is_array($result) && isset($result[$entity_type]) && count($result[$entity_type]) == 1) {
                     $entities = array_keys($result[$entity_type]);
                     $gid = ldap_authorization_og1_entity_id_to_gid($entities[0]);
                 }
             }
             if (!$og_group && $gid) {
                 $og_group = og_load($gid);
             }
             if ($role_target == 'rid') {
                 $role_name = ldap_authorization_og1_role_name_from_rid($role_target_value);
                 $rid = $role_target_value;
             } elseif ($role_target == 'role-name') {
                 $rid = ldap_authorization_og_rid_from_role_name($role_target_value);
                 $role_name = $role_target_value;
             }
             $new_mapping['simplified'] = $og_group->label . ', ' . $role_name;
             $new_mapping['normalized'] = $gid && $rid ? ldap_authorization_og_authorization_id($gid, $rid) : FALSE;
             $new_mappings[] = $new_mapping;
         }
     }
     return $new_mappings;
 }
 /**
  * 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;
 }
Пример #21
0
 /**
  * Set the Transitions $entity.
  *
  * @param string $entity_type
  *   The entity type of the entity.
  * @param mixed $entity
  *   The Entity ID or the Entity object, to add to the Transition.
  *
  * @return object $entity
  *   The Entity, that is added to the Transition.
  */
 public function setEntity($entity_type, $entity)
 {
     if (!is_object($entity)) {
         $entity_id = $entity;
         // Use node API or Entity API to load the object first.
         $entity = entity_load_single($entity_type, $entity_id);
     }
     $this->entity = $entity;
     $this->entity_type = $entity_type;
     list($this->entity_id, $this->revision_id, ) = entity_extract_ids($entity_type, $entity);
     // For backwards compatibility, set nid.
     $this->nid = $this->entity_id;
     return $this->entity;
 }
 /**
  * Private execute method. We don't expose this as it has different return types based on its parameters.
  * @param  boolean $first_result_only Are we only interested in the first results?
  * @return array of EntityDecorator subclass instances or a single instance
  */
 private function executePrivate($first_result_only = FALSE)
 {
     $class = $this->class;
     $result = $this->query->execute();
     if (isset($result[$this->entityType])) {
         if ($first_result_only) {
             $entity_id = current(array_keys($result[$this->entityType]));
             $entity = entity_load_single($this->entityType, $entity_id);
             return $class::buildFromEntity($entity);
         }
         $entities = entity_load($this->entityType, array_keys($result[$this->entityType]));
         return array_map(function ($entity) use($class) {
             return $class::buildFromEntity($entity);
         }, $entities);
     }
     // Fall through return empty array or NULL by default.
     if ($first_result_only) {
         return NULL;
     } else {
         return array();
     }
 }
 public function statusSuccess(\Payment $payment)
 {
     // If the webform submission is still in progress
     // webform_client_form_submit will set the proper redirect
     // otherwise we need to redirect immediately:
     if (!$this->form_state) {
         $page_num = $this->component['page_num'];
         $page_finished = TRUE;
         foreach ($this->submission->webform->componentsByType('paymethod_select') as $cid => $component) {
             if ($cid != $this->component['cid'] && $component['page_num'] == $page_num) {
                 $component_finished = FALSE;
                 if (($pid = $this->submission->valueByCid($cid)) && is_numeric($pid)) {
                     if ($other_payment = entity_load_single('payment', $pid)) {
                         $component_finished = payment_status_is_or_has_ancestor($other_payment->getStatus(), PAYMENT_STATUS_SUCCESS);
                     }
                 }
                 if (!$component_finished) {
                     $page_finished = FALSE;
                     break;
                 }
             }
         }
         if (!$page_finished) {
             drupal_set_message(t('Payment processed successfully.'));
             $this->reenterWebform($page_num);
         } else {
             $node = $this->submission->webform->node;
             $last_component = end($node->webform['components']);
             if ($page_num == $last_component['page_num']) {
                 // @TODO: Store and check what the original form action was.
                 //        Only call finishWebform if it wasn't a "save as draft".
                 $this->finishWebform();
             } else {
                 $this->reenterWebform($page_num + 1);
             }
         }
     }
 }
Пример #24
0
 /**
  * Implements hook_field_update() -> FieldItemInterface::update().
  *
  * @todo: in course of time, this is not used anymore...
  * It is called also from hook_field_insert(), since we need $nid to store {workflow_node_history}.
  * We cannot use hook_field_presave(), since $nid is not yet known at that moment.
  *
  * "Contrary to the old D7 hooks, the methods do not receive the parent entity
  * "or the langcode of the field values as parameters. If needed, those can be accessed
  * "by the getEntity() and getLangcode() methods on the Field and FieldItem classes.
  */
 public function update(&$items)
 {
     // ($entity_type, $entity, $field, $instance, $langcode, &$items) {
     // @todo: apparently, in course of time, this is not used anymore. Restore or remove.
     $field_name = $this->field['field_name'];
     // $field['settings']['wid'] can be numeric or named.
     $workflow = workflow_load_single($this->field['settings']['wid']);
     $wid = $workflow->wid;
     // @todo D8: remove below lines.
     $entity = $this->entity;
     $entity_type = $this->entity_type;
     $entity_id = entity_id($entity_type, $entity);
     if (!$entity) {
         // No entity available, we are on the field Settings page - 'default value' field.
         // This is hidden from the admin, because the default value can be different for every user.
     } elseif (!$entity_id && $entity_type == 'comment') {
         // Not possible: a comment on a non-existent node.
     } elseif ($entity_id && $this->entity_type == 'comment') {
         // This happens when we are on an entity's comment.
         $referenced_entity_type = 'node';
         // Comments only exist on nodes.
         $referenced_entity = entity_load_single($referenced_entity_type, $entity_id);
         // Comments only exist on nodes.
         // Submit the data. $items is reset by reference to normal value, and is magically saved by the field itself.
         $form = array();
         $form_state = array();
         $widget = new WorkflowDefaultWidget($this->field, $this->instance, $referenced_entity_type, $referenced_entity);
         $widget->submit($form, $form_state, $items);
         // $items is a proprietary D7 parameter.
         // Remember: we are on a comment form, so the comment is saved automatically, but the referenced entity is not.
         // @todo: probably we'd like to do this form within the Widget, but
         // $todo: that does not know wether we are on a comment or a node form.
         //
         // Widget::submit() returns the new value in a 'sane' state.
         // Save the referenced entity, but only is transition succeeded, and is not scheduled.
         $old_sid = _workflow_get_sid_by_items($referenced_entity->{$field_name}[LANGUAGE_NONE]);
         $new_sid = _workflow_get_sid_by_items($items);
         if ($old_sid != $new_sid) {
             $referenced_entity->{$field_name}[LANGUAGE_NONE] = $items;
             entity_save($referenced_entity_type, $referenced_entity);
         }
     } elseif ($this->entity_type != 'comment') {
         if (isset($items[0]['value'])) {
             // A 'normal' options.module-widget is used, and $items[0]['value'] is already properly set.
         } elseif (isset($items[0]['workflow'])) {
             // The WorkflowDefaultWidget is used.
             // Submit the data. $items is reset by reference to normal value, and is magically saved by the field itself.
             $form = array();
             $form_state = array();
             $widget = new WorkflowDefaultWidget($this->field, $this->instance, $entity_type, $entity);
             $widget->submit($form, $form_state, $items);
             // $items is a proprietary D7 parameter.
         } else {
             drupal_set_message(t('error in WorkfowItem->update()'), 'error');
         }
     }
     // A 'normal' node add page.
     // We should not be here, since we only do inserts after $entity_id is known.
     // $current_sid = workflow_load_single($wid)->getCreationSid();
 }
Пример #25
0
 /**
  * Deactivate a Workflow State, moving existing nodes to a given State.
  *
  * @param int $new_sid
  *   The state ID, to which all affected entities must be moved.
  *
  * D7.x-2.x: deprecated workflow_delete_workflow_states_by_sid() --> WorkflowState->deactivate() + delete()
  */
 public function deactivate($new_sid)
 {
     global $user;
     // We can use global, since deactivate() is a UI-only function.
     $current_sid = $this->sid;
     $force = TRUE;
     // Notify interested modules. We notify first to allow access to data before we zap it.
     // E.g., Node API (@todo Field API):
     // - re-parents any nodes that we don't want to orphan, whilst deactivating a State.
     // - delete any lingering node to state values.
     module_invoke_all('workflow', 'state delete', $current_sid, $new_sid, NULL, $force);
     // Re-parent any nodes that we don't want to orphan, whilst deactivating a State.
     // This is called in WorkflowState::deactivate().
     // @todo: re-parent Workflow Field, whilst deactivating a state.
     if ($new_sid) {
         // A candidate for the batch API.
         // @TODO: Future updates should seriously consider setting this with batch.
         $comment = t('Previous state deleted');
         foreach (workflow_get_workflow_node_by_sid($current_sid) as $workflow_node) {
             // @todo: add Field support in 'state delete', by using workflow_node_history or reading current field.
             $entity_type = 'node';
             $entity = entity_load_single('node', $workflow_node->nid);
             $field_name = '';
             $transition = new WorkflowTransition();
             $transition->setValues($entity_type, $entity, $field_name, $current_sid, $new_sid, $user->uid, REQUEST_TIME, $comment);
             $transition->force($force);
             // Execute Transition, invoke 'pre' and 'post' events, save new state in workflow_node, save also in workflow_node_history.
             // For Workflow Node, only {workflow_node} and {workflow_node_history} are updated. For Field, also the Entity itself.
             $new_sid = workflow_execute_transition($entity_type, $entity, $field_name, $transition, $force);
         }
     }
     // Delete any lingering node to state values.
     workflow_delete_workflow_node_by_sid($current_sid);
     // Delete the transitions this state is involved in.
     $workflow = workflow_load_single($this->wid);
     /* @var $transition WorkflowTransition */
     foreach ($workflow->getTransitionsBySid($current_sid, 'ALL') as $transition) {
         $transition->delete();
     }
     foreach ($workflow->getTransitionsByTargetSid($current_sid, 'ALL') as $transition) {
         $transition->delete();
     }
     // Delete the state. -- We don't actually delete, just deactivate.
     // This is a matter up for some debate, to delete or not to delete, since this
     // causes name conflicts for states. In the meantime, we just stick with what we know.
     // If you really want to delete the states, use workflow_cleanup module, or delete().
     $this->status = FALSE;
     $this->save();
     // Clear the cache.
     self::getStates(0, TRUE);
 }
Пример #26
0
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'ckan_publisher')->propertyCondition('parent_id', $ckan_publisher->id)->execute();
if (isset($result['ckan_publisher'])) {
    print '<br />child_publishers: <br />';
    foreach ($result['ckan_publisher'] as $key => $value) {
        $child = entity_load_single('ckan_publisher', $key);
        $link = l($child->title, 'ckan_publisher/' . $key);
        print $link . '<br />';
    }
}
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'ckan_dataset')->propertyCondition('publisher_id', $ckan_publisher->id)->execute();
if (isset($result['ckan_dataset'])) {
    print '<br />datasets: <br />';
    foreach ($result['ckan_dataset'] as $key => $value) {
        $dataset = entity_load_single('ckan_dataset', $key);
        // It gets altered in dgu_dataset feature;
        $ckan_link = l($dataset->title, 'ckan_dataset/' . $key);
        $drupal_link = ' | <a href="/ckan_dataset/' . $dataset->id . '">[show in drupal]</a>';
        print $ckan_link . $drupal_link . '<br />';
    }
}
$query = new EntityFieldQuery();
$result = $query->entityCondition('entity_type', 'user')->fieldCondition('field_publishers', 'target_id', $ckan_publisher->id)->execute();
if (isset($result['user'])) {
    print '<br />users: <br />';
    foreach ($result['user'] as $key => $value) {
        $user = user_load($key);
        $link = l($user->name, 'user/' . $key);
        print $link . '<br />';
    }
Пример #27
0
 /**
  * Function to set variables up before form is built
  *
  * @return void
  * @access public
  */
 function preProcess()
 {
     $this->_action = CRM_Utils_Request::retrieve('action', 'String', $this);
     $this->_jobHoursTime = CRM_Hrjobcontract_Page_JobContractTab::getJobHoursTime();
     $this->assign('jobHoursTime', $this->_jobHoursTime);
     $this->_aid = CRM_Utils_Request::retrieve('aid', 'Int', $this);
     $session = CRM_Core_Session::singleton();
     $this->_loginUserID = $session->get('userID');
     if (CRM_Utils_Request::retrieve('cid', 'Positive', $this)) {
         $this->assign('contactId', CRM_Utils_Request::retrieve('cid', 'Positive', $this));
     }
     $activityTypes = CRM_Core_PseudoConstant::activityType();
     $resultHoliday = civicrm_api3('Activity', 'get', array('activity_type_id' => array_search('Public Holiday', $activityTypes)));
     $publicHolidays = array();
     foreach ($resultHoliday['values'] as $key => $val) {
         $pubDate = date("M j, Y", strtotime($val['activity_date_time']));
         $publicHolidays[$pubDate] = $val['subject'];
     }
     $publicHolidays = json_encode($publicHolidays);
     $this->assign('publicHolidays', $publicHolidays);
     // Load the activity entity
     $main_activity = entity_load_single('civicrm_activity', $this->_aid);
     // Check if attachment is set
     if (isset($main_activity->field_attachment['und'][0]['uri'])) {
         $imgpath = $main_activity->field_attachment['und'][0]['uri'];
         $markup = '<div class="show-attached-file"><div class="show-attached-file-label"><b>' . t('Attached file: ') . '</b></div>' . l("View Attachment", file_create_url($imgpath), array('html' => TRUE, 'attributes' => array('target' => '_blank'))) . '</div>';
     } else {
         $markup = ts('No File Attached!');
     }
     // Assign the attached file URL
     $this->assign('attachedFile', $markup);
     if ($this->_action == CRM_Core_Action::VIEW || $this->_action == CRM_Core_Action::UPDATE) {
         $this->_activityId = CRM_Utils_Request::retrieve('aid', 'String', $this);
         $this->assign('upActivityId', $this->_activityId);
         $resultAct = civicrm_api3('Activity', 'get', array('sequential' => 1, 'id' => $this->_activityId, 'return.target_contact_id' => 1, 'return.assignee_contact_id' => 1, 'return.source_contact_id' => 1, 'option.limit' => 365));
         $this->_activityTypeID = $resultAct['values'][0]['activity_type_id'];
         $this->_targetContactID = $resultAct['values'][0]['target_contact_id'][0];
         $this->_actStatusId = $resultAct['values'][0]['status_id'];
         //condition to check if it has any manager against this absence
         if (array_key_exists(0, $resultAct['values'][0]['assignee_contact_id'])) {
             $this->_managerContactID = self::getManagerContacts($this->_targetContactID);
         }
         //Mode is edit if user has edit or admisniter permission or is manager to this absence or
         //(target/requested user and action is update and has manage own Absence permission)
         //(else mode is view if the action is view or already reviewed) and has (view permission
         //or (manage own absence permission and logged in user is target contact itself)
         $absenceStatuses = CRM_HRAbsence_BAO_HRAbsenceType::getActivityStatus();
         if (CRM_Core_Permission::check('administer CiviCRM') || CRM_Core_Permission::check('edit HRAbsences') || in_array($this->_loginUserID, $this->_managerContactID) || $absenceStatuses[$this->_actStatusId] == 'Requested' && $this->_action == CRM_Core_Action::UPDATE && $this->_targetContactID == $this->_loginUserID && CRM_Core_Permission::check('manage own HRAbsences')) {
             $this->_mode = 'edit';
         } elseif (($this->_action == CRM_Core_Action::VIEW || $absenceStatuses[$this->_actStatusId] != 'Requested') && (CRM_Core_Permission::check('view HRAbsences') || CRM_Core_Permission::check('manage own HRAbsences') && ($this->_targetContactID = $this->_loginUserID))) {
             $this->_mode = 'view';
         }
         //check for ACL View/Edit permission
         if (empty($this->_mode)) {
             if (self::isContactAccessible($this->_targetContactID) == CRM_Core_Permission::EDIT) {
                 $this->_mode = 'edit';
             } elseif (self::isContactAccessible($this->_targetContactID) == CRM_Core_Permission::VIEW) {
                 $this->_mode = 'view';
             }
         }
         $displayName = CRM_Contact_BAO_Contact::displayName($this->_targetContactID);
         $activityTypes = CRM_HRAbsence_BAO_HRAbsenceType::getActivityTypes();
         $activityType = $activityTypes[$this->_activityTypeID];
         $activity = CRM_HRAbsence_BAO_HRAbsenceType::getActivityStatus();
         $activityStatus = $activity[$this->_actStatusId];
         CRM_Utils_System::setTitle(ts("Absence for  %1 (%2, %3)", array(1 => $displayName, 2 => $activityType, 3 => $activityStatus)));
         if ($this->_action == CRM_Core_Action::VIEW) {
             $groupTree = CRM_Core_BAO_CustomGroup::getTree('Activity', $this, $this->_activityId, 0, $this->_activityTypeID);
             CRM_Core_BAO_CustomGroup::buildCustomDataView($this, $groupTree);
         } else {
             $this->assign('activityType', $this->_activityTypeID);
             CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeID, 1, 'Activity', $this->_activityId, TRUE);
             $this->assign('customValueCount', $this->_customValueCount);
         }
     } elseif ($this->_action == CRM_Core_Action::ADD) {
         $this->_mode = 'edit';
         CRM_Utils_System::setTitle(ts('Absence Request: Add'));
         $this->_activityTypeID = CRM_Utils_Request::retrieve('atype', 'Positive', $this);
         if ($this->_activityTypeID) {
             //only custom data has preprocess hence directly call it
             $this->assign('activityType', $this->_activityTypeID);
             CRM_Custom_Form_CustomData::preProcess($this, NULL, $this->_activityTypeID, 1, 'Activity', NULL, TRUE);
             $this->assign('customValueCount', $this->_customValueCount);
         }
         $this->_targetContactID = 0;
         if (CRM_Utils_Request::retrieve('cid', 'Positive', $this) !== NULL) {
             $this->_targetContactID = CRM_Utils_Request::retrieve('cid', 'Positive', $this);
         } else {
             //if there is no cid passed then consider target contact as logged in user
             //who will applying leave for himself
             $this->_targetContactID = $this->_loginUserID;
         }
         $this->_managerContactID = self::getManagerContacts($this->_targetContactID);
     }
     $this->assign('mode', $this->_mode);
     CRM_Core_Resources::singleton()->addStyleFile('org.civicrm.hrabsence', 'css/hrabsence.css');
     parent::preProcess();
 }
 /**
  * Return the related entities as rendered HTML markup.
  */
 private function returnMarkup($bean, $result)
 {
     // Start counting results at index of 0.
     $i = 0;
     // Set and index for actual results shown.
     $shown = 0;
     // Set markup array as empty.
     $markup = '';
     // Load and render the related entities.
     foreach ($result as $entity) {
         if (isset($entity['id']) && $shown < $bean->filters['records_shown'] && $i >= $bean->filters['offset_results']) {
             $entity = entity_load_single($bean->settings['entity_type'], $entity['id']);
             $entity_view = entity_view($bean->settings['entity_type'], array($entity), $bean->settings['entity_view_mode']);
             $markup .= drupal_render($entity_view);
             $shown++;
         }
         // Count continues along...
         $i++;
     }
     return $markup;
 }
Пример #29
0
 /**
  * {@inheritdoc}
  */
 public function loadRateLimitEntity($account = NULL)
 {
     $query = new \EntityFieldQuery();
     $results = $query->entityCondition('entity_type', 'rate_limit')->entityCondition('bundle', $this->getPluginId())->propertyCondition('identifier', $this->generateIdentifier($account))->execute();
     if (empty($results['rate_limit'])) {
         return NULL;
     }
     $rlid = key($results['rate_limit']);
     return entity_load_single('rate_limit', $rlid);
 }
Пример #30
0
if ($user->uid == 1 || in_array('data publisher', array_values($user->roles))) {
    ?>
            <span class="dropdown">
              <a class="nav-publisher btn btn-info dropdown-button" data-toggle="dropdown" href="#"><i class="icon-wrench"></i></a>
              <ul class="dropdown-menu dgu-user-dropdown" role="menu" aria-labelledby="dLabel">
                <li role="presentation" class="dropdown-header">Tools</li>
                <li><a href="/dataset/new">Add a Dataset</a></li>
                <li><a href="/harvest">Dataset Harvesting</a></li>
                <li role="presentation" class="dropdown-header">My publishers</li>
                <?php 
    if (!empty($user->field_publishers)) {
        foreach ($user->field_publishers[LANGUAGE_NONE] as $publisher_ref) {
            ?>

                  <?php 
            $publisher = entity_load_single('ckan_publisher', $publisher_ref['target_id']);
            ?>

                  <li><a href="/publisher/<?php 
            print $publisher->name;
            ?>
"><?php 
            print $publisher->title;
            ?>
</a></li>
                <?php 
        }
    }
    ?>
              </ul>
            </span>