<?php
/*
Plugin Name: WP_Meta_Box
Plugin URI: http://wordpress.org/
Description: The WP_Meta_Box class in development for 3.3.
Version: 0.1
Author: The WordPress Team
*/

class WP_Meta_Box {
	/**
	 * The screen where the meta box will be shown.
	 */
	public $screen;

	/**
	 * A unique slug to allow multiple meta boxes of the same class
	 * to exist on the same screen.
	 */
	public $slug;

	/**
	 * A unique identifier for the meta box.
	 *
	 * A string composed from the meta box class, screen, and slug.
	 */
	public $unique_id;

	/**
	 * Arguments passed to the meta box constructor.
	 */
	public $args;

	/**
	 * A registry that tracks each meta box instance.
	 *
	 * @var WP_Meta_Box_Registry
	 */
	private $registry;


	/**
	 * Constructor.
	 *
	 * Any subclasses MUST call parent::_construct( $screen, $args ).
	 *
	 * @param string $screen - The ID (string) for the screen where the meta box will be shown.
	 * @param array  $args - An array of supplied arguments. Optional.
	 *
	 * $args recognized by default:
	 *    title    - The title of the meta box.
	 *    context  - The context within the page where the box should show ('normal', 'advanced').
	 *    priority - The priority within the context where the boxes should show ('high', 'low').
	 *    slug     - A unique string to identify the meta box.
	 */
	public function __construct( $screen, $args = array() ) {
		// Set variables
		$this->screen = $screen;
		$this->slug   = empty( $args['slug'] ) ? '' : $args['slug'];

		// Remove slug from args
		unset( $args['slug'] );

		// Set default args
		$defaults = array(
			'title'         => __( 'Untitled' , 'wordcampbase'),
			'context'       => 'side',
			'priority'      => 'default',
		);
		$this->args = wp_parse_args( $args, $defaults );

		// Add the meta box to the registry.
		// Generates a slug if one doesn't already exist.
		$this->registry = WP_Meta_Box_Registry::instance();
		$this->registry->add( $this );

		// Construct the meta box's unique ID.
		$this->unique_id = get_class( $this ) . "_{$this->screen}_{$this->slug}";

		// Bind hooks
		add_action( 'admin_init',            array( $this, '_register' ) );
		add_action( 'admin_enqueue_scripts', array( $this, '_enqueue_scripts' ) );
	}

	/**
	 * Remove the meta box.
	 */
	public function remove() {
		// Make sure we've removed any data from the registry.
		$this->registry->remove( $this );

		// Unbind actions.
		remove_action( 'admin_init',            array( $this, '_register' ) );
		remove_action( 'admin_enqueue_scripts', array( $this, '_enqueue_scripts' ) );
	}

	/**
	 * Render the meta box. Implement in a subclass.
	 */
	protected function render() {}

	/**
	 * Save the meta box. Implement in a subclass.
	 */
	protected function save() {}

	/**
	 * Fires when the meta box is registered. Override in a subclass.
	 */
	protected function register() {}

	/**
	 * Enqueue meta box scripts. Override in a subclass.
	 */
	protected function enqueue_scripts() {}

	/**
	 * Determine whether the meta box will be saved. Override in a subclass.
	 *
	 * Return true to save, false to cancel.
	 */
	protected function maybe_save() {
		return true;
	}

	/**
	 * Add an action to trigger save.
	 *
	 * Due to the different types of meta boxes, save will not be triggered by default.
	 */
	public function add_save_action( $name, $priority=10 ) {
		add_action( $name, array( $this, '_save' ), $priority, 99 ); // Effectively infinite args.
	}

	/**
	 * Remove a save action.
	 */
	public function remove_save_action( $name, $priority=10 ) {
		remove_action( $name, array( $this, '_save' ), $priority, 99 ); // Effectively infinite args.
	}


	/* =====================================================================
	 * INTERNAL FUNCTIONS
	 * ===================================================================== */

	/**
	 * Internal function. Registers the meta box.
	 */
	public final function _register() {
		$id = "{$this->unique_id}-meta-box";

		add_meta_box( $id, $this->args['title'], array( $this, '_render' ),
			$this->screen, $this->args['context'], $this->args['priority'],
			$this->args );

		$this->register();
	}

	/**
	 * Internal function. Ensures scripts are only loaded when necessary.
	 */
	public final function _enqueue_scripts() {
		$current_screen = get_current_screen();

		if ( isset( $current_screen ) && $this->screen == $current_screen->id )
			$this->enqueue_scripts();
	}

	/**
	 * Internal function, initiates the rendering process.
	 */
	public final function _render( $object, $box ) {
		wp_nonce_field( "{$this->unique_id}_nonce", "_wpnonce_{$this->unique_id}", false );

		$this->render();
	}

	/**
	 * Internal function, initiates the saving process.
	 */
	public final function _save() {
		// Nonce check (sorry, you don't have a choice about this one).
		check_admin_referer( "{$this->unique_id}_nonce", "_wpnonce_{$this->unique_id}" );

		$args = func_get_args();

		// Only save if maybe_save returns true.
		if ( call_user_func_array( array( $this, 'maybe_save' ), $args ) )
			call_user_func_array( array( $this, 'save' ), $args );
	}
}


/**
 * Meta Box Registry
 *
 * Implemented as singleton
 *
 */
class WP_Meta_Box_Registry {

	/**
	 * WP_Meta_Box_Registry singleton implementation
	 *
	 * @var WP_Meta_Box_Registry
	 */
	private static $instance;

	private $instances = array();

	/**
	 * WP_Meta_Box_Registry singleton implementation
	 *
	 * @return WP_Meta_Box_Registry
	 */
	public static function instance() {
		if (null === self::$instance)
			self::$instance = new self();
		return self::$instance;
	}

	/**
	 * Search registry for meta box instances
	 *
	 * @return array result
	 */
	public function search($class_or_object, $screen = false, $slug = false) {
		$instances = array();

		foreach($this->instances as $instance) {

			if ( ! $instance instanceof $class_or_object )
				continue;

			if ( $screen !== false && $instance->screen !== $screen )
				continue;

			if ( $slug !== false && $instance->slug !== $slug )
				continue;

			$instances[] = $instance;
		}

		return $instances;
	}

	/**
	 * Adds a meta box instance.
	 *
	 * If $instance->slug is defined, will use $slug.
	 * If a meta box with the same slug exists, it will be overwritten.
	 *
	 * @param WP_Meta_Box $instance
	 */
	public function add( WP_Meta_Box $instance ) {
		static $counter = 0;

		$hash = spl_object_hash( $instance );

		if ( !empty( $instance->slug ) ) {
			// If slug is specified, remove existing instance
			$instances = $this->find($instance, $instance->screen, $instance->slug);

			if ($instances) 
				$this->remove($instances[0]);

		} else {
			// If no slug is specified, get the numerical index.
			// alternatively get the number of this instances' class by screen and count plus one.
			$instance->slug = ++$counter;
		}

		$this->instances[ $hash ] = $instance;
	}

	// in case this is still needed.
	public function get( WP_Meta_Box $instance ) {
		$hash = spl_object_hash( $instance );

		if ( isset( $this->instances[ $hash ] ) )
			return $instance;

		return false;
	}

	/**
	 * Remove instance from registry
	 *
	 * @param WP_Meta_Box $instance
	 */
	public function remove( WP_Meta_Box $instance ) {
		$hash = spl_object_hash( $instance );

		if ( isset( $this->instances[ $hash ] ) )
			unset( $this->instances[ $hash ] );
	}
}



class WP_CPT_Meta_Box extends WP_Meta_Box {
	function __construct( $screen, $args = array() ) {
		// Call the WP_Meta_Box constructor.
		parent::__construct( $screen, $args );

		// Save the meta box contents when 'save_post' is triggered.
		$this->add_save_action( 'save_post' );
	}

	function maybe_save( $post_id, $post ) {
		// Bail if we're autosaving
		if ( defined( 'DOING_AUTOSAVE' ) && DOING_AUTOSAVE )
			return;

		// @TODO Add revision check

		// Cap check
		if ( ! current_user_can( 'edit_post', $post_id ) )
			return;

		return true;
	}
}