xref: /plugin/todo/syntax/list.php (revision 7e85ccb34c0f6541ee78f7e9cd53cfabb47e5d87)
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]*?>/s'; //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        foreach($todopages as $page) {
323            $todos = array();
324            // contains 3 arrays: an array with complete matches and 2 arrays with subpatterns
325            foreach($page['matches'][1] as $todoindex => $todomatch) {
326                $todo = array_merge(array('todotitle' => trim($page['matches'][2][$todoindex]),  'todoindex' => $todoindex), $this->parseTodoArgs($todomatch), $data);
327
328                if($this->isRequestedTodo($todo)) { $todos[] = $todo; }
329            }
330            if(count($todos) > 0) {
331                $pages[] = array('id' => $page['id'], 'todos' => $todos);
332            }
333        }
334        return $pages;
335    }
336
337    private function htmlShort($R, $todopages, $data) {
338        $done = 0; $todo = 0;
339//echo "<pre>";
340//print_r($todopages);
341//die;
342        foreach($todopages as $page) {
343            foreach($page['todos'] as $value) {
344                $todo++;
345                if ($value['checked']) {
346                    $done++;
347                }
348            }
349        }
350
351        $R->cdata("($done/$todo)");
352    }
353
354    /**
355     * Create html for table with todos
356     *
357     * @param Doku_Renderer_xhtml $R
358     * @param array $todopages
359     * @param array $data array with rendering options
360     */
361    private function htmlTodoTable($R, $todopages, $data) {
362        $R->table_open();
363        foreach($todopages as $page) {
364       	    if ($data['header']!='none') {
365                $R->tablerow_open();
366                $R->tableheader_open();
367                $R->internallink($page['id'], ($data['header']=='firstheader' ? p_get_first_heading($page['id']) : $page['id']));
368                $R->tableheader_close();
369                $R->tablerow_close();
370       	    }
371            foreach($page['todos'] as $todo) {
372//echo "<pre>";var_dump($todo);echo "</pre>";
373                $R->tablerow_open();
374                $R->tablecell_open();
375                $R->doc .= $this->createTodoItem($R, $page['id'], array_merge($todo, $data));
376                $R->tablecell_close();
377                $R->tablerow_close();
378            }
379        }
380        $R->table_close();
381    }
382
383    /**
384     * Check the conditions for adding a todoitem
385     *
386     * @param $data     array the defined filters
387     * @param $checked  bool completion status of task; true: finished, false: open
388     * @param $todouser string user username of user
389     * @return bool if the todoitem should be listed
390     */
391    /**
392     * Check the conditions for adding a todoitem
393     *
394     * @param $data     array the defined filters
395     * @param $checked  bool completion status of task; true: finished, false: open
396     * @param $todouser string user username of user
397     * @return bool if the todoitem should be listed
398     */
399    private function isRequestedTodo($data) {
400        //completion status
401        $condition1 = $data['completed'] === 'all' //all
402                      || $data['completed'] === $data['checked']; //yes or no
403
404        // resolve placeholder in assignees
405        $requestedassignees = array();
406        if(is_array($data['assigned'])) {
407            $requestedassignees = array_map( array($this,"__todolistExpandAssignees"), $data['assigned'] );
408        }
409        //assigned
410        $condition2 = $condition2
411                        || $data['assigned'] === 'all' //all
412                        || (is_bool($data['assigned']) && $data['assigned'] == $data['todouser']); //yes or no
413
414        if (!$condition2 && is_array($data['assigned']) && is_array($data['todousers']))
415            foreach($data['todousers'] as $todouser) {
416                if(in_array($todouser, $requestedassignees)) { $condition2 = true; break; }
417            }
418
419        //completed by
420        if($condition2 && is_array($data['completeduserlist']))
421            $condition2 = in_array($data['completeduser'], $data['completeduserlist']);
422
423        //compare start/due dates
424        if($condition1 && $condition2) {
425            $condition3s = true; $condition3d = true;
426            if(isset($data['startbefore']) || isset($data['startafter']) || isset($data['startat'])) {
427                if(is_object($data['start'])) {
428                    if($data['startignore'] != '!') {
429                        if(isset($data['startbefore'])) { $condition3s = $condition3s && new DateTime($data['startbefore']) > $data['start']; }
430                        if(isset($data['startafter'])) { $condition3s = $condition3s && new DateTime($data['startafter']) < $data['start']; }
431                        if(isset($data['startat'])) { $condition3s = $condition3s && new DateTime($data['startat']) == $data['start']; }
432                    }
433                } else {
434                    if(!$data['startignore'] == '*') { $condition3s = false; }
435                    if($data['startignore'] == '!') { $condition3s = false; }
436                }
437            }
438
439            if(isset($data['duebefore']) || isset($data['dueafter']) || isset($data['dueat'])) {
440                if(is_object($data['due'])) {
441                    if($data['dueignore'] != '!') {
442                        if(isset($data['duebefore'])) { $condition3d = $condition3d && new DateTime($data['duebefore']) > $data['due']; }
443                        if(isset($data['dueafter'])) { $condition3d = $condition3d && new DateTime($data['dueafter']) < $data['due']; }
444                        if(isset($data['dueat'])) { $condition3d = $condition3d && new DateTime($data['dueat']) == $data['due']; }
445                    }
446                 } else {
447                    if(!$data['dueignore'] == '*') { $condition3d = false; }
448                    if($data['dueignore'] == '!') { $condition3d = false; }
449                }
450            }
451            $condition3 = $condition3s && $condition3d;
452        }
453
454	// compare completed date
455        $condition4 = true;
456        if(isset($data['completedbefore'])) {
457            $condition4 = $condition4 && new DateTime($data['completedbefore']) > $data['completeddate'];
458        }
459        if(isset($data['completedafter'])) {
460            $condition4 = $condition4 && new DateTime($data['completedafter']) < $data['completeddate'];
461        }
462        if(isset($data['completedat'])) {
463            $condition4 = $condition4 && new DateTime($data['completedat']) == $data['completeddate'];
464        }
465
466        return $condition1 AND $condition2 AND $condition3 AND $condition4;
467    }
468
469
470    /**
471    * Analyse of relative/absolute Date and return an absolute date
472    *
473    * @param $date      string  absolute/relative value of the date to analyse
474    * @return           array   absolute date or actual date if $date is invalid
475    */
476    private function analyseDate($date) {
477        $result = array($date, '');
478        if(is_string($date)) {
479            if($date == '!') {
480               $result = array('', '!');
481            } elseif ($date =='*') {
482               $result = array('', '*');
483            } else {
484                if(substr($date, -1) == '*') {
485                    $date = substr($date, 0, -1);
486                    $result = array($date, '*');
487                }
488
489                if(date('Y-m-d', strtotime($date)) == $date) {
490                    $result[0] = $date;
491                } elseif(preg_match('/^[\+\-]\d+$/', $date)) { // check if we have a valid relative value
492                    $newdate = date_create(date('Y-m-d'));
493                    date_modify($newdate, $date . ' day');
494                    $result[0] = date_format($newdate, 'Y-m-d');
495                } else {
496                    $result[0] = date('Y-m-d');
497                }
498            }
499        } else { $result[0] = date('Y-m-d'); }
500
501        return $result;
502    }
503
504
505}
506