1<?php
2// must be run within Dokuwiki
3if(!defined('DOKU_INC')) die();
4
5if(!defined('DOKU_PLUGIN')) define('DOKU_PLUGIN',DOKU_INC.'lib/plugins/');
6
7/**
8 * All DokuWiki plugins to extend the parser/rendering mechanism
9 * need to inherit from this class
10 */
11class syntax_plugin_tablecalc extends DokuWiki_Syntax_Plugin {
12	var $id_index=0;
13	/**
14	* left for compatibility
15	*/
16	function getInfo() {
17		return array(
18			'author' => 'Gryaznov Sergey',
19			'email'  => 'stalker@narezka.org',
20			'date'   => '09-02-17',
21			'name'   => 'Table Calculations Plugin',
22			'desc'   => 'Enables Excel style formulas in table syntax',
23			'url'    => 'https://github.com/glasolin/tablecalc',
24		);
25	}
26
27	function getType() { return 'substition'; }
28	function getSort() { return 1213; }
29
30	/**
31	* Connect pattern to lexer
32	*/
33	function connectTo($mode) {
34		$this->Lexer->addSpecialPattern("~~=[_a-z\ A-Z0-9\%\:\.,\\\/\*\-\+\(\)\&\|#><!=;]*~~", $mode, 'plugin_tablecalc');
35	}
36
37	/**
38	* Handle the match
39	*/
40	function handle($match, $state, $pos, Doku_Handler $handler) {
41		global $ID, $ACT, $INFO;
42		$signs="-~=+*.,;\/!|&\(\)";
43		$pattern="/[$signs]*([a-zA-Z]+)\(/is";
44		$aAllowed=array("cell","row","col","cols","rows","sum","average","count","countif","nop","round","range","label","min","max","calc","check","compare", "sumif");
45		if (preg_match_all($pattern,$match,$aMatches)) {
46			foreach ($aMatches[1] as $f) {
47				if (!in_array(strtolower($f),$aAllowed)) {
48					$match=preg_replace("/([$signs]*)$f\(/is","\\1nop(",$match);
49				}
50			}
51		}
52		$aNop=array('~~=','~~');
53		foreach ($aNop as $nop) {
54			$match = str_replace($nop,'',$match);
55		}
56		$match=preg_replace("/#([^\(\);,]+)/","'\\1'",$match);
57		$match=preg_replace("/\(([a-z0-9_]+)\)/","('\\1')",$match);
58		$this->id_index++;
59		return array('formula'=>$match, 'divid'=>'__tablecalc_'.$ID.'_'.$this->id_index,'idx'=>$this->id_index);
60	}
61
62	function render($mode, Doku_Renderer $renderer, $data) {
63		global $INFO, $ID, $conf;
64		//var_dump($data);
65		if($mode == 'xhtml'){
66			$renderer->doc .= '<span id="'.$data['divid'].'"><script type="text/javascript" defer="defer">tablecalc("'.$data['divid'].'","'.$data['formula'].'")</script></span>';
67			return true;
68		}
69		return false;
70	}
71}
72?>
73