xref: /plugin/todo/syntax/todo.php (revision f2dea6eed674d9256601eeef7418aea9a9dc1b48)
1<?php
2/**
3 * ToDo Plugin: Creates a checkbox based todo list
4 *
5 * Syntax: <todo [@username] [#]>Name of Action</todo> -
6 *  Creates a Checkbox with the "Name of Action" as
7 *  the text associated with it. The hash (#, optional)
8 *  will cause the checkbox to be checked by default.
9 *  The @ sign followed by a username can be used to assign this todo to a user.
10 *  examples:
11 *     A todo without user assignment
12 *       <todo>Something todo</todo>
13 *     A completed todo without user assignment
14 *       <todo #>Completed todo</todo>
15 *     A todo assigned to user User
16 *       <todo @leo>Something todo for Leo</todo>
17 *     A completed todo assigned to user User
18 *       <todo @leo #>Todo completed for Leo</todo>
19 *
20 * In combination with dokuwiki searchpattern plugin version (at least v20130408),
21 * it is a lightweight solution for a task management system based on dokuwiki.
22 * use this searchpattern expression for open todos:
23 *     ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
24 * use this searchpattern expression for completed todos:
25 *     ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
26 * do not forget the no-cache option
27 *     ~~NOCACHE~~
28 *
29 *
30 * @license    GPL 2 (http://www.gnu.org/licenses/gpl.html)
31 * @author     Babbage <babbage@digitalbrink.com>; Leo Eibler <dokuwiki@sprossenwanne.at>
32 */
33
34if(!defined('DOKU_INC')) die();
35
36/**
37 * All DokuWiki plugins to extend the parser/rendering mechanism
38 * need to inherit from this class
39 */
40class syntax_plugin_todo_todo extends DokuWiki_Syntax_Plugin {
41
42    /**
43     * Get the type of syntax this plugin defines.
44     *
45     * @return String
46     */
47    public function getType() {
48        return 'substition';
49    }
50
51    /**
52     * Paragraph Type
53     *
54     * 'normal' - The plugin can be used inside paragraphs
55     * 'block'  - Open paragraphs need to be closed before plugin output
56     * 'stack'  - Special case. Plugin wraps other paragraphs.
57     */
58    function getPType(){
59        return 'normal';
60    }
61
62    /**
63     * Where to sort in?
64     *
65     * @return Integer
66     */
67    public function getSort() {
68        return 999;
69    }
70
71    /**
72     * Connect lookup pattern to lexer.
73     *
74     * @param $mode String The desired rendermode.
75     * @return void
76     * @see render()
77     */
78    public function connectTo($mode) {
79        $this->Lexer->addEntryPattern('<todo[\s]*?.*?>(?=.*?</todo>)', $mode, 'plugin_todo_todo');
80        $this->Lexer->addSpecialPattern('~~NOTODO~~', $mode, 'plugin_todo_todo');
81    }
82
83    public function postConnect() {
84        $this->Lexer->addExitPattern('</todo>', 'plugin_todo_todo');
85    }
86
87    /**
88     * Handler to prepare matched data for the rendering process.
89     *
90     * @param $match    string  The text matched by the patterns.
91     * @param $state    int     The lexer state for the match.
92     * @param $pos      int     The character position of the matched text.
93     * @param $handler Doku_Handler  Reference to the Doku_Handler object.
94     * @return int The current lexer state for the match.
95     */
96    public function handle($match, $state, $pos, Doku_Handler $handler) {
97        switch($state) {
98            case DOKU_LEXER_ENTER :
99                #Search to see if the '#' is in the todotag (if so, this means the Action has been completed)
100                $x = preg_match('%<todo([^>]*)>%i', $match, $tododata);
101                if($x) {
102                    $handler->todoargs =  $this->parseTodoArgs($tododata[1]);
103                }
104                if(!isset($handler->todo_index) || !is_numeric($handler->todo_index)) {
105                    $handler->todo_index = 0;
106                }
107                $handler->todo_user = '';
108                $handler->checked = '';
109                break;
110            case DOKU_LEXER_MATCHED :
111                break;
112            case DOKU_LEXER_UNMATCHED :
113                /**
114                 * Structure:
115                 * input(checkbox)
116                 * <span>
117                 * -<a> (if links is on) or <span> (if links is off)
118                 * --<del> (if strikethrough is on) or --NOTHING--
119                 * -</a> or </span>
120                 * </span>
121                 */
122
123                #Make sure there is actually an action to create
124                if(trim($match) != '') {
125
126                    $data = array_merge(array ($state, 'todotitle' => $match, 'todoindex' => $handler->todo_index, 'todouser' => $handler->todo_user, 'checked' => $handler->checked), $handler->todoargs);
127                    $handler->todo_index++;
128                    return $data;
129                }
130
131                break;
132            case DOKU_LEXER_EXIT :
133                #Delete temporary checked variable
134                unset($handler->todo_user);
135                unset($handler->checked);
136                unset($handler->todoargs);
137                //unset($handler->todo_index);
138                break;
139            case DOKU_LEXER_SPECIAL :
140                break;
141        }
142        return array();
143    }
144
145    /**
146     * Handle the actual output creation.
147     *
148     * @param  $mode     String        The output format to generate.
149     * @param $renderer Doku_Renderer A reference to the renderer object.
150     * @param  $data     Array         The data created by the <tt>handle()</tt> method.
151     * @return Boolean true: if rendered successfully, or false: otherwise.
152     */
153    public function render($mode, Doku_Renderer $renderer, $data) {
154        global $ID;
155        list($state, $todotitle) = $data;
156        if($mode == 'xhtml') {
157            /** @var $renderer Doku_Renderer_xhtml */
158            if($state == DOKU_LEXER_UNMATCHED) {
159
160                #Output our result
161                $renderer->doc .= $this->createTodoItem($renderer, $ID, array_merge($data, array('checkbox'=>'yes')));
162                return true;
163            }
164
165        } elseif($mode == 'metadata') {
166            /** @var $renderer Doku_Renderer_metadata */
167            if($state == DOKU_LEXER_UNMATCHED) {
168                $id = $this->_composePageid($todotitle);
169                $renderer->internallink($id, $todotitle);
170            }
171        }
172        return false;
173    }
174
175    /**
176     * Parse the arguments of todotag
177     *
178     * @param string $todoargs
179     * @return array(bool, false|string) with checked and user
180     */
181    protected function parseTodoArgs($todoargs) {
182        $data['checked'] = false;
183        unset($data['start']);
184        unset($data['due']);
185        unset($data['completeddate']);
186        $data['showdate'] = $this->getConf("ShowdateTag");
187        $data['username'] = $this->getConf("Username");
188        $options = explode(' ', $todoargs);
189        foreach($options as $option) {
190            $option = trim($option);
191            if(empty($option)) continue;
192            if($option[0] == '@') {
193                $data['todousers'][] = substr($option, 1); //fill todousers array
194                if(!isset($data['todouser'])) $data['todouser'] = substr($option, 1); //set the first/main todouser
195            }
196            elseif($option[0] == '#') {
197                $data['checked'] = true;
198                @list($completeduser, $completeddate) = explode(':', $option, 2);
199                $data['completeduser'] = substr($completeduser, 1);
200                if(date('Y-m-d', strtotime($completeddate)) == $completeddate) {
201                    $data['completeddate'] = new DateTime($completeddate);
202                }
203            }
204            else {
205                @list($key, $value) = explode(':', $option, 2);
206                switch($key) {
207                    case 'username':
208                        if(in_array($value, array('user', 'real', 'none'))) {
209                            $data['username'] = $value;
210                        }
211                        break;
212                    case 'start':
213                        if(date('Y-m-d', strtotime($value)) == $value) {
214                            $data['start'] = new DateTime($value);
215                        }
216                        break;
217                    case 'due':
218                        if(date('Y-m-d', strtotime($value)) == $value) {
219                            $data['due'] = new DateTime($value);
220                        }
221                        break;
222                    case 'showdate':
223                        if(in_array($value, array('yes', 'no'))) {
224                            $data['showdate'] = ($value == 'yes');
225                        }
226                        break;
227                }
228            }
229        }
230        return $data;
231    }
232
233    /**
234     * @param Doku_Renderer_xhtml $renderer
235     * @param string $id of page
236     * @param array  $data  data for rendering options
237     * @return string html of an item
238     */
239    protected function createTodoItem($renderer, $id, $data) {
240        //set correct context
241        global $ID, $INFO;
242        $oldID = $ID;
243        $ID = $id;
244        $todotitle = $data['todotitle'];
245        $todoindex = $data['todoindex'];
246        $checked = $data['checked'];
247        $return = '';
248
249        if($data['checkbox']) {
250            $return .= '<input type="checkbox" class="todocheckbox"'
251            . ' data-index="' . $todoindex . '"'
252            . ' data-date="' . hsc(@filemtime(wikiFN($ID))) . '"'
253            . ' data-pageid="' . hsc($ID) . '"'
254            . ' data-strikethrough="' . ($this->getConf("Strikethrough") ? '1' : '0') . '"'
255            . ($checked ? ' checked="checked"' : '') . ' /> ';
256        }
257
258        // Username(s) of todouser(s)
259        if (!isset($data['todousers'])) $data['todousers']=array();
260        $todousers = array();
261        foreach($data['todousers'] as $user) {
262            if (($user = $this->_prepUsername($user,$data['username'])) != '') {
263                $todousers[] = $user;
264            }
265        }
266        $todouser=join(', ',$todousers);
267
268        if($todouser!='') {
269            $return .= '<span class="todouser">[' . hsc($todouser) . ']</span>';
270        }
271        if(isset($data['completeduser']) && ($checkeduser=$this->_prepUsername($data['completeduser'],$data['username']))!='') {
272            $return .= '<span class="todouser">[' . hsc('✓ '.$checkeduser);
273            if(isset($data['completeddate'])) { $return .= ', '.$data['completeddate']->format('Y-m-d'); }
274            $return .= ']</span>';
275        }
276
277        // start/due date
278        unset($bg);
279        $now = new DateTime("now");
280        if(!$checked && (isset($data['start']) || isset($data['due'])) && (!isset($data['start']) || $data['start']<$now) && (!isset($data['due']) || $now<$data['due'])) $bg='todostarted';
281        if(!$checked && isset($data['due']) && $now>=$data['due']) $bg='tododue';
282
283        // show start/due date
284        if($data['showdate'] == 1 && (isset($data['start']) || isset($data['due']))) {
285            $return .= '<span class="tododates">[';
286            if(isset($data['start'])) { $return .= $data['start']->format('Y-m-d'); }
287            $return .= ' → ';
288            if(isset($data['due'])) { $return .= $data['due']->format('Y-m-d'); }
289            $return .= ']</span>';
290        }
291
292        $spanclass = 'todotext';
293        if($this->getConf("CheckboxText") && !$this->getConf("AllowLinks") && $oldID == $ID && $data['checkbox']) {
294            $spanclass .= ' clickabletodo todohlght';
295        }
296        if(isset($bg)) $spanclass .= ' '.$bg;
297        $return .= '<span class="' . $spanclass . '">';
298
299        if($checked && $this->getConf("Strikethrough")) {
300            $return .= '<del>';
301        }
302        $return .= '<span class="todoinnertext">';
303        if($this->getConf("AllowLinks")) {
304            $return .= $this->_createLink($renderer, $todotitle, $todotitle);
305        } else {
306            if ($oldID != $ID) {
307                $return .= $renderer->internallink($id, $todotitle, null, true);
308            } else {
309                 $return .= hsc($todotitle);
310            }
311        }
312        $return .= '</span>';
313
314        if($checked && $this->getConf("Strikethrough")) {
315            $return .= '</del>';
316        }
317
318        $return .= '</span>';
319
320        //restore page ID
321        $ID = $oldID;
322        return $return;
323    }
324
325    /**
326     * Prepare user name string.
327     *
328     * @param string $username
329     * @param string $displaytype - one of 'user', 'real', 'none'
330     * @return string
331     */
332    private function _prepUsername($username, $displaytype) {
333
334        switch ($displaytype) {
335            case "real":
336                global $auth;
337                $username = $auth->getUserData($username)['name'];
338                break;
339            case "none":
340                $username="";
341                break;
342            case "user":
343            default:
344                break;
345        }
346
347        return $username;
348    }
349
350     /**
351     * Generate links from our Actions if necessary.
352     *
353     * @param Doku_Renderer_xhtml $renderer
354     * @param string $pagename
355     * @param string $name
356     * @return string
357     */
358    private function _createLink($renderer, $pagename, $name = NULL) {
359        $id = $this->_composePageid($pagename);
360
361        return $renderer->internallink($id, $name, null, true);
362    }
363
364    /**
365     * Compose the pageid of the pages linked by a todoitem
366     *
367     * @param string $pagename
368     * @return string page id
369     */
370    private function _composePageid($pagename) {
371        #Get the ActionNamespace and make sure it ends with a : (if not, add it)
372        $actionNamespace = $this->getConf("ActionNamespace");
373        if(strlen($actionNamespace) == 0 || substr($actionNamespace, -1) != ':') {
374            $actionNamespace .= ":";
375        }
376
377        #Replace ':' in $pagename so we don't create unnecessary namespaces
378        $pagename = str_replace(':', '-', $pagename);
379
380        //resolve and build link
381        $id = $actionNamespace . $pagename;
382        return $id;
383    }
384
385    /**
386     * @brief this function can be called by dokuwiki plugin searchpattern to process the todos found by searchpattern.
387     * use this searchpattern expression for open todos:
388     *          ~~SEARCHPATTERN#'/<todo[^#>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
389     * use this searchpattern expression for completed todos:
390     *          ~~SEARCHPATTERN#'/<todo[^#>]*#[^>]*>.*?<\/todo[\W]*?>/'?? _ToDo ??~~
391     * this handler method uses the table and layout with css classes from searchpattern plugin
392     *
393     * @param $type   string type of the request from searchpattern plugin
394     *                (wholeoutput, intable:whole, intable:prefix, intable:match, intable:count, intable:suffix)
395     *                wholeoutput     = all output is done by THIS plugin (no output will be done by search pattern)
396     *                intable:whole   = the left side of table (page name) is done by searchpattern, the right side
397     *                                  of the table will be done by THIS plugin
398     *                intable:prefix  = on the right side of table - THIS plugin will output a prefix header and
399     *                                  searchpattern will continue it's default output
400     *                intable:match   = if regex, right side of table - THIS plugin will format the current
401     *                                  outputvalue ($value) and output it instead of searchpattern
402     *                intable:count   = if normal, right side of table - THIS plugin will format the current
403     *                                  outputvalue ($value) and output it instead of searchpattern
404     *                intable:suffix  = on the right side of table - THIS plugin will output a suffix footer and
405     *                                  searchpattern will continue it's default output
406     * @param Doku_Renderer_xhtml $renderer current rendering object (use $renderer->doc .= 'text' to output text)
407     * @param array $data     whole data multidemensional array( array( $page => $countOfMatches ), ... )
408     * @param array $matches  whole regex matches multidemensional array( array( 0 => '1st Match', 1 => '2nd Match', ... ), ... )
409     * @param string $page     id of current page
410     * @param array $params   the parameters set by searchpattern (see search pattern documentation)
411     * @param string $value    value which should be outputted by searchpattern
412     * @return bool true if THIS method is responsible for the output (using $renderer->doc) OR false if searchpattern should output it's default
413     */
414    public function _searchpatternHandler($type, $renderer, $data, $matches, $params = array(), $page = null, $value = null) {
415        $renderer->nocache();
416
417        $type = strtolower($type);
418        switch($type) {
419            case 'wholeoutput':
420                // $matches should hold an array with all <todo>matches</todo> or <todo #>matches</todo>
421                if(!is_array($matches)) {
422                    return false;
423                }
424                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($matches,true), FILE_APPEND );
425                //file_put_contents( dirname(__FILE__).'/debug.txt', print_r($params,true), FILE_APPEND );
426                $renderer->doc .= '<div class="sp_main">';
427                $renderer->doc .= '<table class="inline sp_main_table">'; //create table
428
429                foreach($matches as $page => $allTodosPerPage) {
430                    $renderer->doc .= '<tr class="sp_title"><th class="sp_title" colspan="2"><a href="' . wl($page) . '">' . $page . '</a></td></tr>';
431                    //entry 0 contains all whole matches
432                    foreach($allTodosPerPage[0] as $todoindex => $todomatch) {
433                        $x = preg_match('%<todo([^>]*)>(.*)</[\W]*todo[\W]*>%i', $todomatch, $tododata);
434
435                        if($x) {
436                            list($checked, $todouser) = $this->parseTodoArgs($tododata[1]);
437                            $todotitle = trim($tododata[2]);
438                            if(empty($todotitle)) {
439                                continue;
440                            }
441                            $renderer->doc .= '<tr class="sp_result"><td class="sp_page" colspan="2">';
442
443                            // in case of integration with searchpattern there is no chance to find the index of an element
444                            $renderer->doc .= $this->createTodoItem($renderer, $todotitle, $todoindex, $todouser, $checked, $page, array('checkbox'=>'yes', 'username'=>'user'));
445
446                            $renderer->doc .= '</td></tr>';
447                        }
448                    }
449                }
450                $renderer->doc .= '</table>'; //end table
451                $renderer->doc .= '</div>';
452                // true means, that this handler method does the output (searchpattern plugin has nothing to do)
453                return true;
454                break;
455            case 'intable:whole':
456                break;
457            case 'intable:prefix':
458                //$renderer->doc .= '<b>Start on Page '.$page.'</b>';
459                break;
460            case 'intable:match':
461                //$renderer->doc .= 'regex match on page '.$page.': <pre>'.$value.'</pre>';
462                break;
463            case 'intable:count':
464                //$renderer->doc .= 'normal count on page '.$page.': <pre>'.$value.'</pre>';
465                break;
466            case 'intable:suffix':
467                //$renderer->doc .= '<b>End on Page '.$page.'</b>';
468                break;
469            default:
470                break;
471        }
472        // false means, that this handler method does not output anything. all should be done by searchpattern plugin
473        return false;
474    }
475}
476
477//Setup VIM: ex: et ts=4 enc=utf-8 :
478