Rss-Bridge/lib/BridgeAbstract.php

357 lines
8.8 KiB
PHP
Raw Permalink Normal View History

<?php
2018-11-16 21:48:59 +01:00
/**
* This file is part of RSS-Bridge, a PHP project capable of generating RSS and
* Atom feeds for websites that don't have one.
*
* For the full license information, please view the UNLICENSE file distributed
* with this source code.
*
* @package Core
* @license http://unlicense.org/ UNLICENSE
* @link https://github.com/rss-bridge/rss-bridge
*/
2018-11-06 19:23:32 +01:00
2018-11-16 21:48:59 +01:00
/**
* An abstract class for bridges
*
* This class implements {@see BridgeInterface} with most common functions in
* order to reduce code duplication. Bridges should inherit from this class
* instead of implementing the interface manually.
*
* @todo Move constants to the interface (this is supported by PHP)
* @todo Change visibility of constants to protected
* @todo Return `self` on more functions to allow chaining
* @todo Add specification for PARAMETERS ()
* @todo Add specification for $items
*/
abstract class BridgeAbstract implements BridgeInterface {
2018-11-16 21:48:59 +01:00
/**
* Name of the bridge
*
* Use {@see BridgeAbstract::getName()} to read this parameter
*/
const NAME = 'Unnamed bridge';
2018-11-16 21:48:59 +01:00
/**
* URI to the site the bridge is intended to be used for.
*
* Use {@see BridgeAbstract::getURI()} to read this parameter
*/
const URI = '';
2018-11-16 21:48:59 +01:00
/**
* A brief description of what the bridge can do
*
* Use {@see BridgeAbstract::getDescription()} to read this parameter
*/
const DESCRIPTION = 'No description provided';
2018-11-16 21:48:59 +01:00
/**
* The name of the maintainer. Multiple maintainers can be separated by comma
*
* Use {@see BridgeAbstract::getMaintainer()} to read this parameter
*/
const MAINTAINER = 'No maintainer';
2018-11-16 21:48:59 +01:00
/**
* The default cache timeout for the bridge
*
* Use {@see BridgeAbstract::getCacheTimeout()} to read this parameter
*/
const CACHE_TIMEOUT = 3600;
2018-11-16 21:48:59 +01:00
/**
* Configuration for the bridge
*
* Use {@see BridgeAbstract::getConfiguration()} to read this parameter
*/
const CONFIGURATION = array();
2018-11-16 21:48:59 +01:00
/**
* Parameters for the bridge
*
* Use {@see BridgeAbstract::getParameters()} to read this parameter
*/
const PARAMETERS = array();
2018-11-16 21:48:59 +01:00
/**
* Holds the list of items collected by the bridge
*
* Items must be collected by {@see BridgeInterface::collectData()}
*
* Use {@see BridgeAbstract::getItems()} to access items.
*
* @var array
*/
protected $items = array();
2018-11-16 21:48:59 +01:00
/**
* Holds the list of input parameters used by the bridge
*
* Do not access this parameter directly!
* Use {@see BridgeAbstract::setInputs()} and {@see BridgeAbstract::getInput()} instead!
*
* @var array
*/
protected $inputs = array();
/**
2018-11-16 21:48:59 +01:00
* Holds the name of the queried context
*
* @var string
*/
protected $queriedContext = '';
/** {@inheritdoc} */
public function getItems(){
return $this->items;
}
/**
2018-11-16 21:48:59 +01:00
* Sets the input values for a given context.
*
* @param array $inputs Associative array of inputs
2018-11-16 21:48:59 +01:00
* @param string $queriedContext The context name
* @return void
*/
protected function setInputs(array $inputs, $queriedContext){
// Import and assign all inputs to their context
foreach($inputs as $name => $value) {
foreach(static::PARAMETERS as $context => $set) {
if(array_key_exists($name, static::PARAMETERS[$context])) {
$this->inputs[$context][$name]['value'] = $value;
}
}
}
// Apply default values to missing data
$contexts = array($queriedContext);
if(array_key_exists('global', static::PARAMETERS)) {
$contexts[] = 'global';
}
foreach($contexts as $context) {
foreach(static::PARAMETERS[$context] as $name => $properties) {
if(isset($this->inputs[$context][$name]['value'])) {
continue;
}
$type = isset($properties['type']) ? $properties['type'] : 'text';
switch($type) {
case 'checkbox':
if(!isset($properties['defaultValue'])) {
$this->inputs[$context][$name]['value'] = false;
} else {
$this->inputs[$context][$name]['value'] = $properties['defaultValue'];
}
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', static::PARAMETERS)) {
foreach(static::PARAMETERS['global'] as $name => $properties) {
if(isset($inputs[$name])) {
$value = $inputs[$name];
} 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 = array($queriedContext => $this->inputs[$queriedContext]);
} else {
$this->inputs = array();
}
}
/**
2018-11-16 21:48:59 +01:00
* Set inputs for the bridge
*
* Returns errors and aborts execution if the provided input parameters are
* invalid.
*
* @param array List of input parameters. Each element in this list must
* relate to an item in {@see BridgeAbstract::PARAMETERS}
* @return void
*/
public function setDatas(array $inputs){
if(isset($inputs['context'])) { // Context hinting (optional)
$this->queriedContext = $inputs['context'];
unset($inputs['context']);
}
if(empty(static::PARAMETERS)) {
Return exceptions in requested feed formats (#841) * [Exceptions] Don't return header for bridge exceptions * [Exceptions] Add link to list in exception message This is an alternative when the button is not rendered for some reason. * [index] Don't return bridge exception for formats * [index] Return feed item for bridge exceptions * [BridgeAbstract] Rename 'getCacheTime' to 'getModifiedTime' * [BridgeAbstract] Move caching to index.php to separate concerns index.php needs more control over caching behavior in order to cache exceptions. This cannot be done in a bridge, as the bridge might be broken, thus preventing caching from working. This also (and more importantly) separates concerns. The bridge should not even care if caching is involved or not. Its purpose is to collect and provide data. Response times should be faster, as more complex bridge functions like 'setDatas' (evaluates all input parameters to predict the current context) and 'collectData' (collects data from sites) can be skipped entirely. Notice: In its current form, index.php takes care of caching. This could, however, be moved into a separate class (i.e. CacheAbstract) in order to make implementation details cache specific. * [index] Add '_error_time' parameter to $item['uri'] This ensures that error messages are recognized by feed readers as new errors after 24 hours. During that time the same item is returned no matter how often the cache is cleared. References https://github.com/RSS-Bridge/rss-bridge/issues/814#issuecomment-420876162 * [index] Include '_error_time' in the title for errors This prevents feed readers from "updating" feeds based on the title * [index] Handle "HTTP_IF_MODIFIED_SINCE" client requests Implementation is based on `BridgeAbstract::dieIfNotModified()`, introduced in 422c125d8e25b9ac5209580b1976fb5d75dab8f8 and simplified based on https://stackoverflow.com/a/10847262 Basically, before returning cached data we check if the client send the "HTTP_IF_MODIFIED_SINCE" header. If the modification time is more recent or equal to the cache time, we reply with "HTTP/1.1 304 Not Modified" (same as before). Otherwise send the cached data. * [index] Don't encode exception message with `htmlspecialchars` * [Exceptions] Include error message in exception * [index] Show different error message for error code 0
2018-10-15 17:21:43 +02:00
if(!empty($inputs)) {
returnClientError('Invalid parameters value(s)');
}
return;
Return exceptions in requested feed formats (#841) * [Exceptions] Don't return header for bridge exceptions * [Exceptions] Add link to list in exception message This is an alternative when the button is not rendered for some reason. * [index] Don't return bridge exception for formats * [index] Return feed item for bridge exceptions * [BridgeAbstract] Rename 'getCacheTime' to 'getModifiedTime' * [BridgeAbstract] Move caching to index.php to separate concerns index.php needs more control over caching behavior in order to cache exceptions. This cannot be done in a bridge, as the bridge might be broken, thus preventing caching from working. This also (and more importantly) separates concerns. The bridge should not even care if caching is involved or not. Its purpose is to collect and provide data. Response times should be faster, as more complex bridge functions like 'setDatas' (evaluates all input parameters to predict the current context) and 'collectData' (collects data from sites) can be skipped entirely. Notice: In its current form, index.php takes care of caching. This could, however, be moved into a separate class (i.e. CacheAbstract) in order to make implementation details cache specific. * [index] Add '_error_time' parameter to $item['uri'] This ensures that error messages are recognized by feed readers as new errors after 24 hours. During that time the same item is returned no matter how often the cache is cleared. References https://github.com/RSS-Bridge/rss-bridge/issues/814#issuecomment-420876162 * [index] Include '_error_time' in the title for errors This prevents feed readers from "updating" feeds based on the title * [index] Handle "HTTP_IF_MODIFIED_SINCE" client requests Implementation is based on `BridgeAbstract::dieIfNotModified()`, introduced in 422c125d8e25b9ac5209580b1976fb5d75dab8f8 and simplified based on https://stackoverflow.com/a/10847262 Basically, before returning cached data we check if the client send the "HTTP_IF_MODIFIED_SINCE" header. If the modification time is more recent or equal to the cache time, we reply with "HTTP/1.1 304 Not Modified" (same as before). Otherwise send the cached data. * [index] Don't encode exception message with `htmlspecialchars` * [Exceptions] Include error message in exception * [index] Show different error message for error code 0
2018-10-15 17:21:43 +02:00
}
$validator = new ParameterValidator();
if(!$validator->validateData($inputs, static::PARAMETERS)) {
$parameters = array_map(
function($i){ return $i['name']; }, // Just display parameter names
$validator->getInvalidParameters()
);
returnClientError(
'Invalid parameters value(s): '
. implode(', ', $parameters)
);
}
// Guess the context from input data
if(empty($this->queriedContext)) {
$this->queriedContext = $validator->getQueriedContext($inputs, static::PARAMETERS);
}
if(is_null($this->queriedContext)) {
returnClientError('Required parameter(s) missing');
} elseif($this->queriedContext === false) {
returnClientError('Mixed context parameters');
}
$this->setInputs($inputs, $this->queriedContext);
}
/**
* Loads configuration for the bridge
*
* Returns errors and aborts execution if the provided configuration is
* invalid.
*
* @return void
*/
public function loadConfiguration() {
foreach(static::CONFIGURATION as $optionName => $optionValue) {
$configurationOption = Configuration::getConfig(get_class($this), $optionName);
if($configurationOption !== null) {
$this->configuration[$optionName] = $configurationOption;
continue;
}
if(isset($optionValue['required']) && $optionValue['required'] === true) {
returnServerError(
'Missing configuration option: '
. $optionName
);
} elseif(isset($optionValue['defaultValue'])) {
$this->configuration[$optionName] = $optionValue['defaultValue'];
}
}
}
/**
* Returns the value for the provided input
*
* @param string $input The input name
2018-11-16 21:48:59 +01:00
* @return mixed|null The input value or null if the input is not defined
*/
protected function getInput($input){
if(!isset($this->inputs[$this->queriedContext][$input]['value'])) {
return null;
}
return $this->inputs[$this->queriedContext][$input]['value'];
}
/**
* Returns the value for the selected configuration
*
* @param string $input The option name
* @return mixed|null The option value or null if the input is not defined
*/
public function getOption($name){
if(!isset($this->configuration[$name])) {
return null;
}
return $this->configuration[$name];
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getDescription(){
return static::DESCRIPTION;
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getMaintainer(){
return static::MAINTAINER;
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getName(){
return static::NAME;
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getIcon(){
return static::URI . '/favicon.ico';
}
/** {@inheritdoc} */
public function getConfiguration(){
return static::CONFIGURATION;
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getParameters(){
return static::PARAMETERS;
}
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getURI(){
return static::URI;
}
2016-12-06 01:01:07 +01:00
2018-11-16 21:48:59 +01:00
/** {@inheritdoc} */
public function getCacheTimeout(){
Return exceptions in requested feed formats (#841) * [Exceptions] Don't return header for bridge exceptions * [Exceptions] Add link to list in exception message This is an alternative when the button is not rendered for some reason. * [index] Don't return bridge exception for formats * [index] Return feed item for bridge exceptions * [BridgeAbstract] Rename 'getCacheTime' to 'getModifiedTime' * [BridgeAbstract] Move caching to index.php to separate concerns index.php needs more control over caching behavior in order to cache exceptions. This cannot be done in a bridge, as the bridge might be broken, thus preventing caching from working. This also (and more importantly) separates concerns. The bridge should not even care if caching is involved or not. Its purpose is to collect and provide data. Response times should be faster, as more complex bridge functions like 'setDatas' (evaluates all input parameters to predict the current context) and 'collectData' (collects data from sites) can be skipped entirely. Notice: In its current form, index.php takes care of caching. This could, however, be moved into a separate class (i.e. CacheAbstract) in order to make implementation details cache specific. * [index] Add '_error_time' parameter to $item['uri'] This ensures that error messages are recognized by feed readers as new errors after 24 hours. During that time the same item is returned no matter how often the cache is cleared. References https://github.com/RSS-Bridge/rss-bridge/issues/814#issuecomment-420876162 * [index] Include '_error_time' in the title for errors This prevents feed readers from "updating" feeds based on the title * [index] Handle "HTTP_IF_MODIFIED_SINCE" client requests Implementation is based on `BridgeAbstract::dieIfNotModified()`, introduced in 422c125d8e25b9ac5209580b1976fb5d75dab8f8 and simplified based on https://stackoverflow.com/a/10847262 Basically, before returning cached data we check if the client send the "HTTP_IF_MODIFIED_SINCE" header. If the modification time is more recent or equal to the cache time, we reply with "HTTP/1.1 304 Not Modified" (same as before). Otherwise send the cached data. * [index] Don't encode exception message with `htmlspecialchars` * [Exceptions] Include error message in exception * [index] Show different error message for error code 0
2018-10-15 17:21:43 +02:00
return static::CACHE_TIMEOUT;
}
/** {@inheritdoc} */
public function detectParameters($url){
$regex = '/^(https?:\/\/)?(www\.)?(.+?)(\/)?$/';
if(empty(static::PARAMETERS)
&& preg_match($regex, $url, $urlMatches) > 0
&& preg_match($regex, static::URI, $bridgeUriMatches) > 0
&& $urlMatches[3] === $bridgeUriMatches[3]) {
return array();
} else {
return null;
}
}
}