Checking caller of a hook Is it possible to know which code called a hook? I have two cases--one where I want to return, one where I want to continue.


Anonymous user views a page, thus firing hook_entity_load() (I want to deny this--return)
Cron creates page as anonymous user, thus firing hook_entity_load() (I want to accept this--continue)


If I can check to see if cron called the hook, I'll continue. Is there a way to do this?
I don't know of a "drupal" way to do this but The calling function will be in the backtrace. I have two helpers I use strictly for debugging. It's not a pretty solution but you might be able to check calling function.

Calling function:

// Returns the name of the calling function.
// Since this function call adds to the stack [0]
// The function calling this adds to the stack [1]
// That means [2] is the desired function name.
function getCallingFunction()
{
  $callers = debug_backtrace();
  return $callers[2]['function'];
}


Full stack:

// Returns the full stack.
function getCallingFunctionStack()
{
  $callers = debug_backtrace();
  $stack = array();
  foreach ($callers as $caller)
  {
    $stack[] = $caller['function'];
  }

  return implode('-&gt;', $stack);
}


I do not see a way to prove you are in a cron run but You can check if cron is running with:

if (!lock_acquire('cron', 0)) {
  // cron is running.
}


But this does not mean you are a cron user. It just means cron is running during this access attempt.

You could do something like store the cron session id in a variable on hook_cron_queue_info then check if that is the current session id. Kind of dirty but pretty much guarantees you are in cron.

Several other ideas can be found on this question.