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' is already used for going to top of page, bug #76
37//	    'key' => 't',
38            'open' => '<todo>',
39            'close' => '</todo>',
40            'block' => false,
41        );
42    }
43
44    /**
45     * Handles ajax requests for to do plugin
46     *
47     * @brief This method is called by ajax if the user clicks on the to-do checkbox or the to-do text.
48     * It sets the to-do state to completed or reset it to open.
49     *
50     * POST Parameters:
51     *   index    int the position of the occurrence of the input element (starting with 0 for first element/to-do)
52     *   checked    int should the to-do set to completed (1) or to open (0)
53     *   path    string id/path/name of the page
54     *
55     * @date 20140317 Leo Eibler <dokuwiki@sprossenwanne.at> \n
56     *                use todo content as change description \n
57     * @date 20131008 Gerrit Uitslag <klapinklapin@gmail.com> \n
58     *                move ajax.php to action.php, added lock and conflict checks and improved saving
59     * @date 20130405 Leo Eibler <dokuwiki@sprossenwanne.at> \n
60     *                replace old sack() method with new jQuery method and use post instead of get \n
61     * @date 20130407 Leo Eibler <dokuwiki@sprossenwanne.at> \n
62     *                add user assignment for todos \n
63     * @date 20130408 Christian Marg <marg@rz.tu-clausthal.de> \n
64     *                change only the clicked to-do item instead of all items with the same text \n
65     *                origVal is not used anymore, we use the index (occurrence) of input element \n
66     * @date 20130408 Leo Eibler <dokuwiki@sprossenwanne.at> \n
67     *                migrate changes made by Christian Marg to current version of plugin \n
68     *
69     *
70     * @param Doku_Event $event
71     * @param mixed $param not defined
72     */
73    public function _ajax_call(&$event, $param) {
74        global $ID, $conf, $lang;
75
76        if($event->data !== 'plugin_todo') {
77            return;
78        }
79        //no other ajax call handlers needed
80        $event->stopPropagation();
81        $event->preventDefault();
82
83        #Variables
84        // by einhirn <marg@rz.tu-clausthal.de> determine checkbox index by using class 'todocheckbox'
85
86        if(isset($_REQUEST['index'], $_REQUEST['checked'], $_REQUEST['pageid'])) {
87            // index = position of occurrence of <input> element (starting with 0 for first element)
88            $index = (int) $_REQUEST['index'];
89            // checked = flag if input is checked means to do is complete (1) or not (0)
90            $checked = (boolean) urldecode($_REQUEST['checked']);
91            // path = page ID
92            $ID = cleanID(urldecode($_REQUEST['pageid']));
93        } else {
94            return;
95        }
96
97        $date = 0;
98        if(isset($_REQUEST['date'])) $date = (int) $_REQUEST['date'];
99
100        $INFO = pageinfo();
101
102        #Determine Permissions
103        if(auth_quickaclcheck($ID) < AUTH_EDIT) {
104            echo "You do not have permission to edit this file.\nAccess was denied.";
105            return;
106        }
107        // Check, if page is locked
108        if(checklock($ID)) {
109            $locktime = filemtime(wikiLockFN($ID));
110            $expire = dformat($locktime + $conf['locktime']);
111            $min = round(($conf['locktime'] - (time() - $locktime)) / 60);
112
113            $msg = $this->getLang('lockedpage').'
114'.$lang['lockedby'] . ': ' . editorinfo($INFO['locked']) . '
115' . $lang['lockexpire'] . ': ' . $expire . ' (' . $min . ' min)';
116            $this->printJson(array('message' => $msg));
117            return;
118        }
119
120        //conflict check
121        if($date != 0 && $INFO['meta']['date']['modified'] > $date) {
122            $this->printJson(array('message' => $this->getLang('refreshpage')));
123            return;
124        }
125
126        #Retrieve Page Contents
127        $wikitext = rawWiki($ID);
128
129        #Determine position of tag
130        if($index >= 0) {
131            $index++;
132            // index is only set on the current page with the todos
133            // the occurances are counted, untill the index-th input is reached which is updated
134            $todoTagStartPos = $this->_strnpos($wikitext, '<todo', $index);
135            $todoTagEndPos = strpos($wikitext, '>', $todoTagStartPos) + 1;
136
137            if($todoTagEndPos > $todoTagStartPos) {
138                // @date 20140714 le add todo text to minorchange
139                $todoTextEndPos = strpos( $wikitext, '</todo', $todoTagEndPos );
140                $todoText = substr( $wikitext, $todoTagEndPos, $todoTextEndPos-$todoTagEndPos );
141                // update text
142                $oldTag = substr($wikitext, $todoTagStartPos, ($todoTagEndPos - $todoTagStartPos));
143                $newTag = $this->_buildTodoTag($oldTag, $checked);
144                $wikitext = substr_replace($wikitext, $newTag, $todoTagStartPos, ($todoTagEndPos - $todoTagStartPos));
145
146                // save Update (Minor)
147                lock($ID);
148                // @date 20140714 le add todo text to minorchange, use different message for checked or unchecked
149                saveWikiText($ID, $wikitext, $this->getLang($checked?'checkboxchange_on':'checkboxchange_off').': '.$todoText, $minoredit = true);
150                unlock($ID);
151
152                $return = array(
153                    'date' => @filemtime(wikiFN($ID)),
154                    'succeed' => true
155                );
156                $this->printJson($return);
157            }
158        }
159    }
160
161    /**
162     * Encode and print an arbitrary variable into JSON format
163     *
164     * @param mixed $return
165     */
166    private function printJson($return) {
167        $json = new JSON();
168        echo $json->encode($return);
169    }
170
171    /**
172     * @brief gets current to-do tag and returns a new one depending on checked
173     * @param $todoTag    string current to-do tag e.g. <todo @user>
174     * @param $checked    int check flag (todo completed=1, todo uncompleted=0)
175     * @return string new to-do completed or uncompleted tag e.g. <todo @user #>
176     */
177    private function _buildTodoTag($todoTag, $checked) {
178        $user = '';
179        if($checked == 1) {
180            if(!empty($_SERVER['REMOTE_USER'])) { $user = $_SERVER['REMOTE_USER']; }
181            $newTag = preg_replace('/>/', ' #'.$user.':'.date('Y-m-d').'>', $todoTag);
182        } else {
183            $newTag = preg_replace('/[\s]*[#].*>/', '>', $todoTag);
184        }
185        return $newTag;
186    }
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}
199