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