xref: /plugin/todo/syntax/list.php (revision 7eccb63f3d9671cd58768f0b8a57b1a03ae61fe4)
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' => 'id',
61            'completed' => 'all',
62            'assigned' => 'all',
63            'checkbox' => 'yes',
64            'username' => 'user'
65        );
66        $allowedvalues = array('yes', 'no');
67        foreach($options as $option) {
68            @list($key, $value) = explode(':', $option, 2);
69            switch($key) {                case 'header': // how should the header be rendered?
70                    if(in_array($value, array('id', 'firstheader'))) {
71                        $data['header'] = $value;
72                    }
73                    break;
74                case 'checkbox': // should checkbox be rendered?
75                    if(in_array($value, $allowedvalues)) {
76                        $data['checkbox'] = ($value == 'yes');
77                    }
78                    break;
79                case 'completed':
80                    if(in_array($value, $allowedvalues)) {
81                        $data['completed'] = ($value == 'yes');
82                    }
83                    break;
84                case 'username': // how should the username be rendered?
85                    if(in_array($value, array('user', 'real', 'none'))) {
86                        $data['username'] = $value;
87                    }
88                    break;
89                case 'assigned':
90                    if(in_array($value, $allowedvalues)) {
91                        $data['assigned'] = ($value == 'yes');
92                        break;
93                    }
94                    //assigned?
95                    $data['assigned'] = explode(',', $value);
96					// @date 20140317 le: if check for logged in user, also check for logged in user email address
97					if( in_array( '@@USER@@', $data['assigned'] ) ) {
98						$data['assigned'][] = '@@MAIL@@';
99					}
100                    $data['assigned'] = array_map(
101                        function ($user) {
102                            //placeholder (inspired by replacement-patterns - see https://www.dokuwiki.org/namespace_templates#replacement_patterns)
103                            if( $user == '@@USER@@' || $user == '@@MAIL@@' ) {
104                                return $user;
105                            }
106                            //user
107                            return ltrim($user, '@');
108                        }, $data['assigned']
109                    );
110                    break;
111            }
112        }
113        return $data;
114    }
115
116    /**
117     * Render xhtml output or metadata
118     *
119     * @param string $mode Renderer mode (supported modes: xhtml)
120     * @param Doku_Renderer $renderer The renderer
121     * @param array $data The data from the handler() function
122     * @return bool If rendering was successful.
123     */
124    public function render($mode, Doku_Renderer &$renderer, $data) {
125        global $conf;
126
127        if($mode != 'xhtml') return false;
128        /** @var Doku_Renderer_xhtml $renderer */
129
130        $opts['pattern'] = '/<todo([^>]*)>(.*)<\/todo[\W]*?>/'; //all todos in a wiki page
131        //TODO check if storing subpatterns doesn't cost too much resources
132
133        // search(&$data, $base,            $func,                       $opts,$dir='',$lvl=1,$sort='natural')
134        search($todopages, $conf['datadir'], array($this, 'search_todos'), $opts); //browse wiki pages with callback to search_pattern
135
136        $todopages = $this->filterpages($todopages, $data);
137
138        $this->htmlTodoTable($renderer, $todopages, $data);
139
140        return true;
141    }
142
143    /**
144     * Custom search callback
145     *
146     * This function is called for every found file or
147     * directory. When a directory is given to the function it has to
148     * decide if this directory should be traversed (true) or not (false).
149     * Return values for files are ignored
150     *
151     * All functions should check the ACL for document READ rights
152     * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
153     * would break the recursion (You can have an nonreadable dir over a readable
154     * one deeper nested) also make sure to check the file type (for example
155     * in case of lockfiles).
156     *
157     * @param array &$data  - Reference to the result data structure
158     * @param string $base  - Base usually $conf['datadir']
159     * @param string $file  - current file or directory relative to $base
160     * @param string $type  - Type either 'd' for directory or 'f' for file
161     * @param int    $lvl   - Current recursion depht
162     * @param array  $opts  - option array as given to search()
163     * @return bool if this directory should be traversed (true) or not (false). Return values for files are ignored.
164     */
165    public function search_todos(&$data, $base, $file, $type, $lvl, $opts) {
166        $item['id'] = pathID($file); //get current file ID
167
168        //we do nothing with directories
169        if($type == 'd') return true;
170
171        //only search txt files
172        if(substr($file, -4) != '.txt') return true;
173
174        //check ACL
175        if(auth_quickaclcheck($item['id']) < AUTH_READ) return false;
176
177        $wikitext = rawWiki($item['id']); //get wiki text
178
179        $item['count'] = preg_match_all($opts['pattern'], $wikitext, $matches); //count how many times appears the pattern
180        if(!empty($item['count'])) { //if it appears at least once
181            $item['matches'] = $matches;
182            $data[] = $item;
183        }
184        return true;
185    }
186
187    /**
188     * filter the pages
189     *
190     * @param $todopages array pages with all todoitems
191     * @param $data      array listing parameters
192     * @return array filtered pages
193     */
194    private function filterpages($todopages, $data) {
195        $pages = array();
196        foreach($todopages as $page) {
197            $todos = array();
198            // contains 3 arrays: an array with complete matches and 2 arrays with subpatterns
199            foreach($page['matches'][1] as $todoindex => $todomatch) {
200                list($checked, $todouser) = $this->parseTodoArgs($todomatch);
201                $todotitle = trim($page['matches'][2][$todoindex]);
202
203                if($this->isRequestedTodo($data, $checked, $todouser)) {
204                    $todos[] = array($todotitle, $todoindex, $todouser, $checked);
205                }
206            }
207            if(count($todos) > 0) {
208                $pages[] = array('id' => $page['id'], 'todos' => $todos);
209            }
210        }
211        return $pages;
212    }
213
214    /**
215     * Create html for table with todos
216     *
217     * @param Doku_Renderer_xhtml $R
218     * @param array $todopages
219     * @param array $data array with rendering options
220     */
221    private function htmlTodoTable($R, $todopages, $data) {
222        $R->table_open();
223        foreach($todopages as $page) {
224            $R->tablerow_open();
225            $R->tableheader_open();
226            $R->internallink($page['id'], ($data['header']=='firstheader' ? p_get_first_heading($page['id']) : $page['id']));
227            $R->tableheader_close();
228            $R->tablerow_close();
229            foreach($page['todos'] as $todo) {
230                $R->tablerow_open();
231                $R->tablecell_open();
232                $R->doc .= $this->createTodoItem($R, $todo[0], $todo[1], $todo[2], $todo[3], $page['id'], $data);
233                $R->tablecell_close();
234                $R->tablerow_close();
235            }
236        }
237        $R->table_close();
238    }
239
240    /**
241     * Check the conditions for adding a todoitem
242     *
243     * @param $data     array the defined filters
244     * @param $checked  bool completion status of task; true: finished, false: open
245     * @param $todouser string user username of user
246     * @return bool if the todoitem should be listed
247     */
248    private function isRequestedTodo($data, $checked, $todouser) {
249
250        //completion status
251        $condition1 = $data['completed'] === 'all' //all
252                      || $data['completed'] === $checked; //yes or no
253
254        // resolve placeholder in assignees
255        $requestedassignees = array();
256        if(is_array($data['assigned'])) {
257            $requestedassignees = array_map(
258                function($user) {
259					global $USERINFO;
260                    if($user == '@@USER@@' && !empty($_SERVER['REMOTE_USER'])) {  //$INPUT->server->str('REMOTE_USER')
261                            return $_SERVER['REMOTE_USER'];
262                    }
263					// @date 20140317 le: check for logged in user email address
264					if( $user == '@@MAIL@@' && isset( $USERINFO['mail'] ) ) {
265							return $USERINFO['mail'];
266					}
267                    return $user;
268                },
269                $data['assigned']
270            );
271        }
272        //assigned
273        $condition2 =   $data['assigned'] === 'all' //all
274                        || (is_bool($data['assigned']) && $data['assigned'] == $todouser) //yes or no
275                        || (is_array($data['assigned']) && in_array($todouser, $requestedassignees)); //one of the requested users?
276
277        return $condition1 AND $condition2;
278    }
279}
280