2

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.

1 Answer 1

4

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
  ->fieldCondtition(...)
  ->addMetaData('account', user_load(1))
  ->execute();

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
  ->fieldCondition(...)
  ->addTag('DANGEROUS_ACCESS_CHECK_OPT_OUT')
  ->execute();

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();
  drupal_save_session(FALSE);
  $user = user_load(1);
  _mymodule_do_some_stuff();
  $user = $original_user;
  drupal_save_session($old_state);
}

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.

3
  • What are the differences between these 3 options? Are they functionally equivalent? Commented Feb 13, 2015 at 16:15
  • @aaronbauman - I added a comparison of the three options. Commented Feb 16, 2015 at 16:05
  • Thank you @AliceHeaton precisely what I needed to do in my code!
    – uotonyh
    Commented Apr 13, 2022 at 23:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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