I’ve got a small issue running the following query:

$qry = new EntityFieldQuery();
$qry->entityCondition('entity_type', 'node')
        ->propertyCondition('status', 1)
        ->propertyCondition('changed', $since, '>')
        ->fieldCondition('group_audience', 'gid', (array) $groups, 'IN' );

When I run this manually as user #1 it is all fine. When I run this through cron (which has no user) the organic group access control appears to forbid returning any results (based on no permissions for the current user I guess). This issue is with the last fieldCondition, when removed, it all works as expected.


Cron runs as the anomymous user. The idea is that it should only call APIs that don't require users. EntityFieldQuery however allows you to either bypass node access checks, or to set the user the query will run as.

Option 1: Set the user to run the query as:

$query = new EntityFieldQuery;
$result = $query
  ->addMetaData('account', user_load(1))

Option 2: Bypass node access by setting the DANGEROUS_ACCESS_CHECK_OPT_OUT tag (since Drupal 7.15 I believe)

$query = new EntityFieldQuery();
$result = $query

Option 3: You can run your cron code as another user by setting the $user global variable. For instance:

function mymodule_cron() {
  global $user;
  $original_user = $user;
  $old_state = drupal_save_session();
  $user = user_load(1);
  $user = $original_user;

Option 1 is the cleanest way to do what was requested - it relies on an existing functionality to run a query as a different user. You can use user 1, or create a custom user who has exactly the permissions you require for your operation.

Option 2 is functionally equivalent to using Option 1 with user 1. It is less flexible than option 1, so there isn't really a case to use it (but included here for completeness).

Option 1 and 2 are limited to entity field query, which is what the OP asked. To do other operations as another user, you need to impersonate that user completely - which is what Option 3 does.

  • What are the differences between these 3 options? Are they functionally equivalent? Feb 13 '15 at 16:15
  • @aaronbauman - I added a comparison of the three options. Feb 16 '15 at 16:05

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.