xref: /plugin/todo/syntax/list.php (revision 0d312c3820ae83cf8b3601acbea58d5b9148a16a)
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            'completeduserlist' => 'all',
64            'ns' => 'all',
65            'showdate' => $this->getConf("ShowdateList"),
66            'checkbox' => $this->getConf("Checkbox"),
67            'username' => $this->getConf("Username"),
68            'short' => false,
69        );
70        $allowedvalues = array('yes', 'no');
71        foreach($options as $option) {
72            @list($key, $value) = explode(':', $option, 2);
73            switch($key) {
74                case 'header': // how should the header be rendered?
75                    if(in_array($value, array('id', 'firstheader', 'none'))) {
76                        $data['header'] = $value;
77                    }
78                    break;
79                case 'short':
80                    if(in_array($value, $allowedvalues)) {
81                        $data['short'] = ($value == 'yes');
82                    }
83                    break;
84                case 'showdate':
85                    if(in_array($value, $allowedvalues)) {
86                        $data['showdate'] = ($value == 'yes');
87                    }
88                    break;
89                case 'checkbox': // should checkbox be rendered?
90                    if(in_array($value, $allowedvalues)) {
91                        $data['checkbox'] = ($value == 'yes');
92                    }
93                    break;
94                case 'completed':
95                    if(in_array($value, $allowedvalues)) {
96                        $data['completed'] = ($value == 'yes');
97                    }
98                    break;
99                case 'username': // how should the username be rendered?
100                    if(in_array($value, array('user', 'real', 'none'))) {
101                        $data['username'] = $value;
102                    }
103                    break;
104                case 'assigned':
105                    if(in_array($value, $allowedvalues)) {
106                        $data['assigned'] = ($value == 'yes');
107                        break;
108                    }
109                    //assigned?
110                    $data['assigned'] = explode(',', $value);
111                    // @date 20140317 le: if check for logged in user, also check for logged in user email address
112                    if( in_array( '@@USER@@', $data['assigned'] ) ) {
113                        $data['assigned'][] = '@@MAIL@@';
114                    }
115                    $data['assigned'] = array_map( array($this,"__todolistTrimUser"), $data['assigned'] );
116                    break;
117                case 'completeduser':
118                    $data['completeduserlist'] = explode(',', $value);
119                                        // @date 20140317 le: if check for logged in user, also check for logged in user email address
120                                        if(in_array('@@USER@@', $data['completeduserlist'])) {
121                                                $data['completeduserlist'][] = '@@MAIL@@';
122                                        }
123                    $data['completeduserlist'] = array_map( array($this,"__todolistTrimUser"), $data['completeduserlist'] );
124                    break;
125                case 'ns':
126                    $data['ns'] = $value;
127                    break;
128                case 'startbefore':
129                    list($data['startbefore'], $data['startignore']) = $this->analyseDate($value);
130                    break;
131                case 'startafter':
132                    list($data['startafter'], $data['startignore']) = $this->analyseDate($value);
133                    break;
134                case 'startat':
135                    list($data['startat'], $data['startignore']) = $this->analyseDate($value);
136                    break;
137                case 'duebefore':
138                    list($data['duebefore'], $data['dueignore']) = $this->analyseDate($value);
139                    break;
140                case 'dueafter':
141                    list($data['dueafter'], $data['dueignore']) = $this->analyseDate($value);
142                    break;
143                case 'dueat':
144                    list($data['dueat'], $data['dueignore']) = $this->analyseDate($value);
145                    break;
146                case 'completedbefore':
147                    list($data['completedbefore']) = $this->analyseDate($value);
148                    break;
149                case 'completedafter':
150                    list($data['completedafter']) = $this->analyseDate($value);
151                    break;
152                case 'completedat':
153                    list($data['completedat']) = $this->analyseDate($value);
154                    break;
155             }
156        }
157        return $data;
158    }
159
160    /**
161     * Render xhtml output or metadata
162     *
163     * @param string $mode Renderer mode (supported modes: xhtml)
164     * @param Doku_Renderer $renderer The renderer
165     * @param array $data The data from the handler() function
166     * @return bool If rendering was successful.
167     */
168    public function render($mode, Doku_Renderer $renderer, $data) {
169        global $conf;
170
171        if($mode != 'xhtml') return false;
172        /** @var Doku_Renderer_xhtml $renderer */
173
174        $opts['pattern'] = '/<todo([^>]*)>(.*)<\/todo[\W]*?>/'; //all todos in a wiki page
175        $opts['ns'] = $data['ns'];
176        //TODO check if storing subpatterns doesn't cost too much resources
177
178        // search(&$data, $base,            $func,                       $opts,$dir='',$lvl=1,$sort='natural')
179        search($todopages, $conf['datadir'], array($this, 'search_todos'), $opts); //browse wiki pages with callback to search_pattern
180
181        $todopages = $this->filterpages($todopages, $data);
182
183        if($data['short']) {
184            $this->htmlShort($renderer, $todopages, $data);
185        } else {
186            $this->htmlTodoTable($renderer, $todopages, $data);
187        }
188
189        return true;
190    }
191
192    /**
193     * Custom search callback
194     *
195     * This function is called for every found file or
196     * directory. When a directory is given to the function it has to
197     * decide if this directory should be traversed (true) or not (false).
198     * Return values for files are ignored
199     *
200     * All functions should check the ACL for document READ rights
201     * namespaces (directories) are NOT checked (when sneaky_index is 0) as this
202     * would break the recursion (You can have an nonreadable dir over a readable
203     * one deeper nested) also make sure to check the file type (for example
204     * in case of lockfiles).
205     *
206     * @param array &$data  - Reference to the result data structure
207     * @param string $base  - Base usually $conf['datadir']
208     * @param string $file  - current file or directory relative to $base
209     * @param string $type  - Type either 'd' for directory or 'f' for file
210     * @param int    $lvl   - Current recursion depht
211     * @param array  $opts  - option array as given to search()
212     * @return bool if this directory should be traversed (true) or not (false). Return values for files are ignored.
213     */
214    public function search_todos(&$data, $base, $file, $type, $lvl, $opts) {
215        $item['id'] = pathID($file); //get current file ID
216
217        //we do nothing with directories
218        if($type == 'd') return true;
219
220        //only search txt files
221        if(substr($file, -4) != '.txt') return true;
222
223        //check ACL
224        if(auth_quickaclcheck($item['id']) < AUTH_READ) return false;
225
226        // filter namespaces
227        if(!$this->filter_ns($item['id'], $opts['ns'])) return false;
228
229        $wikitext = rawWiki($item['id']); //get wiki text
230
231        // check if ~~NOTODO~~ is set on the page to skip this page
232        if(1 == preg_match('/~~NOTODO~~/', $wikitext)) return false;
233
234        $item['count'] = preg_match_all($opts['pattern'], $wikitext, $matches); //count how many times appears the pattern
235        if(!empty($item['count'])) { //if it appears at least once
236            $item['matches'] = $matches;
237            $data[] = $item;
238        }
239        return true;
240    }
241
242    /**
243     * filter namespaces
244     *
245     * @param $todopages array pages with all todoitems
246     * @param $item     string listing parameters
247     * @return boolean if item id is in namespace
248     */
249    private function filter_ns($item, $ns) {
250        global $ID;
251        // check if we should accept currant namespace+subnamespaces or only subnamespaces
252        $wildsubns = substr($ns, -2) == '.:';
253        $onlysubns = !$wildsubns && (substr($ns, -1) == ':' || substr($ns, -2) == ':.');
254//        $onlyns =  $onlysubns && substr($ns, -1) == '.';
255
256        // if first char of ns is '.'replace it with current ns
257        if ($ns[0] == '.') {
258            $ns = substr($ID, 0, strrpos($ID, ':')+1).ltrim($ns, '.:');
259        }
260        $ns = trim($ns, '.:');
261        $len = strlen($ns);
262        $parsepage = false;
263
264        if ($parsepage = $ns == 'all') {
265            // Always return the todo pages
266        } elseif ($ns == '/') {
267            // Only return the todo page if it's in the root namespace
268            $parsepage = strpos($item, ':') === FALSE;
269        } elseif ($wildsubns) {
270            $p = strpos($item.':', ':', $len+1);
271            $x = substr($item, $len+1, $p-$len);
272            $parsepage = 0 === strpos($item, rtrim($ns.':'.$x, ':').':');
273        } elseif ($onlysubns) {
274            $parsepage = 0 === strpos($item, $ns.':');
275        } elseif ($parsepage = substr($item, 0, $len) == $ns) {
276        }
277        return $parsepage;
278    }
279
280    /**
281     * Expand assignee-placeholders
282     *
283     * @param $user	String to be worked on
284     * @return	expanded string
285     */
286    private function __todolistExpandAssignees($user) {
287        global $USERINFO;
288        if($user == '@@USER@@' && !empty($_SERVER['REMOTE_USER'])) {  //$INPUT->server->str('REMOTE_USER')
289            return $_SERVER['REMOTE_USER'];
290        }
291        // @date 20140317 le: check for logged in user email address
292        if( $user == '@@MAIL@@' && isset( $USERINFO['mail'] ) ) {
293            return $USERINFO['mail'];
294        }
295        return  $user;
296    }
297
298    /**
299     * Trim input if it's a user
300     *
301     * @param $user	String to be worked on
302     * @return	trimmed string
303     */
304    private function __todolistTrimUser($user) {
305        //placeholder (inspired by replacement-patterns - see https://www.dokuwiki.org/namespace_templates#replacement_patterns)
306        if( $user == '@@USER@@' || $user == '@@MAIL@@' ) {
307            return $user;
308        }
309        //user
310        return trim(ltrim($user, '@'));
311    }
312
313    /**
314     * filter the pages
315     *
316     * @param $todopages array pages with all todoitems
317     * @param $data      array listing parameters
318     * @return array filtered pages
319     */
320    private function filterpages($todopages, $data) {
321        $pages = array();
322        if(count($todopages)>0) {
323            foreach($todopages as $page) {
324                $todos = array();
325                // contains 3 arrays: an array with complete matches and 2 arrays with subpatterns
326                foreach($page['matches'][1] as $todoindex => $todomatch) {
327                    $todo = array_merge(array('todotitle' => trim($page['matches'][2][$todoindex]),  'todoindex' => $todoindex), $this->parseTodoArgs($todomatch), $data);
328
329                    if($this->isRequestedTodo($todo)) { $todos[] = $todo; }
330                }
331                if(count($todos) > 0) {
332                    $pages[] = array('id' => $page['id'], 'todos' => $todos);
333                }
334            }
335            return $pages;
336        }
337    return null;
338    }
339
340
341    private function htmlShort($R, $todopages, $data) {
342        $done = 0; $todo = 0;
343//echo "<pre>";
344//print_r($todopages);
345//die;
346        foreach($todopages as $page) {
347            foreach($page['todos'] as $value) {
348                $todo++;
349                if ($value['checked']) {
350                    $done++;
351                }
352            }
353        }
354
355        $R->cdata("($done/$todo)");
356    }
357
358    /**
359     * Create html for table with todos
360     *
361     * @param Doku_Renderer_xhtml $R
362     * @param array $todopages
363     * @param array $data array with rendering options
364     */
365    private function htmlTodoTable($R, $todopages, $data) {
366        $R->table_open();
367        foreach($todopages as $page) {
368       	    if ($data['header']!='none') {
369                $R->tablerow_open();
370                $R->tableheader_open();
371                $R->internallink($page['id'], ($data['header']=='firstheader' ? p_get_first_heading($page['id']) : $page['id']));
372                $R->tableheader_close();
373                $R->tablerow_close();
374       	    }
375            foreach($page['todos'] as $todo) {
376//echo "<pre>";var_dump($todo);echo "</pre>";
377                $R->tablerow_open();
378                $R->tablecell_open();
379                $R->doc .= $this->createTodoItem($R, $page['id'], array_merge($todo, $data));
380                $R->tablecell_close();
381                $R->tablerow_close();
382            }
383        }
384        $R->table_close();
385    }
386
387    /**
388     * Check the conditions for adding a todoitem
389     *
390     * @param $data     array the defined filters
391     * @param $checked  bool completion status of task; true: finished, false: open
392     * @param $todouser string user username of user
393     * @return bool if the todoitem should be listed
394     */
395    /**
396     * Check the conditions for adding a todoitem
397     *
398     * @param $data     array the defined filters
399     * @param $checked  bool completion status of task; true: finished, false: open
400     * @param $todouser string user username of user
401     * @return bool if the todoitem should be listed
402     */
403    private function isRequestedTodo($data) {
404        //completion status
405        $condition1 = $data['completed'] === 'all' //all
406                      || $data['completed'] === $data['checked']; //yes or no
407
408        // resolve placeholder in assignees
409        $requestedassignees = array();
410        if(is_array($data['assigned'])) {
411            $requestedassignees = array_map( array($this,"__todolistExpandAssignees"), $data['assigned'] );
412        }
413        //assigned
414        $condition2 = $condition2
415                        || $data['assigned'] === 'all' //all
416                        || (is_bool($data['assigned']) && $data['assigned'] == $data['todouser']); //yes or no
417
418        if (!$condition2 && is_array($data['assigned']) && is_array($data['todousers']))
419            foreach($data['todousers'] as $todouser) {
420                if(in_array($todouser, $requestedassignees)) { $condition2 = true; break; }
421            }
422
423        //completed by
424        if($condition2 && is_array($data['completeduserlist']))
425            $condition2 = in_array($data['completeduser'], $data['completeduserlist']);
426
427        //compare start/due dates
428        if($condition1 && $condition2) {
429            $condition3s = true; $condition3d = true;
430            if(isset($data['startbefore']) || isset($data['startafter']) || isset($data['startat'])) {
431                if(is_object($data['start'])) {
432                    if($data['startignore'] != '!') {
433                        if(isset($data['startbefore'])) { $condition3s = $condition3s && new DateTime($data['startbefore']) > $data['start']; }
434                        if(isset($data['startafter'])) { $condition3s = $condition3s && new DateTime($data['startafter']) < $data['start']; }
435                        if(isset($data['startat'])) { $condition3s = $condition3s && new DateTime($data['startat']) == $data['start']; }
436                    }
437                } else {
438                    if(!$data['startignore'] == '*') { $condition3s = false; }
439                    if($data['startignore'] == '!') { $condition3s = false; }
440                }
441            }
442
443            if(isset($data['duebefore']) || isset($data['dueafter']) || isset($data['dueat'])) {
444                if(is_object($data['due'])) {
445                    if($data['dueignore'] != '!') {
446                        if(isset($data['duebefore'])) { $condition3d = $condition3d && new DateTime($data['duebefore']) > $data['due']; }
447                        if(isset($data['dueafter'])) { $condition3d = $condition3d && new DateTime($data['dueafter']) < $data['due']; }
448                        if(isset($data['dueat'])) { $condition3d = $condition3d && new DateTime($data['dueat']) == $data['due']; }
449                    }
450                 } else {
451                    if(!$data['dueignore'] == '*') { $condition3d = false; }
452                    if($data['dueignore'] == '!') { $condition3d = false; }
453                }
454            }
455            $condition3 = $condition3s && $condition3d;
456        }
457
458        // compare completed date
459        $condition4 = true;
460        if(isset($data['completedbefore'])) {
461            $condition4 = $condition4 && new DateTime($data['completedbefore']) > $data['completeddate'];
462        }
463        if(isset($data['completedafter'])) {
464            $condition4 = $condition4 && new DateTime($data['completedafter']) < $data['completeddate'];
465        }
466        if(isset($data['completedat'])) {
467            $condition4 = $condition4 && new DateTime($data['completedat']) == $data['completeddate'];
468        }
469
470        return $condition1 AND $condition2 AND $condition3 AND $condition4;
471    }
472
473
474    /**
475    * Analyse of relative/absolute Date and return an absolute date
476    *
477    * @param $date      string  absolute/relative value of the date to analyse
478    * @return           array   absolute date or actual date if $date is invalid
479    */
480    private function analyseDate($date) {
481        $result = array($date, '');
482        if(is_string($date)) {
483            if($date == '!') {
484               $result = array('', '!');
485            } elseif ($date =='*') {
486               $result = array('', '*');
487            } else {
488                if(substr($date, -1) == '*') {
489                    $date = substr($date, 0, -1);
490                    $result = array($date, '*');
491                }
492
493                if(date('Y-m-d', strtotime($date)) == $date) {
494                    $result[0] = $date;
495                } elseif(preg_match('/^[\+\-]\d+$/', $date)) { // check if we have a valid relative value
496                    $newdate = date_create(date('Y-m-d'));
497                    date_modify($newdate, $date . ' day');
498                    $result[0] = date_format($newdate, 'Y-m-d');
499                } else {
500                    $result[0] = date('Y-m-d');
501                }
502            }
503        } else { $result[0] = date('Y-m-d'); }
504
505        return $result;
506    }
507
508
509}
510