<?php

/**
 * Implements hook_trigger_info().
 */
function actions_loop_test_trigger_info() {
  return array(
    'actions_loop_test' => array(
      'watchdog' => array(
        'label' => t('When a message is logged'),
      ),
    ),
  );
}

/**
 * Implements hook_watchdog().
 */
function actions_loop_test_watchdog(array $log_entry) {
  // If the triggering actions are not explicitly enabled, abort.
  if (empty($_GET['trigger_actions_on_watchdog'])) {
    return;
  }
  // Get all the action ids assigned to the trigger on the watchdog hook's
  // "run" event.
  $aids = trigger_get_assigned_actions('watchdog');
  // We can pass in any applicable information in $context. There isn't much in
  // this case, but we'll pass in the hook name as the bare minimum.
  $context = array(
    'hook' => 'watchdog',
  );
  // Fire the actions on the associated object ($log_entry) and the context
  // variable.
  actions_do(array_keys($aids), $log_entry, $context);
}

/**
 * Implements hook_init().
 */
function actions_loop_test_init() {
  if (!empty($_GET['trigger_actions_on_watchdog'])) {
    watchdog_skip_semaphore('actions_loop_test', 'Triggering action loop');
  }
}

/**
 * Implements hook_action_info().
 */
function actions_loop_test_action_info() {
  return array(
    'actions_loop_test_log' => array(
      'label' => t('Write a message to the log.'),
      'type' => 'system',
      'configurable' => FALSE,
      'triggers' => array('any'),
    ),
  );
}

/**
 * Write a message to the log.
 */
function actions_loop_test_log() {
  $count = &drupal_static(__FUNCTION__, 0);
  $count++;
  watchdog_skip_semaphore('actions_loop_test', "Test log #$count");
}

/**
 * Replacement of the watchdog() function that eliminates the use of semaphores
 * so that we can test the abortion of an action loop.
 */
function watchdog_skip_semaphore($type, $message, $variables = array(), $severity = WATCHDOG_NOTICE, $link = NULL) {
  global $user, $base_root;

  // Prepare the fields to be logged
  $log_entry = array(
    'type'        => $type,
    'message'     => $message,
    'variables'   => $variables,
    'severity'    => $severity,
    'link'        => $link,
    'user'        => $user,
    'uid'         => isset($user->uid) ? $user->uid : 0,
    'request_uri' => $base_root . request_uri(),
    'referer'     => $_SERVER['HTTP_REFERER'],
    'ip'          => ip_address(),
    'timestamp'   => REQUEST_TIME,
  );

  // Call the logging hooks to log/process the message
  foreach (module_implements('watchdog') as $module) {
    module_invoke($module, 'watchdog', $log_entry);
  }
}
