xref: /plugin/todo/action.php (revision 52ab628c465f4b533af47599e93f5433c02d5489)
1<?php
2
3/**
4 * ToDo Action Plugin: Inserts button for ToDo plugin into toolbar
5 *
6 * Original Example: http://www.dokuwiki.org/devel:action_plugins
7 * @author     Babbage <babbage@digitalbrink.com>
8 * @date 20130405 Leo Eibler <dokuwiki@sprossenwanne.at> \n
9 *                replace old sack() method with new jQuery method and use post instead of get \n
10 * @date 20130408 Leo Eibler <dokuwiki@sprossenwanne.at> \n
11 *                remove getInfo() call because it's done by plugin.info.txt (since dokuwiki 2009-12-25 Lemming)
12 */
13
14if(!defined('DOKU_INC')) die();
15/**
16 * Class action_plugin_todo registers actions
17 */
18class action_plugin_todo extends DokuWiki_Action_Plugin {
19
20    /**
21     * Register the eventhandlers
22     */
23    public function register(Doku_Event_Handler $controller) {
24        $controller->register_hook('TOOLBAR_DEFINE', 'AFTER', $this, 'insert_button', array());
25        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, '_ajax_call', array());
26    }
27
28    /**
29     * Inserts the toolbar button
30     */
31    public function insert_button(&$event, $param) {
32        $event->data[] = array(
33            'type' => 'format',
34            'title' => $this->getLang('qb_todobutton'),
35            'icon' => '../../plugins/todo/todo.png',
36            'key' => 't',
37            'open' => '<todo>',
38            'close' => '</todo>',
39            'block' => false,
40        );
41    }
42
43    /**
44     * Handles ajax requests for to do plugin
45     *
46     * @brief This method is called by ajax if the user clicks on the to-do checkbox or the to-do text.
47     * It sets the to-do state to completed or reset it to open.
48     *
49     * POST Parameters:
50     *   index    int the position of the occurrence of the input element (starting with 0 for first element/to-do)
51     *   checked    int should the to-do set to completed (1) or to open (0)
52     *   path    string id/path/name of the page
53     *
54     * @date 20131008 Gerrit Uitslag <klapinklapin@gmail.com> \n
55     *                move ajax.php to action.php, added lock and conflict checks and improved saving
56     * @date 20130405 Leo Eibler <dokuwiki@sprossenwanne.at> \n
57     *                replace old sack() method with new jQuery method and use post instead of get \n
58     * @date 20130407 Leo Eibler <dokuwiki@sprossenwanne.at> \n
59     *                add user assignment for todos \n
60     * @date 20130408 Christian Marg <marg@rz.tu-clausthal.de> \n
61     *                change only the clicked to-do item instead of all items with the same text \n
62     *                origVal is not used anymore, we use the index (occurrence) of input element \n
63     * @date 20130408 Leo Eibler <dokuwiki@sprossenwanne.at> \n
64     *                migrate changes made by Christian Marg to current version of plugin \n
65     *
66     *
67     * @param Doku_Event $event
68     * @param mixed $param not defined
69     */
70    public function _ajax_call(&$event, $param) {
71        global $ID, $conf, $lang;
72
73        if($event->data !== 'plugin_todo') {
74            return;
75        }
76        //no other ajax call handlers needed
77        $event->stopPropagation();
78        $event->preventDefault();
79
80        #Variables
81        // by einhirn <marg@rz.tu-clausthal.de> determine checkbox index by using class 'todocheckbox'
82
83        if(isset($_REQUEST['index'], $_REQUEST['checked'], $_REQUEST['pageid'])) {
84            // index = position of occurrence of <input> element (starting with 0 for first element)
85            $index = (int) $_REQUEST['index'];
86            // checked = flag if input is checked means to do is complete (1) or not (0)
87            $checked = (boolean) urldecode($_REQUEST['checked']);
88            // path = page ID
89            $ID = cleanID(urldecode($_REQUEST['pageid']));
90        } else {
91            return;
92        }
93
94        $date = 0;
95        if(isset($_REQUEST['date'])) $date = (int) $_REQUEST['date'];
96
97        $INFO = pageinfo();
98
99        #Determine Permissions
100        if(auth_quickaclcheck($ID) < AUTH_EDIT) {
101            echo "You do not have permission to edit this file.\nAccess was denied.";
102            return;
103        }
104        // Check, if page is locked
105        if(checklock($ID)) {
106            $locktime = filemtime(wikiLockFN($ID));
107            $expire = dformat($locktime + $conf['locktime']);
108            $min = round(($conf['locktime'] - (time() - $locktime)) / 60);
109
110            $msg = $this->getLang('lockedpage').'
111'.$lang['lockedby'] . ': ' . editorinfo($INFO['locked']) . '
112' . $lang['lockexpire'] . ': ' . $expire . ' (' . $min . ' min)';
113            $this->printJson(array('message' => $msg));
114            return;
115        }
116
117        //conflict check
118        if($date != 0 && $INFO['meta']['date']['modified'] > $date) {
119            $this->printJson(array('message' => $this->getLang('refreshpage')));
120            return;
121        }
122
123        #Retrieve Page Contents
124        $wikitext = rawWiki($ID);
125
126        #Determine position of tag
127        if($index >= 0) {
128            $index++;
129            // index is only set on the current page with the todos
130            // the occurances are counted, untill the index-th input is reached which is updated
131            $todoTagStartPos = $this->_strnpos($wikitext, '<todo', $index);
132            $todoTagEndPos = strpos($wikitext, '>', $todoTagStartPos) + 1;
133
134            if($todoTagEndPos > $todoTagStartPos) {
135                // update text
136                $oldTag = substr($wikitext, $todoTagStartPos, ($todoTagEndPos - $todoTagStartPos));
137                $newTag = $this->_buildTodoTag($oldTag, $checked);
138                $wikitext = substr_replace($wikitext, $newTag, $todoTagStartPos, ($todoTagEndPos - $todoTagStartPos));
139
140                // save Update (Minor)
141                lock($ID);
142                saveWikiText($ID, $wikitext, $this->getLang('checkboxchange'), $minoredit = true);
143                unlock($ID);
144
145                $return = array(
146                    'date' => @filemtime(wikiFN($ID)),
147                    'succeed' => true
148                );
149                $this->printJson($return);
150            }
151        }
152    }
153
154    /**
155     * Encode and print an arbitrary variable into JSON format
156     *
157     * @param mixed $return
158     */
159    private function printJson($return) {
160        $json = new JSON();
161        echo $json->encode($return);
162    }
163
164    /**
165     * @brief gets current to-do tag and returns a new one depending on checked
166     * @param $todoTag    string current to-do tag e.g. <todo @user>
167     * @param $checked    int check flag (todo completed=1, todo uncompleted=0)
168     * @return string new to-do completed or uncompleted tag e.g. <todo @user #>
169     */
170    private function _buildTodoTag($todoTag, $checked) {
171        $x = preg_match('%<todo([^>]*)>%i', $todoTag, $matches);
172        $newTag = '<todo';
173        if($x) {
174            if(($userPos = strpos($matches[1], '@')) !== false) {
175                $submatch = substr($todoTag, $userPos);
176                $x = preg_match('%@([-.\w]+)%i', $submatch, $matchinguser);
177                if($x) {
178                    $newTag .= ' @' . $matchinguser[1];
179                }
180            }
181        }
182        if($checked == 1) {
183            $newTag .= ' #';
184        }
185        $newTag .= '>';
186        return $newTag;
187    }
188
189    /**
190     * Find position of $occurance-th $needle in haystack
191     */
192    private function _strnpos($haystack, $needle, $occurance, $pos = 0) {
193        for($i = 1; $i <= $occurance; $i++) {
194            $pos = strpos($haystack, $needle, $pos) + 1;
195        }
196        return $pos - 1;
197    }
198}