<?php
/**
 * This file is part of the mobileOK Pythia plug-in for Wordpress and defines
 * and registers the the actions and filters of the plug-in in admin mode.
 * 
 * @author Sylvain Lequeux
 * @author Francois Daoust <fd@w3.org>
 * @package mobileOKPythia
 * @subpackage Wordpress
 * @version $Revision: 1.13 $
 * @link http://www.w3.org/2009/11/mobileOKPythia/plugin-wordpress.html mobileOK Pythia for WordPress
 * @license http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231.html W3C Software Notice and License
 * @copyright Copyright (c) 2009, W3C (MIT, ERCIM, Keio)
 */


/**
 * Include required files.
 */
// AskPythia's DDR Service configuration
require_once(dirname(__FILE__) . '/../common/plugins/DDRServiceConfigurationFactory.php');
require_once(dirname(__FILE__) . '/WURFLServiceConfiguration.php');


/**
 * The mobileOKPythiaForWordpressAdmin class contains the logic of the
 * mobileOK Pythia plugin for Wordpress for admin pages.
 * 
 * The class generates the admin menu pages as needed and registers the
 * admin hooks handled by the plugin.
 * 
 * The mobileOK Pythia plugin is designed to help generate a mobileOK
 * version of a blog.
 * 
 * @author Sylvain Lequeux
 * @author Francois Daoust <fd@w3.org>
 * @package mobileOKPythia
 * @subpackage Wordpress
 * @version $Revision: 1.13 $
 * @link http://www.w3.org/2009/11/mobileOKPythia/plugin-wordpress.html mobileOK Pythia for WordPress
 * @license http://www.w3.org/Consortium/Legal/2002/copyright-software-20021231.html W3C Software Notice and License
 * @copyright Copyright (c) 2009, W3C (MIT, ERCIM, Keio)
 */
class mobileOKPythiaForWordpressAdmin {
	private $ddr_implementations;
	
	/**
	 * Creates an empty instance of the mobileOKPythiaForWordpressAdmin class. 
	 * 
	 * @return A new mobileOKPythiaForWordpressAdmin instance.
	 */
	public function __construct() {
	}
	
	/**
	 * Initializes this instance, i.e. registers the hooks and
	 * prepares the identification of the requesting device.
	 */
	public function init() {
		// Load internationalization properties
		$plugin_dir = basename(dirname(__FILE__));
		load_plugin_textdomain('mobileOKPythia', 'wp-content/plugins/' . $plugin_dir, $plugin_dir);
		
		// Adds the link to validate the post with the W3C mobileOK Checker
		add_meta_box(
			'link_mobileok_checker',
			__("Is your post mobileOK?", "mobileOKPythia"),
			array($this, 'addLinkToMobileOKChecker'),
			'post', 'side', 'high');
			
		add_options_page(
			'mobileOK Pythia Options',
			'mobileOK Pythia',
			8,
			'admin_mobileOKPythia',
			array($this, 'printAllOptions'));
	  
		// General options
		add_option('mobileOKPythia_ddrsimpleapi_implementation', 'WURFL', '', 'yes');
		
		add_option('mobileOKPythia_link_powder', 'no', '', 'yes');
		add_option('mobileOKPythia_powder_file', 'wp-content/plugins/mobileOKPythia/cache/powder.xml', '', 'yes');
		
		// Table linearisation options
	  	add_option('mobileOKPythia_linear_tables', 'yes', '', 'yes');
	  	
	  	// Image resizing options
	  	add_option('mobileOKPythia_resize_img', 'yes', '', 'yes');
	  	add_option('mobileOKPythia_img_cache', 'wp-content/plugins/mobileOKPythia/cache/', '', 'yes');
	  		  	
	  	// Pagination options
	  	add_option('mobileOKPythia_pagination', 'yes', '', 'yes');
	  	add_option('mobileOKPythia_max_image_size', '40', '', 'yes');
	  	add_option('mobileOKPythia_max_weight', '20', '', 'yes');
	  	
	  	// Template switching options
	  	add_option("mobileOKPythia_template_switching", 'no', '', 'yes');
	  	add_option('mobileOKPythia_mobile_template', 'mobileok-default', '', 'yes');
	  	
	  	// Delete popups option
	  	add_option('mobileOKPythia_delete_popup', 'yes', '', 'yes');
	  	
	  	// Delete script option
	  	add_option('mobileOKPythia_delete_script', 'yes', '', 'yes');
	  	
	  	// Delete embeds option
	  	add_option('mobileOKPythia_delete_embeds', 'yes', '', 'yes');
	  	
	  	// Serve content as XHTML
	  	add_option('mobileOKPythia_serve_xhtml', 'no', '', 'yes');
	  	
	  	$path_ddr_implementations = dirname(__FILE__) . '/../common/ddrsimpleapi/implementation';
		$this->ddr_implementations = array();
		$handle = opendir($path_ddr_implementations);
		while (false !== ($file = readdir($handle))) {		
	        if (is_dir($path_ddr_implementations . '/' . $file)
	        && ($file != '.') && ($file != '..')
	        && ($file != 'basic') && ($file != 'CVS')) {
	        	$this->ddr_implementations[] = $file;
	        	$config = DDRServiceConfigurationFactory::getServiceConfiguration($file, NULL);
				$config->addOptions();
	        }
	    }
	    closedir($handle);
	}
	
	
	/**
	 * Inserts a link to check current post with the W3C mobileOK Checker
	 * in the post authoring page.
	 */
	public function addLinkToMobileOKChecker(){
		$path = get_bloginfo('wpurl').'/wp-content/plugins/mobileOKPythia/images/mobileOK.png';
		if ( 'publish' == $post->post_status ) {
			$link = esc_url(get_permalink($post->ID));
		} else {
			$link = esc_url(apply_filters('preview_post_link', add_query_arg('preview', 'true', get_permalink($post->ID))));
		}
		$link = 'http://validator.w3.org/mobile/check?docAddr=' . urlencode($link) . '&amp;async=true&amp;view=cat';	
		
		$html = '<div style="height:62px">';
		$html .= '<img src="'.$path.'" width="61" height="60" alt="' . __("Is your post mobileOK?", 'mobileOKPythia') . '" style="float:left; margin-right: 1em;"/>';
		$html .= '<p>' . __("Check the mobile-friendliness of your post with the ") . '';
		$html .= '<a href="'.$link.'" target="_blank">W3C mobileOK Checker</a><br/>';
		$html .= '(' . __('opens in a new window', 'mobileOKPythia') . ')';
		$html .= '</p></div>';
		echo $html;
	}
	
	/**
	 * Displays all the options.
	 */
	function printAllOptions() {
		echo '<div class="wrap"><h2>';
		_e('mobileOK Pythia settings', 'mobileOKPythia');
		echo '</h2>';
		echo '<form method="post" action="options.php">';
		wp_nonce_field('update-options');
		
		echo '<table class="form-table">';
		$this->printAskPythiaOptions();
		$this->printTransPythiaOptions();
		$this->printPowderOptions();
		echo '</table>';
		
		?>
		<input type="hidden" name="action" value="update" />
		<input type="hidden" name="page_options" value="
			mobileOKPythia_ddrsimpleapi_implementation,
			mobileOKPythia_link_powder,
			mobileOKPythia_powder_file,
			<?php
			foreach($this->ddr_implementations as $implementation){
				$config = DDRServiceConfigurationFactory::getServiceConfiguration($implementation);
				echo $config->getOptions();
			}
			?>
			mobileOKPythia_linear_tables,
			mobileOKPythia_pagination,
			mobileOKPythia_resize_img,
			mobileOKPythia_img_cache,
			mobileOKPythia_pagination,
			mobileOKPythia_max_image_size,
			mobileOKPythia_max_weight,
			mobileOKPythia_template_switching,
			mobileOKPythia_mobile_template,
			mobileOKPythia_delete_popup,
			mobileOKPythia_delete_script,
			mobileOKPythia_delete_embeds,
			mobileOKPythia_serve_xhtml" />
		<p class="submit">
			<input type="submit" class="button-primary" value="<?php _e('Save Changes', 'mobileOKPythia')?>" />
		</p>
		</form>
		<?php
		echo '</div>';
	}
	
	
	/**
	 * Displays a checkable fieldset.
	 * 
	 * @param $optionName string The name of the option in Wordpress database.
	 * @param $legend string Legend of the fieldset
	 * @param $desc string A short description of the option
	 * @param $innerOptions string Inner options that can be selected when the option is checked.
	 */
	function printCheckableFieldset($optionName, $legend, $desc, $innerOptions){
		?>
		<fieldset>
			<legend class="screen-reader-text">
				<span><?php _e($legend, 'mobileOKPythia'); ?></span>
			</legend>
			<?php
			echo $this->getCheckableOption($optionName, $desc); 
			
			if ($innerOptions && ($innerOptions != '')) {
				?>
				<div style="margin-left:3em">
					<?php echo $innerOptions; ?>
				</div>
				<?php 
			}
			?>
		</fieldset>
		<?php
	}
	
	
	/**
	 * Displays a checkable option.
	 * 
	 * @param $optionName the name of the option in Wordpress database.
	 * @param $desc a short description to explain the check box
	 */
	function getCheckableOption($optionName, $desc){
		$option = '<label for="'
			. $optionName
			. '">'
			. '<input type="checkbox" name="'
			. $optionName
			. '" value="yes"';
		if(get_option($optionName) == "yes"){
			$option .= 'checked="checked"';
		}
		$option .= '/>'
			. __($desc, 'mobileOKPythia')
			. '</label>';
		return $option;
	}
	
	
	/**
	 * Prints options for AskPythia.
	 */
	function printAskPythiaOptions() {
	    ?>
	    <tr valign="top">
			<th scope="row"><?php _e('AskPythia', 'mobileOKPythia'); ?></th>
			<td>
				<?php _e('AskPythia is an implementation of the <a href="http://www.w3.org/TR/DDR-Simple-API/">Device Description Repository Simple API</a> standard. It is used within mobileOK Pythia to identify and retrieve the properties of the requesting device. This plug-in ships with an implementation on top of <a href="http://wurfl.sourceforge.net/">WURFL</a>, but other implementations that follow the DDR Simple API may be used.', 'mobileOKPythia'); ?>
				<?php
				if ((count($this->ddr_implementations) == 1) && ($this->ddr_implementations[0] == 'WURFL')) {
					echo '<input type="hidden" name="mobileOKPythia_ddrsimpleapi_implementation" id="mobileOKPythia_ddrsimpleapi_implementation" value="WURFL" />';
					$config = DDRServiceConfigurationFactory::getServiceConfiguration('WURFL', NULL);
					$config->printOptions();
				}
				else {
				 	?>
					<select name="mobileOKPythia_ddrsimpleapi_implementation" id="mobileOKPythia_ddrsimpleapi_implementation">
					<?php 
					foreach($this->ddr_implementations as $implementation){
						echo '<option value="' . $implementation . '" ';
						if($implementation == get_option('mobileOKPythia_ddrsimpleapi_implementation')) {
							echo 'selected ';
							$selected = $implementation;
						}
					echo '>' . $implementation . '</option>';
					}
					?>
					</select>
					<span class="description">
						<?php _e('Name of the device description repository used to identify and retrieve the properties of the requesting device.', 'mobileOKPythia'); ?>
					</span>
					<?php
					foreach($this->ddr_implementations as $implementation){
						$config = DDRServiceConfigurationFactory::getServiceConfiguration($implementation);
						$config->printOptions();
					}
				} 
				?>
			</td>
		</tr>
	    <?php 
	}
	
	
	/**
	 * Prints POWDER-related options
	 */
	function printPowderOptions() {
		?>
	    <tr valign="top">
			<th scope="row"><?php _e('mobileOK POWDER file', 'mobileOKPythia'); ?></th>
			<td>
				<?php 
				_e('<a href="http://www.w3.org/TR/powder-dr">POWDER</a> provides a machine-readable means to describe a Web site. This plug-in can generate an XML POWDER file that asserts that the blog is mobileOK. This claim could then be used by search engines as an indication that this blog is mobile-friendly.', 'mobileOKPythia');
				
				$innerOptions = '<label for="mobileOKPythia_powder_file"><span>'
					. __('POWDER file to generate and return (read/write access required for generation). The path must be relative to the root folder of Wordpress (e.g. <code>wp-content/plugins/mobileOKPythia/cache/powder.xml</code>).', 'mobileOKPythia')
					. '</span><br /><input type="text" name="mobileOKPythia_powder_file" value="'
					. get_option('mobileOKPythia_powder_file')
					. '" size="70" />'
					. '</label>';
				
				$this->printCheckableFieldset('mobileOKPythia_link_powder', 'POWDER file generation', 'Generate mobileOK POWDER file and link served content to the POWDER file using an HTTP <code>Link</code> header', $innerOptions);
				?>
			</td>
		</tr>
		<?php
	}
	
	
	/**
	 * Prints options for template switching.
	 */
	function printTemplateSwitchingOptions(){
		$innerOptions = '<label for="mobileOKPythia_mobile_template"><span>'
			. __('Name of the template for mobile devices', 'mobileOKPythia')
			. '</span><input type="text" name="mobileOKPythia_mobile_template" value="'
			. get_option('mobileOKPythia_mobile_template')
			. '" />'
			. '<br/>'
			. __('Desktop devices will receive the theme that is currently activated', 'mobileOKPythia')
			. ' (<em>' . get_option('template') . '</em>).'
			. '</label>';
		
		$this->printCheckableFieldset(
			'mobileOKPythia_template_switching', 
			'Template switching',
			'Switch to a mobile-friendly template when the requesting device is identified as a mobile device.',
			$innerOptions);
	}
	
	
	/**
	 * Prints options for template switching.
	 */
	function printImageResizingOptions(){
		$innerOptions = '<label for="mobileOKPythia_img_cache"><span>'
			. __('Image cache directory where converted images will be saved (read/write access required). The path must be relative to the root folder of Wordpress (e.g. <code>wp-content/plugins/mobileOKPythia/cache</code>).', 'mobileOKPythia')
			. '</span><br /><input type="text" name="mobileOKPythia_img_cache" value="'
			. get_option('mobileOKPythia_img_cache')
			. '" size="70" />'
			. '</label>'
			. '<br />'
			. '<label for="mobileOKPythia_max_image_size"><span>'
			. __('Maximum image size before the image gets deleted', 'mobileOKPythia')
			. '</span><input type="text" name="mobileOKPythia_max_image_size" value="'
			. get_option('mobileOKPythia_max_image_size')
			. '" size="3" /> KB'
			. '</label>'; 
			
		$this->printCheckableFieldset(
			'mobileOKPythia_resize_img',
			'Images adaptation',
			'Adapt images to fit the screen size and supported formats of the requesting device. The GD extension library is required.',
			$innerOptions);
	}
	
	
	/**
	 * Prints options for pagination.
	 */
	function printPaginationOptions(){
		$innerOptions = '<label for="mobileOKPythia_max_weight"><span>'
			. __('Maximum size allowed per page', 'mobileOKPythia')
			. '</span><input type="text" name="mobileOKPythia_max_weight" value="'
			. get_option('mobileOKPythia_max_weight')
			. '" size="3" /> KB'
			. '</label>'
			. '<br />';
		
		$this->printCheckableFieldset(
			'mobileOKPythia_pagination',
			'Pagination',
			'Automatically paginate long blog posts on mobile devices',
			$innerOptions);
	}
	
	
/**
	 * Prints options for tables linearization.
	 */
	function printTablesLinearizationOptions(){
		$innerOptions = '';		
		$this->printCheckableFieldset(
			'mobileOKPythia_linear_tables',
			'Tables linearization',
			'Automatically linearizes tables when the requesting device does not support them',
			$innerOptions);
	}

	/**
	 * Prints the WURFL preparation database form
	 */
	function printPrepareDatabase(){
		?>
			<div class="wrap">
				<?php
				require_once(dirname(__FILE__) . '/../common/ddrsimpleapi/implementation/WURFL/WURFLPrepareDatabase.php');
				?>
			</div>
		<?php 
	}


	/**
	 * Prints TransPythia options.
	 */
	function printTransPythiaOptions(){
		?>
		<tr valign="top">
			<th scope="row"><?php _e('TransPythia', 'mobileOKPythia'); ?></th>
			<td>
				<?php
				_e('TransPythia is a transcoding library aimed at adapting content to fit the properties of requesting devices. Its goal is to generate mobileOK content by default, i.e. when the properties of the requesting device are unknown. TransPythia should not affect content served to regular <em>desktop</em> browsers.', 'mobileOKPythia');
				$this->printTemplateSwitchingOptions();
				$this->printImageResizingOptions();
				$this->printPaginationOptions();
				$this->printTablesLinearizationOptions();
				$this->printCheckableFieldset(
					'mobileOKPythia_delete_popup',
					'Popup windows suppression',
					'Suppress pop-up windows when the requesting device is identified as a mobile device.',
					'');
				$this->printCheckableFieldset(
					'mobileOKPythia_delete_script',
					'Scripts suppression',
					'Suppress scripts when the requesting device does not support scripting.',
					'');
				$this->printCheckableFieldset(
					'mobileOKPythia_delete_embeds',
					'Embedded elements suppression',
					'Suppress embedded elements (applet, embed, iframe), when the requesting device is identified as a mobile device.',
					'');
				$this->printCheckableFieldset(
					'mobileOKPythia_serve_xhtml',
					'XHTML content',
					'Serve content using the recommended <code>application/xhtml+xml</code> media type when the requesting device supports it. Note the content must pass markup validation or browsers may fail to render the resulting content.',
					'');
				
				?>
			</td>
		</tr>
		<?php
	}
}

?>