xref: /plugin/todo/syntax/list.php (revision f1a46b725509f2a47028d1219969b64a1bc032d3)
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            'ns' => 'all',
64            'showdate' => $this->getConf("ShowdateList"),
65            'checkbox' => $this->getConf("Checkbox"),
66            'username' => $this->getConf("Username"),
67        );
68        $allowedvalues = array('yes', 'no');
69        foreach($options as $option) {
70            @list($key, $value) = explode(':', $option, 2);
71            switch($key) {
72            	case 'header': // how should the header be rendered?
73                    if(in_array($value, array('id', 'firstheader', 'none'))) {
74                        $data['header'] = $value;
75                    }
76                    break;
77                case 'showdate':
78                    if(in_array($value, $allowedvalues)) {
79                        $data['showdate'] = ($value == 'yes');
80                    }
81                    break;
82                case 'checkbox': // should checkbox be rendered?
83                    if(in_array($value, $allowedvalues)) {
84                        $data['checkbox'] = ($value == 'yes');
85                    }
86                    break;
87                case 'completed':
88                    if(in_array($value, $allowedvalues)) {
89                        $data['completed'] = ($value == 'yes');
90                    }
91                    break;
92                case 'username': // how should the username be rendered?
93                    if(in_array($value, array('user', 'real', 'none'))) {
94                        $data['username'] = $value;
95                    }
96                    break;
97                case 'assigned':
98                    if(in_array($value, $allowedvalues)) {
99                        $data['assigned'] = ($value == 'yes');
100                        break;
101                    }
102                    //assigned?
103                    $data['assigned'] = explode(',', $value);
104					// @date 20140317 le: if check for logged in user, also check for logged in user email address
105					if( in_array( '@@USER@@', $data['assigned'] ) ) {
106						$data['assigned'][] = '@@MAIL@@';
107					}
108                    $data['assigned'] = array_map(
109                        function ($user) {
110                            //placeholder (inspired by replacement-patterns - see https://www.dokuwiki.org/namespace_templates#replacement_patterns)
111                            if( $user == '@@USER@@' || $user == '@@MAIL@@' ) {
112                                return $user;
113                            }
114                            //user
115                            return trim(ltrim($user, '@'));
116                        }, $data['assigned']
117                    );
118                    break;
119                case 'ns':
120                    $data['ns'] = $value;
121                    break;
122                case 'startbefore':
123                    $data['startbefore'] = $this->analyseDate($value);
124                    break;
125                case 'startafter':
126                    $data['startafter'] = $this->analyseDate($value);
127                    break;
128                 case 'duebefore':
129                    $data['duebefore'] = $this->analyseDate($value);
130                    break;
131                 case 'dueafter':
132                    $data['dueafter'] = $this->analyseDate($value);
133                    break;
134             }
135        }
136        return $data;
137    }
138
139    /**
140     * Render xhtml output or metadata
141     *
142     * @param string $mode Renderer mode (supported modes: xhtml)
143     * @param Doku_Renderer $renderer The renderer
144     * @param array $data The data from the handler() function
145     * @return bool If rendering was successful.
146     */
147    public function render($mode, Doku_Renderer &$renderer, $data) {
148        global $conf;
149
150        if($mode != 'xhtml') return false;
151        /** @var Doku_Renderer_xhtml $renderer */
152
153        $opts['pattern'] = '/<todo([^>]*)>(.*)<\/todo[\W]*?>/'; //all todos in a wiki page
154        //TODO check if storing subpatterns doesn't cost too much resources
155
156        // search(&$data, $base,            $func,                       $opts,$dir='',$lvl=1,$sort='natural')
157        search($todopages, $conf['datadir'], array($this, 'search_todos'), $opts); //browse wiki pages with callback to search_pattern
158
159        $todopages = $this->filterpages($todopages, $data);
160
161        $this->htmlTodoTable($renderer, $todopages, $data);
162
163        return true;
164    }
165
166    /**
167     * Custom search callback
168     *
169     * This function is called for every found file or
170     * directory. When a directory is given to the function it has to
171     * decide if this directory should be traversed (true) or not (false).
172     * Return values for files are ignored
173     *
174     * All functions should check the ACL for document READ rights
175     * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
176     * would break the recursion (You can have an nonreadable dir over a readable
177     * one deeper nested) also make sure to check the file type (for example
178     * in case of lockfiles).
179     *
180     * @param array &$data  - Reference to the result data structure
181     * @param string $base  - Base usually $conf['datadir']
182     * @param string $file  - current file or directory relative to $base
183     * @param string $type  - Type either 'd' for directory or 'f' for file
184     * @param int    $lvl   - Current recursion depht
185     * @param array  $opts  - option array as given to search()
186     * @return bool if this directory should be traversed (true) or not (false). Return values for files are ignored.
187     */
188    public function search_todos(&$data, $base, $file, $type, $lvl, $opts) {
189        $item['id'] = pathID($file); //get current file ID
190
191        //we do nothing with directories
192        if($type == 'd') return true;
193
194        //only search txt files
195        if(substr($file, -4) != '.txt') return true;
196
197        //check ACL
198        if(auth_quickaclcheck($item['id']) < AUTH_READ) return false;
199
200        $wikitext = rawWiki($item['id']); //get wiki text
201
202        $item['count'] = preg_match_all($opts['pattern'], $wikitext, $matches); //count how many times appears the pattern
203        if(!empty($item['count'])) { //if it appears at least once
204            $item['matches'] = $matches;
205            $data[] = $item;
206        }
207        return true;
208    }
209
210    /**
211     * filter the pages
212     *
213     * @param $todopages array pages with all todoitems
214     * @param $data      array listing parameters
215     * @return array filtered pages
216     */
217    private function filterpages($todopages, $data) {
218        $pages = array();
219        foreach($todopages as $page) {
220            $parsepage = 0;
221            if ($data['ns'] == 'all') {
222                // Always return the todo pages
223                $parsepage = 1;
224            } elseif ($data['ns'] == '/') {
225                // Only return the todo page if it's in the root namespace
226                if (strpos($page['id'], ':') === FALSE) $parsepage = 1;
227            } elseif (substr( $page['id'], 0, strlen($data['ns']) ) === $data['ns']) {
228                // Only return the todo page if it starts with the given string
229                $parsepage = 1;
230            }
231            if ($parsepage == 1) {
232                $todos = array();
233                // contains 3 arrays: an array with complete matches and 2 arrays with subpatterns
234                foreach($page['matches'][1] as $todoindex => $todomatch) {
235                    $todo = array_merge(array('todotitle' => trim($page['matches'][2][$todoindex]),  'todoindex' => $todoindex), $this->parseTodoArgs($todomatch), $data);
236
237                    if($this->isRequestedTodo($todo)) { $todos[] = $todo; }
238                }
239                if(count($todos) > 0) {
240                    $pages[] = array('id' => $page['id'], 'todos' => $todos);
241                }
242            }
243        }
244        return $pages;
245    }
246
247    /**
248     * Create html for table with todos
249     *
250     * @param Doku_Renderer_xhtml $R
251     * @param array $todopages
252     * @param array $data array with rendering options
253     */
254    private function htmlTodoTable($R, $todopages, $data) {
255        $R->table_open();
256        foreach($todopages as $page) {
257       	    if ($data['header']!='none') {
258                $R->tablerow_open();
259                $R->tableheader_open();
260                $R->internallink($page['id'], ($data['header']=='firstheader' ? p_get_first_heading($page['id']) : $page['id']));
261                $R->tableheader_close();
262                $R->tablerow_close();
263       	    }
264            foreach($page['todos'] as $todo) {
265//echo "<pre>";var_dump($todo);echo "</pre>";
266                $R->tablerow_open();
267                $R->tablecell_open();
268                $R->doc .= $this->createTodoItem($R, $page['id'], array_merge($todo, $data));
269                $R->tablecell_close();
270                $R->tablerow_close();
271            }
272        }
273        $R->table_close();
274    }
275
276    /**
277     * Check the conditions for adding a todoitem
278     *
279     * @param $data     array the defined filters
280     * @param $checked  bool completion status of task; true: finished, false: open
281     * @param $todouser string user username of user
282     * @return bool if the todoitem should be listed
283     */
284    private function isRequestedTodo($data) {
285        //completion status
286        $condition1 = $data['completed'] === 'all' //all
287                      || $data['completed'] === $data['checked']; //yes or no
288
289        // resolve placeholder in assignees
290        $requestedassignees = array();
291        if(is_array($data['assigned'])) {
292            $requestedassignees = array_map(
293                function($user) {
294					global $USERINFO;
295                    if($user == '@@USER@@' && !empty($_SERVER['REMOTE_USER'])) {  //$INPUT->server->str('REMOTE_USER')
296                            return $_SERVER['REMOTE_USER'];
297                    }
298					// @date 20140317 le: check for logged in user email address
299					if( $user == '@@MAIL@@' && isset( $USERINFO['mail'] ) ) {
300							return $USERINFO['mail'];
301					}
302                    return  $user;
303                },
304                $data['assigned']
305            );
306        }
307        //assigned
308        $condition2 = $condition2
309                        || $data['assigned'] === 'all' //all
310                        || (is_bool($data['assigned']) && $data['assigned'] == $data['todouser']); //yes or no
311
312        if (!$condition2 && is_array($data['assigned']) && is_array($data['todousers']))
313            foreach($data['todousers'] as $todouser) {
314                if(in_array($todouser, $requestedassignees)) { $condition2 = true; break; }
315            }
316
317        //compare start/due dates
318        if(isset($data['startbefore']) || isset($data['startafter']) || isset($data['duebefore']) || isset($data['dueafter'])) {
319            $condition3 = false;
320            if((isset($data['startbefore']) && isset($data['start'])) || (isset($data['startafter']) && isset($data['start']))
321              || (isset($data['duebefore']) && isset($data['due'])) || (isset($data['dueafter']) && isset($data['due']))) {
322                $condition3 = true;
323                if(isset($data['startbefore'])) { $condition3 = $condition3 && new DateTime($data['startbefore']) > $data['start']; }
324                if(isset($data['startafter'])) { $condition3 = $condition3 && new DateTime($data['startafter']) < $data['start']; }
325                if(isset($data['duebefore'])) { $condition3 = $condition3 && new DateTime($data['startbefore']) > $data['due']; }
326                if(isset($data['dueafter'])) { $condition3 = $condition3 && new DateTime($data['duebefore']) < $data['due']; }
327            }
328        } else { $condition3 = true; }
329        return $condition1 AND $condition2 AND $condition3;
330    }
331
332    /**
333    * Analyse of relative/absolute Date and return an absolute date
334    *
335    * @param $date	string	absolute/relative value of the date to analyse
336    * @return 		string   absolute date or actual date if $date is invalid
337    */
338    private function analyseDate($date) {
339        if(is_string($date)) {
340            if(date('Y-m-d', strtotime($date)) == $date) {
341                $result = $date;
342            } elseif(preg_match('/^[\+\-]\d+$/', $date)) { // check if we have a valid relative value
343                $newdate = date_create(date('Y-m-d'));
344                date_modify($newdate, $date . ' day');
345                $result = date_format($newdate, 'Y-m-d');
346            } else {
347                $result = date('Y-m-d');
348            }
349        } else {
350            $result = date('Y-m-d');
351        }
352        return $result;
353    }
354}
355