xref: /plugin/tagging/helper.php (revision 59a953ffb19d0abf0c85655e9c16c565d5a351bb)
1<?php
2
3if(!defined('DOKU_INC')) die();
4
5class helper_plugin_tagging extends DokuWiki_Plugin {
6
7    /**
8     * Gives access to the database
9     *
10     * Initializes the SQLite helper and register the CLEANTAG function
11     *
12     * @return helper_plugin_sqlite|bool false if initialization fails
13     */
14    public function getDB() {
15        static $db = null;
16        if(!is_null($db)) {
17            return $db;
18        }
19
20        /** @var helper_plugin_sqlite $db */
21        $db = plugin_load('helper', 'sqlite');
22        if(is_null($db)) {
23            msg('The tagging plugin needs the sqlite plugin', -1);
24            return false;
25        }
26        $db->init('tagging', dirname(__FILE__) . '/db/');
27        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
28        return $db;
29    }
30
31    /**
32     * Return the user to use for accessing tags
33     *
34     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
35     *
36     * @return bool|string
37     */
38    public function getUser() {
39        if(!isset($_SERVER['REMOTE_USER'])) return false;
40        if($this->getConf('singleusermode')) return 'auto';
41        return $_SERVER['REMOTE_USER'];
42    }
43
44    /**
45     * Canonicalizes the tag to its lower case nospace form
46     *
47     * @param $tag
48     * @return string
49     */
50    public function cleanTag($tag) {
51        $tag = str_replace(' ', '', $tag);
52        $tag = str_replace('-', '', $tag);
53        $tag = str_replace('_', '', $tag);
54        $tag = utf8_strtolower($tag);
55        return $tag;
56    }
57
58    /**
59     * Create or Update tags of a page
60     *
61     * Uses the translation plugin to store the language of a page (if available)
62     *
63     * @param string $id The page ID
64     * @param string $user
65     * @param array $tags
66     * @return bool|SQLiteResult
67     */
68    public function replaceTags($id, $user, $tags) {
69        global $conf;
70        /** @var helper_plugin_translation $trans */
71        $trans = plugin_load('helper', 'translation');
72        if($trans) {
73            $lang = $trans->realLC($trans->getLangPart($id));
74        } else {
75            $lang = $conf['lang'];
76        }
77
78        $db = $this->getDB();
79        $db->query('BEGIN TRANSACTION');
80        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
81        foreach($tags as $tag) {
82            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
83        }
84
85        foreach($queries as $query) {
86            if(!call_user_func_array(array($db, 'query'), $query)) {
87                $db->query('ROLLBACK TRANSACTION');
88                return false;
89            }
90        }
91        return $db->query('COMMIT TRANSACTION');
92    }
93
94    /**
95     * Get a list of Tags or Pages matching search criteria
96     *
97     * @param array $filter What to search for array('field' => 'searchterm')
98     * @param string $type What field to return 'tag'|'pid'
99     * @param int $limit Limit to this many results, 0 for all
100     * @return array associative array in form of value => count
101     */
102    public function findItems($filter, $type, $limit = 0) {
103        $db = $this->getDB();
104        if(!$db) return array();
105
106        // create WHERE clause
107        $where = '1=1';
108        foreach($filter as $field => $value) {
109            // compare clean tags only
110            if($field === 'tag') {
111                $field = 'CLEANTAG(tag)';
112                $q     = 'CLEANTAG(?)';
113            } else {
114                $q = '?';
115            }
116
117            if (substr($field,0,6) === 'notpid') {
118                $field = 'pid';
119
120                // detect LIKE filters
121                if($this->useLike($value)) {
122                    $where .= " AND $field NOT LIKE $q";
123                } else {
124                    $where .= " AND $field != $q";
125                }
126            } else {
127                // detect LIKE filters
128                if($this->useLike($value)) {
129                    $where .= " AND $field LIKE $q";
130                } else {
131                    $where .= " AND $field = $q";
132                }
133            }
134        }
135        $where .= 'AND GETACCESSLEVEL(item) >= ' . AUTH_READ;
136
137        // group and order
138        if($type == 'tag') {
139            $groupby = 'CLEANTAG(tag)';
140            $orderby = 'CLEANTAG(tag)';
141        } else {
142            $groupby = $type;
143            $orderby = "cnt DESC, $type";
144        }
145
146        // limit results
147        if($limit) {
148            $limit = " LIMIT $limit";
149        } else {
150            $limit = '';
151        }
152
153        // create SQL
154        $sql = "SELECT $type AS item, COUNT(*) AS cnt
155                  FROM taggings
156                 WHERE $where
157              GROUP BY $groupby
158              ORDER BY $orderby
159                $limit
160              ";
161
162        // run query and turn into associative array
163        $res = $db->query($sql, array_values($filter));
164        $res = $db->res2arr($res);
165
166        $ret = array();
167        foreach($res as $row) {
168            if (!isHiddenPage($row['item'])) {
169                $ret[$row['item']] = $row['cnt'];
170            }
171        }
172        return $ret;
173    }
174
175    /**
176     * Check if the given string is a LIKE statement
177     *
178     * @param string $value
179     * @return bool
180     */
181    private function useLike($value) {
182        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
183    }
184
185    /**
186     * Constructs the URL to search for a tag
187     *
188     * @param string $tag
189     * @param string $ns
190     * @return string
191     */
192    public function getTagSearchURL($tag, $ns = '') {
193        // wrap tag in quotes if non clean
194        $ctag = utf8_stripspecials($this->cleanTag($tag));
195        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
196
197        $ret = '?do=search&id=' . rawurlencode($tag);
198        if($ns) $ret .= rawurlencode(' @' . $ns);
199
200        return $ret;
201    }
202
203    /**
204     * Calculates the size levels for the given list of clouds
205     *
206     * Automatically determines sensible tresholds
207     *
208     * @param array $tags list of tags => count
209     * @param int $levels
210     * @return mixed
211     */
212    public function cloudData($tags, $levels = 10) {
213        $min = min($tags);
214        $max = max($tags);
215
216        // calculate tresholds
217        $tresholds = array();
218        for($i = 0; $i <= $levels; $i++) {
219            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
220        }
221
222        // assign weights
223        foreach($tags as $tag => $cnt) {
224            foreach($tresholds as $tresh => $val) {
225                if($cnt <= $val) {
226                    $tags[$tag] = $tresh;
227                    break;
228                }
229                $tags[$tag] = $levels;
230            }
231        }
232        return $tags;
233    }
234
235    /**
236     * Display a tag cloud
237     *
238     * @param array $tags list of tags => count
239     * @param string $type 'tag'
240     * @param Callable $func The function to print the link (gets tag and ns)
241     * @param bool $wrap wrap cloud in UL tags?
242     * @param bool $return returnn HTML instead of printing?
243     * @param string $ns Add this namespace to search links
244     * @return string
245     */
246    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
247        global $INFO;
248
249        $hidden_str = $this->getConf('hiddenprefix');
250        $hidden_len = strlen($hidden_str);
251
252        $ret = '';
253        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
254        if(count($tags) === 0) {
255            // Produce valid XHTML (ul needs a child)
256            $this->setupLocale();
257            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
258        } else {
259            $tags = $this->cloudData($tags);
260            foreach($tags as $val => $size) {
261                // skip hidden tags for users that can't edit
262                if($type == 'tag' and
263                    $hidden_len and
264                    substr($val, 0, $hidden_len) == $hidden_str and
265                    !($this->getUser() && $INFO['writable'])
266                ) {
267                    continue;
268                }
269
270                $ret .= '<li class="t' . $size . '"><div class="li">';
271                $ret .= call_user_func($func, $val, $ns);
272                $ret .= '</div></li>';
273            }
274        }
275        if($wrap) $ret .= '</ul>';
276        if($return) return $ret;
277        echo $ret;
278        return '';
279    }
280
281    /**
282     * Get the link to a search for the given tag
283     *
284     * @param string $tag search for this tag
285     * @param string $ns limit search to this namespace
286     * @return string
287     */
288    protected function linkToSearch($tag, $ns = '') {
289        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
290    }
291
292    /**
293     * Display the Tags for the current page and prepare the tag editing form
294     *
295     * @param bool $print Should the HTML be printed or returned?
296     * @return string
297     */
298    public function tpl_tags($print = true) {
299        global $INFO;
300        global $lang;
301        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
302
303        $ret = '';
304
305        $ret .= '<div class="plugin_tagging_edit">';
306        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
307
308        if($this->getUser() && $INFO['writable']) {
309            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
310            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
311            $form = new Doku_Form(array('id' => 'tagging__edit'));
312            $form->addHidden('tagging[id]', $INFO['id']);
313            $form->addHidden('call', 'plugin_tagging_save');
314            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
315            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
316            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
317            $ret .= $form->getForm();
318        }
319        $ret .= '</div>';
320
321        if($print) echo $ret;
322        return $ret;
323    }
324
325    /**
326     * @return array
327     */
328    public function getAllTags() {
329
330        $db  = $this->getDb();
331        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
332
333        $tags_tmp = $db->res2arr($res);
334        $tags     = array();
335        foreach($tags_tmp as $tag) {
336            $tid = $this->cleanTag($tag['tag']);
337
338            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
339            $tags[$tid]['orig'][] = $tag['tag'];
340
341            if(isset($tags[$tid]['count'])) {
342                $tags[$tid]['count']++;
343                $tags[$tid]['tagger'][] = $tag['tagger'];
344            } else {
345                $tags[$tid]['count']  = 1;
346                $tags[$tid]['tagger'] = array($tag['tagger']);
347            }
348        }
349        return $tags;
350    }
351
352    /**
353     * Renames a tag
354     *
355     * @param string $formerTagName
356     * @param string $newTagName
357     */
358    public function renameTag($formerTagName, $newTagName) {
359
360        if(empty($formerTagName) || empty($newTagName)) {
361            msg($this->getLang("admin enter tag names"), -1);
362            return;
363        }
364
365        $db = $this->getDb();
366
367        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
368        $check = $db->res2arr($res);
369
370        if(empty($check)) {
371            msg($this->getLang("admin tag does not exists"), -1);
372            return;
373        }
374
375        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
376        $db->res2arr($res);
377
378        msg($this->getLang("admin renamed"), 1);
379        return;
380    }
381
382}
383