xref: /plugin/tagging/helper.php (revision 204c069b8283f2494df9107ab62d37e45921a471)
1f61105deSAdrian Lang<?php
2f61105deSAdrian Lang
3f61105deSAdrian Langif(!defined('DOKU_INC')) die();
43496cc8aSAndreas Gohr
5e4543b6dSAdrian Langclass helper_plugin_tagging extends DokuWiki_Plugin {
6f61105deSAdrian Lang
7289f50bdSAndreas Gohr    /**
8b12334e1SAndreas Gohr     * Gives access to the database
9b12334e1SAndreas Gohr     *
10b12334e1SAndreas Gohr     * Initializes the SQLite helper and register the CLEANTAG function
11b12334e1SAndreas Gohr     *
12b12334e1SAndreas Gohr     * @return helper_plugin_sqlite|bool false if initialization fails
13289f50bdSAndreas Gohr     */
14289f50bdSAndreas Gohr    public function getDB() {
15302a38efSAndreas Gohr        static $db = null;
16f61105deSAdrian Lang        if(!is_null($db)) {
17f61105deSAdrian Lang            return $db;
18f61105deSAdrian Lang        }
19f61105deSAdrian Lang
20302a38efSAndreas Gohr        /** @var helper_plugin_sqlite $db */
21f61105deSAdrian Lang        $db = plugin_load('helper', 'sqlite');
22f61105deSAdrian Lang        if(is_null($db)) {
23f61105deSAdrian Lang            msg('The tagging plugin needs the sqlite plugin', -1);
24f61105deSAdrian Lang            return false;
25f61105deSAdrian Lang        }
267e6afce6SAndreas Gohr        $db->init('tagging', dirname(__FILE__) . '/db/');
27302a38efSAndreas Gohr        $db->create_function('CLEANTAG', array($this, 'cleanTag'), 1);
28f61105deSAdrian Lang        return $db;
29f61105deSAdrian Lang    }
30f61105deSAdrian Lang
31302a38efSAndreas Gohr    /**
322ace74f4SAndreas Gohr     * Return the user to use for accessing tags
332ace74f4SAndreas Gohr     *
342ace74f4SAndreas Gohr     * Handles the singleuser mode by returning 'auto' as user. Returnes false when no user is logged in.
352ace74f4SAndreas Gohr     *
362ace74f4SAndreas Gohr     * @return bool|string
372ace74f4SAndreas Gohr     */
382ace74f4SAndreas Gohr    public function getUser() {
392ace74f4SAndreas Gohr        if(!isset($_SERVER['REMOTE_USER'])) return false;
402ace74f4SAndreas Gohr        if($this->getConf('singleusermode')) return 'auto';
412ace74f4SAndreas Gohr        return $_SERVER['REMOTE_USER'];
422ace74f4SAndreas Gohr    }
432ace74f4SAndreas Gohr
442ace74f4SAndreas Gohr    /**
45302a38efSAndreas Gohr     * Canonicalizes the tag to its lower case nospace form
46302a38efSAndreas Gohr     *
47302a38efSAndreas Gohr     * @param $tag
48302a38efSAndreas Gohr     * @return string
49302a38efSAndreas Gohr     */
50302a38efSAndreas Gohr    public function cleanTag($tag) {
51302a38efSAndreas Gohr        $tag = str_replace(' ', '', $tag);
52302a38efSAndreas Gohr        $tag = utf8_strtolower($tag);
53302a38efSAndreas Gohr        return $tag;
54302a38efSAndreas Gohr    }
55302a38efSAndreas Gohr
5656d82720SAndreas Gohr    /**
5756d82720SAndreas Gohr     * Create or Update tags of a page
5856d82720SAndreas Gohr     *
5956d82720SAndreas Gohr     * Uses the translation plugin to store the language of a page (if available)
6056d82720SAndreas Gohr     *
6156d82720SAndreas Gohr     * @param string $id The page ID
6256d82720SAndreas Gohr     * @param string $user
6356d82720SAndreas Gohr     * @param array $tags
6456d82720SAndreas Gohr     * @return bool|SQLiteResult
6556d82720SAndreas Gohr     */
66f61105deSAdrian Lang    public function replaceTags($id, $user, $tags) {
6756d82720SAndreas Gohr        global $conf;
6856d82720SAndreas Gohr        /** @var helper_plugin_translation $trans */
6956d82720SAndreas Gohr        $trans = plugin_load('helper', 'translation');
7056d82720SAndreas Gohr        if($trans) {
7156d82720SAndreas Gohr            $lang = $trans->realLC($trans->getLangPart($id));
7256d82720SAndreas Gohr        } else {
7356d82720SAndreas Gohr            $lang = $conf['lang'];
7456d82720SAndreas Gohr        }
7556d82720SAndreas Gohr
76f61105deSAdrian Lang        $db = $this->getDB();
77f61105deSAdrian Lang        $db->query('BEGIN TRANSACTION');
78f61105deSAdrian Lang        $queries = array(array('DELETE FROM taggings WHERE pid = ? AND tagger = ?', $id, $user));
79f61105deSAdrian Lang        foreach($tags as $tag) {
8056d82720SAndreas Gohr            $queries[] = array('INSERT INTO taggings (pid, tagger, tag, lang) VALUES(?, ?, ?, ?)', $id, $user, $tag, $lang);
81f61105deSAdrian Lang        }
82f61105deSAdrian Lang
83f61105deSAdrian Lang        foreach($queries as $query) {
84f61105deSAdrian Lang            if(!call_user_func_array(array($db, 'query'), $query)) {
85f61105deSAdrian Lang                $db->query('ROLLBACK TRANSACTION');
86f61105deSAdrian Lang                return false;
87f61105deSAdrian Lang            }
88f61105deSAdrian Lang        }
89f61105deSAdrian Lang        return $db->query('COMMIT TRANSACTION');
90f61105deSAdrian Lang    }
91f61105deSAdrian Lang
920a518a11SAndreas Gohr    /**
93b12334e1SAndreas Gohr     * Get a list of Tags or Pages matching search criteria
940a518a11SAndreas Gohr     *
95b12334e1SAndreas Gohr     * @param array $filter What to search for array('field' => 'searchterm')
96b12334e1SAndreas Gohr     * @param string $type What field to return 'tag'|'pid'
97077ff864SAndreas Gohr     * @param int $limit Limit to this many results, 0 for all
980a518a11SAndreas Gohr     * @return array associative array in form of value => count
990a518a11SAndreas Gohr     */
100077ff864SAndreas Gohr    public function findItems($filter, $type, $limit = 0) {
101f61105deSAdrian Lang        $db = $this->getDB();
102b12334e1SAndreas Gohr        if(!$db) return array();
103f61105deSAdrian Lang
104b12334e1SAndreas Gohr        // create WHERE clause
105b12334e1SAndreas Gohr        $where = '1=1';
106b12334e1SAndreas Gohr        foreach($filter as $field => $value) {
107b12334e1SAndreas Gohr            // compare clean tags only
108b12334e1SAndreas Gohr            if($field === 'tag') {
109b12334e1SAndreas Gohr                $field = 'CLEANTAG(tag)';
110b12334e1SAndreas Gohr                $q     = 'CLEANTAG(?)';
111b12334e1SAndreas Gohr            } else {
112b12334e1SAndreas Gohr                $q = '?';
113b12334e1SAndreas Gohr            }
114*204c069bSMichael Große
115*204c069bSMichael Große            if (substr($field,0,6) === 'notpid') {
116*204c069bSMichael Große                $field = 'pid';
117*204c069bSMichael Große
118*204c069bSMichael Große                // detect LIKE filters
119*204c069bSMichael Große                if($this->useLike($value)) {
120*204c069bSMichael Große                    $where .= " AND $field NOT LIKE $q";
121*204c069bSMichael Große                } else {
122*204c069bSMichael Große                    $where .= " AND $field != $q";
123*204c069bSMichael Große                }
124*204c069bSMichael Große            } else {
125b12334e1SAndreas Gohr                // detect LIKE filters
126b12334e1SAndreas Gohr                if($this->useLike($value)) {
127b12334e1SAndreas Gohr                    $where .= " AND $field LIKE $q";
128b12334e1SAndreas Gohr                } else {
129b12334e1SAndreas Gohr                    $where .= " AND $field = $q";
130b12334e1SAndreas Gohr                }
131b12334e1SAndreas Gohr            }
132*204c069bSMichael Große        }
133b12334e1SAndreas Gohr        // group and order
134b12334e1SAndreas Gohr        if($type == 'tag') {
135b12334e1SAndreas Gohr            $groupby = 'CLEANTAG(tag)';
136b12334e1SAndreas Gohr            $orderby = 'CLEANTAG(tag)';
137b12334e1SAndreas Gohr        } else {
138b12334e1SAndreas Gohr            $groupby = $type;
139466524f5SAndreas Gohr            $orderby = "cnt DESC, $type";
140b12334e1SAndreas Gohr        }
141b12334e1SAndreas Gohr
142077ff864SAndreas Gohr        // limit results
143077ff864SAndreas Gohr        if($limit) {
144077ff864SAndreas Gohr            $limit = " LIMIT $limit";
145077ff864SAndreas Gohr        } else {
146077ff864SAndreas Gohr            $limit = '';
147077ff864SAndreas Gohr        }
148077ff864SAndreas Gohr
149b12334e1SAndreas Gohr        // create SQL
150b12334e1SAndreas Gohr        $sql = "SELECT $type AS item, COUNT(*) AS cnt
151b12334e1SAndreas Gohr                  FROM taggings
152b12334e1SAndreas Gohr                 WHERE $where
153b12334e1SAndreas Gohr              GROUP BY $groupby
154077ff864SAndreas Gohr              ORDER BY $orderby
155077ff864SAndreas Gohr                $limit
156077ff864SAndreas Gohr              ";
157b12334e1SAndreas Gohr
158b12334e1SAndreas Gohr        // run query and turn into associative array
159b12334e1SAndreas Gohr        $res = $db->query($sql, array_values($filter));
160f61105deSAdrian Lang        $res = $db->res2arr($res);
161b12334e1SAndreas Gohr
162f61105deSAdrian Lang        $ret = array();
163b12334e1SAndreas Gohr        foreach($res as $row) {
164b12334e1SAndreas Gohr            $ret[$row['item']] = $row['cnt'];
165f61105deSAdrian Lang        }
166f61105deSAdrian Lang        return $ret;
167f61105deSAdrian Lang    }
168f61105deSAdrian Lang
169b12334e1SAndreas Gohr    /**
170b12334e1SAndreas Gohr     * Check if the given string is a LIKE statement
171b12334e1SAndreas Gohr     *
172b12334e1SAndreas Gohr     * @param string $value
173b12334e1SAndreas Gohr     * @return bool
174b12334e1SAndreas Gohr     */
175b12334e1SAndreas Gohr    private function useLike($value) {
176b12334e1SAndreas Gohr        return strpos($value, '%') === 0 || strrpos($value, '%') === strlen($value) - 1;
177b2073787SDominik Eckelmann    }
178b2073787SDominik Eckelmann
179302a38efSAndreas Gohr    /**
180302a38efSAndreas Gohr     * Constructs the URL to search for a tag
181302a38efSAndreas Gohr     *
1825540f91dSAndreas Gohr     * @param string $tag
1835540f91dSAndreas Gohr     * @param string $ns
184302a38efSAndreas Gohr     * @return string
185302a38efSAndreas Gohr     */
1865540f91dSAndreas Gohr    public function getTagSearchURL($tag, $ns = '') {
187bed9f360SAndreas Gohr        // wrap tag in quotes if non clean
1882cb25ec1SAndreas Gohr        $ctag = utf8_stripspecials($this->cleanTag($tag));
189bed9f360SAndreas Gohr        if($ctag != utf8_strtolower($tag)) $tag = '"' . $tag . '"';
190bed9f360SAndreas Gohr
191bed9f360SAndreas Gohr        $ret = '?do=search&id=' . rawurlencode($tag);
1925540f91dSAndreas Gohr        if($ns) $ret .= rawurlencode(' @' . $ns);
1935540f91dSAndreas Gohr
1945540f91dSAndreas Gohr        return $ret;
195f61105deSAdrian Lang    }
196f61105deSAdrian Lang
1975540f91dSAndreas Gohr    /**
1985540f91dSAndreas Gohr     * Calculates the size levels for the given list of clouds
1995540f91dSAndreas Gohr     *
2005540f91dSAndreas Gohr     * Automatically determines sensible tresholds
2015540f91dSAndreas Gohr     *
2025540f91dSAndreas Gohr     * @param array $tags list of tags => count
2035540f91dSAndreas Gohr     * @param int $levels
2045540f91dSAndreas Gohr     * @return mixed
2055540f91dSAndreas Gohr     */
206f61105deSAdrian Lang    public function cloudData($tags, $levels = 10) {
207f61105deSAdrian Lang        $min = min($tags);
208f61105deSAdrian Lang        $max = max($tags);
209f61105deSAdrian Lang
210f61105deSAdrian Lang        // calculate tresholds
211f61105deSAdrian Lang        $tresholds = array();
212f61105deSAdrian Lang        for($i = 0; $i <= $levels; $i++) {
213f61105deSAdrian Lang            $tresholds[$i] = pow($max - $min + 1, $i / $levels) + $min - 1;
214f61105deSAdrian Lang        }
215f61105deSAdrian Lang
216f61105deSAdrian Lang        // assign weights
217f61105deSAdrian Lang        foreach($tags as $tag => $cnt) {
218f61105deSAdrian Lang            foreach($tresholds as $tresh => $val) {
219f61105deSAdrian Lang                if($cnt <= $val) {
220f61105deSAdrian Lang                    $tags[$tag] = $tresh;
221f61105deSAdrian Lang                    break;
222f61105deSAdrian Lang                }
223f61105deSAdrian Lang                $tags[$tag] = $levels;
224f61105deSAdrian Lang            }
225f61105deSAdrian Lang        }
226f61105deSAdrian Lang        return $tags;
227f61105deSAdrian Lang    }
228f61105deSAdrian Lang
2295540f91dSAndreas Gohr    /**
2305540f91dSAndreas Gohr     * Display a tag cloud
2315540f91dSAndreas Gohr     *
2325540f91dSAndreas Gohr     * @param array $tags list of tags => count
2335540f91dSAndreas Gohr     * @param string $type 'tag'
2345540f91dSAndreas Gohr     * @param Callable $func The function to print the link (gets tag and ns)
2355540f91dSAndreas Gohr     * @param bool $wrap wrap cloud in UL tags?
2365540f91dSAndreas Gohr     * @param bool $return returnn HTML instead of printing?
2375540f91dSAndreas Gohr     * @param string $ns Add this namespace to search links
2385540f91dSAndreas Gohr     * @return string
2395540f91dSAndreas Gohr     */
2405540f91dSAndreas Gohr    public function html_cloud($tags, $type, $func, $wrap = true, $return = false, $ns = '') {
241a66f6715SAndreas Gohr        global $INFO;
242a66f6715SAndreas Gohr
243a66f6715SAndreas Gohr        $hidden_str = $this->getConf('hiddenprefix');
244a66f6715SAndreas Gohr        $hidden_len = strlen($hidden_str);
245a66f6715SAndreas Gohr
246f61105deSAdrian Lang        $ret = '';
2470dbdc3fcSAdrian Lang        if($wrap) $ret .= '<ul class="tagging_cloud clearfix">';
248f61105deSAdrian Lang        if(count($tags) === 0) {
249f61105deSAdrian Lang            // Produce valid XHTML (ul needs a child)
250f61105deSAdrian Lang            $this->setupLocale();
251f61105deSAdrian Lang            $ret .= '<li><div class="li">' . $this->lang['js']['no' . $type . 's'] . '</div></li>';
252f61105deSAdrian Lang        } else {
253f61105deSAdrian Lang            $tags = $this->cloudData($tags);
254f61105deSAdrian Lang            foreach($tags as $val => $size) {
255a66f6715SAndreas Gohr                // skip hidden tags for users that can't edit
256a66f6715SAndreas Gohr                if($type == 'tag' and
257a66f6715SAndreas Gohr                    $hidden_len and
258a66f6715SAndreas Gohr                    substr($val, 0, $hidden_len) == $hidden_str and
259a66f6715SAndreas Gohr                    !($this->getUser() && $INFO['writable'])
260a66f6715SAndreas Gohr                ) {
261a66f6715SAndreas Gohr                    continue;
262a66f6715SAndreas Gohr                }
263a66f6715SAndreas Gohr
264f61105deSAdrian Lang                $ret .= '<li class="t' . $size . '"><div class="li">';
2655540f91dSAndreas Gohr                $ret .= call_user_func($func, $val, $ns);
266f61105deSAdrian Lang                $ret .= '</div></li>';
267f61105deSAdrian Lang            }
268f61105deSAdrian Lang        }
269f61105deSAdrian Lang        if($wrap) $ret .= '</ul>';
270f61105deSAdrian Lang        if($return) return $ret;
271f61105deSAdrian Lang        echo $ret;
2725540f91dSAndreas Gohr        return '';
273f61105deSAdrian Lang    }
274f61105deSAdrian Lang
2755540f91dSAndreas Gohr    /**
2765540f91dSAndreas Gohr     * Get the link to a search for the given tag
2775540f91dSAndreas Gohr     *
2785540f91dSAndreas Gohr     * @param string $tag search for this tag
2795540f91dSAndreas Gohr     * @param string $ns limit search to this namespace
2805540f91dSAndreas Gohr     * @return string
2815540f91dSAndreas Gohr     */
2825540f91dSAndreas Gohr    protected function linkToSearch($tag, $ns = '') {
2835540f91dSAndreas Gohr        return '<a href="' . hsc($this->getTagSearchURL($tag, $ns)) . '">' . $tag . '</a>';
284f61105deSAdrian Lang    }
285f61105deSAdrian Lang
286fb1d0583SAndreas Gohr    /**
287fb1d0583SAndreas Gohr     * Display the Tags for the current page and prepare the tag editing form
2883496cc8aSAndreas Gohr     *
2893496cc8aSAndreas Gohr     * @param bool $print Should the HTML be printed or returned?
2903496cc8aSAndreas Gohr     * @return string
291fb1d0583SAndreas Gohr     */
2923496cc8aSAndreas Gohr    public function tpl_tags($print = true) {
293f61105deSAdrian Lang        global $INFO;
294f61105deSAdrian Lang        global $lang;
295fbf38c5bSAndreas Gohr        $tags = $this->findItems(array('pid' => $INFO['id']), 'tag');
2963496cc8aSAndreas Gohr
2973496cc8aSAndreas Gohr        $ret = '';
2983496cc8aSAndreas Gohr
2993496cc8aSAndreas Gohr        $ret .= '<div class="plugin_tagging_edit">';
3003496cc8aSAndreas Gohr        $ret .= $this->html_cloud($tags, 'tag', array($this, 'linkToSearch'), true, true);
301f61105deSAdrian Lang
3022ace74f4SAndreas Gohr        if($this->getUser() && $INFO['writable']) {
303f61105deSAdrian Lang            $lang['btn_tagging_edit'] = $lang['btn_secedit'];
3043496cc8aSAndreas Gohr            $ret .= html_btn('tagging_edit', $INFO['id'], '', array());
305289f50bdSAndreas Gohr            $form = new Doku_Form(array('id' => 'tagging__edit'));
306fbf38c5bSAndreas Gohr            $form->addHidden('tagging[id]', $INFO['id']);
307289f50bdSAndreas Gohr            $form->addHidden('call', 'plugin_tagging_save');
3082ace74f4SAndreas Gohr            $form->addElement(form_makeTextField('tagging[tags]', implode(', ', array_keys($this->findItems(array('pid' => $INFO['id'], 'tagger' => $this->getUser()), 'tag')))));
309289f50bdSAndreas Gohr            $form->addElement(form_makeButton('submit', 'save', $lang['btn_save'], array('id' => 'tagging__edit_save')));
310289f50bdSAndreas Gohr            $form->addElement(form_makeButton('submit', 'cancel', $lang['btn_cancel'], array('id' => 'tagging__edit_cancel')));
3113496cc8aSAndreas Gohr            $ret .= $form->getForm();
312f61105deSAdrian Lang        }
3133496cc8aSAndreas Gohr        $ret .= '</div>';
3143496cc8aSAndreas Gohr
3153496cc8aSAndreas Gohr        if($print) echo $ret;
3163496cc8aSAndreas Gohr        return $ret;
317f61105deSAdrian Lang    }
318872edc7cSRené Corinth
3198a1a3846SAndreas Gohr    /**
3208a1a3846SAndreas Gohr     * @return array
3218a1a3846SAndreas Gohr     */
322872edc7cSRené Corinth    public function getAllTags() {
323872edc7cSRené Corinth
324872edc7cSRené Corinth        $db  = $this->getDb();
3258a1a3846SAndreas Gohr        $res = $db->query('SELECT pid, tag, tagger FROM taggings ORDER BY tag');
326872edc7cSRené Corinth
327872edc7cSRené Corinth        $tags_tmp = $db->res2arr($res);
328872edc7cSRené Corinth        $tags     = array();
329872edc7cSRené Corinth        foreach($tags_tmp as $tag) {
330302a38efSAndreas Gohr            $tid = $this->cleanTag($tag['tag']);
331872edc7cSRené Corinth
332fb1d0583SAndreas Gohr            if(!isset($tags[$tid]['orig'])) $tags[$tid]['orig'] = array();
333fb1d0583SAndreas Gohr            $tags[$tid]['orig'][] = $tag['tag'];
334872edc7cSRené Corinth
335302a38efSAndreas Gohr            if(isset($tags[$tid]['count'])) {
336302a38efSAndreas Gohr                $tags[$tid]['count']++;
337302a38efSAndreas Gohr                $tags[$tid]['tagger'][] = $tag['tagger'];
338872edc7cSRené Corinth            } else {
339302a38efSAndreas Gohr                $tags[$tid]['count']  = 1;
340302a38efSAndreas Gohr                $tags[$tid]['tagger'] = array($tag['tagger']);
341872edc7cSRené Corinth            }
342872edc7cSRené Corinth        }
343872edc7cSRené Corinth        return $tags;
344872edc7cSRené Corinth    }
345872edc7cSRené Corinth
3468a1a3846SAndreas Gohr    /**
3478a1a3846SAndreas Gohr     * Renames a tag
3488a1a3846SAndreas Gohr     *
3498a1a3846SAndreas Gohr     * @param string $formerTagName
3508a1a3846SAndreas Gohr     * @param string $newTagName
3518a1a3846SAndreas Gohr     */
352872edc7cSRené Corinth    public function renameTag($formerTagName, $newTagName) {
353872edc7cSRené Corinth
354872edc7cSRené Corinth        if(empty($formerTagName) || empty($newTagName)) {
3558a1a3846SAndreas Gohr            msg($this->getLang("admin enter tag names"), -1);
3568a1a3846SAndreas Gohr            return;
357872edc7cSRené Corinth        }
358872edc7cSRené Corinth
359872edc7cSRené Corinth        $db = $this->getDb();
360872edc7cSRené Corinth
361fb1d0583SAndreas Gohr        $res   = $db->query('SELECT pid FROM taggings WHERE CLEANTAG(tag) = ?', $this->cleanTag($formerTagName));
362872edc7cSRené Corinth        $check = $db->res2arr($res);
363872edc7cSRené Corinth
364872edc7cSRené Corinth        if(empty($check)) {
3658a1a3846SAndreas Gohr            msg($this->getLang("admin tag does not exists"), -1);
3668a1a3846SAndreas Gohr            return;
367872edc7cSRené Corinth        }
368872edc7cSRené Corinth
369fb1d0583SAndreas Gohr        $res = $db->query("UPDATE taggings SET tag = ? WHERE CLEANTAG(tag) = ?", $newTagName, $this->cleanTag($formerTagName));
370872edc7cSRené Corinth        $db->res2arr($res);
371872edc7cSRené Corinth
372fb1d0583SAndreas Gohr        msg($this->getLang("admin renamed"), 1);
3738a1a3846SAndreas Gohr        return;
374872edc7cSRené Corinth    }
375872edc7cSRené Corinth
376f61105deSAdrian Lang}
377