<?php
/*
Plugin Name: FeedCache Pipes
Plugin URI: http://www.craigjolicoeur.com/feedcache-pipes
Description: Caches RSS Feeds for display on WP site sidebar.  This prevents multiple HTTP requests with each page load since the feeds can be read from the cache file.  One feed is created from multiple sources and sorted by date.
Author: Craig P Jolicoeur
Version: 1.1.2
Author URI: http://www.craigjolicoeur.com/
*/

//***************************************************
//
//         DO NOT EDIT BELOW THIS LINE                         
//
//***************************************************

// Pre-2.6 compatibility
if ( !defined('WP_CONTENT_URL') ) {
	define('WP_CONTENT_URL', get_option('siteurl') . '/wp-content');
}
if ( !defined('WP_CONTENT_DIR') ) {
	define('WP_CONTENT_DIR', ABSPATH . 'wp-content');
}

// Constants
define("FCPIPES_PATH", WP_CONTENT_DIR . '/plugins/'. plugin_basename(dirname(__FILE__)));
define("FCPIPES_URL", WP_CONTENT_URL . '/plugins/'. plugin_basename(dirname(__FILE__)));
define("FCPIPES_FILES_PATH", FCPIPES_PATH . '/');
define("DEFAULT_PRE_TAG", "<h3>");
define("DEFAULT_POST_TAG", "</h3>");
define("DEFAULT_FORMAT_TEXT", "true");
define("DEFAULT_GROUP_NUM", '2');
define("DEFAULT_DISPLAY_NUM", '5');
define("MAX_GROUPSIZE", 99);

// Include Spyc PHP YAML library
include_once(FCPIPES_PATH . '/lib/spyc/spyc.php');

// Wordpress hooks
add_action('admin_menu', 'fcpipes');
register_activation_hook(__FILE__, 'fcpipes_install');

// DB setup
$fcpipes_db_version = "1.0";
function fcpipes_install () {
	global $wpdb;
	global $fcpipes_db_version;
	
	// Install DB table if not already installed
	$table_name = $wpdb->prefix . "fcpipes_data";
	if ($wpdb->get_var("show tables like '$table_name'") != $table_name) {
		$sql = "CREATE TABLE " . $table_name . " (
			id mediumint(9) NOT NULL AUTO_INCREMENT,
			group_id mediumint(9) NOT NULL,
			data text default NULL,
			updated_at datetime default NULL,
			UNIQUE KEY id (id),
			UNIQUE KEY group_id (group_id)
			);";
			
			require_once(ABSPATH . 'wp-admin/includes/upgrade.php');
			dbDelta($sql);
			
			add_option("fcpipes_db_version", $fcpipes_db_version);
	}

	// Check if DB table upgrade is needed
	$installed_ver = get_option("fcpipes_db_version");
	if ($installed_ver != $fcpipes_db_version) {
		$sql = ""; // New DB schema here
		
		require_once(ABSPATH . 'wp-admin/inclues/upgrade.php');
		dbDelta($sql);
		
		update_option("fcpipes_db_version", $fcpipes_db_verion);
	}

  $new_groups = array();
  $new_options = array(
    'group_num' => DEFAULT_GROUP_NUM,
    'display_num' => DEFAULT_DISPLAY_NUM,
    'title_pre' => DEFAULT_PRE_TAG,
    'title_post' => DEFAULT_POST_TAG,
    'format_text' => DEFAULT_FORMAT_TEXT,
    'target_blank' => false
  );
  // if old options exist, update to new system
  foreach ( $new_options as $key => $value ) {
    if ( $existing = get_option("fcpipes_$key") ) {
      $new_options[$key] = $existing;
      delete_option("feedcache_$key");
    }
  }
  // if old groups exist, update to new system
  for ( $i=1; $i<=99; $i++ ) {
    if ( $existing = get_option("fcpipes_rss_list$i") ) {
      $new_groups["group$i"]['feeds'] = $existing;
      $new_groups["group$i"]['count'] = DEFAULT_DISPLAY_NUM;
      $new_groups["group$i"]['excerpt'] = 'on';
      delete_option("fcpipes_rss_list$i");
    }
  }
  add_option('plugin_fcpipes_groups', $new_groups);
  add_option('plugin_fcpipes_options', $new_options);

  // if old groups format exists, update to new system
  $groups = get_option('plugin_fcpipes_groups');
  $new_groups = array();
  if ( !array_key_exists("feeds", $groups["group1"]) ) {
    for ( $i=1; $i<=99; $i++ ) {
      if ( array_key_exists("group$i", $groups) ) {
        $new_groups["group$i"]['feeds'] = $groups["group$i"];
        $new_groups["group$i"]['count'] = DEFAULT_DISPLAY_NUM;
        $new_groups["group$i"]['excerpt'] = 'on';
      }
    } 
    update_option('plugin_fcpipes_groups', $new_groups);
  }
}

// Functions
function fcpipes_display_feeds($rss_group = '1') {
	global $wpdb;
	$feed_data = $wpdb->get_row("SELECT * FROM " . $wpdb->prefix . "fcpipes_data WHERE group_id = $rss_group");
	return $feed_data->data;
}

function fcpipes_build_config_file($config_settings) {
		$fpath = FCPIPES_FILES_PATH . "fcpipes-config.yml";
		$yaml = Spyc::YAMLDump($config_settings);

		// create the config file if it doesn't exist and make it writeable
		if (!file_exists($fpath)) {
			$tmp_handle = fopen($fpath, 'w') or die("can't create file");
			fclose($tmp_handle);
			chmod($fpath, 0666);
		}

	  if (is_writable($fpath)) {
	    if (!$handle = fopen($fpath, "w")) {
	      echo "Cannot open file ($fpath)";
	      exit;
	    }
	    if (fwrite($handle, "$yaml") === FALSE) {
	      echo "Cannot write to file ($fpath)";
	      exit;
	    }
	    fclose($handle);
	  } else {
	    echo "The config file ($fpath) is not writable";
	  }
}

function fcpipes() {
  if ( current_user_can('switch_themes') ) {
    add_submenu_page('options-general.php', 'FeedCache Pipes Options', 'FeedCache Pipes', 'switch_themes', __FILE__, 'fcpipes_subpanel');
  }
}

function fcpipes_admin_footer() {
  $plugin_data = get_plugin_data(__FILE__);
  printf('%1$s plugin | Version %2$s | by %3$s<br />', $plugin_data['Title'], $plugin_data['Version'], $plugin_data['Author']);
}

function fcpipes_subpanel() {
  add_action('in_admin_footer', 'fcpipes_admin_footer');
  global $wpdb;

  if ($_POST['stage'] == 'prep') {
    $options = get_option('plugin_fcpipes_options');
    $options['group_num'] = $_POST['fcpipes_group_num'];
    update_option('plugin_fcpipes_options', $options);
  }
		
  $options = get_option('plugin_fcpipes_options');
  $number_of_groups = $options['group_num'];

  if ($_POST['stage'] == 'process' ) {
    for ($i=1; $i<=$number_of_groups; $i++) {
      $group_array["group$i"]['feeds'] = $_POST["group$i"]['feeds'];
      $group_array["group$i"]['count'] = $_POST["group$i"]['count'];
      $group_array["group$i"]['excerpt'] = $_POST["group$i"]['excerpt'];
      $group_array["group$i"]['strip_html'] = $_POST["group$i"]['strip_html'];
      $group_array["group$i"]['feed_url'] = FCPIPES_URL."/files/group$i.xml";
    }
    update_option('plugin_fcpipes_groups', $group_array);

    $new_options = $_POST['fcpipes'];
    $new_options['group_num'] = $number_of_groups;
    update_option('plugin_fcpipes_options', $new_options);
    
    $config_settings = array_merge( $group_array, $new_options );
		$config_settings["db_prefix"] = '"'.$wpdb->prefix.'"';
		$config_settings["db_host"] = '"'.DB_HOST.'"';
		$config_settings["db_name"] = '"'.DB_NAME.'"';
		$config_settings["db_user"] = '"'.DB_USER.'"';
		$config_settings["db_password"] = '"'.DB_PASSWORD.'"';
    fcpipes_build_config_file( $config_settings );
  }

  $options = get_option('plugin_fcpipes_options');
  $groups = get_option('plugin_fcpipes_groups');
?>
    
  <div class="wrap">
    <h2 id="write-post">FeedCache Pipes</h2>
    <p>Fill in the list of RSS feeds you want to process and how you want them formatted and displayed on your site.  If you notice any bugs or have suggestions please contact the developers at <a href="http://www.craigjolicoeur.com/blog/feedcache-pipes" title="Craig Jolicoeur's FeedCache Pipes Homepage">FeedCache Pipes on craigjolicoeur.com</a>.</p>

    <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>" name="prep_form">
      <input type="hidden" name="stage" value="prep" />
      <table class="form-table">
        <tbody>
          <tr valign="top">
            <th scope="row">How many RSS Groups?</th>
            <td>
              <select name="fcpipes_group_num" onchange="document.prep_form.submit();">
                <?php
                  for($i=1; $i <= MAX_GROUPSIZE; $i++) {
                    if($i == $number_of_groups) {
                      echo "<option value='$i' selected>$i</option>";
                    }
                    else {
                      echo "<option value='$i'>$i</option>";
                    }
                  }
                ?>
              </select>
            </td>
          </tr>
        </tbody>
      </table>
    </form><!-- end #prep_form -->
    <hr />
              
    <form method="post" action="<?php echo $_SERVER['REQUEST_URI']; ?>">
      <input type="hidden" name="stage" value="process" />
      <input type="hidden" name="fcpipes[title_pre]" value="<h3>" />
      <input type="hidden" name="fcpipes[title_post]" value="</h3>" />
      <fieldset class="options">
        <div>
          <p>Enter the list of RSS Feeds [1 per line] for each group</p>

          <?php for ($i=1; $i<=$number_of_groups; $i++) { ?>
            <h3>Group <?php echo $i; ?></h3>
            <p>
              <span style="float:right;">Number of articles to display: <input type="text" name="group<?php echo $i; ?>[count]" style="width:30px;" value="<?php echo $groups["group$i"]['count']; ?>" /></span>
              Show RSS excerpt? <input type="checkbox" name="group<?php echo $i; ?>[excerpt]" <?php if ($groups["group$i"]['excerpt'] == 'on') { echo 'checked=true'; }  ?>>
              Strip HTML tags? <input type="checkbox" name="group<?php echo $i; ?>[strip_html]" <?php if ($groups["group$i"]['strip_html'] == 'on') { echo 'checked=true'; } ?>>
            </p>
            <textarea name="group<?php echo $i; ?>[feeds]" rows="10" style="width:100%;"><?php echo $groups["group$i"]['feeds']; ?></textarea>
            <p><strong>XML Feed:</strong> <a href="<?php echo FCPIPES_URL."/files/group$i.xml"; ?>" title='FCPipes Group Feed'><?php echo FCPIPES_URL."/files/group$i.xml"; ?></a></p>
            <hr />
          <?php } ?>
        </div>
        <div>
          <p>
            <label for='fcpipes_display_num'>Default number of articles to display: </label>
            <input type="text" name="fcpipes[display_num]" style="width: 30px;" value="<?php echo $options['display_num']; ?>" />
          </p>
          <p>
            <label for='fcpipes_format_text'>Format feed text for proper capitalization: </label>
            <select name="fcpipes[format_text]">
              <option value='true' <?php if ($options['format_text'] == 'true') { echo 'selected'; } ?> >True</option>
              <option value='false' <?php if ($options['format_text'] == 'false') { echo 'selected'; } ?> >False</option>
            </select>
          </p>
          <p>
            <label for='fcpipes_target_blank'>Open feed links in a new window: </label>
            <select name="fcpipes[target_blank]">
              <option value='true' <?php if ($options['target_blank'] == 'true') { echo 'selected'; } ?> >True</option>
              <option value='false' <?php if ($options['target_blank'] == 'false') { echo 'selected'; } ?> >False</option>
            </select>
          </p>
        </div>
      </fieldset><!-- .options -->

      <div class="submit">
        <input type="submit" value="Update FeedCache Pipes Preferences &raquo;" name="Submit" />
      </div>
    </form><!-- end main form -->

    <hr />
    <div class="options" id="script-settings">
      <h3>CRON Script Settings</h3>
      <p> 
        Here is the <b>fcpipes directory path</b> to use in the CRON script:<br />
        <?php echo FCPIPES_PATH . "<br />"; ?>
      </p>
    </div>
  </div><!-- end .wrap -->

<?php            
}
?>
