<?php
/**
 * quiz plugin : Create a book from some pages.
 *
 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
 * @author     Luigi Micco <l.micco@tiscali.it>
 */

// must be run within Dokuwiki
if (!defined('DOKU_INC')) die();

if (!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN', DOKU_INC . 'lib/plugins/');
require_once(DOKU_PLUGIN . 'syntax.php');
require_once(DOKU_INC.'inc/search.php');

/**
 * All DokuWiki plugins to extend the parser/rendering mechanism
 * need to inherit from this class
 */
class syntax_plugin_quiz extends DokuWiki_Syntax_Plugin {
    

    function setupLocale(){
        parent::setupLocale(); 
    }

    function connectTo($mode) {
        $this->Lexer->addSpecialPattern('{{quiz>.+?}}', $mode, 'plugin_quiz');
    }

    //function getType() { return 'substition'; }
    function getType(){ return 'container';}
    function getPType(){ return 'block';}

    /**
     * Where to sort in?
     */
    function getSort(){
        return 190; 
    }


    function handle($match, $state, $pos, &$handler) {
      
      $match = substr($match, 2, -2); // strip markup
      list($match, $flags) = explode('&', $match, 2);

      // break the pattern up into its constituent parts 
      list($include, $id, $section) = preg_split('/>|#/u', $match, 3); 
      return array($include, $id, explode('&', $flags)); 
   
    }

    function render($mode, &$renderer, $data) {
      list($type, $quiz_file, $flags) = $data; 

      if ($type == "quiz") {
        if ($mode == 'xhtml') {
          $param = array();
          
          $param['learning'] = 0;
          $param['rndchoice'] = 0;
          $param['rndquest'] = 0;
          $param['highscores'] = 0;
          $param['showintro'] = 0;
          
          foreach($flags as $value) {
            if (in_array(strtolower($value), array('learning', 'rndchoice','rndquest','highscores', 'showintro') )) {
              $param[strtolower($value)] = 1;
            }
          }  

          $quiz_file = preg_replace("/{{([^|}]+).*}}/","$1",$quiz_file);
          $renderer->info['cache'] = FALSE;
          require_once('class_quiz.php');
          $quiz=new quiz($quiz_file, $param);
          $renderer->doc .= '<div id="quiz-div__'.$quiz_file.'">'.$quiz->do_quiz_here().'</div>'; 
        }  
       }
       return false;
    }

   
}
?>
