<?php
/**
 * Ajax test cases
 *
 * @package    WordPress
 * @subpackage Unit Tests
 * @since      3.4.0
 */

/**
 * Sample blog data
 */
include_once(DIR_TESTDATA . '/sample_blogs.php');

/**
 * Admin ajax functions to be tested
 */
include_once( ABSPATH . 'wp-admin/includes/ajax-actions.php' );

/**
 * Exception for cases of wp_die()
 *
 * @package    WordPress
 * @subpackage Unit Tests
 * @since      3.4.0
 */
class WPAjaxDieException extends Exception {}

/**
 * Ajax test case class
 *
 * @package    WordPress
 * @subpackage Unit Tests
 * @since      3.4.0
 */
class AjaxTest extends _WPDataset2 {
	
	/**
	 * Last AJAX response.  This is set via echo -or- wp_die.
	 * @var type 
	 */
	protected $_last_response = '';

	/**
	 * List of ajax actions called via POST
	 * @var type 
	 */
	protected $_core_actions_get = array( 'fetch-list', 'ajax-tag-search', 'compression-test', 'imgedit-preview', 'oembed_cache' );

	/**
	 * List of ajax actions called via GET
	 * @var type 
	 */
	protected $_core_actions_post = array(
		'oembed_cache', 'image-editor', 'delete-comment', 'delete-tag', 'delete-link',
		'delete-meta', 'delete-post', 'trash-post', 'untrash-post', 'delete-page', 'dim-comment',
		'add-link-category', 'add-tag', 'get-tagcloud', 'get-comments', 'replyto-comment',
		'edit-comment', 'add-menu-item', 'add-meta', 'add-user', 'autosave', 'closed-postboxes',
		'hidden-columns', 'update-welcome-panel', 'menu-get-metabox', 'wp-link-ajax',
		'menu-locations-save', 'menu-quick-search', 'meta-box-order', 'get-permalink',
		'sample-permalink', 'inline-save', 'inline-save-tax', 'find_posts', 'widgets-order',
		'save-widget', 'set-post-thumbnail', 'date_format', 'time_format', 'wp-fullscreen-save-post',
		'wp-remove-post-lock', 'dismiss-wp-pointer',
	);

	/**
	 * Constructor.
	 * Register all of the ajax actions
	 */
	public function __construct() {
		parent::__construct();
		foreach ( array_merge( $this->_core_actions_get, $this->_core_actions_post ) as $action )
			if ( function_exists( 'wp_ajax_' . str_replace( '-', '_', $action ) ) )
				add_action( 'wp_ajax_' . $action, 'wp_ajax_' . str_replace( '-', '_', $action ), 1 );
	}

	/**
	 * Set up the test fixture.  Override wp_die()'s behavior
	 */
	public function setUp() {
		parent::setUp();
		add_filter( 'wp_die_ajax_handler', array( $this, 'getDieHandler' ), 1, 1 );
		if ( !defined( 'DOING_AJAX' ) )
			define( 'DOING_AJAX', true );
	}
	
	/**
	 * Tear down the test fixture.  Reset $_POST, and restore wp_die()'s behavior
	 */
	public function tearDown() {
		$_POST = array();
		remove_filter( 'wp_die_ajax_handler', array( $this, 'getDieHandler' ), 1, 1 );
	}

	/**
	 * Return our callback handler
	 * @return callback
	 */
	public function getDieHandler() {
		return array( $this, 'dieHandler' );
	}

	/**
	 * Handler for wp_die()
	 * Save the output for analysis, stop execution by throwing an exception.
	 * If you're testing ajax and you expect wp_die(<anything>), you must use:
	 * <code>
	 * $this->setExpectedException('WPAjaxDieException');
	 * $this->assertEquals(<anything>, $this->_last_message);
	 * </code>
	 * @param string $message 
	 */
	public function dieHandler( $message ) {
		$this->_last_response = $message;
		if ( !empty( $message ) )
			throw new WPAjaxDieException( $message );
	}

	/**
	 * Switch between user roles
	 * E.g. administrator, editor, author, contributor, subscriber
	 * @param string $role 
	 */
	protected function _setRole( $role ) {
		$post = $_POST;
		$user_id = $this->_make_user( $role );
		wp_set_current_user( $user_id );
		$_POST = array_merge($_POST, $post);
	}

	/**
	 * Mimic the ajax handling of admin-ajax.php
	 * Capture the output via output buffering, and if there is any, store
	 * it in $this->_last_message.
	 * @param string $action 
	 */
	protected function _handleAjax($action) {
		
		// Start output buffering
		ob_start();

		// Build the request
		$_POST['action'] = $action;
		$_GET['action']  = $action;
		$_REQUEST        = array_merge( $_POST, $_GET );

		// Call the hooks
		do_action( 'admin_init' );
		do_action( 'wp_ajax_' . $_REQUEST['action'], $_REQUEST['action'] );

		// Save the output
		$buffer = ob_get_clean();		
		if ( !empty($buffer) )
			$this->_last_response = $buffer;
	}
}

/**
 * Testing ajax comment functionality
 *
 * @package    WordPress
 * @subpackage Unit Tests
 * @since      3.4.0
 */
class TestAjaxComments extends AjaxTest {
	
	/**
	 * List of comments
	 * @var array
	 */
	protected $_comments = array();

	/**
	 * Set up the test fixture
	 */
	public function setUp() {
		parent::setUp();
		$this->_comments = get_comments(array(
			'status'  => 'all',
			'search'  => '',
			'user_id' => '',
			'offset'  => 2,
			'number'  => 20,
			'post_id' => 0,
			'type'    => '',
			'orderby' => '',
			'order'   => ''
		));
	}

	/**
	 * Delete a comment as an administrator (expects success)
	 */
	public function test_ajax_trash_comment_as_admin() {

		// Become an administrator
		$this->_setRole( 'administrator' );

		// Set up the $_POST request
		$comment              = $this->_comments[0];
		$_POST['id']          = $comment->comment_ID;
		$_POST['_ajax_nonce'] = wp_create_nonce( 'delete-comment_' . $comment->comment_ID );
		$_POST['trash']       = 1;
		$_POST['_total']      = wp_count_comments( 0 );
		$_POST['_per_page']   = 20;
		$_POST['_page']       = 2;
		$_POST['_url']        = admin_url( 'edit-comments.php' );
		
		// Make the request
		$this->_handleAjax( 'delete-comment' );

		// Get the response
		$xml = simplexml_load_string( $this->_last_response, 'SimpleXMLElement', LIBXML_NOCDATA );
		
		// Ensure everything is correct
		$this->assertEquals( $xml->response[0]->comment['id'], $comment->comment_ID );
		$this->assertEquals( $xml->response['action'], 'delete-comment_' . $comment->comment_ID );
		$this->assertGreaterThanOrEqual( time() - 10, (int) $xml->response[0]->comment[0]->supplemental[0]->time[0] );
		$this->assertLessThanOrEqual( time(), (int) $xml->response[0]->comment[0]->supplemental[0]->time[0] );
	}

	/**
	 * Delete a comment as a subscriber (expects permission denied)
	 */
	public function test_ajax_trash_comment_as_subscriber() {
	
		// Become a subscriber		
		$this->_setRole( 'subscriber' );

		// Set up the $_POST request
		$comment              = $this->_comments[1];
		$_POST['id']          = $comment->comment_ID;
		$_POST['_ajax_nonce'] = wp_create_nonce( 'delete-comment_' . $comment->comment_ID );
		$_POST['trash']       = 1;
		$_POST['_total']      = wp_count_comments( 0 );
		$_POST['_per_page']   = 20;
		$_POST['_page']       = 2;
		$_POST['_url']        = admin_url( 'edit-comments.php' );
		
		// Make the request
		$this->setExpectedException( 'WPAjaxDieException' );
		$this->_handleAjax( 'delete-comment' );

		// Get the response
		$this->assertEquals( -1, $this->_last_response );
	}

	/**
	 * @todo wp_ajax_dim_comment()
	 * @todo wp_ajax_get_comments()
	 * @todo wp_ajax_replyto_comment()
	 * @todo wp_ajax_edit_comment()
	 */
}
