1<?php
2/**
3 * DokuWiki Plugin top (Action Component)
4 *
5 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
6 * @author  Andreas Gohr <gohr@cosmocode.de>
7 */
8
9class action_plugin_top extends DokuWiki_Action_Plugin {
10
11    /**
12     * Registers a callback function for a given event
13     *
14     * @param Doku_Event_Handler $controller DokuWiki's event controller object
15     * @return void
16     */
17    public function register(Doku_Event_Handler $controller)
18    {
19        global $ACT;
20        global $JSINFO;
21        $JSINFO['act'] = $ACT;
22
23        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, 'handleAjax');
24        $controller->register_hook('FEED_MODE_UNKNOWN', 'BEFORE', $this, 'handleFeed');
25    }
26
27    /**
28     * Handle Ajax calls intended for this plugin
29     *
30     * @param Doku_Event $event  event object by reference
31     * @return void
32     */
33
34    public function handleAjax(Doku_Event $event)
35    {
36        if ($event->data != 'plugin_top') return;
37        $event->preventDefault();
38        $event->stopPropagation();
39
40        global $INPUT;
41        $page = cleanID($INPUT->str('page'));
42        if (!$page) return;
43
44        /** @var helper_plugin_top $hlp */
45        $hlp = plugin_load('helper', 'top');
46        $hlp->add($page);
47        header('Content-Type: text/plain; charset=utf-8');
48        echo 'counted';
49    }
50
51    /**
52     * Fetch and add top pages to FeedCreator.
53     *
54     * Supported feed parameters:
55     * - mode: plugin-top (required)
56     * - lang: optional
57     * - month: optional (YYYYMM)
58     * - num: optional number of results (default = 10)
59     *
60     * @param Doku_Event $event
61     */
62    public function handleFeed(Doku_Event $event)
63    {
64        $opt = $event->data['opt'];
65        if ($opt['feed_mode'] !== 'plugin-top') return;
66
67        $event->preventDefault();
68
69        // set defaults as expected by the helper's best() method
70        $lang = isset($opt['lang']) ? $opt['lang'] : null;
71        $month = isset($opt['month']) ? $opt['month'] : null;
72        $num = isset($opt['num']) ? $opt['num'] : 10;
73
74        /** @var helper_plugin_top $hlp */
75        $hlp = plugin_load('helper', 'top');
76        $pages = $hlp->best($lang, $month, $num);
77
78        if (empty($pages)) return;
79
80        foreach ($pages as $page) {
81            if (!$hlp->isReadable($page['page'])) continue;
82            $event->data['data'][] = [
83                'id' => $page['page'],
84                'score' => $page['value'],
85            ];
86        }
87    }
88}
89// vim:ts=4:sw=4:et:
90