<?php
/*
Plugin Name: Fortune widget
Description: Displays a fortune from a fortune collection using the <a href="http://www.aasted.org/quote/">php-fortune</a> by Henrik Aasted Sorensen.  Either copy your fortune files (both the base file and the .dat file) into <code>wp-content/plugins/widgets/fortune</code> OR modify both <code>$baseFortuneDir</code> values in this script to where the fortune files are installed on your system... 
Author: Jason V. Mock
Version: 0.3
License: Creative Commons Attribution-Noncommercial-Share Alike 2.5 License
Author URI: http://www.jason.mock.ws

NOTE: USE AT YOUR OWN RISK!  USE OF THIS SCRIPT INDICATES THAT THE USER ACCEPTS ANY POSITIVE OR NEGATIVE SIDE EFFECTS!!
*/

// Put functions into one big function we'll call at the plugins_loaded
// action. This ensures that all required plugin functions are defined.
function widget_fortune_init() {

	// Check for the required plugin functions. This will prevent fatal
	// errors occurring when you deactivate the dynamic-sidebar plugin.
	if ( !function_exists('register_sidebar_widget') )
		return;

   function endsWith( $str, $sub ) {
      return ( substr( $str, strlen( $str ) - strlen( $sub ) ) === $sub );
   }

	// This is the function that outputs our little Google search form.
	function widget_fortune($args) {
	   $baseFortuneDir = ABSPATH.'wp-content/plugins/widgets/fortune';
	
		// $args is an array of strings that help widgets to conform to
		// the active theme: before_widget, before_title, after_widget,
		// and after_title are the array keys. Default tags: li and h2.
		extract($args);

		// Each widget can store its own options. We keep strings here.
		$options = get_option('widget_fortune');
		$title = $options['title'];
		$fortunename = $options['fortunename'];

		// These lines generate our output. Widgets can be very complex
		// but as you can see here, they can also be very, very simple.
		echo $before_widget . $before_title . $title . $after_title;
		$fortuneInc = $baseFortuneDir."/fortune.php";
		$fortuneFile = $baseFortuneDir."/$fortunename".".dat";
		if(file_exists($fortuneInc) && file_exists($fortuneFile)){
			include_once($fortuneInc);
			$f = new Fortune;
			echo $f->getRandomQuote($fortuneFile);
	   } else {
			echo "Unable to find fortune file $fortunename";
		}
		echo $after_widget;
	}

	// This is the function that outputs the form to let the users edit
	// the widget's title. It's an optional feature that users cry for.
	function widget_fortune_control() {
	   $baseFortuneDir = ABSPATH.'wp-content/plugins/widgets/fortune';

		// Get our options and see if we're handling a form submission.
		$options = get_option('widget_fortune');
		if ( !is_array($options) )
			$options = array('title'=>'', 'fortunename'=>__('Fortune Widget', 'widgets'));
		if ( $_POST['fortune-submit'] ) {

			// Remember to sanitize and format use input appropriately.
			$options['title'] = strip_tags(stripslashes($_POST['fortune-title']));
			$options['fortunename'] = strip_tags(stripslashes($_POST['fortunename']));
			update_option('widget_fortune', $options);
		}

		// Be sure you format your options to be valid HTML attributes.
		$title = htmlspecialchars($options['title'], ENT_QUOTES);
		$fortunename = htmlspecialchars($options['fortunename'], ENT_QUOTES);
		
		// Here is our little form segment. Notice that we don't need a
		// complete form. This will be embedded into the existing form.
		echo '<p style="text-align:right;"><label for="fortune-title">' . __('Title:') . ' <input style="width: 200px;" id="fortune-title" name="fortune-title" type="text" value="'.$title.'" /></label></p>';

      echo '<p style="text-align:right;"><label for="fortunename">' . __('Fortune Name:', 'widgets') . ' <select style="width: 200px;" id="fortunename" name="fortunename">';

      $found = false;
      if (is_dir($baseFortuneDir)){
         if ($dh = opendir($baseFortuneDir)){
            while (($file = readdir($dh)) !== false){
               if(endsWith($file,".dat")){
                  $fName = basename($file, ".dat");
                  echo '<OPTION';
                  if($fortuneName == $fName){
                     echo " selected value=\"$fName\"";
                  }
                  echo ">$fName</OPTION>";
                  $found = true;
               }
            }
         closedir($dh);
         }
      } 
      echo '</select>';
		echo '<input type="hidden" id="fortune-submit" name="fortune-submit" value="1" />';
      if(!$found){
         echo '<p style="font-size:.8em;">Copy your fortune files into wp-content/widgets/fortune<br/>';
      }
	}
	
	register_sidebar_widget(array('Fortune', 'widgets'), 'widget_fortune');
	register_widget_control(array('Fortune', 'widgets'), 'widget_fortune_control', 310, 100);
}

add_action('widgets_init', 'widget_fortune_init');

?>
