<?php
// $Id: trigger.test,v 1.31 2010/04/10 10:49:15 dries Exp $

/**
 * Class with common helper methods.
 */
class TriggerWebTestCase extends DrupalWebTestCase {

  /**
   * Configure an advanced action.
   *
   * @param $action
   *   The name of the action callback. For example: 'user_block_user_action'
   * @param $edit
   *   The $edit array for the form to be used to configure.
   *   Example members would be 'actions_label' (always), 'message', etc.
   * @return
   *   the aid (action id) of the configured action, or FALSE if none.
   */
  protected function configureAdvancedAction($action, $edit) {
    // Create an advanced action.
    $hash = md5($action);
    $this->drupalPost("admin/config/system/actions/configure/$hash", $edit, t('Save'));
    $this->assertText(t('The action has been successfully saved.'));

    // Now we have to find out the action ID of what we created.
    return db_query('SELECT aid FROM {actions} WHERE callback = :callback AND label = :label', array(':callback' => $action, ':label' => $edit['actions_label']))->fetchField();
  }

}

/**
 * Test node triggers.
 */
class TriggerContentTestCase extends TriggerWebTestCase {
  var $_cleanup_roles = array();
  var $_cleanup_users = array();

  public static function getInfo() {
    return array(
      'name' => 'Trigger content (node) actions',
      'description' => 'Perform various tests with content actions.',
      'group' => 'Trigger',
    );
  }

  function setUp() {
    parent::setUp('trigger', 'trigger_test');
  }

  /**
   * Various tests, all in one function to assure they happen in the right order.
   */
  function testActionsContent() {
    global $user;
    $content_actions = array('node_publish_action', 'node_unpublish_action', 'node_make_sticky_action', 'node_make_unsticky_action', 'node_promote_action', 'node_unpromote_action');

    $test_user = $this->drupalCreateUser(array('administer actions'));
    $web_user = $this->drupalCreateUser(array('create page content', 'access content', 'administer nodes'));
    foreach ($content_actions as $action) {
      $hash = md5($action);
      $info = $this->actionInfo($action);

      // Assign an action to a trigger, then pull the trigger, and make sure
      // the actions fire.
      $this->drupalLogin($test_user);
      $edit = array('aid' => $hash);
      $this->drupalPost('admin/structure/trigger/node', $edit, t('Assign'), array(), array(), 'trigger-node-presave-assign-form');
      // Create an unpublished node.
      $this->drupalLogin($web_user);
      $edit = array();
      $langcode = LANGUAGE_NONE;
      $edit["title"] = '!SimpleTest test node! ' . $this->randomName(10);
      $edit["body[$langcode][0][value]"] = '!SimpleTest test body! ' . $this->randomName(32) . ' ' . $this->randomName(32);
      $edit[$info['property']] = !$info['expected'];
      $this->drupalPost('node/add/page', $edit, t('Save'));
      // Make sure the text we want appears.
      $this->assertRaw(t('!post %title has been created.', array('!post' => 'Basic page', '%title' => $edit["title"])), t('Make sure the Basic page has actually been created'));
      // Action should have been fired.
      $loaded_node = $this->drupalGetNodeByTitle($edit["title"]);
      $this->assertTrue($loaded_node->$info['property'] == $info['expected'], t('Make sure the @action action fired.', array('@action' => $info['name'])));
      // Leave action assigned for next test

      // There should be an error when the action is assigned to the trigger
      // twice.
      $this->drupalLogin($test_user);
      // This action already assigned in this test.
      $edit = array('aid' => $hash);
      $this->drupalPost('admin/structure/trigger/node', $edit, t('Assign'), array(), array(), 'trigger-node-presave-assign-form');
      $this->assertRaw(t('The action you chose is already assigned to that trigger.'), t('Check to make sure an error occurs when assigning an action to a trigger twice.'));

      // The action should be able to be unassigned from a trigger.
      $this->drupalPost('admin/structure/trigger/unassign/node/node_presave/' . $hash, array(), t('Unassign'));
      $this->assertRaw(t('Action %action has been unassigned.', array('%action' => ucfirst($info['name']))), t('Check to make sure the @action action can be unassigned from the trigger.', array('@action' => $info['name'])));
      $assigned = db_query("SELECT COUNT(*) FROM {trigger_assignments} WHERE aid IN (:keys)", array(':keys' => $content_actions))->fetchField();
      $this->assertFalse($assigned, t('Check to make sure unassign worked properly at the database level.'));
    }
  }

  /**
   * Test that node actions are fired for each node individually if acting on
   * multiple nodes.
   */
  function testActionContentMultiple() {
    // Assign an action to the node save/update trigger.
    $test_user = $this->drupalCreateUser(array('administer actions', 'administer nodes', 'create page content', 'access administration pages', 'access content overview'));
    $this->drupalLogin($test_user);

    for ($index = 0; $index < 3; $index++) {
      $edit = array('title' => $this->randomName());
      $this->drupalPost('node/add/page', $edit, t('Save'));
    }

    $action_id = 'trigger_test_generic_any_action';
    $hash = md5($action_id);
    $edit = array('aid' => $hash);
    $this->drupalPost('admin/structure/trigger/node', $edit, t('Assign'), array(), array(), 'trigger-node-update-assign-form');

    $edit = array(
      'operation' => 'unpublish',
      'nodes[1]' => TRUE,
      'nodes[2]' => TRUE,
    );
    $this->drupalPost('admin/content', $edit, t('Update'));
    $count = variable_get('trigger_test_generic_any_action', 0);
    $this->assertTrue($count == 2, t('Action was triggered 2 times. Actual: %count', array('%count' => $count)));
  }

  /**
   * Helper function for testActionsContent(): returns some info about each of the content actions.
   *
   * @param $action
   *   The name of the action to return info about.
   * @return
   *   An associative array of info about the action.
   */
  function actionInfo($action) {
    $info = array(
      'node_publish_action' => array(
        'property' => 'status',
        'expected' => 1,
        'name' => t('publish content'),
      ),
      'node_unpublish_action' => array(
        'property' => 'status',
        'expected' => 0,
        'name' => t('unpublish content'),
      ),
      'node_make_sticky_action' => array(
        'property' => 'sticky',
        'expected' => 1,
        'name' => t('make content sticky'),
      ),
      'node_make_unsticky_action' => array(
        'property' => 'sticky',
        'expected' => 0,
        'name' => t('make content unsticky'),
      ),
      'node_promote_action' => array(
        'property' => 'promote',
        'expected' => 1,
        'name' => t('promote content to front page'),
      ),
      'node_unpromote_action' => array(
        'property' => 'promote',
        'expected' => 0,
        'name' => t('remove content from front page'),
      ),
    );
    return $info[$action];
  }
}

/**
 * Test cron trigger.
 */
class TriggerCronTestCase extends TriggerWebTestCase {
  public static function getInfo() {
    return array(
      'name' => 'Trigger cron (system) actions',
      'description' => 'Perform various tests with cron trigger.',
      'group' => 'Trigger',
    );
  }

  function setUp() {
    parent::setUp('trigger', 'trigger_test');
  }

  /**
   * Test assigning multiple actions to the cron trigger.
   *
   * This test ensures that both simple and multiple complex actions
   * succeed properly. This is done in the cron trigger test because
   * cron allows passing multiple actions in at once.
   */
  function testActionsCron() {
    // Create an administrative user.
    $test_user = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($test_user);

    // Assign a non-configurable action to the cron run trigger.
    $edit = array('aid' => md5('trigger_test_system_cron_action'));
    $this->drupalPost('admin/structure/trigger/system', $edit, t('Assign'), array(), array(), 'trigger-cron-assign-form');

    // Assign a configurable action to the cron trigger.
    $action_label = $this->randomName();
    $edit = array(
      'actions_label' => $action_label,
      'subject' => $action_label,
    );
    $aid = $this->configureAdvancedAction('trigger_test_system_cron_conf_action', $edit);
    // $aid is likely 3 but if we add more uses for the sequences table in
    // core it might break, so it is easier to get the value from the database.
    $edit = array('aid' => md5($aid));
    $this->drupalPost('admin/structure/trigger/system', $edit, t('Assign'), array(), array(), 'trigger-cron-assign-form');

    // Add a second configurable action to the cron trigger.
    $action_label = $this->randomName();
    $edit = array(
      'actions_label' => $action_label,
      'subject' => $action_label,
    );
    $aid = $this->configureAdvancedAction('trigger_test_system_cron_conf_action', $edit);
    $edit = array('aid' => md5($aid));
    $this->drupalPost('admin/structure/trigger/system', $edit, t('Assign'), array(), array(), 'trigger-cron-assign-form');

    // Force a cron run.
    $this->cronRun();

    // Make sure the non-configurable action has fired.
    $action_run = variable_get('trigger_test_system_cron_action', FALSE);
    $this->assertTrue($action_run, t('Check that the cron run triggered the test action.'));

    // Make sure that both configurable actions have fired.
    $action_run = variable_get('trigger_test_system_cron_conf_action', 0) == 2;
    $this->assertTrue($action_run, t('Check that the cron run triggered both complex actions.'));
  }
}

/**
 * Test other triggers.
 */
class TriggerOtherTestCase extends TriggerWebTestCase {
  var $_cleanup_roles = array();
  var $_cleanup_users = array();

  public static function getInfo() {
    return array(
      'name' => 'Trigger other actions',
      'description' => 'Test triggering of user, comment, taxonomy actions.',
      'group' => 'Trigger',
    );
  }

  function setUp() {
    parent::setUp('trigger', 'trigger_test', 'contact');
  }

  /**
   * Test triggering on user create and user login.
   */
  function testActionsUser() {
    // Assign an action to the create user trigger.
    $test_user = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($test_user);
    $action_id = 'trigger_test_generic_action';
    $hash = md5($action_id);
    $edit = array('aid' => $hash);
    $this->drupalPost('admin/structure/trigger/user', $edit, t('Assign'), array(), array(), 'trigger-user-insert-assign-form');

    // Set action variable to FALSE.
    variable_set( $action_id, FALSE );

    // Create an unblocked user
    $web_user = $this->drupalCreateUser(array('administer users'));
    $this->drupalLogin($web_user);
    $name = $this->randomName();
    $pass = user_password();
    $edit = array();
    $edit['name'] = $name;
    $edit['mail'] = $name . '@example.com';
    $edit['pass[pass1]'] = $pass;
    $edit['pass[pass2]'] = $pass;
    $edit['status'] = 1;
    $this->drupalPost('admin/people/create', $edit, t('Create new account'));

    // Verify that the action variable has been set.
    $this->assertTrue(variable_get($action_id, FALSE), t('Check that creating a user triggered the test action.'));

    // Reset the action variable.
    variable_set($action_id, FALSE);

    $this->drupalLogin($test_user);
    // Assign a configurable action 'System message' to the user_login trigger.
    $action_edit = array(
      'actions_label' => $this->randomName(16),
      'message' => t("You have logged in:") . $this->randomName(16),
    );

    // Configure an advanced action that we can assign.
    $aid = $this->configureAdvancedAction('system_message_action', $action_edit);
    $edit = array('aid' => md5($aid));
    $this->drupalPost('admin/structure/trigger/user', $edit, t('Assign'), array(), array(), 'trigger-user-login-assign-form');

    // Verify that the action has been assigned to the correct hook.
    $actions = trigger_get_assigned_actions('user_login');
    $this->assertEqual(1, count($actions), t('One Action assigned to the hook'));
    $this->assertEqual($actions[$aid]['label'], $action_edit['actions_label'], t('Correct action label found.'));

    // User should get the configured message at login.
    $contact_user = $this->drupalCreateUser(array('access site-wide contact form'));;
    $this->drupalLogin($contact_user);
    $this->assertText($action_edit['message']);
  }

  /**
   * Test triggering on comment save.
   */
  function testActionsComment() {
    // Assign an action to the comment save trigger.
    $test_user = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($test_user);
    $action_id = 'trigger_test_generic_action';
    $hash = md5($action_id);
    $edit = array('aid' => $hash);
    $this->drupalPost('admin/structure/trigger/comment', $edit, t('Assign'), array(), array(), 'trigger-comment-insert-assign-form');

    // Set action variable to FALSE.
    variable_set($action_id, FALSE);

    // Create a node and add a comment to it.
    $web_user = $this->drupalCreateUser(array('create article content', 'access content', 'post comments without approval', 'post comments'));
    $this->drupalLogin($web_user);
    $node = $this->drupalCreateNode(array('type' => 'article', 'promote' => 1));
    $edit = array();
    $edit['subject'] = $this->randomName(10);
    $edit['comment_body[' . LANGUAGE_NONE . '][0][value]'] = $this->randomName(10) . ' ' . $this->randomName(10);
    $this->drupalGet('comment/reply/' . $node->nid);
    $this->drupalPost(NULL, $edit, t('Save'));

    // Verify that the action variable has been set.
    $this->assertTrue(variable_get($action_id, FALSE), t('Check that creating a comment triggered the action.'));
  }

  /**
   * Test triggering on taxonomy new term.
   */
  function testActionsTaxonomy() {
    // Assign an action to the taxonomy term save trigger.
    $test_user = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($test_user);
    $action_id = 'trigger_test_generic_action';
    $hash = md5($action_id);
    $edit = array('aid' => $hash);
    $this->drupalPost('admin/structure/trigger/taxonomy', $edit, t('Assign'), array(), array(), 'trigger-taxonomy-term-insert-assign-form');

    // Set action variable to FALSE.
    variable_set($action_id, FALSE);

    // Create a taxonomy vocabulary and add a term to it.

    // Create a vocabulary.
    $vocabulary = new stdClass();
    $vocabulary->name = $this->randomName();
    $vocabulary->description = $this->randomName();
    $vocabulary->machine_name = drupal_strtolower($this->randomName());
    $vocabulary->help = '';
    $vocabulary->nodes = array('article' => 'article');
    $vocabulary->weight = mt_rand(0, 10);
    taxonomy_vocabulary_save($vocabulary);

    $term = new stdClass();
    $term->name = $this->randomName();
    $term->vid = $vocabulary->vid;
    taxonomy_term_save($term);

    // Verify that the action variable has been set.
    $this->assertTrue(variable_get($action_id, FALSE), t('Check that creating a taxonomy term triggered the action.'));
  }

}

/**
 * Test that orphaned actions are properly handled.
 */
class TriggerOrphanedActionsTestCase extends DrupalWebTestCase {

  public static function getInfo() {
    return array(
      'name' => 'Trigger orphaned actions',
      'description' => 'Test triggering an action that has since been removed.',
      'group' => 'Trigger',
    );
  }

  function setUp() {
    parent::setUp('trigger', 'trigger_test');
  }

  /**
   * Test logic around orphaned actions.
   */
  function testActionsOrphaned() {
    $action = 'trigger_test_generic_any_action';
    $hash = md5($action);

    // Assign an action from a disable-able module to a trigger, then pull the
    // trigger, and make sure the actions fire.
    $test_user = $this->drupalCreateUser(array('administer actions'));
    $this->drupalLogin($test_user);
    $edit = array('aid' => $hash);
    $this->drupalPost('admin/structure/trigger/node', $edit, t('Assign'), array(), array(), 'trigger-node-presave-assign-form');

    // Create an unpublished node.
    $web_user = $this->drupalCreateUser(array('create page content', 'edit own page content', 'access content', 'administer nodes'));
    $this->drupalLogin($web_user);
    $edit = array();
    $langcode = LANGUAGE_NONE;
    $edit["title"] = '!SimpleTest test node! ' . $this->randomName(10);
    $edit["body[$langcode][0][value]"] = '!SimpleTest test body! ' . $this->randomName(32) . ' ' . $this->randomName(32);
    $this->drupalPost('node/add/page', $edit, t('Save'));
    $this->assertRaw(t('!post %title has been created.', array('!post' => 'Basic page', '%title' => $edit["title"])), t('Make sure the Basic page has actually been created'));

    // Action should have been fired.
    $this->assertTrue(variable_get('trigger_test_generic_any_action', FALSE), t('Trigger test action successfully fired.'));

    // Disable the module that provides the action and make sure the trigger
    // doesn't white screen.
    module_disable(array('trigger_test'));
    $loaded_node = $this->drupalGetNodeByTitle($edit["title"]);
    $edit["body[$langcode][0][value]"] = '!SimpleTest test body! ' . $this->randomName(32) . ' ' . $this->randomName(32);
    $this->drupalPost("node/$loaded_node->nid/edit", $edit, t('Save'));

    // If the node body was updated successfully we have dealt with the
    // unavailable action.
    $this->assertRaw(t('!post %title has been updated.', array('!post' => 'Basic page', '%title' => $edit["title"])), t('Make sure the Basic page can be updated with the missing trigger function.'));
  }
}
