1 <?php
2 /**
3  * CSV Plugin: displays a single value from a CSV file
4  *
5  * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
6  * @author     Andreas Gohr <gohr@cosmocode.de>
7  */
8 
9 /**
10  * Display a single CSV value
11  */
12 class syntax_plugin_csv_value extends DokuWiki_Syntax_Plugin
13 {
14 
15     protected $rowcache = array();
16 
17     /** @inheritdoc */
18     public function getType()
19     {
20         return 'substition';
21     }
22 
23     /** @inheritdoc */
24     public function getSort()
25     {
26         return 155;
27     }
28 
29     /** @inheritdoc */
30     public function getPType()
31     {
32         return 'normal';
33     }
34 
35     /** @inheritdoc */
36     public function connectTo($mode)
37     {
38         $this->Lexer->addSpecialPattern('<csvval[^>]*>', $mode, 'plugin_csv_value');
39     }
40 
41     /** @inheritdoc */
42     public function handle($match, $state, $pos, Doku_Handler $handler)
43     {
44         $optstr = substr($match, 7, -1); // <csvval ... >
45         $opt = helper_plugin_csv::parseOptions($optstr);
46 
47         return $opt;
48     }
49 
50     /**
51      * @param array $opt
52      * @return string
53      */
54     public function getCachedValue($opt)
55     {
56         $r = $opt['outr'] + $opt['hdr_rows'];
57         $c = $opt['outc'];
58         unset($opt['output']);
59         unset($opt['outr']);
60         unset($opt['outc']);
61 
62         $cache = md5(serialize($opt));
63         if (!isset($this->rowcache[$cache])) {
64             try {
65                 $content = helper_plugin_csv::loadContent($opt['file']);
66             } catch (\Exception $e) {
67                 return $e->getMessage();
68             }
69             $this->rowcache[$cache] = helper_plugin_csv::prepareData($content, $opt);
70         }
71 
72         if (isset($this->rowcache[$cache][$r][$c])) {
73             return $this->rowcache[$cache][$r][$c];
74         } else {
75             return 'Failed to find requested value';
76         }
77     }
78 
79     /** @inheritdoc */
80     public function render($mode, Doku_Renderer $renderer, $opt)
81     {
82         if ($mode == 'metadata') return false;
83 
84         if ($opt['file'] === '') {
85             $renderer->cdata('no csv file given');
86             return true;
87         }
88 
89         if (!media_ispublic($opt['file'])) $renderer->info['cache'] = false;
90 
91         $value = $this->getCachedValue($opt);
92         $renderer->cdata($value);
93         return true;
94     }
95 
96 }
97