<?php
/**
 * amazon-Plugin: Searches for books in amazon 
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Thomas Baumann <tom@tiri.li>
 */
 
if(!defined('DOKU_INC')) define('DOKU_INC',realpath(dirname(__FILE__).'/../../').'/');
if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'inc/plugins/');
require_once(DOKU_PLUGIN.'syntax.php');
// require_once('/usr/share/pear/PHP/Compat/Function/file_put_contents.php');
require_once('class.xmlreader.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_amazon extends DokuWiki_Syntax_Plugin {
   function getInfo(){
      return array(
          'author' => 'Thomas Baumann',
          'email'  => 'tom@tiri.li',
          'date'   => '2005-10-31',
          'name'   => 'Amazon Plugin',
          'desc'   => 'Search and display Amazon link',
          'url'    => 'https://www.dokuwiki.org/plugin:amazon_heavy'
      );
  }
  /**
  * What kind of syntax are we?
  */
  function getType(){
    return 'protected';
  }
 
  /**
  * Where to sort in?
  */
  function getSort(){
    return 400;
  }
 
 
    /**
     * Connect pattern to lexer
     */
    function connectTo($mode) {
        $this->Lexer->addEntryPattern('<amazon(?=.*\x3C/amazon\x3E)',$mode,'plugin_amazon');
    }
 
    function postConnect() {
      $this->Lexer->addExitPattern('</amazon>','plugin_amazon');
    }
 
    /**
     * Handle the match
     */
 
 
    function handle($match, $state, $pos) {
      if ( $state == DOKU_LEXER_UNMATCHED ) {
        $matches = preg_split('/>/u',$match,2);
        $matches[0] = trim($matches[0]);
        if ( trim($matches[0]) == '' ) {
          $matches[0] = NULL;
        }
        return array($matches[1],$matches[0]);
      }
      return TRUE;
    }
    /**
     * Create output
     */
    function render($mode, &$renderer, $data) {
      global $conf;
      if($mode == 'xhtml' && strlen($data[0]) > 1) {
        if ( !is_dir($conf['mediadir'] . '/amazon') ) mkdir($conf['mediadir'] . '/amazon', 0777-$conf['dmask']);
        $hash = md5(serialize($data[0]));
        $filename = $conf['mediadir'] . '/amazon/'.$hash.'.xml';

        if ( is_readable($filename) ) {
          $xmlreader = new xmlreader ($filename);
          $xml=$xmlreader->parse();
          $feed = $xml['ProductInfo']['#']['Details'];
          $renderer->doc .= $this->plugin_render($feed);
          return true;
        }
 
        if (!$this->getUrl($filename, $data[0])) {
          $xmlreader = new xmlreader ($filename);
          $xml=$xmlreader->parse();
          $feed = $xml['ProductInfo']['#']['Details'];
          $renderer->doc .= $this->plugin_render($feed);
        } else {
          $renderer->doc .= '**ERROR RENDERING**';
        }
        return true;
      }
      return false;
    }
 
    function getUrl($filename, &$data) {
      // $data enthaelt alles zwischen den <amazon>..</amazon> tags
      global $conf;

      // amazon array erzeugen
      $amazon=array();
      $tmp_amazon=explode("\n",$data);
      foreach ($tmp_amazon as $line) {
        if ($line) {
	  list($var,$value)=split("=",$line);
          $amazon[$var]=$value;
        }
      }

      if ($amazon['keyword'] == "") $amazon['keyword']="wiki";
      if ($amazon['mode'] == "") $amazon['mode']="books-de";
      if ($amazon['text'] == "") $amazon['text']="&nbsp;";

      $xmlurl=$conf['amazon_xml']."KeywordSearch=".rawurlencode($amazon['keyword'])."&dev-t=".$conf['amazon_dev']."&f=xml&locale=de&mode=".$amazon['mode']."&page=1&t=".$conf['amazon_id']."&type=".$amazon['type'];

      $data=array();
      $data[0]=$xmlurl;
      $data[1]=$amazon['text'];

      $retval = exec('/usr/bin/lynx --dump "'.$xmlurl.'" > '.$filename);

      return 0;
    }

    // output text string 
    function plugin_render($feed) {
          $html="<table>";
          for ($i=0; $i<sizeof ($feed); $i++)
          {
            $item  = $feed[$i];
            $html .= "<tr><td><a href=\"".$item["@"]["url"]."\">";
            $html .= "<img src=\"".$item["#"]["ImageUrlSmall"][0]["#"]."\" alt=\"".$item["#"]["ProductName"][0]["#"]."\"></img></a></td>";
            $html .= "<td><h2>".$item["#"]["ProductName"][0]["#"]."</h2>(Autor: ".$item["#"]["Authors"][0]["#"]["Author"][0]["#"].")<br />";
            $html .= "&nbsp;<a href=\"".$item["@"]["url"]."\">";
            $html .= "<b>Art.# ".$item["#"]["Asin"][0]["#"];
            if ($item["#"]["Isbn"][0]["#"]) $html .= " (ISBN: ".$item["#"]["Isbn"][0]["#"].")";
            $html .= "</b></a><br />";
            if ($item["#"]["BrowseList"][0]["#"]["BrowseNode"][0]["#"]["BrowseName"][0]["#"])
              $html .= "&nbsp;".$item["#"]["BrowseList"][0]["#"]["BrowseNode"][0]["#"]["BrowseName"][0]["#"]."<br />";
            if ($item["#"]["Media"][0]["#"]) 
              $html .= "&nbsp;".$item["#"]["Media"][0]["#"]."<br />";
            if ($item["#"]["Reviews"][0]["#"]["CustomerReview"][0]["#"]["Comment"][0]["#"]) 
              $html .= "&nbsp;".$item["#"]["Reviews"][0]["#"]["CustomerReview"][0]["#"]["Comment"][0]["#"]."<br />";
/*  $amazon[]= $item["#"]["Asin"][0]["#"];
    $amazon[]= $item["#"]["ProductName"][0]["#"];
    $amazon[]= $item["#"]["ImageUrlSmall"][0]["#"];
    $amazon[]= $item["#"]["OurPrice"][0]["#"];
    $amazon[]= $item["#"]["BrowseList"][0]["#"]["BrowseNode"][0]["#"]["BrowseName"][0]["#"];
    $amazon[]= $item["#"]["Isbn"][0]["#"];
    $amazon[]= $item["#"]["Media"][0]["#"];
    $amazon[]= $item["#"]["Reviews"][0]["#"]["CustomerReview"][0]["#"]["Comment"][0]["#"];
*/
        $html .= "</td></tr>\n";
          }
    $html .= "</table>";
      return $html;
    // p_render($format, p_get_instructions($text),$info); 
    }
}
