1<?php
2/**
3 *
4 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
5 * @author  Andreas Valder <valder@isf.rwth-aachen.de>
6 */
7
8// must be run within Dokuwiki
9if(!defined('DOKU_INC')) die();
10class action_plugin_ckgdoku_tagapi extends DokuWiki_Action_Plugin {
11  private $tagplugin = null;
12    /**
13     * Registers a callback function for a given event
14     *
15     * @param Doku_Event_Handler $controller DokuWiki's event controller object
16     * @return void
17     */
18    public function register(Doku_Event_Handler $controller) {
19
20       $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handle_ajax_call_unknown');
21
22    }
23
24    /**
25     * @param Doku_Event $event  event object by reference
26     * @param mixed      $param  [the parameters passed as fifth argument to register_hook() when this
27     *                           handler was registered]
28     * @return void
29     */
30
31    public function handle_ajax_call_unknown(Doku_Event &$event, $param) {
32      if ($event->data !== 'tagapi_list') {
33        return;
34      }
35      $event->stopPropagation();
36      $event->preventDefault();
37
38      if ($this->tagplugin = $this->loadHelper('tag')) {
39        $tags = $this->tagplugin->tagOccurrences(array(), NULL, true);
40        $a = print_r($tags,true);
41       // file_put_contents(DOKU_INC . 'tags.txt', $a);
42      } else {
43        $tags = array();
44      }
45
46      // sort tags by name ($tags is in the form $tag => $count)
47      ksort($tags);
48      echo '{"tags":[';
49      $firstelement = true;
50      foreach (array_keys($tags) as $tag) {
51        if ($firstelement) {
52          $firstelement = false;
53        } else {
54          echo ',';
55        }
56        echo '{"name":"'.$this->tagToName($tag).'","id":"'.$tag.'"}';
57      }
58      echo']}';
59    }
60
61    private function tagToName($t) {
62      $exists = false;
63      $id = $t;
64      resolve_pageID($this->tagplugin->namespace, $id, $exists);
65      $name = p_get_first_heading($id, false);
66      if (empty($name)) {
67        $name = $t;
68      } else {
69        $name = $name;
70      }
71      return $name;
72    }
73}