<?php
/*
Plugin Name: Stewart's Theme Widgets
Plugin URI: http://www.ugelow.com/code
Description: Creates widgets from files prefixed 'widget-' or 'widget_' in your theme folder. Based on <a href="http://guff.szub.net/" target="_blank">Kaf Oseo's</a> My Widget.
Author: Stewart Ugelow
Version: 1.0
Author URI: http://www.ugelow.com

    Stewart's Theme Widgets is released under the GNU General Public License (GPL)
    http://www.gnu.org/licenses/gpl.txt

    This is a WordPress plugin (http://wordpress.org) and widget
    (http://automattic.com/code/widgets/).
*/

//----------------------------------------------------------------------------
//FIND WIDGETS IN THEME DIRECTORY
//----------------------------------------------------------------------------

function get_theme_widgets() {
    
$themes get_themes();
    
$theme get_current_theme();
    
$theme_files $themes[$theme]['Template Files'];
    
$theme_dir $themes[$theme]['Template Dir'].'/';
    foreach (
$theme_files as $theme_file) {
        if ((
strstr($theme_file,$theme_dir.'widget_')) OR (strstr($theme_file,$theme_dir.'widget-'))) {
            
$theme_widgets[] = str_replace($theme_dir,'',$theme_file);
        } 
//if
    
//foreach
    
return ($theme_widgets);
//get_theme_widgets()    

function get_theme_widget_data($widget) {
    
$widget_data implode(''file(TEMPLATEPATH."/$widget"));
    
preg_match("|Widget Name:(.*)|i"$widget_data$name);
    
$name trim($name[1]);
    return 
$name
//get_theme_widget_data

//----------------------------------------------------------------------------
//MAIN WIDGET BODY
//----------------------------------------------------------------------------


// We're putting the plugin's functions in one big function we then
// call at 'plugins_loaded' (add_action() at bottom) to ensure the
// required Sidebar Widget functions are available.
function widget_theme_widget_init() {

    
// Check to see required Widget API functions are defined...
    
if ( !function_exists('register_sidebar_widget') || !function_exists('register_widget_control') )
        return; 
// ...and if not, exit gracefully from the script.

    // This function prints the sidebar widget--the cool stuff!
    
function widget_theme_widget($args$number 1) {

        
// $args is an array of strings which help your widget
        // conform to the active theme: before_widget, before_title,
        // after_widget, and after_title are the array keys.
        
extract($args);

        
// Collect our widget's options, or define their defaults.
        
$options get_option('widget_theme_widget');
        
        
$title $options[$number]['title'];
        
$text $options[$number]['text'];
        
$to_use $options[$number]['to_use'];

         
// It's important to use the $before_widget, $before_title,
         // $after_title and $after_widget variables in your output.
        
echo $before_widget;
        echo 
$before_title $title $after_title;
        echo 
$text;
        
        
// INCLUDE THE WIDGET TEMPLATE FROM THE THEME 
        
if (strlen($to_use) <> 0) {
            include(
TEMPLATEPATH "/$to_use");
        } 
//$to_use
        
else {
        
//UNCOMMENT FOR DEBUGGING
            
print("ERROR: No widget selected.");
        } 
//else
    
        
echo $after_widget;
    }

    
// This is the function that outputs the form to let users edit
    // the widget's title and so on. It's an optional feature, but
    // we'll use it because we can!
    
function widget_theme_widget_control($number) {

        
// Collect our widget's options.
        
$options get_option('widget_theme_widget');

        
// This is for handing the control form submission.
        
if ( $_POST["theme_widget-submit-$number"] ) {
            
            
// Clean up control form submission options
            
$newoptions[$number]['title'] = strip_tags(stripslashes($_POST["theme_widget-title-$number"]));
            
$newoptions[$number]['text'] = strip_tags(stripslashes($_POST["theme_widget-text-$number"]));
            
$newoptions[$number]['to_use'] = strip_tags(stripslashes($_POST["theme_widget-to-use-$number"]));
            
$options $newoptions;
            
update_option('widget_theme_widget'$options);            
        }

        
// Format options as valid HTML. Hey, why not.
        
$title htmlspecialchars($options[$number]['title'], ENT_QUOTES);
        
$text htmlspecialchars($options[$number]['text'], ENT_QUOTES);
        
$to_use $options[$number]['to_use'];

// The HTML below is the control form for editing options.

?>
        <div>
        <label for="theme_widget-title" style="line-height:35px;display:block;">Widget title: <input type="text" id="theme_widget-title-<?php echo "$number"?>" name="theme_widget-title-<?php echo "$number"?>" value="<?php echo $title?>" /></label>
        <label for="theme_widget-text" style="line-height:35px;display:block;">Widget text: <input type="text" id="theme_widget-text-<?php echo "$number"?>" name="theme_widget-text-<?php echo "$number"?>" value="<?php echo $text?>" /></label>
        <label for="theme_widget-to-use" style="line-height:35px;display:block;"><?php

        
//OUTPUT THEME WIDGETS ON FORM
        
$theme_widgets get_theme_widgets();
            if (
count($theme_widgets) > 0) {
                print(
"<p>Select a widget from the <strong>".get_current_theme()."</strong> theme</p>");
                print(
"<table>\n");
                foreach (
$theme_widgets as $theme_widget) {
                    
                    
$theme_widget_checked '';
                    if (
$theme_widget == $to_use) {
                        
$theme_widget_checked 'checked="checked"';
                    } 
//if
                    
                    
$theme_widget_data get_theme_widget_data($theme_widget);
                    if (
$theme_widget_data <> '') {
                        
$theme_widget_data "<td>&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;Name: $theme_widget_data</td>";
                    } 
//
                    
                    
print('<tr style="vertical-align: middle;"><td><input '.$theme_widget_checked." name=\"theme_widget-to-use-$number\" id=\"theme_widget-to-use-$number\"".' type="radio" value="'.$theme_widget.'" /></td><td>&nbsp;&nbsp;&nbsp;</td><td>'.$theme_widget.$theme_widget_data."</td></tr>\n");
                } 
//foreach
                
print("</table>\n");
            } 
//if
            
else {
                print(
"<p>There are no widget templates in the <strong>".get_current_theme()."</strong> directory.</p>");
            } 
//else
        
?></label>
                
        <input type="hidden" name="theme_widget-submit-<?php echo "$number"?>" id="theme_widget-submit-<?php echo "$number"?>" value="1" />
        </div>
    <?php
    
// end of widget_theme_widget_control()
    
}

    
// This registers the widget. About time.
    //register_sidebar_widget('Theme Widget', 'widget_theme_widget');

    // This registers the (optional!) widget control form.
    //register_widget_control('Theme Widget', 'widget_theme_widget_control');
    
    
widget_theme_widget_register();
}

//----------------------------------------------------------------------------
//MULTIPLE WIDGET HANDLING
//----------------------------------------------------------------------------


function widget_theme_widget_setup() {
    
$options $newoptions get_option('widget_theme_widget');
    if ( isset(
$_POST['theme-widget-number-submit']) ) {
        
$number = (int) $_POST['theme-widget-number'];
        if ( 
$number $number 1;
        
$newoptions['number'] = $number;
    }
    if ( 
$options != $newoptions ) {
        
$options $newoptions;
        
update_option('widget_theme_widget'$options);
        
widget_theme_widget_register($options['number']);
    }
}

function 
widget_theme_widget_page() {
    
$options $newoptions get_option('widget_theme_widget');
?>
    <div class="wrap">
        <form method="POST">
            <h2>Theme Widgets</h2>
            <p style="line-height: 30px;"><?php _e('How many theme widgets would you like?'); ?>
            
            <input name="theme-widget-number" type="text" id="theme-widget-number" value="<?php echo $options['number']; ?>" size="3" />

            <span class="submit"><input type="submit" name="theme-widget-number-submit" id="theme-widget-number-submit" value="<?php _e('Save'); ?>" /></span></p>
            <p><?php 
            $theme_widget_count 
count(get_theme_widgets()); 
            if (
$theme_widget_count <> 1
                    print(
"(There are currently <strong>$theme_widget_count</strong> widget templates in the <strong>".get_current_theme()."</strong> directory.)");
            else    
                    print(
"(There is currently <strong>1</strong> widget template in the <strong>".get_current_theme()."</strong> directory.)");                    
            
?></p>
        </form>
    </div>
<?php
}

function 
widget_theme_widget_register() {
    
$options get_option('widget_theme_widget');
    
$number $options['number'];
    if ( 
$number $number 1;
    
$max $number;
    for (
$i 1$i <= $max$i++) {
        
$name = array('Theme Widget %s'null$i);
        
register_sidebar_widget($name$i <= $number 'widget_theme_widget' /* unregister */ ''$i);
        
register_widget_control($name$i <= $number 'widget_theme_widget_control' /* unregister */ ''460350$i);
    }
    
add_action('sidebar_admin_setup''widget_theme_widget_setup');
    
add_action('sidebar_admin_page''widget_theme_widget_page');
}


//----------------------------------------------------------------------------
//HOOK IN
//----------------------------------------------------------------------------

// Delays plugin execution until Dynamic Sidebar has loaded first.
add_action('plugins_loaded''widget_theme_widget_init');

?>