xref: /plugin/todo/syntax/list.php (revision e425e3b2a65263932683b969ff377ef7e45c2eae)
1<?php
2/**
3 * DokuWiki Plugin todo_list (Syntax Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 */
7
8// must be run within Dokuwiki
9if(!defined('DOKU_INC')) die();
10
11/**
12 * Class syntax_plugin_todo_list
13 */
14class syntax_plugin_todo_list extends syntax_plugin_todo_todo {
15
16    /**
17     * @return string Syntax mode type
18     */
19    public function getType() {
20        return 'substition';
21    }
22
23    /**
24     * @return string Paragraph type
25     */
26    public function getPType() {
27        return 'block';
28    }
29
30    /**
31     * @return int Sort order - Low numbers go before high numbers
32     */
33    public function getSort() {
34        return 250;
35    }
36
37    /**
38     * Connect lookup pattern to lexer.
39     *
40     * @param string $mode Parser mode
41     */
42    public function connectTo($mode) {
43        $this->Lexer->addSpecialPattern('~~TODOLIST[^~]*~~', $mode, 'plugin_todo_list');
44    }
45
46    /**
47     * Handle matches of the todolist syntax
48     *
49     * @param string $match The match of the syntax
50     * @param int $state The state of the handler
51     * @param int $pos The position in the document
52     * @param Doku_Handler $handler The handler
53     * @return array Data for the renderer
54     */
55    public function handle($match, $state, $pos, Doku_Handler &$handler) {
56
57        $options = substr($match, 10, -2); // strip markup
58        $options = explode(' ', $options);
59        $data = array(
60            'header' => $this->getConf("Header"),
61            'completed' => 'all',
62            'assigned' => 'all',
63            'showdate' => $this->getConf("ShowdateList"),
64            'checkbox' => $this->getConf("Checkbox"),
65            'username' => $this->getConf("Username"),
66        );
67        $allowedvalues = array('yes', 'no');
68        foreach($options as $option) {
69            @list($key, $value) = explode(':', $option, 2);
70            switch($key) {
71            	case 'header': // how should the header be rendered?
72                    if(in_array($value, array('id', 'firstheader', 'none'))) {
73                        $data['header'] = $value;
74                    }
75                    break;
76                case 'showdate':
77                    if(in_array($value, $allowedvalues)) {
78                        $data['showdate'] = ($value == 'yes');
79                    }
80                    break;
81                case 'checkbox': // should checkbox be rendered?
82                    if(in_array($value, $allowedvalues)) {
83                        $data['checkbox'] = ($value == 'yes');
84                    }
85                    break;
86                case 'completed':
87                    if(in_array($value, $allowedvalues)) {
88                        $data['completed'] = ($value == 'yes');
89                    }
90                    break;
91                case 'username': // how should the username be rendered?
92                    if(in_array($value, array('user', 'real', 'none'))) {
93                        $data['username'] = $value;
94                    }
95                    break;
96                case 'assigned':
97                    if(in_array($value, $allowedvalues)) {
98                        $data['assigned'] = ($value == 'yes');
99                        break;
100                    }
101                    //assigned?
102                    $data['assigned'] = explode(',', $value);
103					// @date 20140317 le: if check for logged in user, also check for logged in user email address
104					if( in_array( '@@USER@@', $data['assigned'] ) ) {
105						$data['assigned'][] = '@@MAIL@@';
106					}
107                    $data['assigned'] = array_map(
108                        function ($user) {
109                            //placeholder (inspired by replacement-patterns - see https://www.dokuwiki.org/namespace_templates#replacement_patterns)
110                            if( $user == '@@USER@@' || $user == '@@MAIL@@' ) {
111                                return $user;
112                            }
113                            //user
114                            return trim(ltrim($user, '@'));
115                        }, $data['assigned']
116                    );
117                    break;
118            }
119        }
120        return $data;
121    }
122
123    /**
124     * Render xhtml output or metadata
125     *
126     * @param string $mode Renderer mode (supported modes: xhtml)
127     * @param Doku_Renderer $renderer The renderer
128     * @param array $data The data from the handler() function
129     * @return bool If rendering was successful.
130     */
131    public function render($mode, Doku_Renderer &$renderer, $data) {
132        global $conf;
133
134        if($mode != 'xhtml') return false;
135        /** @var Doku_Renderer_xhtml $renderer */
136
137        $opts['pattern'] = '/<todo([^>]*)>(.*)<\/todo[\W]*?>/'; //all todos in a wiki page
138        //TODO check if storing subpatterns doesn't cost too much resources
139
140        // search(&$data, $base,            $func,                       $opts,$dir='',$lvl=1,$sort='natural')
141        search($todopages, $conf['datadir'], array($this, 'search_todos'), $opts); //browse wiki pages with callback to search_pattern
142
143        $todopages = $this->filterpages($todopages, $data);
144
145        $this->htmlTodoTable($renderer, $todopages, $data);
146
147        return true;
148    }
149
150    /**
151     * Custom search callback
152     *
153     * This function is called for every found file or
154     * directory. When a directory is given to the function it has to
155     * decide if this directory should be traversed (true) or not (false).
156     * Return values for files are ignored
157     *
158     * All functions should check the ACL for document READ rights
159     * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
160     * would break the recursion (You can have an nonreadable dir over a readable
161     * one deeper nested) also make sure to check the file type (for example
162     * in case of lockfiles).
163     *
164     * @param array &$data  - Reference to the result data structure
165     * @param string $base  - Base usually $conf['datadir']
166     * @param string $file  - current file or directory relative to $base
167     * @param string $type  - Type either 'd' for directory or 'f' for file
168     * @param int    $lvl   - Current recursion depht
169     * @param array  $opts  - option array as given to search()
170     * @return bool if this directory should be traversed (true) or not (false). Return values for files are ignored.
171     */
172    public function search_todos(&$data, $base, $file, $type, $lvl, $opts) {
173        $item['id'] = pathID($file); //get current file ID
174
175        //we do nothing with directories
176        if($type == 'd') return true;
177
178        //only search txt files
179        if(substr($file, -4) != '.txt') return true;
180
181        //check ACL
182        if(auth_quickaclcheck($item['id']) < AUTH_READ) return false;
183
184        $wikitext = rawWiki($item['id']); //get wiki text
185
186        $item['count'] = preg_match_all($opts['pattern'], $wikitext, $matches); //count how many times appears the pattern
187        if(!empty($item['count'])) { //if it appears at least once
188            $item['matches'] = $matches;
189            $data[] = $item;
190        }
191        return true;
192    }
193
194    /**
195     * filter the pages
196     *
197     * @param $todopages array pages with all todoitems
198     * @param $data      array listing parameters
199     * @return array filtered pages
200     */
201    private function filterpages($todopages, $data) {
202        $pages = array();
203        foreach($todopages as $page) {
204            $todos = array();
205            // contains 3 arrays: an array with complete matches and 2 arrays with subpatterns
206            foreach($page['matches'][1] as $todoindex => $todomatch) {
207                $todo = array_merge(array('todotitle' => trim($page['matches'][2][$todoindex]),  'todoindex' => $todoindex), $this->parseTodoArgs($todomatch), $data);
208
209                if($this->isRequestedTodo($todo)) { $todos[] = $todo; }
210            }
211            if(count($todos) > 0) {
212                $pages[] = array('id' => $page['id'], 'todos' => $todos);
213            }
214        }
215        return $pages;
216    }
217
218    /**
219     * Create html for table with todos
220     *
221     * @param Doku_Renderer_xhtml $R
222     * @param array $todopages
223     * @param array $data array with rendering options
224     */
225    private function htmlTodoTable($R, $todopages, $data) {
226        $R->table_open();
227        foreach($todopages as $page) {
228       	    if ($data['header']!='none') {
229                $R->tablerow_open();
230                $R->tableheader_open();
231                $R->internallink($page['id'], ($data['header']=='firstheader' ? p_get_first_heading($page['id']) : $page['id']));
232                $R->tableheader_close();
233                $R->tablerow_close();
234       	    }
235            foreach($page['todos'] as $todo) {
236//echo "<pre>";var_dump($todo);echo "</pre>";
237                $R->tablerow_open();
238                $R->tablecell_open();
239                $R->doc .= $this->createTodoItem($R, $page['id'], array_merge($todo, $data));
240                $R->tablecell_close();
241                $R->tablerow_close();
242            }
243        }
244        $R->table_close();
245    }
246
247    /**
248     * Check the conditions for adding a todoitem
249     *
250     * @param $data     array the defined filters
251     * @param $checked  bool completion status of task; true: finished, false: open
252     * @param $todouser string user username of user
253     * @return bool if the todoitem should be listed
254     */
255    private function isRequestedTodo($data) {
256
257        //completion status
258        $condition1 = $data['completed'] === 'all' //all
259                      || $data['completed'] === $data['checked']; //yes or no
260
261        // resolve placeholder in assignees
262        $requestedassignees = array();
263        if(is_array($data['assigned'])) {
264            $requestedassignees = array_map(
265                function($user) {
266					global $USERINFO;
267                    if($user == '@@USER@@' && !empty($_SERVER['REMOTE_USER'])) {  //$INPUT->server->str('REMOTE_USER')
268                            return $_SERVER['REMOTE_USER'];
269                    }
270					// @date 20140317 le: check for logged in user email address
271					if( $user == '@@MAIL@@' && isset( $USERINFO['mail'] ) ) {
272							return $USERINFO['mail'];
273					}
274                    return  $user;
275                },
276                $data['assigned']
277            );
278        }
279        //assigned
280        $condition2 = $condition2
281                        || $data['assigned'] === 'all' //all
282                        || (is_bool($data['assigned']) && $data['assigned'] == $data['todouser']); //yes or no
283
284        if (!$condition2 && is_array($data['assigned']) && is_array($data['todousers']))
285            foreach($data['todousers'] as $todouser) {
286                if(in_array($todouser, $requestedassignees)) { $condition2 = true; break; }
287            }
288
289        return $condition1 AND $condition2;
290    }
291}
292tableheader_open();
293                $R-
294