1
0
mirror of https://github.com/RSS-Bridge/rss-bridge.git synced 2025-07-30 21:30:14 +02:00

Merge branch 'methods2functions' of https://framagit.org/peetah/rss-bridge

This commit is contained in:
logmanoriginal
2016-10-02 16:05:58 +02:00
114 changed files with 899 additions and 904 deletions

View File

@@ -9,25 +9,11 @@ abstract class BridgeAbstract implements BridgeInterface {
const CACHE_TIMEOUT = 3600;
const PARAMETERS = array();
public $useProxy = true;
protected $cache;
protected $items = array();
protected $inputs = array();
protected $queriedContext = '';
protected function returnError($message, $code){
throw new \HttpException($message, $code);
}
protected function returnClientError($message){
$this->returnError($message, 400);
}
protected function returnServerError($message){
$this->returnError($message, 500);
}
/**
* Return items stored in the bridge
* @return mixed
@@ -36,105 +22,6 @@ abstract class BridgeAbstract implements BridgeInterface {
return $this->items;
}
protected function validateTextValue($value, $pattern = null){
if(!is_null($pattern)){
$filteredValue = filter_var($value
, FILTER_VALIDATE_REGEXP
, array('options' => array(
'regexp' => '/^' . $pattern . '$/'
))
);
} else {
$filteredValue = filter_var($value);
}
if($filteredValue === false)
return null;
return $filteredValue;
}
protected function validateNumberValue($value){
$filteredValue = filter_var($value, FILTER_VALIDATE_INT);
if($filteredValue === false && !empty($value))
return null;
return $filteredValue;
}
protected function validateCheckboxValue($value){
$filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if(is_null($filteredValue))
return null;
return $filteredValue;
}
protected function validateListValue($value, $expectedValues){
$filteredValue = filter_var($value);
if($filteredValue === false)
return null;
if(!in_array($filteredValue, $expectedValues)){ // Check sub-values?
foreach($expectedValues as $subName => $subValue){
if(is_array($subValue) && in_array($filteredValue, $subValue))
return $filteredValue;
}
return null;
}
return $filteredValue;
}
protected function validateData(&$data){
if(!is_array($data))
return false;
foreach($data as $name => $value){
$registered = false;
foreach(static::PARAMETERS as $context => $set){
if(array_key_exists($name, $set)){
$registered = true;
if(!isset($set[$name]['type'])){
$set[$name]['type'] = 'text';
}
switch($set[$name]['type']){
case 'number':
$data[$name] = $this->validateNumberValue($value);
break;
case 'checkbox':
$data[$name] = $this->validateCheckboxValue($value);
break;
case 'list':
$data[$name] = $this->validateListValue($value, $set[$name]['values']);
break;
default:
case 'text':
if(isset($set[$name]['pattern'])){
$data[$name] = $this->validateTextValue($value, $set[$name]['pattern']);
} else {
$data[$name] = $this->validateTextValue($value);
}
break;
}
if(is_null($data[$name])){
echo 'Parameter \'' . $name . '\' is invalid!' . PHP_EOL;
return false;
}
}
}
if(!$registered)
return false;
}
return true;
}
protected function setInputs(array $inputs, $queriedContext){
// Import and assign all inputs to their context
@@ -261,7 +148,7 @@ abstract class BridgeAbstract implements BridgeInterface {
if(empty(static::PARAMETERS)){
if(!empty($inputs)){
$this->returnClientError('Invalid parameters value(s)');
returnClientError('Invalid parameters value(s)');
}
$this->collectData();
@@ -271,16 +158,16 @@ abstract class BridgeAbstract implements BridgeInterface {
return;
}
if(!$this->validateData($inputs)){
$this->returnClientError('Invalid parameters value(s)');
if(!validateData($inputs, static::PARAMETERS)){
returnClientError('Invalid parameters value(s)');
}
// Guess the paramter context from input data
$this->queriedContext = $this->getQueriedContext($inputs);
if(is_null($this->queriedContext)){
$this->returnClientError('Required parameter(s) missing');
returnClientError('Required parameter(s) missing');
} elseif($this->queriedContext === false){
$this->returnClientError('Mixed context parameters');
returnClientError('Mixed context parameters');
}
$this->setInputs($inputs, $this->queriedContext);
@@ -310,157 +197,4 @@ abstract class BridgeAbstract implements BridgeInterface {
public function setCache(\CacheAbstract $cache){
$this->cache = $cache;
}
public function debugMessage($text){
if(!file_exists('DEBUG')) {
return;
}
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$calling = $backtrace[2];
$message = $calling['file'] . ':'
. $calling['line'] . ' class '
. get_class($this) . '->'
. $calling['function'] . ' - '
. $text;
error_log($message);
}
protected function getContents($url
, $use_include_path = false
, $context = null
, $offset = 0
, $maxlen = null){
$contextOptions = array(
'http' => array(
'user_agent' => ini_get('user_agent')
)
);
if(defined('PROXY_URL') && $this->useProxy){
$contextOptions['http']['proxy'] = PROXY_URL;
$contextOptions['http']['request_fulluri'] = true;
if(is_null($context)){
$context = stream_context_create($contextOptions);
} else {
$prevContext = $context;
if(!stream_context_set_option($context, $contextOptions)){
$context = $prevContext;
}
}
}
if(is_null($maxlen)){
$content = @file_get_contents($url, $use_include_path, $context, $offset);
} else {
$content = @file_get_contents($url, $use_include_path, $context, $offset, $maxlen);
}
if($content === false)
$this->debugMessage('Cant\'t download ' . $url);
// handle compressed data
foreach($http_response_header as $header){
if(stristr($header, 'content-encoding')){
switch(true){
case stristr($header, 'gzip'):
$content = gzinflate(substr($content, 10, -8));
break;
case stristr($header, 'compress'):
//TODO
case stristr($header, 'deflate'):
//TODO
case stristr($header, 'brotli'):
//TODO
$this->returnServerError($header . '=> Not implemented yet');
break;
case stristr($header, 'identity'):
break;
default:
$this->returnServerError($header . '=> Unknown compression');
}
}
}
return $content;
}
protected function getSimpleHTMLDOM($url
, $use_include_path = false
, $context = null
, $offset = 0
, $maxLen = null
, $lowercase = true
, $forceTagsClosed = true
, $target_charset = DEFAULT_TARGET_CHARSET
, $stripRN = true
, $defaultBRText = DEFAULT_BR_TEXT
, $defaultSpanText = DEFAULT_SPAN_TEXT){
$content = $this->getContents($url, $use_include_path, $context, $offset, $maxLen);
return str_get_html($content
, $lowercase
, $forceTagsClosed
, $target_charset
, $stripRN
, $defaultBRText
, $defaultSpanText);
}
/**
* Maintain locally cached versions of pages to avoid multiple downloads.
* @param url url to cache
* @param duration duration of the cache file in seconds (default: 24h/86400s)
* @return content of the file as string
*/
public function getSimpleHTMLDOMCached($url
, $duration = 86400
, $use_include_path = false
, $context = null
, $offset = 0
, $maxLen = null
, $lowercase = true
, $forceTagsClosed = true
, $target_charset = DEFAULT_TARGET_CHARSET
, $stripRN = true
, $defaultBRText = DEFAULT_BR_TEXT
, $defaultSpanText = DEFAULT_SPAN_TEXT){
$this->debugMessage('Caching url ' . $url . ', duration ' . $duration);
$filepath = __DIR__ . '/../cache/pages/' . sha1($url) . '.cache';
$this->debugMessage('Cache file ' . $filepath);
if(file_exists($filepath) && filectime($filepath) < time() - $duration){
unlink ($filepath);
$this->debugMessage('Cached file deleted: ' . $filepath);
}
if(file_exists($filepath)){
$this->debugMessage('Loading cached file ' . $filepath);
touch($filepath);
$content = file_get_contents($filepath);
} else {
$this->debugMessage('Caching ' . $url . ' to ' . $filepath);
$dir = substr($filepath, 0, strrpos($filepath, '/'));
if(!is_dir($dir)){
$this->debugMessage('Creating directory ' . $dir);
mkdir($dir, 0777, true);
}
$content = $this->getContents($url, $use_include_path, $context, $offset, $maxLen);
if($content !== false){
file_put_contents($filepath, $content);
}
}
return str_get_html($content
, $lowercase
, $forceTagsClosed
, $target_charset
, $stripRN
, $defaultBRText
, $defaultSpanText);
}
}

View File

@@ -9,46 +9,46 @@ abstract class FeedExpander extends BridgeAbstract {
public function collectExpandableDatas($url, $maxItems = -1){
if(empty($url)){
$this->returnServerError('There is no $url for this RSS expander');
returnServerError('There is no $url for this RSS expander');
}
$this->debugMessage('Loading from ' . $url);
debugMessage('Loading from ' . $url);
/* Notice we do not use cache here on purpose:
* we want a fresh view of the RSS stream each time
*/
$content = $this->getContents($url)
or $this->returnServerError('Could not request ' . $url);
$content = getContents($url)
or returnServerError('Could not request ' . $url);
$rssContent = simplexml_load_string($content);
$this->debugMessage('Detecting feed format/version');
debugMessage('Detecting feed format/version');
switch(true){
case isset($rssContent->item[0]):
$this->debugMessage('Detected RSS 1.0 format');
debugMessage('Detected RSS 1.0 format');
$this->feedType = "RSS_1_0";
break;
case isset($rssContent->channel[0]):
$this->debugMessage('Detected RSS 0.9x or 2.0 format');
debugMessage('Detected RSS 0.9x or 2.0 format');
$this->feedType = "RSS_2_0";
break;
case isset($rssContent->entry[0]):
$this->debugMessage('Detected ATOM format');
debugMessage('Detected ATOM format');
$this->feedType = "ATOM_1_0";
break;
default:
$this->debugMessage('Unknown feed format/version');
$this->returnServerError('The feed format is unknown!');
debugMessage('Unknown feed format/version');
returnServerError('The feed format is unknown!');
break;
}
$this->debugMessage('Calling function "collect_' . $this->feedType . '_data"');
debugMessage('Calling function "collect_' . $this->feedType . '_data"');
$this->{'collect_' . $this->feedType . '_data'}($rssContent, $maxItems);
}
protected function collect_RSS_1_0_data($rssContent, $maxItems){
$this->load_RSS_2_0_feed_data($rssContent->channel[0]);
foreach($rssContent->item as $item){
$this->debugMessage('parsing item ' . var_export($item, true));
debugMessage('parsing item ' . var_export($item, true));
$this->items[] = $this->parseItem($item);
if($maxItems !== -1 && count($this->items) >= $maxItems) break;
}
@@ -56,13 +56,13 @@ abstract class FeedExpander extends BridgeAbstract {
protected function collect_RSS_2_0_data($rssContent, $maxItems){
$rssContent = $rssContent->channel[0];
$this->debugMessage('RSS content is ===========\n'
debugMessage('RSS content is ===========\n'
. var_export($rssContent, true)
. '===========');
$this->load_RSS_2_0_feed_data($rssContent);
foreach($rssContent->item as $item){
$this->debugMessage('parsing item ' . var_export($item, true));
debugMessage('parsing item ' . var_export($item, true));
$this->items[] = $this->parseItem($item);
if($maxItems !== -1 && count($this->items) >= $maxItems) break;
}
@@ -71,7 +71,7 @@ abstract class FeedExpander extends BridgeAbstract {
protected function collect_ATOM_1_0_data($content, $maxItems){
$this->load_ATOM_feed_data($content);
foreach($content->entry as $item){
$this->debugMessage('parsing item ' . var_export($item, true));
debugMessage('parsing item ' . var_export($item, true));
$this->items[] = $this->parseItem($item);
if($maxItems !== -1 && count($this->items) >= $maxItems) break;
}
@@ -190,7 +190,7 @@ abstract class FeedExpander extends BridgeAbstract {
case 'ATOM_1_0':
return $this->parseATOMItem($item);
break;
default: $this->returnClientError('Unknown version ' . $this->getInput('version') . '!');
default: returnClientError('Unknown version ' . $this->getInput('version') . '!');
}
}

View File

@@ -1,307 +0,0 @@
<?php
class HTMLUtils {
public static function displayBridgeCard($bridgeName, $formats, $isActive = true){
$bridgeElement = Bridge::create($bridgeName);
$bridgeClass = $bridgeName . 'Bridge';
if($bridgeElement == false)
return "";
$name = '<a href="' . $bridgeClass::URI . '">' . $bridgeClass::NAME . '</a>';
$description = $bridgeClass::DESCRIPTION;
$card = <<<CARD
<section id="bridge-{$bridgeName}" data-ref="{$bridgeName}">
<h2>{$name}</h2>
<p class="description">
{$description}
</p>
<input type="checkbox" class="showmore-box" id="showmore-{$bridgeName}" />
<label class="showmore" for="showmore-{$bridgeName}">Show more</label>
CARD;
// If we don't have any parameter for the bridge, we print a generic form to load it.
if(count($bridgeClass::PARAMETERS) == 0){
$card .= HTMLUtils::getFormHeader($bridgeName);
if($isActive){
if(defined('PROXY_URL') && PROXY_BYBRIDGE){
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode('proxyoff')
. '-'
. urlencode('_noproxy');
$card .= '<input id="'
. $idArg
. '" type="checkbox" name="_noproxy" />'
. PHP_EOL;
$card .= '<label for="'
. $idArg
. '">Disable proxy ('
. ((defined('PROXY_NAME') && PROXY_NAME) ? PROXY_NAME : PROXY_URL)
. ')</label><br />'
. PHP_EOL;
}
$card .= HTMLUtils::getHelperButtonsFormat($formats);
} else {
$card .= '<span style="font-weight: bold;">Inactive</span>';
}
$card .= '</form>' . PHP_EOL;
}
$hasGlobalParameter = array_key_exists('global', $bridgeClass::PARAMETERS);
if($hasGlobalParameter){
$globalParameters = $bridgeClass::PARAMETERS['global'];
}
foreach($bridgeClass::PARAMETERS as $parameterName => $parameter){
if(!is_numeric($parameterName) && $parameterName == 'global')
continue;
if($hasGlobalParameter)
$parameter = array_merge($parameter, $globalParameters);
if(!is_numeric($parameterName))
$card .= '<h5>' . $parameterName . '</h5>' . PHP_EOL;
$card .= HTMLUtils::getFormHeader($bridgeName);
foreach($parameter as $id => $inputEntry){
$additionalInfoString = '';
if(isset($inputEntry['required']) && $inputEntry['required'] === true)
$additionalInfoString .= ' required';
if(isset($inputEntry['pattern']))
$additionalInfoString .= ' pattern="' . $inputEntry['pattern'] . '"';
if(isset($inputEntry['title']))
$additionalInfoString .= ' title="' . $inputEntry['title'] . '"';
if(!isset($inputEntry['exampleValue']))
$inputEntry['exampleValue'] = '';
if(!isset($inputEntry['defaultValue']))
$inputEntry['defaultValue'] = '';
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode($parameterName)
. '-'
. urlencode($id);
$card .= '<label for="'
. $idArg
. '">'
. $inputEntry['name']
. ' : </label>'
. PHP_EOL;
if(!isset($inputEntry['type']) || $inputEntry['type'] == 'text'){
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="text" value="'
. $inputEntry['defaultValue']
. '" placeholder="'
. $inputEntry['exampleValue']
. '" name="'
. $id
. '" /><br />'
. PHP_EOL;
} elseif($inputEntry['type'] == 'number'){
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="number" value="'
. $inputEntry['defaultValue']
. '" placeholder="'
. $inputEntry['exampleValue']
. '" name="'
. $id
. '" /><br />'
. PHP_EOL;
} else if($inputEntry['type'] == 'list'){
$card .= '<select '
. $additionalInfoString
. ' id="'
. $idArg
. '" name="'
. $id
. '" >';
foreach($inputEntry['values'] as $name => $value){
if(is_array($value)){
$card .= '<optgroup label="' . htmlentities($name) . '">';
foreach($value as $subname => $subvalue){
if($inputEntry['defaultValue'] === $subname
|| $inputEntry['defaultValue'] === $subvalue){
$card .= '<option value="'
. $subvalue
. '" selected>'
. $subname
. '</option>';
} else {
$card .= '<option value="'
. $subvalue
. '">'
. $subname
. '</option>';
}
}
$card .= '</optgroup>';
} else {
if($inputEntry['defaultValue'] === $name
|| $inputEntry['defaultValue'] === $value){
$card .= '<option value="'
. $value
. '" selected>'
. $name
. '</option>';
} else {
$card .= '<option value="'
. $value
. '">'
. $name
. '</option>';
}
}
}
$card .= '</select><br >';
} elseif($inputEntry['type'] == 'checkbox'){
if($inputEntry['defaultValue'] === 'checked')
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="checkbox" name="'
. $id
. '" checked /><br />'
. PHP_EOL;
else
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="checkbox" name="'
. $id
. '" /><br />'
. PHP_EOL;
}
}
if($isActive){
if(defined('PROXY_URL') && PROXY_BYBRIDGE){
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode('proxyoff')
. '-'
. urlencode('_noproxy');
$card .= '<input id="'
. $idArg
. '" type="checkbox" name="_noproxy" />'
. PHP_EOL;
$card .= '<label for="'
. $idArg
. '">Disable proxy ('
. ((defined('PROXY_NAME') && PROXY_NAME) ? PROXY_NAME : PROXY_URL)
. ')</label><br />'
. PHP_EOL;
}
$card .= HTMLUtils::getHelperButtonsFormat($formats);
} else {
$card .= '<span style="font-weight: bold;">Inactive</span>';
}
$card .= '</form>' . PHP_EOL;
}
$card .= '<label class="showless" for="showmore-' . $bridgeName . '">Show less</label>';
$card .= '<p class="maintainer">' . $bridgeClass::MAINTAINER . '</p>';
$card .= '</section>';
return $card;
}
private static function getHelperButtonsFormat($formats){
$buttons = '';
foreach($formats as $name){
$buttons .= '<button type="submit" name="format" value="'
. $name
. '">'
. $name
. '</button>'
. PHP_EOL;
}
return $buttons;
}
private static function getFormHeader($bridge){
return <<<EOD
<form method="GET" action="?">
<input type="hidden" name="action" value="display" />
<input type="hidden" name="bridge" value="{$bridge}" />
EOD;
}
}
class HTMLSanitizer {
var $tagsToRemove;
var $keptAttributes;
var $onlyKeepText;
public static $DEFAULT_CLEAR_TAGS = ["script", "iframe", "input", "form"];
public static $KEPT_ATTRIBUTES = ["title", "href", "src"];
public static $ONLY_TEXT = [];
public function __construct($tags_to_remove = null
, $kept_attributes = null
, $only_keep_text = null){
$this->tagsToRemove = is_null($tags_to_remove) ? HTMLSanitizer::$DEFAULT_CLEAR_TAGS : $tags_to_remove;
$this->keptAttributes = is_null($kept_attributes) ? HTMLSanitizer::$KEPT_ATTRIBUTES : $kept_attributes;
$this->onlyKeepText = is_null($only_keep_text) ? HTMLSanitizer::$ONLY_TEXT : $only_keep_text;
}
public function sanitize($textToSanitize){
$htmlContent = str_get_html($textToSanitize);
foreach($htmlContent->find('*[!b38fd2b1fe7f4747d6b1c1254ccd055e]') as $element){
if(in_array($element->tag, $this->onlyKeepText)){
$element->outertext = $element->plaintext;
} elseif(in_array($element->tag, $this->tagsToRemove)){
$element->outertext = '';
} else {
foreach($element->getAllAttributes() as $attributeName => $attribute){
if(!in_array($attributeName, $this->keptAttributes))
$element->removeAttribute($attributeName);
}
}
}
return $htmlContent;
}
public static function defaultImageSrcTo($content, $server){
foreach($content->find('img') as $image){
if(is_null(strpos($image->src, "http"))
&& is_null(strpos($image->src, "//"))
&& is_null(strpos($image->src, "data:")))
$image->src = $server . $image->src;
}
return $content;
}
}

View File

@@ -15,7 +15,11 @@ require __DIR__ . '/BridgeAbstract.php';
require __DIR__ . '/FeedExpander.php';
require __DIR__ . '/Cache.php';
require __DIR__ . '/CacheAbstract.php';
require __DIR__ . '/HTMLUtils.php';
require __DIR__ . '/validation.php';
require __DIR__ . '/html.php';
require __DIR__ . '/error.php';
require __DIR__ . '/contents.php';
$vendorLibSimpleHtmlDom = __DIR__ . PATH_VENDOR . '/simplehtmldom/simple_html_dom.php';
if( !file_exists($vendorLibSimpleHtmlDom) ){

142
lib/contents.php Normal file
View File

@@ -0,0 +1,142 @@
<?php
function getContents($url
, $use_include_path = false
, $context = null
, $offset = 0
, $maxlen = null
){
$contextOptions = array(
'http' => array(
'user_agent' => ini_get('user_agent')
)
);
if(defined('PROXY_URL') && !defined('NOPROXY')){
$contextOptions['http']['proxy'] = PROXY_URL;
$contextOptions['http']['request_fulluri'] = true;
if(is_null($context)){
$context = stream_context_create($contextOptions);
} else {
$prevContext = $context;
if(!stream_context_set_option($context, $contextOptions)){
$context = $prevContext;
}
}
}
if(is_null($maxlen)){
$content = @file_get_contents($url, $use_include_path, $context, $offset);
} else {
$content = @file_get_contents($url, $use_include_path, $context, $offset, $maxlen);
}
if($content === false)
debugMessage('Cant\'t download ' . $url);
// handle compressed data
foreach($http_response_header as $header){
if(stristr($header, 'content-encoding')){
switch(true){
case stristr($header, 'gzip'):
$content = gzinflate(substr($content, 10, -8));
break;
case stristr($header, 'compress'):
//TODO
case stristr($header, 'deflate'):
//TODO
case stristr($header, 'brotli'):
//TODO
returnServerError($header . '=> Not implemented yet');
break;
case stristr($header, 'identity'):
break;
default:
returnServerError($header . '=> Unknown compression');
}
}
}
return $content;
}
function getSimpleHTMLDOM($url
, $use_include_path = false
, $context = null
, $offset = 0
, $maxLen = null
, $lowercase = true
, $forceTagsClosed = true
, $target_charset = DEFAULT_TARGET_CHARSET
, $stripRN = true
, $defaultBRText = DEFAULT_BR_TEXT
, $defaultSpanText = DEFAULT_SPAN_TEXT
){
$content = getContents($url, $use_include_path, $context, $offset, $maxLen);
return str_get_html($content
, $lowercase
, $forceTagsClosed
, $target_charset
, $stripRN
, $defaultBRText
, $defaultSpanText);
}
/**
* Maintain locally cached versions of pages to avoid multiple downloads.
* @param url url to cache
* @param duration duration of the cache file in seconds (default: 24h/86400s)
* @return content of the file as string
*/
function getSimpleHTMLDOMCached($url
, $duration = 86400
, $use_include_path = false
, $context = null
, $offset = 0
, $maxLen = null
, $lowercase = true
, $forceTagsClosed = true
, $target_charset = DEFAULT_TARGET_CHARSET
, $stripRN = true
, $defaultBRText = DEFAULT_BR_TEXT
, $defaultSpanText = DEFAULT_SPAN_TEXT
){
debugMessage('Caching url ' . $url . ', duration ' . $duration);
$filepath = __DIR__ . '/../cache/pages/' . sha1($url) . '.cache';
debugMessage('Cache file ' . $filepath);
if(file_exists($filepath) && filectime($filepath) < time() - $duration){
unlink ($filepath);
debugMessage('Cached file deleted: ' . $filepath);
}
if(file_exists($filepath)){
debugMessage('Loading cached file ' . $filepath);
touch($filepath);
$content = file_get_contents($filepath);
} else {
debugMessage('Caching ' . $url . ' to ' . $filepath);
$dir = substr($filepath, 0, strrpos($filepath, '/'));
if(!is_dir($dir)){
debugMessage('Creating directory ' . $dir);
mkdir($dir, 0777, true);
}
$content = getContents($url, $use_include_path, $context, $offset, $maxLen);
if($content !== false){
file_put_contents($filepath, $content);
}
}
return str_get_html($content
, $lowercase
, $forceTagsClosed
, $target_charset
, $stripRN
, $defaultBRText
, $defaultSpanText);
}
?>

30
lib/error.php Normal file
View File

@@ -0,0 +1,30 @@
<?php
function returnError($message, $code){
throw new \HttpException($message, $code);
}
function returnClientError($message){
returnError($message, 400);
}
function returnServerError($message){
returnError($message, 500);
}
function debugMessage($text){
if(!file_exists('DEBUG')) {
return;
}
$backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
$calling = $backtrace[2];
$message = $calling['file'] . ':'
. $calling['line'] . ' class '
. $calling['class'] . '->'
. $calling['function'] . ' - '
. $text;
error_log($message);
}
?>

292
lib/html.php Normal file
View File

@@ -0,0 +1,292 @@
<?php
function displayBridgeCard($bridgeName, $formats, $isActive = true){
$getHelperButtonsFormat = function($formats){
$buttons = '';
foreach($formats as $name){
$buttons .= '<button type="submit" name="format" value="'
. $name
. '">'
. $name
. '</button>'
. PHP_EOL;
}
return $buttons;
};
$getFormHeader = function($bridge){
return <<<EOD
<form method="GET" action="?">
<input type="hidden" name="action" value="display" />
<input type="hidden" name="bridge" value="{$bridge}" />
EOD;
};
$bridgeElement = Bridge::create($bridgeName);
$bridgeClass = $bridgeName . 'Bridge';
if($bridgeElement == false)
return "";
$name = '<a href="' . $bridgeClass::URI . '">' . $bridgeClass::NAME . '</a>';
$description = $bridgeClass::DESCRIPTION;
$card = <<<CARD
<section id="bridge-{$bridgeName}" data-ref="{$bridgeName}">
<h2>{$name}</h2>
<p class="description">
{$description}
</p>
<input type="checkbox" class="showmore-box" id="showmore-{$bridgeName}" />
<label class="showmore" for="showmore-{$bridgeName}">Show more</label>
CARD;
// If we don't have any parameter for the bridge, we print a generic form to load it.
if(count($bridgeClass::PARAMETERS) == 0){
$card .= $getFormHeader($bridgeName);
if($isActive){
if(defined('PROXY_URL') && PROXY_BYBRIDGE){
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode('proxyoff')
. '-'
. urlencode('_noproxy');
$card .= '<input id="'
. $idArg
. '" type="checkbox" name="_noproxy" />'
. PHP_EOL;
$card .= '<label for="'
. $idArg
. '">Disable proxy ('
. ((defined('PROXY_NAME') && PROXY_NAME) ? PROXY_NAME : PROXY_URL)
. ')</label><br />'
. PHP_EOL;
}
$card .= $getHelperButtonsFormat($formats);
} else {
$card .= '<span style="font-weight: bold;">Inactive</span>';
}
$card .= '</form>' . PHP_EOL;
}
$hasGlobalParameter = array_key_exists('global', $bridgeClass::PARAMETERS);
if($hasGlobalParameter){
$globalParameters = $bridgeClass::PARAMETERS['global'];
}
foreach($bridgeClass::PARAMETERS as $parameterName => $parameter){
if(!is_numeric($parameterName) && $parameterName == 'global')
continue;
if($hasGlobalParameter)
$parameter = array_merge($parameter, $globalParameters);
if(!is_numeric($parameterName))
$card .= '<h5>' . $parameterName . '</h5>' . PHP_EOL;
$card .= $getFormHeader($bridgeName);
foreach($parameter as $id => $inputEntry){
$additionalInfoString = '';
if(isset($inputEntry['required']) && $inputEntry['required'] === true)
$additionalInfoString .= ' required';
if(isset($inputEntry['pattern']))
$additionalInfoString .= ' pattern="' . $inputEntry['pattern'] . '"';
if(isset($inputEntry['title']))
$additionalInfoString .= ' title="' . $inputEntry['title'] . '"';
if(!isset($inputEntry['exampleValue']))
$inputEntry['exampleValue'] = '';
if(!isset($inputEntry['defaultValue']))
$inputEntry['defaultValue'] = '';
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode($parameterName)
. '-'
. urlencode($id);
$card .= '<label for="'
. $idArg
. '">'
. $inputEntry['name']
. ' : </label>'
. PHP_EOL;
if(!isset($inputEntry['type']) || $inputEntry['type'] == 'text'){
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="text" value="'
. $inputEntry['defaultValue']
. '" placeholder="'
. $inputEntry['exampleValue']
. '" name="'
. $id
. '" /><br />'
. PHP_EOL;
} elseif($inputEntry['type'] == 'number'){
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="number" value="'
. $inputEntry['defaultValue']
. '" placeholder="'
. $inputEntry['exampleValue']
. '" name="'
. $id
. '" /><br />'
. PHP_EOL;
} else if($inputEntry['type'] == 'list'){
$card .= '<select '
. $additionalInfoString
. ' id="'
. $idArg
. '" name="'
. $id
. '" >';
foreach($inputEntry['values'] as $name => $value){
if(is_array($value)){
$card .= '<optgroup label="' . htmlentities($name) . '">';
foreach($value as $subname => $subvalue){
if($inputEntry['defaultValue'] === $subname
|| $inputEntry['defaultValue'] === $subvalue){
$card .= '<option value="'
. $subvalue
. '" selected>'
. $subname
. '</option>';
} else {
$card .= '<option value="'
. $subvalue
. '">'
. $subname
. '</option>';
}
}
$card .= '</optgroup>';
} else {
if($inputEntry['defaultValue'] === $name
|| $inputEntry['defaultValue'] === $value){
$card .= '<option value="'
. $value
. '" selected>'
. $name
. '</option>';
} else {
$card .= '<option value="'
. $value
. '">'
. $name
. '</option>';
}
}
}
$card .= '</select><br >';
} elseif($inputEntry['type'] == 'checkbox'){
if($inputEntry['defaultValue'] === 'checked')
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="checkbox" name="'
. $id
. '" checked /><br />'
. PHP_EOL;
else
$card .= '<input '
. $additionalInfoString
. ' id="'
. $idArg
. '" type="checkbox" name="'
. $id
. '" /><br />'
. PHP_EOL;
}
}
if($isActive){
if(defined('PROXY_URL') && PROXY_BYBRIDGE){
$idArg = 'arg-'
. urlencode($bridgeName)
. '-'
. urlencode('proxyoff')
. '-'
. urlencode('_noproxy');
$card .= '<input id="'
. $idArg
. '" type="checkbox" name="_noproxy" />'
. PHP_EOL;
$card .= '<label for="'
. $idArg
. '">Disable proxy ('
. ((defined('PROXY_NAME') && PROXY_NAME) ? PROXY_NAME : PROXY_URL)
. ')</label><br />'
. PHP_EOL;
}
$card .= $getHelperButtonsFormat($formats);
} else {
$card .= '<span style="font-weight: bold;">Inactive</span>';
}
$card .= '</form>' . PHP_EOL;
}
$card .= '<label class="showless" for="showmore-' . $bridgeName . '">Show less</label>';
$card .= '<p class="maintainer">' . $bridgeClass::MAINTAINER . '</p>';
$card .= '</section>';
return $card;
}
function sanitize($textToSanitize
,$removedTags=array('script','iframe','input','form')
,$keptAttributes=array('title','href','src')
,$keptText=array()){
$htmlContent = str_get_html($textToSanitize);
foreach($htmlContent->find('*[!b38fd2b1fe7f4747d6b1c1254ccd055e]') as $element){
if(in_array($element->tag, $keptText)){
$element->outertext = $element->plaintext;
} elseif(in_array($element->tag, $removedTags)){
$element->outertext = '';
} else {
foreach($element->getAllAttributes() as $attributeName => $attribute){
if(!in_array($attributeName, $keptAttributes))
$element->removeAttribute($attributeName);
}
}
}
return $htmlContent;
}
function defaultImageSrcTo($content, $server){
foreach($content->find('img') as $image){
if(is_null(strpos($image->src, "http"))
&& is_null(strpos($image->src, "//"))
&& is_null(strpos($image->src, "data:")))
$image->src = $server . $image->src;
}
return $content;
}
?>

103
lib/validation.php Normal file
View File

@@ -0,0 +1,103 @@
<?php
function validateData(&$data,$parameters){
$validateTextValue = function($value, $pattern = null){
if(!is_null($pattern)){
$filteredValue = filter_var($value
, FILTER_VALIDATE_REGEXP
, array('options' => array(
'regexp' => '/^' . $pattern . '$/'
))
);
} else {
$filteredValue = filter_var($value);
}
if($filteredValue === false)
return null;
return $filteredValue;
};
$validateNumberValue = function($value){
$filteredValue = filter_var($value, FILTER_VALIDATE_INT);
if($filteredValue === false && !empty($value))
return null;
return $filteredValue;
};
$validateCheckboxValue = function($value){
$filteredValue = filter_var($value, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE);
if(is_null($filteredValue))
return null;
return $filteredValue;
};
$validateListValue = function($value, $expectedValues){
$filteredValue = filter_var($value);
if($filteredValue === false)
return null;
if(!in_array($filteredValue, $expectedValues)){ // Check sub-values?
foreach($expectedValues as $subName => $subValue){
if(is_array($subValue) && in_array($filteredValue, $subValue))
return $filteredValue;
}
return null;
}
return $filteredValue;
};
if(!is_array($data))
return false;
foreach($data as $name => $value){
$registered = false;
foreach($parameters as $context => $set){
if(array_key_exists($name, $set)){
$registered = true;
if(!isset($set[$name]['type'])){
$set[$name]['type'] = 'text';
}
switch($set[$name]['type']){
case 'number':
$data[$name] = $validateNumberValue($value);
break;
case 'checkbox':
$data[$name] = $validateCheckboxValue($value);
break;
case 'list':
$data[$name] = $validateListValue($value, $set[$name]['values']);
break;
default:
case 'text':
if(isset($set[$name]['pattern'])){
$data[$name] = $validateTextValue($value, $set[$name]['pattern']);
} else {
$data[$name] = $validateTextValue($value);
}
break;
}
if(is_null($data[$name])){
echo 'Parameter \'' . $name . '\' is invalid!' . PHP_EOL;
return false;
}
}
}
if(!$registered)
return false;
}
return true;
}
?>