1<?php
2/**
3 * DokuWiki EpnSmartLink Plugin
4 * @date 29.10.2017
5 * @author Vidschofelix <vidschofelix@gmx.com>
6 */
7
8if(!defined('DOKU_INC')) die();
9
10class action_plugin_epnsmartlink extends DokuWiki_Admin_Plugin
11{
12    /**
13     * registers ajax hook
14     * @param Doku_Event_Handler $controller
15     */
16    public function register(Doku_Event_Handler $controller)
17    {
18        $controller->register_hook('AJAX_CALL_UNKNOWN', 'BEFORE', $this, '_get_conf');
19    }
20
21    /**
22     * handles conf ajax requests
23     * @param Doku_Event $event
24     * @param            $param
25     */
26    public function _get_conf(Doku_Event $event, $param)
27    {
28        if ($event->data !== 'epnsmartlink_getconf') {
29            return;
30        }
31
32        $event->stopPropagation();
33        $event->preventDefault();
34
35        $epnUrl = $this->getConf('epn-smart-url');
36        if (!$this->getConf('epn-smart-enable') || !$this->isValidJsUrl($epnUrl)) {
37            return;
38        }
39
40        $campaign = $this->getCampaign();
41
42        $data = array(
43            'url'      => $epnUrl,
44            'campaign' => $campaign
45        );
46
47        $json = new JSON();
48
49        header('Content-Type: application/json');
50        echo $json->encode($data);
51    }
52
53    /**
54     * @param string $epnUrl
55     * @return bool
56     */
57    protected function isValidJsUrl($epnUrl)
58    {
59        if (substr($epnUrl, -3) === '.js') {
60            return true;
61        }
62
63        return false;
64    }
65
66    protected function getCampaign()
67    {
68        //if support is on, return for 5% dev-campaign
69        if ($this->getConf('epn-smart-support') && (rand(1, 100) <= 5 )) {
70            return 5338205943;
71        }
72
73        return $this->getConf('epn-smart-campaign');
74    }
75}
76