xref: /plugin/tagging/helper.php (revision d092e7b8bfa6b15a4508b1daab70e097dee89674)
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        // group and order
136        if($type == 'tag') {
137            $groupby = 'CLEANTAG(tag)';
138            $orderby = 'CLEANTAG(tag)';
139        } else {
140            $groupby = $type;
141            $orderby = "cnt DESC, $type";
142        }
143
144        // limit results
145        if($limit) {
146            $limit = " LIMIT $limit";
147        } else {
148            $limit = '';
149        }
150
151        // create SQL
152        $sql = "SELECT $type AS item, COUNT(*) AS cnt
153                  FROM taggings
154                 WHERE $where
155              GROUP BY $groupby
156              ORDER BY $orderby
157                $limit
158              ";
159
160        // run query and turn into associative array
161        $res = $db->query($sql, array_values($filter));
162        $res = $db->res2arr($res);
163
164        $ret = array();
165        foreach($res as $row) {
166            if (!isHiddenPage($row['item']) && auth_quickaclcheck($row['item']) >= AUTH_READ) {
167                $ret[$row['item']] = $row['cnt'];
168            }
169        }
170        return $ret;
171    }
172
173    /**
174     * Check if the given string is a LIKE statement
175     *
176     * @param string $value
177     * @return bool
178     */
179    private function useLike($value) {
180        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
181    }
182
183    /**
184     * Constructs the URL to search for a tag
185     *
186     * @param string $tag
187     * @param string $ns
188     * @return string
189     */
190    public function getTagSearchURL($tag, $ns = '') {
191        // wrap tag in quotes if non clean
192        $ctag = utf8_stripspecials($this->cleanTag($tag));
193        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
194
195        $ret = '?do=search&id=' . rawurlencode($tag);
196        if($ns) $ret .= rawurlencode(' @' . $ns);
197
198        return $ret;
199    }
200
201    /**
202     * Calculates the size levels for the given list of clouds
203     *
204     * Automatically determines sensible tresholds
205     *
206     * @param array $tags list of tags => count
207     * @param int $levels
208     * @return mixed
209     */
210    public function cloudData($tags, $levels = 10) {
211        $min = min($tags);
212        $max = max($tags);
213
214        // calculate tresholds
215        $tresholds = array();
216        for($i = 0; $i <= $levels; $i++) {
217            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
218        }
219
220        // assign weights
221        foreach($tags as $tag => $cnt) {
222            foreach($tresholds as $tresh => $val) {
223                if($cnt <= $val) {
224                    $tags[$tag] = $tresh;
225                    break;
226                }
227                $tags[$tag] = $levels;
228            }
229        }
230        return $tags;
231    }
232
233    /**
234     * Display a tag cloud
235     *
236     * @param array $tags list of tags => count
237     * @param string $type 'tag'
238     * @param Callable $func The function to print the link (gets tag and ns)
239     * @param bool $wrap wrap cloud in UL tags?
240     * @param bool $return returnn HTML instead of printing?
241     * @param string $ns Add this namespace to search links
242     * @return string
243     */
244    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
245        global $INFO;
246
247        $hidden_str = $this->getConf('hiddenprefix');
248        $hidden_len = strlen($hidden_str);
249
250        $ret = '';
251        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
252        if(count($tags) === 0) {
253            // Produce valid XHTML (ul needs a child)
254            $this->setupLocale();
255            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
256        } else {
257            $tags = $this->cloudData($tags);
258            foreach($tags as $val => $size) {
259                // skip hidden tags for users that can't edit
260                if($type == 'tag' and
261                    $hidden_len and
262                    substr($val, 0, $hidden_len) == $hidden_str and
263                    !($this->getUser() && $INFO['writable'])
264                ) {
265                    continue;
266                }
267
268                $ret .= '<li class="t' . $size . '"><div class="li">';
269                $ret .= call_user_func($func, $val, $ns);
270                $ret .= '</div></li>';
271            }
272        }
273        if($wrap) $ret .= '</ul>';
274        if($return) return $ret;
275        echo $ret;
276        return '';
277    }
278
279    /**
280     * Get the link to a search for the given tag
281     *
282     * @param string $tag search for this tag
283     * @param string $ns limit search to this namespace
284     * @return string
285     */
286    protected function linkToSearch($tag, $ns = '') {
287        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
288    }
289
290    /**
291     * Display the Tags for the current page and prepare the tag editing form
292     *
293     * @param bool $print Should the HTML be printed or returned?
294     * @return string
295     */
296    public function tpl_tags($print = true) {
297        global $INFO;
298        global $lang;
299        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
300
301        $ret = '';
302
303        $ret .= '<div class="plugin_tagging_edit">';
304        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
305
306        if($this->getUser() && $INFO['writable']) {
307            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
308            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
309            $form = new Doku_Form(array('id' => 'tagging__edit'));
310            $form->addHidden('tagging[id]', $INFO['id']);
311            $form->addHidden('call', 'plugin_tagging_save');
312            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
313            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
314            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
315            $ret .= $form->getForm();
316        }
317        $ret .= '</div>';
318
319        if($print) echo $ret;
320        return $ret;
321    }
322
323    /**
324     * @return array
325     */
326    public function getAllTags() {
327
328        $db  = $this->getDb();
329        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
330
331        $tags_tmp = $db->res2arr($res);
332        $tags     = array();
333        foreach($tags_tmp as $tag) {
334            $tid = $this->cleanTag($tag['tag']);
335
336            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
337            $tags[$tid]['orig'][] = $tag['tag'];
338
339            if(isset($tags[$tid]['count'])) {
340                $tags[$tid]['count']++;
341                $tags[$tid]['tagger'][] = $tag['tagger'];
342            } else {
343                $tags[$tid]['count']  = 1;
344                $tags[$tid]['tagger'] = array($tag['tagger']);
345            }
346        }
347        return $tags;
348    }
349
350    /**
351     * Renames a tag
352     *
353     * @param string $formerTagName
354     * @param string $newTagName
355     */
356    public function renameTag($formerTagName, $newTagName) {
357
358        if(empty($formerTagName) || empty($newTagName)) {
359            msg($this->getLang("admin enter tag names"), -1);
360            return;
361        }
362
363        $db = $this->getDb();
364
365        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
366        $check = $db->res2arr($res);
367
368        if(empty($check)) {
369            msg($this->getLang("admin tag does not exists"), -1);
370            return;
371        }
372
373        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
374        $db->res2arr($res);
375
376        msg($this->getLang("admin renamed"), 1);
377        return;
378    }
379
380}
381