<?php
/**
 * @license    http://www.cecill.info/licences/Licence_CeCILL-B_V1-fr.html
 * @author     Francois <dokuplugin@merciol.fr>
 *
 * Plugin tiledblog: display blog in tile
 */
 
if (!defined ('DOKU_INC'))
    die ();
if (!defined ('DOKU_PLUGIN'))
    define ('DOKU_PLUGIN', DOKU_INC.'lib/plugins/');
require_once (DOKU_PLUGIN.'syntax.php');

class syntax_plugin_tiledblog extends DokuWiki_Syntax_Plugin {
 
    // ============================================================
    function getInfo () {
        return confToHash (dirname (__FILE__).'/INFO.txt');
    }
    function getType () { return 'substition'; }
    function getPType () { return 'block'; }
    function getSort () { return 299; }
    function connectTo ($mode) {
        $this->Lexer->addSpecialPattern ('\{\{tiledBlog.*?\}\}', $mode, 'plugin_tiledblog');
    }
 
    // ============================================================
    function handle ($match, $state, $pos, Doku_Handler $handler) {
        switch ($state) {
        case DOKU_LEXER_SPECIAL :
            return trim (substr ($match, 11, -2)); // "{{tiledBlog" => 11 "}}" => 2
        }
        return false;
    }

    // ============================================================
    function render ($mode, Doku_Renderer $renderer, $indata) {
        if ($mode != 'xhtml')
            return false;
        $data = " ".$indata." ";
        if (preg_match_all ("#(\"[^\"]*\")* help (\"[^\"]*\")*#", strtolower ($data), $dumy) > 0) {
            $this->help ($renderer);
            return true;
        }
        global $ID;
        $ns = getNS ($ID);
        // namespace
        if (preg_match_all ("#^ >([^ ]*) .*#", strtolower ($data), $dumy) > 0) {
            $ns = $dumy[1][0];
            if (($ns == '*') || ($ns == ':'))
                $ns = '';
            elseif ($ns == '.')
                $ns = getNS ($ID);
            else
                $ns = cleanID ($ns);
        }
        global $conf;
        $savedir = ((!$conf['savedir'] || strpos ($conf['savedir'], '.') === 0) ? DOKU_INC : "").$conf['savedir']."/";
        $cacheDir = $savedir."cache/tiledblog/";
        if (!is_dir ($cacheDir)) {
            @mkdir ($cacheDir);
            @chmod ($cacheDir, 0775);
        }
        $renderer->info ['cache'] = FALSE;
        if (preg_match_all ("#(\"[^\"]*\")* sample (\"[^\"]*\")*#", strtolower ($data), $dumy) > 0) {
            $this->sample ($renderer, $ns, $cacheDir);
            return true;
        }
        $this->tile ($renderer, $ns, $cacheDir);
        return true;
    }

    // ============================================================
    function sample (Doku_Renderer $renderer, $ns, $cacheDir) {
        $filename = $cacheDir.md5($ns)."-sample.cache";
        if (file_exists ($filename) &&
            (time () - filemtime ($filename) < $this->getConf ('sampleDelai'))) {
            $renderer->doc .= file_get_contents ($filename);
            return;
        }
        if ($helperPlugin =& plugin_load ('helper', 'blog')) {
            $entries = $helperPlugin->getBlog ($ns);
            $width = $this->getConf ('iconSize');
            $keys = array_keys ($entries);
            $rand = array_rand ($keys);
            $text = $this->getEntry ($entries [$keys [$rand]], $width);
            $renderer->doc .= $text.NL;
            file_put_contents ($filename, $text);
        }
    }

    // ============================================================
    function tile (Doku_Renderer $renderer, $ns, $cacheDir) {
        $formPos = $this->getConf ('formPosition');
        $blogPlugin =& plugin_load ('syntax', 'blog_blog');
        $createPerm = (auth_quickaclcheck ($ns.':*') >= AUTH_CREATE);
        if ($formPos == 'top')
            $this->displayForm ($renderer, $blogPlugin, $ns, $createPerm);

        $filename = $cacheDir.md5($ns)."-tile.cache";
        if (file_exists ($filename) &&
            (time () - filemtime ($filename) < $this->getConf ('sampleDelai'))) {
            $renderer->doc .= file_get_contents ($filename);
        } else {
            if ($helperPlugin =& plugin_load ('helper', 'blog'))
                $entries = $helperPlugin->getBlog ($ns);
            $text = '
     <div class="tiledblog">';
                  $width = $this->getConf ('iconSize');
                  foreach ($entries as $entry)
                      $text .= $this->getEntry ($entry, $width);
                  $text .= '
     </div>';
                  $renderer->doc .= $text.NL;
                  file_put_contents ($filename, $text);
        }

        if ($formPos == 'bottom')
            $this->displayForm ($renderer, $blogPlugin, $ns, $createPerm);
    }


    // ============================================================
    function displayForm (Doku_Renderer $renderer, syntax_plugin_blog_blog $blogPlugin, $ns, $createPerm) {
        if ($createPerm)
            $renderer->doc .= $blogPlugin->_newEntryForm ($ns, "");
        global $INFO;
        if (! $this->isAdmin ())
            return;
        $renderer->doc .= '<div><form>';
        foreach (array ('clear', 'clearAll') as $action)
            $renderer->doc .= '<input value="'.$this->getLang ($action).'" onclick="javascript:tiledblogAjax (\''.$action.'\', \''.$ns.'\')" type="button">';
       $renderer->doc .= '</form></div>';
    }

    // ============================================================
    function isAdmin () {
        global $INFO;
        return
            isset ($INFO ['userinfo']) &&
            isset ($INFO ['userinfo']['grps']) &&
            in_array (trim ($this->getConf ('adminGroup')), $INFO ['userinfo']['grps']);
    }

    // ============================================================
    function getEntry ($entry, $width) {
        if (auth_quickaclcheck($entry['id']) < AUTH_READ)
            return;
        $id    = $entry['id'];
        $file  = wikiFN ($entry['id']);
        if (!@file_exists($file))
            return '';
        $title = $entry['title'];
        $meta  = p_get_metadata ($id);
        $img   = $meta['relation']['firstimage'];
        $date  = dformat ($meta['date']['created']);
        global $_REQUEST;
        return '
     <div class="tileblog">
      <a href="'.wl ($id).'">
       <div class="image">
        <img src="'.ml ($img, array ('cache'=>$_REQUEST['cache'], 'w'=>$width)).'" width="'.$width.'"/>
       </div>
       <p class="title">'.$title.'</p>
       <p class="date">'.$date.'</p>
      </a>
     </div>';
    }

    // ============================================================
    function help (Doku_Renderer $renderer) {
        $url = "http://admin.parlenet.org/plugins/tiledblog/";
        $renderer->doc .=
                       '      <h1>Help TiledBlog V2.0</h1>'.NL.
                       '      <ul>'.NL.
                       '        <li><b>{{tiledBlog&gt;</b>namespace [help] <b>}}</b></li>'.NL.
                       '      </ul>'.NL.
                       '      <p><a class="urlextern" rel="nofollow" title="'.$url.'" href="'.$url.'">'.$url.'</a></p>'.NL;
    }

    // ============================================================
} // syntax_plugin_tiledblog
?>