You are here

function commerce_cart_commerce_entity_access_condition_commerce_order_alter in Commerce Core 7

Implements hook_commerce_entity_access_condition_commerce_order_alter().

This alter hook allows the Cart module to add conditions to the query used to determine if a user has view access to a given order. The Cart module will always grant users access to view their own carts (independent of any permission settings) and also grants anonymous users access to view their completed orders if they've been given the permission.

File

modules/cart/commerce_cart.module, line 1000
Implements the shopping cart system and add to cart features.

Code

function commerce_cart_commerce_entity_access_condition_commerce_order_alter(&$conditions, $context) {

  // Find the user's cart order ID and anonymous user's completed orders.
  $current_order_id = commerce_cart_order_id($context['account']->uid);
  $completed_order_ids = commerce_cart_order_session_order_ids(TRUE);

  // Always give the current user access to their own cart regardless of order
  // view permissions.
  if (!empty($current_order_id)) {
    $conditions
      ->condition($context['base_table'] . '.order_id', $current_order_id);
  }

  // Bail now if the access query is for an authenticated user or if the
  // anonymous user doesn't have any completed orders.
  if ($context['account']->uid || empty($completed_order_ids)) {
    return;
  }

  // If the user has access to view his own orders of any bundle...
  if (user_access('view own ' . $context['entity_type'] . ' entities', $context['account'])) {

    // Add a condition granting the user view access to any completed orders
    // in his session.
    $conditions
      ->condition($context['base_table'] . '.order_id', $completed_order_ids, 'IN');
  }

  // Add additional conditions on a per order bundle basis.
  $entity_info = entity_get_info($context['entity_type']);
  foreach ($entity_info['bundles'] as $bundle_name => $bundle_info) {

    // Otherwise if the user has access to view his own entities of the current
    // bundle, add an AND condition group that grants access if the entity
    // specified by the view query matches the same bundle and belongs to the user.
    if (user_access('view own ' . $context['entity_type'] . ' entities of bundle ' . $bundle_name, $context['account'])) {
      $conditions
        ->condition(db_and()
        ->condition($context['base_table'] . '.' . $entity_info['entity keys']['bundle'], $bundle_name)
        ->condition($context['base_table'] . '.order_id', $completed_order_ids, 'IN'));
    }
  }
}