<?php
/* RSSReader 0.2.3 - a parser hook for MediaWiki
 * Copyright (C) 2007  Artem Kaznatcheev
 *
 * This program is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 2 of the License, or
 * (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

# Not a valid entry point, skip unless MEDIAWIKI is defined
if (!defined('MEDIAWIKI')) {exit( 1 );}

$wgExtensionFunctions[] = "efRSSReader";

$wgExtensionCredits['parserhook'][] = array(
  'name' => 'RSS Reader',
  'version' => '0.2.3',
  'author' => 'Artem Kaznatcheev',
  'description' => 'adds an rss tag',
  'url' => 'http://www.mediawiki.org/wiki/Extension:RSS_Reader'
);

error_reporting (E_ERROR | E_WARNING | E_PARSE);

### Global Variables ###
$egRSSReaderPath  = $wgScriptPath."/extensions/RSSReader"; //path to follow for server scripts
$egCacheTime      = 2;   //default cache time in seconds
$egCacheTimeMin   = 1800;   //minimum cache time in seconds
$egCacheTimeMax   = 7200;   //maximum cache time in seconds
$egCache          = false;   //boolean to determine if caching should be done
$egNoFollow       = false;  //boolean to determine if links created by the extension should have rel="nofollow"
$egWidthMin       = 200;    //minimim width in pixels
$egWidthMax       = 800;    //maximum width in pixels

/*
 *select if wikiRSS or lastRSS should be loaded
 *set rssType to the proper object type
 *each object of rssType must have the same interface
 */
if (file_exists(dirname( __FILE__ )."/wikiRSS.php" )) {
  require_once ( dirname( __FILE__ )."/wikiRSS.php" ); //loads wikiRSS.php
  $rssType = wikiRSS; //set rssType to wikiRSS
} else if (file_exists(dirname( __FILE__ )."/lastRSS.php")) {
  require_once ( dirname( __FILE__ )."/lastRSS.php" ); //loads lastRSS.php
  $rssType = "lastRSS"; //set rssType to lastRSS
}

function efRSSReader() {
  global $wgParser;
  $wgParser->setHook( "rss", "efCreateRSSReader" );
}

function efCreateRSSReader($input, $argv, &$parser){
  global $wgOut, $egRSSReaderPath, $egCacheTime, $egCacheTimeMin,
    $egCacheTimeMax, $egCache, $rssType, $egNoFollow, $egWidthMin, $egWidthMax;

  $parser->disableCache(); //disable cache so feed is fetched everytime page is visited
  if (!$input){ //if no input do nothing
  } else {
    $fields = explode("|",$input); //get the urls between the tags

    /*
     * Check if a "number=n" argument has been provided
     * if it has and is an int, then set the $number field to the proper value
     * else set $number field to zero (which means "all available")
     */
    if (!$argv["number"]){ //check if argument has been provided
      $number=0; //set default if no argument has been provided
    } else {
      if ((int)$argv["number"]."" == $argv["number"]) { //check if argument is an integer
        $number = $argv["number"]; //set $number field
      } else {
        $number=0; //if not an integer, then set default
      }
    }

    /*
     * Check if a "width=n" argument has been provided
     * if it has and is an int, then set the $width field to the proper value
     * else set $width field to zero (which means "no width")
     */
    if (!$argv["width"]){ //check if argument has been provided
      $width=0; //set default if no argument has been provided
    } else {
      if ((int)$argv["width"]."" == $argv["width"]) { //check if argument is an integer
        if (($argv["width"]>=$egWidthMin)&&($argv["width"]<=$egWidthMax)) {
          $width = $argv["width"]; //set $width field
        } else $width = 0; //if out of range, then set default
      } else {
        $width=0; //if not an integer, then set default
      }
    }

    /*
     * Check if a "time=n" argument has been provided
     * if it has and is between $egCacheTimeMin and $egCacheTimeMax
     * then set $cacheTime to the value
     * else set $cacheTime to $egCacheTime (the default CacheTime)
     */
    if (!$argv["time"]){ //check if argument has been provided
      $cacheTime = $egCacheTime; //set default if no argument has been provided
    } else {
      if ((int)$argv["time"]."" == $argv["time"]) { //check if argument is an integer
        if (($argv["time"]>=$egCacheTimeMin)&&($argv["time"]<=$egCacheTimeMax)) { //check if argument is in range
          $cacheTime = $argv["time"]; //set $cacheTime field
        } else {
          $cacheTime = $egCacheTime; //set default if argument is outside range
        }
      } else {
        $cacheTime=$egCacheTime; //set default if not an integer
      }
    }

    /* Check if a "desc=off" parameter has been provided and set desc */
    $desc = true; //set the default
    if ($argv["desc"]){ //check if argument has been provided
      if ($argv["desc"]=="off") $desc = false;
    }

    $wgOut->addScript('<link rel="stylesheet" type="text/css" href="'.$egRSSReaderPath.'/RSSReader.css" />'); //add CSS

    if (!$width) {
      $output .= '
        <table id="RSSMainBody" width="100%"  class="windowbg3">
        <tr>
      ';
    } else {
      $output .= '
        <table id="RSSMainBody" style="float:right;width:'.$width.'" class="windowbg3">
        <tr>
      ';
    }

    $width = intval(100/sizeof($fields) - 5); //calculates the desired width for each feed and makes sure it is an int

    // Create wikiRSS or lastRSS object
    $rss = new $rssType; //initialize an object of rssType
    // Set public variables
    if (($rssType == lastRSS)&&($egCache)) $rss->cache_dir = dirname( __FILE__ ).'/cache/'; //directory of cache
    $rss->cache = $egCache; //cache attribute
    $rss->cache_time = $cacheTime; //refresh time in seconds
    $rss->date_format = 'l';

    foreach ($fields as $field) {
      $output .= '<td valign="top" style="width: '.$width.'%;">'; //table cell that contains a single RSS feed
      if ($rssArray = $rss->get($field)){
        $output .=
          '<div class="RSSReader-head">'.
            '<h3><a href="'.
            $rssArray['link'].
            '"';
        if ($egNoFollow) $output .= 'rel="nofollow"'; //decide if nofollow is needed
        $output .= '>'.
            $rssArray['title'].
            '</a></h3>';
        if ($desc) $output .= $rssArray['description']; //decide if description is required
        $output .= '</div>';
        /*Outputs the items*/
        $i = 0; //counter for number of items already displayed
        foreach ($rssArray['items'] as $item){
          $output .= begin_box_return('<a href="'.$item['link'].'">'.str_replace(array("<![CDATA[","]]>"),array("",""),$item['title']).'</a>');
          $output .= str_replace(array("<![CDATA[","]]>"),array("",""),$item['description']) . ' <i>[<a href="'.$item['link'].'">more</a>]</i>';
          $output .= "<br /><br /><i>Published on $item[pubDate] by <a href='mailto:$item[author]'>$item[author]</a> | <a href='$item[comments]'>comment?</a></i>";
          $output .= end_box_return();
          /*$output .= '<li><a href="'.$item['link'].'" ';
          if ($egNoFollow) $output .= 'rel="nofollow"'; //decide if nofollow is needed
          $output .= '>'.$item['title'].'</a></li>';*/
          $i += 1;
          if ($i == $number) { break; } //if reached the number of desired display items stop working on displaying more items
          } //close foreach items
      } else { $output .= "Error: It's not possible to get $field..."; } //output error if not possible to fetch RSS
      $output .= '</td>';
    } //close foreach fields
    $output .= "</tr></table>";
  } //close main "else"
  return $output;
}

function begin_box_return($title) {
global $theme;
return <<<HERE
<table cellspacing="1" cellpadding="0" border="0" width="100%" align="center" class="bordercolor">
<tr>
<td class="catbg">
<table cellspacing="0" cellpadding="4" width="100%" class="bordercolor">
<tr>
<td class="catbg"><strong>$title</strong></td></td>
</tr>
</table>

</tr>
<tr>
<td class="windowbg2">
HERE;
}

function end_box_return() {
return <<<THERE
</td></tr></table><br />
THERE;
}
?>