1<?php
2
3use dokuwiki\HTTP\DokuHTTPClient;
4use DOMWrap\Document;
5
6/**
7 * DokuWiki Plugin amazonlight (Syntax Component)
8 *
9 * @license GPL 2 http://www.gnu.org/licenses/gpl-2.0.html
10 * @author  Andreas Gohr <andi@splitbrain.org>
11 */
12class syntax_plugin_amazonlight extends syntax_plugin_doi_isbn
13{
14
15    /** @var array what regions to use for the different countries */
16    const REGIONS = [
17        'us' => 'www.amazon.com',
18        'ca' => 'www.amazon.ca',
19        'de' => 'www.amazon.de',
20        'gb' => 'www.amazon.co.uk',
21        'fr' => 'www.amazon.fr',
22        'jp' => 'www.amazon.co.jp',
23    ];
24
25    public function getConf($setting, $notset = false)
26    {
27        $config = parent::getConf($setting);
28        if(!$config) {
29            $doi = plugin_load('syntax', 'doi_isbn');
30            $config = $doi->getConf($setting, $notset);
31        }
32        return $config;
33    }
34
35    /**
36     * Connect lookup pattern to lexer.
37     *
38     * @param string $mode Parser mode
39     */
40    public function connectTo($mode)
41    {
42        $this->Lexer->addSpecialPattern('\{\{amazon>[\w:\\- =]+\}\}', $mode, 'plugin_amazonlight');
43    }
44
45    /** @inheritDoc */
46    public function handle($match, $state, $pos, Doku_Handler $handler)
47    {
48        $match = substr($match, 9, -2);
49        list($ctry, $asin) = sexplode(':', $match, 2);
50
51        // no country given?
52        if (empty($asin)) {
53            $asin = $ctry;
54            $ctry = 'us';
55        }
56
57        // default parameters...
58        $params = array(
59            'imgw' => $this->getConf('imgw'),
60            'imgh' => $this->getConf('imgh'),
61        );
62        // ...can be overridden
63        list($asin, $more) = sexplode(' ', $asin, 2);
64        $params['id'] = $asin;
65
66        if (preg_match('/(\d+)x(\d+)/i', $more, $match)) {
67            $params['imgw'] = $match[1];
68            $params['imgh'] = $match[2];
69        }
70
71        // correct country given?
72        if ($ctry === 'uk') $ctry = 'gb';
73        if (!preg_match('/^(us|gb|jp|de|fr|ca)$/', $ctry)) {
74            $ctry = 'us';
75        }
76        $params['country'] = $ctry;
77
78        return $params;
79    }
80
81    public function render($mode, Doku_Renderer $renderer, $data)
82    {
83        $region = self::REGIONS[$data['country']];
84        $data['url'] = 'https://' . $region . '/dp/' . $data['id'];
85        if($this->getConf('partner_'.$data['country'])) {
86            $data['url'] .= '/?tag='.$this->getConf('partner_'.$data['country']);
87        }
88
89        return parent::render($mode, $renderer, $data);
90    }
91}
92
93