xref: /plugin/tagging/helper.php (revision 3bbb8b9b617360c97791d7a1586a472334bf2d2a)
1<?php
2/**
3 * Tagging Plugin (hlper component)
4 *
5 * @license GPL 2
6 */
7class helper_plugin_tagging extends DokuWiki_Plugin {
8
9    /**
10     * Gives access to the database
11     *
12     * Initializes the SQLite helper and register the CLEANTAG function
13     *
14     * @return helper_plugin_sqlite|bool false if initialization fails
15     */
16    public function getDB() {
17        static $db = null;
18        if ($db !== null) {
19            return $db;
20        }
21
22        /** @var helper_plugin_sqlite $db */
23        $db = plugin_load('helper', 'sqlite');
24        if ($db === null) {
25            msg('The tagging plugin needs the sqlite plugin', -1);
26
27            return false;
28        }
29        $db->init('tagging', __DIR__ . '/db/');
30        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
31        $db->create_function('GROUP_SORT',
32            function ($group, $newDelimiter) {
33                $ex = explode(',', $group);
34                sort($ex);
35
36                return implode($newDelimiter, $ex);
37            }, 2);
38
39        return $db;
40    }
41
42    /**
43     * Return the user to use for accessing tags
44     *
45     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
46     *
47     * @return bool|string
48     */
49    public function getUser() {
50        if (!isset($_SERVER['REMOTE_USER'])) {
51            return false;
52        }
53        if ($this->getConf('singleusermode')) {
54            return 'auto';
55        }
56
57        return $_SERVER['REMOTE_USER'];
58    }
59
60    /**
61     * Canonicalizes the tag to its lower case nospace form
62     *
63     * @param $tag
64     *
65     * @return string
66     */
67    public function cleanTag($tag) {
68        $tag = str_replace(array(' ', '-', '_'), '', $tag);
69        $tag = utf8_strtolower($tag);
70
71        return $tag;
72    }
73
74    /**
75     * Canonicalizes the namespace, remove the first colon and add glob
76     *
77     * @param $namespace
78     *
79     * @return string
80     */
81    public function globNamespace($namespace) {
82        return cleanId($namespace) . '%';
83    }
84
85    /**
86     * Create or Update tags of a page
87     *
88     * Uses the translation plugin to store the language of a page (if available)
89     *
90     * @param string $id The page ID
91     * @param string $user
92     * @param array  $tags
93     *
94     * @return bool|SQLiteResult
95     */
96    public function replaceTags($id, $user, $tags) {
97        global $conf;
98        /** @var helper_plugin_translation $trans */
99        $trans = plugin_load('helper', 'translation');
100        if ($trans) {
101            $lang = $trans->realLC($trans->getLangPart($id));
102        } else {
103            $lang = $conf['lang'];
104        }
105
106        $db = $this->getDB();
107        $db->query('BEGIN TRANSACTION');
108        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
109        foreach ($tags as $tag) {
110            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
111        }
112
113        foreach ($queries as $query) {
114            if (!call_user_func_array(array($db, 'query'), $query)) {
115                $db->query('ROLLBACK TRANSACTION');
116
117                return false;
118            }
119        }
120
121        return $db->query('COMMIT TRANSACTION');
122    }
123
124    /**
125     * Get a list of Tags or Pages matching search criteria
126     *
127     * @param array  $filter What to search for array('field' => 'searchterm')
128     * @param string $type   What field to return 'tag'|'pid'
129     * @param int    $limit  Limit to this many results, 0 for all
130     *
131     * @return array associative array in form of value => count
132     */
133    public function findItems($filter, $type, $limit = 0) {
134        $db = $this->getDB();
135        if (!$db) {
136            return array();
137        }
138
139        // create WHERE clause
140        $where = '1=1';
141        foreach ($filter as $field => $value) {
142            // compare clean tags only
143            if ($field === 'tag') {
144                $field = 'CLEANTAG(tag)';
145                $q = 'CLEANTAG(?)';
146            } else {
147                $q = '?';
148            }
149
150            if (substr($field, 0, 6) === 'notpid') {
151                $field = 'pid';
152
153                // detect LIKE filters
154                if ($this->useLike($value)) {
155                    $where .= " AND $field NOT LIKE $q";
156                } else {
157                    $where .= " AND $field != $q";
158                }
159            } else {
160                // detect LIKE filters
161                if ($this->useLike($value)) {
162                    $where .= " AND $field LIKE $q";
163                } else {
164                    $where .= " AND $field = $q";
165                }
166            }
167        }
168        $where .= ' AND GETACCESSLEVEL(pid) >= ' . AUTH_READ;
169
170        // group and order
171        if ($type === 'tag') {
172            $groupby = 'CLEANTAG(tag)';
173            $orderby = 'CLEANTAG(tag)';
174        } else {
175            $groupby = $type;
176            $orderby = "cnt DESC, $type";
177        }
178
179        // limit results
180        if ($limit) {
181            $limit = " LIMIT $limit";
182        } else {
183            $limit = '';
184        }
185
186        // create SQL
187        $sql = "SELECT $type AS item, COUNT(*) AS cnt
188                  FROM taggings
189                 WHERE $where
190              GROUP BY $groupby
191              ORDER BY $orderby
192                $limit
193              ";
194
195        // run query and turn into associative array
196        $res = $db->query($sql, array_values($filter));
197        $res = $db->res2arr($res);
198
199        $ret = array();
200        foreach ($res as $row) {
201            $ret[$row['item']] = $row['cnt'];
202        }
203
204        return $ret;
205    }
206
207    /**
208     * Check if the given string is a LIKE statement
209     *
210     * @param string $value
211     *
212     * @return bool
213     */
214    private function useLike($value) {
215        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
216    }
217
218    /**
219     * Constructs the URL to search for a tag
220     *
221     * @param string $tag
222     * @param string $ns
223     *
224     * @return string
225     */
226    public function getTagSearchURL($tag, $ns = '') {
227        // wrap tag in quotes if non clean
228        $ctag = utf8_stripspecials($this->cleanTag($tag));
229        if ($ctag != utf8_strtolower($tag)) {
230            $tag = '"' . $tag . '"';
231        }
232
233        $ret = '?do=search&id=' . rawurlencode($tag);
234        if ($ns) {
235            $ret .= rawurlencode(' @' . $ns);
236        }
237
238        return $ret;
239    }
240
241    /**
242     * Calculates the size levels for the given list of clouds
243     *
244     * Automatically determines sensible tresholds
245     *
246     * @param array $tags list of tags => count
247     * @param int   $levels
248     *
249     * @return mixed
250     */
251    public function cloudData($tags, $levels = 10) {
252        $min = min($tags);
253        $max = max($tags);
254
255        // calculate tresholds
256        $tresholds = array();
257        for ($i = 0; $i <= $levels; $i++) {
258            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
259        }
260
261        // assign weights
262        foreach ($tags as $tag => $cnt) {
263            foreach ($tresholds as $tresh => $val) {
264                if ($cnt <= $val) {
265                    $tags[$tag] = $tresh;
266                    break;
267                }
268                $tags[$tag] = $levels;
269            }
270        }
271
272        return $tags;
273    }
274
275    /**
276     * Display a tag cloud
277     *
278     * @param array    $tags   list of tags => count
279     * @param string   $type   'tag'
280     * @param Callable $func   The function to print the link (gets tag and ns)
281     * @param bool     $wrap   wrap cloud in UL tags?
282     * @param bool     $return returnn HTML instead of printing?
283     * @param string   $ns     Add this namespace to search links
284     *
285     * @return string
286     */
287    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
288        global $INFO;
289
290        $hidden_str = $this->getConf('hiddenprefix');
291        $hidden_len = strlen($hidden_str);
292
293        $ret = '';
294        if ($wrap) {
295            $ret .= '<ul class="tagging_cloud clearfix">';
296        }
297        if (count($tags) === 0) {
298            // Produce valid XHTML (ul needs a child)
299            $this->setupLocale();
300            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
301        } else {
302            $tags = $this->cloudData($tags);
303            foreach ($tags as $val => $size) {
304                // skip hidden tags for users that can't edit
305                if ($type === 'tag' and
306                    $hidden_len and
307                    substr($val, 0, $hidden_len) == $hidden_str and
308                    !($this->getUser() && $INFO['writable'])
309                ) {
310                    continue;
311                }
312
313                $ret .= '<li class="t' . $size . '"><div class="li">';
314                $ret .= call_user_func($func, $val, $ns);
315                $ret .= '</div></li>';
316            }
317        }
318        if ($wrap) {
319            $ret .= '</ul>';
320        }
321        if ($return) {
322            return $ret;
323        }
324        echo $ret;
325
326        return '';
327    }
328
329    /**
330     * Get the link to a search for the given tag
331     *
332     * @param string $tag search for this tag
333     * @param string $ns  limit search to this namespace
334     *
335     * @return string
336     */
337    protected function linkToSearch($tag, $ns = '') {
338        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
339    }
340
341    /**
342     * Display the Tags for the current page and prepare the tag editing form
343     *
344     * @param bool $print Should the HTML be printed or returned?
345     *
346     * @return string
347     */
348    public function tpl_tags($print = true) {
349        global $INFO;
350        global $lang;
351
352        $filter = array('pid' => $INFO['id']);
353        if ($this->getConf('singleusermode')) {
354            $filter['tagger'] = 'auto';
355        }
356
357        $tags = $this->findItems($filter, 'tag');
358
359        $ret = '';
360
361        $ret .= '<div class="plugin_tagging_edit">';
362        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
363
364        if ($this->getUser() && $INFO['writable']) {
365            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
366            $ret .= '<div id="tagging__edit_buttons_group">';
367            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
368            if (auth_isadmin()) {
369                $ret .= '<label>' . $this->getLang('toggle admin mode') . '<input type="checkbox" id="tagging__edit_toggle_admin" /></label>';
370            }
371            $ret .= '</div>';
372            $form = new dokuwiki\Form\Form();
373            $form->id('tagging__edit');
374            $form->setHiddenField('tagging[id]', $INFO['id']);
375            $form->setHiddenField('call', 'plugin_tagging_save');
376            $tags = $this->findItems(array(
377                'pid'    => $INFO['id'],
378                'tagger' => $this->getUser(),
379            ), 'tag');
380            $form->addTextarea('tagging[tags]')->val(implode(', ', array_keys($tags)))->addClass('edit');
381            $form->addButton('', $lang['btn_save'])->id('tagging__edit_save');
382            $form->addButton('', $lang['btn_cancel'])->id('tagging__edit_cancel');
383            $ret .= $form->toHTML();
384        }
385        $ret .= '</div>';
386
387        if ($print) {
388            echo $ret;
389        }
390
391        return $ret;
392    }
393
394    /**
395     * @param string $namespace empty for entire wiki
396     *
397     * @return array
398     */
399    public function getAllTags($namespace = '', $order_by = 'tag', $desc = false) {
400        $order_fields = array('pid', 'tid', 'orig', 'taggers', 'count');
401        if (!in_array($order_by, $order_fields)) {
402            msg('cannot sort by ' . $order_by . ' field does not exists', -1);
403            $order_by = 'tag';
404        }
405
406        $db = $this->getDb();
407
408        $query = 'SELECT    "pid",
409                            CLEANTAG("tag") AS "tid",
410                            GROUP_SORT(GROUP_CONCAT("tag"), \', \') AS "orig",
411                            GROUP_SORT(GROUP_CONCAT("tagger"), \', \') AS "taggers",
412                            COUNT(*) AS "count"
413                        FROM "taggings"
414                        WHERE "pid" LIKE ?
415                        GROUP BY "tid"
416                        ORDER BY ' . $order_by;
417        if ($desc) {
418            $query .= ' DESC';
419        }
420
421        $res = $db->query($query, $this->globNamespace($namespace));
422
423        return $db->res2arr($res);
424    }
425
426    /**
427     * Get all pages with tags and their tags
428     *
429     * @return array ['pid' => ['tag1','tag2','tag3']]
430     */
431    public function getAllTagsByPage() {
432        $query = '
433        SELECT pid, GROUP_CONCAT(tag) AS tags
434        FROM taggings
435        GROUP BY pid
436        ';
437        $db = $this->getDb();
438        $res = $db->query($query);
439        return array_map(
440            function ($i) {
441                return explode(',', $i);
442            },
443            array_column($db->res2arr($res), 'tags', 'pid')
444        );
445    }
446
447    /**
448     * Renames a tag
449     *
450     * @param string $formerTagName
451     * @param string $newTagName
452     */
453    public function renameTag($formerTagName, $newTagName) {
454
455        if (empty($formerTagName) || empty($newTagName)) {
456            msg($this->getLang("admin enter tag names"), -1);
457
458            return;
459        }
460
461        $db = $this->getDb();
462
463        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
464        $check = $db->res2arr($res);
465
466        if (empty($check)) {
467            msg($this->getLang("admin tag does not exists"), -1);
468
469            return;
470        }
471
472        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
473        $db->res2arr($res);
474
475        msg($this->getLang("admin renamed"), 1);
476
477        return;
478    }
479
480    /**
481     * Rename or delete a tag for all users
482     *
483     * @param string $pid
484     * @param string $formerTagName
485     * @param string $newTagName
486     *
487     * @return array
488     */
489    public function modifyPageTag($pid, $formerTagName, $newTagName) {
490
491        $db = $this->getDb();
492
493        $res = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ? AND pid = ?', $this->cleanTag($formerTagName), $pid);
494        $check = $db->res2arr($res);
495
496        if (empty($check)) {
497            return array(true, $this->getLang('admin tag does not exists'));
498        }
499
500        if (empty($newTagName)) {
501            $res = $db->query('DELETE FROM taggings WHERE pid = ? AND CLEANTAG(tag) = ?', $pid, $this->cleanTag($formerTagName));
502        } else {
503            $res = $db->query('UPDATE taggings SET tag = ? WHERE pid = ? AND CLEANTAG(tag) = ?', $newTagName, $pid, $this->cleanTag($formerTagName));
504        }
505        $db->res2arr($res);
506
507        return array(false, $this->getLang('admin renamed'));
508    }
509
510    /**
511     * Deletes a tag
512     *
513     * @param array  $tags
514     * @param string $namespace current namespace context as in getAllTags()
515     */
516    public function deleteTags($tags, $namespace = '') {
517        if (empty($tags)) {
518            return;
519        }
520
521        $namespace = cleanId($namespace);
522
523        $db = $this->getDB();
524
525        $queryBody = 'FROM taggings WHERE pid LIKE ? AND (' .
526            implode(' OR ', array_fill(0, count($tags), 'CLEANTAG(tag) = ?')) . ')';
527        $args = array_map(array($this, 'cleanTag'), $tags);
528        array_unshift($args, $this->globNamespace($namespace));
529
530
531        $affectedPagesQuery= 'SELECT DISTINCT pid ' . $queryBody;
532        $resAffectedPages = $db->query($affectedPagesQuery, $args);
533        $numAffectedPages = count($resAffectedPages->fetchAll());
534
535        $deleteQuery = 'DELETE ' . $queryBody;
536        $db->query($deleteQuery, $args);
537
538        msg(sprintf($this->getLang("admin deleted"), count($tags), $numAffectedPages), 1);
539    }
540}
541