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