aboutsummaryrefslogtreecommitdiff
path: root/lib/BridgeAbstract.php
blob: b814097adc0510b2fec7ce6931da9e473bd96d68 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
<?php

abstract class BridgeAbstract
{
    const NAME = null;
    const URI = null;
    const DONATION_URI = '';
    const DESCRIPTION = 'No description provided';

    /**
     * Preferably a github username
     */
    const MAINTAINER = 'No maintainer';

    /**
     * Cache TTL in seconds
     */
    const CACHE_TIMEOUT = 3600;

    const CONFIGURATION = [];
    const PARAMETERS = [];
    const TEST_DETECT_PARAMETERS = [];

    /**
     * This is a convenient const for the limit option in bridge contexts.
     * Can be inlined and modified if necessary.
     */
    protected const LIMIT = [
        'name'          => 'Limit',
        'type'          => 'number',
        'title'         => 'Maximum number of items to return',
    ];

    protected array $items = [];
    protected array $inputs = [];
    protected ?string $queriedContext = '';
    private array $configuration = [];

    protected CacheInterface $cache;
    protected Logger $logger;

    public function __construct(
        CacheInterface $cache,
        Logger $logger
    ) {
        $this->cache = $cache;
        $this->logger = $logger;
    }

    abstract public function collectData();

    public function getFeed(): array
    {
        return [
            'name'          => $this->getName(),
            'uri'           => $this->getURI(),
            'donationUri'   => $this->getDonationURI(),
            'icon'          => $this->getIcon(),
        ];
    }

    public function getName()
    {
        return static::NAME ?? $this->getShortName();
    }

    public function getURI()
    {
        return static::URI ?? 'https://github.com/RSS-Bridge/rss-bridge/';
    }

    public function getDonationURI(): string
    {
        return static::DONATION_URI;
    }

    public function getIcon()
    {
        if (static::URI) {
            // This favicon may or may not exist
            return rtrim(static::URI, '/') . '/favicon.ico';
        }
        return '';
    }

    public function getOption(string $name)
    {
        return $this->configuration[$name] ?? null;
    }

    /**
     * The description is only used in bridge card rendering on frontpage
     */
    public function getDescription()
    {
        return static::DESCRIPTION;
    }

    public function getMaintainer(): string
    {
        return static::MAINTAINER;
    }

    /**
     * A more correct method name would have been "getContexts"
     */
    public function getParameters(): array
    {
        return static::PARAMETERS;
    }

    public function getItems()
    {
        return $this->items;
    }

    public function getCacheTimeout()
    {
        return static::CACHE_TIMEOUT;
    }

    public function loadConfiguration()
    {
        foreach (static::CONFIGURATION as $optionName => $optionValue) {
            $section = $this->getShortName();
            $configurationOption = Configuration::getConfig($section, $optionName);

            if ($configurationOption !== null) {
                $this->configuration[$optionName] = $configurationOption;
                continue;
            }

            if (isset($optionValue['required']) && $optionValue['required'] === true) {
                throw new \Exception(sprintf('Missing configuration option: %s', $optionName));
            } elseif (isset($optionValue['defaultValue'])) {
                $this->configuration[$optionName] = $optionValue['defaultValue'];
            }
        }
    }

    public function setInput(array $input)
    {
        // This is the submitted context
        $contextName = $input['context'] ?? null;
        if ($contextName) {
            // Context hinting (optional)
            $this->queriedContext = $contextName;
            unset($input['context']);
        }

        $contexts = $this->getParameters();

        if (!$contexts) {
            if ($input) {
                throw new \Exception('Invalid parameters value(s)');
            }
            return;
        }

        $validator = new ParameterValidator();

        // $input IS PASSED BY REFERENCE!
        $errors = $validator->validateInput($input, $contexts);
        if ($errors !== []) {
            $invalidParameterKeys = array_column($errors, 'name');
            throw new \Exception(sprintf('Invalid parameters value(s): %s', implode(', ', $invalidParameterKeys)));
        }

        // Guess the context from input data
        if (empty($this->queriedContext)) {
            $queriedContext = $validator->getQueriedContext($input, $contexts);
            $this->queriedContext = $queriedContext;
        }

        if (is_null($this->queriedContext)) {
            throw new \Exception('Required parameter(s) missing');
        } elseif ($this->queriedContext === false) {
            throw new \Exception('Mixed context parameters');
        }

        $this->setInputWithContext($input, $this->queriedContext);
    }

    private function setInputWithContext(array $input, $queriedContext)
    {
        // Import and assign all inputs to their context
        foreach ($input as $name => $value) {
            foreach ($this->getParameters() as $context => $set) {
                if (array_key_exists($name, $this->getParameters()[$context])) {
                    $this->inputs[$context][$name]['value'] = $value;
                }
            }
        }

        // Apply default values to missing data
        $contextNames = [$queriedContext];
        if (array_key_exists('global', $this->getParameters())) {
            $contextNames[] = 'global';
        }

        foreach ($contextNames as $context) {
            if (!isset($this->getParameters()[$context])) {
                // unknown context provided by client, throw exception here? or continue?
            }

            foreach ($this->getParameters()[$context] as $name => $properties) {
                if (isset($this->inputs[$context][$name]['value'])) {
                    continue;
                }

                $type = $properties['type'] ?? 'text';

                switch ($type) {
                    case 'checkbox':
                        $this->inputs[$context][$name]['value'] = $input[$context][$name]['value'] ?? false;
                        break;
                    case 'list':
                        if (!isset($properties['defaultValue'])) {
                            $firstItem = reset($properties['values']);
                            if (is_array($firstItem)) {
                                $firstItem = reset($firstItem);
                            }
                            $this->inputs[$context][$name]['value'] = $firstItem;
                        } else {
                            $this->inputs[$context][$name]['value'] = $properties['defaultValue'];
                        }
                        break;
                    default:
                        if (isset($properties['defaultValue'])) {
                            $this->inputs[$context][$name]['value'] = $properties['defaultValue'];
                        }
                        break;
                }
            }
        }

        // Copy global parameter values to the guessed context
        if (array_key_exists('global', $this->getParameters())) {
            foreach ($this->getParameters()['global'] as $name => $properties) {
                if (isset($input[$name])) {
                    $value = $input[$name];
                } else {
                    if ($properties['type'] ?? null === 'checkbox') {
                        $value = false;
                    } elseif (isset($properties['defaultValue'])) {
                        $value = $properties['defaultValue'];
                    } else {
                        continue;
                    }
                }
                $this->inputs[$queriedContext][$name]['value'] = $value;
            }
        }

        // Only keep guessed context parameters values
        if (isset($this->inputs[$queriedContext])) {
            $this->inputs = [
                $queriedContext => $this->inputs[$queriedContext],
            ];
        } else {
            $this->inputs = [];
        }
    }

    protected function getInput($input)
    {
        return $this->inputs[$this->queriedContext][$input]['value'] ?? null;
    }

    /**
     * Get the key name of a given input
     * Can process multilevel arrays with two levels, the max level a list can have
     *
     * @param string $input The input name
     * @return string|null The accompaning key to a given input or null if the input is not defined
     */
    public function getKey($input)
    {
        if (!isset($this->inputs[$this->queriedContext][$input]['value'])) {
            return null;
        }

        $contexts = $this->getParameters();

        if (array_key_exists('global', $contexts)) {
            if (array_key_exists($input, $contexts['global'])) {
                $contextName = 'global';
            }
        }
        if (!isset($contextName)) {
            $contextName = $this->queriedContext;
        }

        $needle = $this->inputs[$this->queriedContext][$input]['value'];
        foreach ($contexts[$contextName][$input]['values'] as $first_level_key => $first_level_value) {
            if (!is_array($first_level_value) && $needle === (string)$first_level_value) {
                return $first_level_key;
            } elseif (is_array($first_level_value)) {
                foreach ($first_level_value as $second_level_key => $second_level_value) {
                    if ($needle === (string)$second_level_value) {
                        return $second_level_key;
                    }
                }
            }
        }
    }

    public function detectParameters($url)
    {
        $regex = '/^(https?:\/\/)?(www\.)?(.+?)(\/)?$/';

        $contexts = $this->getParameters();

        if (
            empty($contexts)
            && preg_match($regex, $url, $urlMatches) > 0
            && preg_match($regex, static::URI, $bridgeUriMatches) > 0
            && $urlMatches[3] === $bridgeUriMatches[3]
        ) {
            return [];
        }
        return null;
    }

    protected function loadCacheValue(string $key, $default = null)
    {
        return $this->cache->get($this->getShortName() . '_' . $key, $default);
    }

    protected function saveCacheValue(string $key, $value, int $ttl = 86400)
    {
        $this->cache->set($this->getShortName() . '_' . $key, $value, $ttl);
    }

    public function getShortName(): string
    {
        return (new \ReflectionClass($this))->getShortName();
    }
}