From fd4af15ce67b6c075feef536cb870920682d831c Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoit=2ES=20=C2=AB=C2=A0Benpro=C2=A0=C2=BB?= Date: Thu, 6 Feb 2014 11:34:19 +0100 Subject: [PATCH 1/2] Respect PHP Coding Standards. PSR-1 and PSR-2. PSR-0 need more modifications. --- bridges/CryptomeBridge.php | 20 +++--- bridges/DansTonChatBridge.php | 28 ++++---- bridges/DuckDuckGoBridge.php | 28 ++++---- bridges/FSBridge.php | 65 +++++++++--------- bridges/FlickrExploreBridge.php | 24 ++++--- bridges/GoogleSearchBridge.php | 29 ++++---- bridges/GuruMedBridge.php | 67 ++++++++++--------- bridges/IdenticaBridge.php | 27 ++++---- bridges/InstagramBridge.php | 86 ++++++++++++------------ bridges/OpenClassroomsBridge.php | 28 ++++---- bridges/PinterestBridge.php | 111 +++++++++++++++---------------- bridges/ScmbBridge.php | 60 +++++++++-------- bridges/TwitterBridge.php | 26 ++++---- bridges/WikipediaENBridge.php | 32 +++++---- bridges/WikipediaEOBridge.php | 32 +++++---- bridges/WikipediaFRBridge.php | 28 ++++---- bridges/YoutubeBridge.php | 28 ++++---- caches/FileCache.php | 37 +++++++---- formats/AtomFormat.php | 21 +++--- formats/HtmlFormat.php | 14 ++-- formats/JsonFormat.php | 12 ++-- formats/PlaintextFormat.php | 13 ++-- index.php | 27 ++++---- lib/Bridge.php | 95 ++++++++++++++------------ lib/Cache.php | 42 +++++++----- lib/Exceptions.php | 14 ++-- lib/Format.php | 98 +++++++++++++++------------ lib/Item.php | 11 +-- lib/RssBridge.php | 6 +- 29 files changed, 604 insertions(+), 505 deletions(-) diff --git a/bridges/CryptomeBridge.php b/bridges/CryptomeBridge.php index 1409ecfa..aedd8bf3 100644 --- a/bridges/CryptomeBridge.php +++ b/bridges/CryptomeBridge.php @@ -8,9 +8,10 @@ * @description Returns the N most recent documents. * @use1(n="number") */ -class CryptomeBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class CryptomeBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $num = 90; $link = 'http://cryptome.org/'; @@ -22,8 +23,8 @@ class CryptomeBridge extends BridgeAbstract{ $num = min(max(1, $param['n']+0), $num); } - foreach($html->find('pre') as $element) { - for ( $i = 0; $i < $num; ++$i ) { + foreach ($html->find('pre') as $element) { + for ($i = 0; $i < $num; ++$i) { $item = new \Item(); $item->uri = $link.substr($element->find('a', $i)->href, 20); $item->title = substr($element->find('b', $i)->plaintext, 22); @@ -34,15 +35,18 @@ class CryptomeBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return 'Cryptome'; } - public function getURI(){ + public function getURI() + { return 'https://secure.netsolhost.com/cryptome.org/'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/bridges/DansTonChatBridge.php b/bridges/DansTonChatBridge.php index 3bb6e0b4..7473c7de 100644 --- a/bridges/DansTonChatBridge.php +++ b/bridges/DansTonChatBridge.php @@ -7,32 +7,36 @@ * @name DansTonChat Bridge * @description Returns latest quotes from DansTonChat. */ -class DansTonChatBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class DansTonChatBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $link = 'http://danstonchat.com/latest.html'; $html = file_get_html($link) or $this->returnError('Could not request DansTonChat.', 404); - foreach($html->find('div.item') as $element) { - $item = new \Item(); - $item->uri = $element->find('a', 0)->href; - $item->title = 'DansTonChat '.$element->find('a', 1)->plaintext; - $item->content = $element->find('a', 0)->innertext; - $this->items[] = $item; + foreach ($html->find('div.item') as $element) { + $item = new \Item(); + $item->uri = $element->find('a', 0)->href; + $item->title = 'DansTonChat '.$element->find('a', 1)->plaintext; + $item->content = $element->find('a', 0)->innertext; + $this->items[] = $item; } } - public function getName(){ + public function getName() + { return 'DansTonChat'; } - public function getURI(){ + public function getURI() + { return 'http://danstonchat.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/bridges/DuckDuckGoBridge.php b/bridges/DuckDuckGoBridge.php index a194a5c7..328fc88c 100644 --- a/bridges/DuckDuckGoBridge.php +++ b/bridges/DuckDuckGoBridge.php @@ -8,32 +8,36 @@ * @description Returns most recent results from DuckDuckGo. * @use1(u="keyword") */ -class DuckDuckGoBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class DuckDuckGoBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $link = 'https://duckduckgo.com/html/?q='.$param[u].'+sort:date'; $html = file_get_html($link) or $this->returnError('Could not request DuckDuckGo.', 404); - foreach($html->find('div.results_links') as $element) { - $item = new \Item(); - $item->uri = $element->find('a', 0)->href; - $item->title = $element->find('a', 1)->innertext; - $item->content = $element->find('div.snippet', 0)->plaintext; - $this->items[] = $item; + foreach ($html->find('div.results_links') as $element) { + $item = new \Item(); + $item->uri = $element->find('a', 0)->href; + $item->title = $element->find('a', 1)->innertext; + $item->content = $element->find('div.snippet', 0)->plaintext; + $this->items[] = $item; } } - public function getName(){ + public function getName() + { return 'DuckDuckGo'; } - public function getURI(){ + public function getURI() + { return 'https://duckduckgo.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/bridges/FSBridge.php b/bridges/FSBridge.php index 1ffd25d8..51c0e9b0 100644 --- a/bridges/FSBridge.php +++ b/bridges/FSBridge.php @@ -6,50 +6,53 @@ * @name Futurasciences * @description Returns the 20 newest posts from FS (full text) */ -class FSBridge extends BridgeAbstract{ +class FSBridge extends BridgeAbstract +{ + public function collectData(array $param) + { + public function FS_StripCDATA($string) + { + $string = str_replace('', '', $string); + return $string; + } + public function FS_ExtractContent($url) + { + $html2 = file_get_html($url); + $text = $html2->find('div.fiche-actualite', 0)->innertext; - - - public function collectData(array $param){ - - function FS_StripCDATA($string) { - $string = str_replace('', '', $string); - return $string; - } - function FS_ExtractContent($url) { - $html2 = file_get_html($url); - $text = $html2->find('div.fiche-actualite', 0)->innertext; - return $text; - } + return $text; + } $html = file_get_html('http://www.futura-sciences.com/rss/actualites.xml') or $this->returnError('Could not request Futura Sciences.', 404); - $limit = 0; + $limit = 0; - foreach($html->find('item') as $element) { - if($limit < 20) { - $item = new \Item(); - $item->title = FS_StripCDATA($element->find('title', 0)->innertext); - $item->uri = FS_StripCDATA($element->find('guid', 0)->plaintext); - $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); - $item->content = FS_ExtractContent($item->uri); - $this->items[] = $item; - $limit++; - } - } - + foreach ($html->find('item') as $element) { + if ($limit < 20) { + $item = new \Item(); + $item->title = FS_StripCDATA($element->find('title', 0)->innertext); + $item->uri = FS_StripCDATA($element->find('guid', 0)->plaintext); + $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); + $item->content = FS_ExtractContent($item->uri); + $this->items[] = $item; + $limit++; + } + } } - public function getName(){ + public function getName() + { return 'Futura Sciences'; } - public function getURI(){ + public function getURI() + { return 'http://www.futura-sciences.com/'; } - public function getCacheDuration(){ + public function getCacheDuration() + { // return 3600; // 1 hour return 0; // 1 hour } diff --git a/bridges/FlickrExploreBridge.php b/bridges/FlickrExploreBridge.php index c3b4976d..e3b535cd 100644 --- a/bridges/FlickrExploreBridge.php +++ b/bridges/FlickrExploreBridge.php @@ -1,17 +1,18 @@ returnError('Could not request Flickr.', 404); - - foreach($html->find('span.photo_container') as $element) { + + foreach ($html->find('span.photo_container') as $element) { $item = new \Item(); $item->uri = 'http://flickr.com'.$element->find('a',0)->href; $item->thumbnailUri = $element->find('img',0)->getAttribute('data-defer-src'); @@ -21,15 +22,18 @@ class FlickrExploreBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return 'Flickr Explore'; } - public function getURI(){ + public function getURI() + { return 'http://www.flickr.com/explore'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } -} \ No newline at end of file +} diff --git a/bridges/GoogleSearchBridge.php b/bridges/GoogleSearchBridge.php index 7f8f3153..ce100844 100644 --- a/bridges/GoogleSearchBridge.php +++ b/bridges/GoogleSearchBridge.php @@ -13,26 +13,26 @@ * @description Returns most recent results from Google search. * @use1(q="keyword") */ -class GoogleSearchBridge extends BridgeAbstract{ - +class GoogleSearchBridge extends BridgeAbstract +{ private $request; - - public function collectData(array $param){ + + public function collectData(array $param) + { $html = ''; if (isset($param['q'])) { /* keyword search mode */ $this->request = $param['q']; $html = file_get_html('http://www.google.com/search?q=' . urlencode($this->request) . '&num=100&complete=0&tbs=qdr:y,sbd:1') or $this->returnError('No results for this query.', 404); - } - else{ + } else { $this->returnError('You must specify a keyword (?q=...).', 400); } $emIsRes = $html->find('div[id=ires]',0); - if( !is_null($emIsRes) ){ - foreach($emIsRes->find('li[class=g]') as $element) { + if ( !is_null($emIsRes) ) { + foreach ($emIsRes->find('li[class=g]') as $element) { $item = new Item(); - + // Extract direct URL from google href (eg. /url?q=...) $t = $element->find('a[href]',0)->href; $item->uri = 'http://google.com'.$t; @@ -45,15 +45,18 @@ class GoogleSearchBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return (!empty($this->request) ? $this->request .' - ' : '') .'Google search'; } - public function getURI(){ + public function getURI() + { return 'http://google.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 1800; // 30 minutes } -} \ No newline at end of file +} diff --git a/bridges/GuruMedBridge.php b/bridges/GuruMedBridge.php index d312c241..b7f2268e 100644 --- a/bridges/GuruMedBridge.php +++ b/bridges/GuruMedBridge.php @@ -1,55 +1,58 @@ ', '', $string); + return $string; + } + public function GurumedExtractContent($url) + { + $html2 = file_get_html($url); + $text = $html2->find('div.entry', 0)->innertext; - - - public function collectData(array $param){ - - function GurumedStripCDATA($string) { - $string = str_replace('', '', $string); - return $string; - } - function GurumedExtractContent($url) { - $html2 = file_get_html($url); - $text = $html2->find('div.entry', 0)->innertext; - return $text; - } + return $text; + } $html = file_get_html('http://gurumed.org/feed') or $this->returnError('Could not request Gurumed.', 404); - $limit = 0; + $limit = 0; - foreach($html->find('item') as $element) { - if($limit < 10) { - $item = new \Item(); - $item->title = GurumedStripCDATA($element->find('title', 0)->innertext); - $item->uri = GurumedStripCDATA($element->find('guid', 0)->plaintext); - $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); - $item->content = GurumedExtractContent($item->uri); - $this->items[] = $item; - $limit++; - } - } - + foreach ($html->find('item') as $element) { + if ($limit < 10) { + $item = new \Item(); + $item->title = GurumedStripCDATA($element->find('title', 0)->innertext); + $item->uri = GurumedStripCDATA($element->find('guid', 0)->plaintext); + $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); + $item->content = GurumedExtractContent($item->uri); + $this->items[] = $item; + $limit++; + } + } } - public function getName(){ + public function getName() + { return 'Gurumed'; } - public function getURI(){ + public function getURI() + { return 'http://gurumed.org/'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 3600; // 1 hour } } diff --git a/bridges/IdenticaBridge.php b/bridges/IdenticaBridge.php index 8d4ede50..4223495d 100644 --- a/bridges/IdenticaBridge.php +++ b/bridges/IdenticaBridge.php @@ -1,26 +1,26 @@ request = $param['u']; + $this->request = $param['u']; $html = file_get_html('https://identi.ca/'.urlencode($this->request)) or $this->returnError('Requested username can\'t be found.', 404); - } - else { + } else { $this->returnError('You must specify an Identica username (?u=...).', 400); } - foreach($html->find('li.major') as $dent) { + foreach ($html->find('li.major') as $dent) { $item = new \Item(); $item->uri = html_entity_decode($dent->find('a', 0)->href); // get dent link $item->timestamp = strtotime($dent->find('abbr.easydate', 0)->plaintext); // extract dent timestamp @@ -30,15 +30,18 @@ class IdenticaBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return (!empty($this->request) ? $this->request .' - ' : '') .'Identica Bridge'; } - public function getURI(){ + public function getURI() + { return 'https://identica.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 300; // 5 minutes } } diff --git a/bridges/InstagramBridge.php b/bridges/InstagramBridge.php index 8a5575eb..8bf3d9a8 100644 --- a/bridges/InstagramBridge.php +++ b/bridges/InstagramBridge.php @@ -7,74 +7,70 @@ * @description Returns the newest images * @use1(u="username") */ -class InstagramBridge extends BridgeAbstract{ - +class InstagramBridge extends BridgeAbstract +{ private $request; - - public function collectData(array $param){ + + public function collectData(array $param) + { $html = ''; if (isset($param['u'])) { /* user timeline mode */ $this->request = $param['u']; $html = file_get_html('http://instagram.com/'.urlencode($this->request)) or $this->returnError('Could not request Instagram.', 404); - } - else { + } else { $this->returnError('You must specify a Instagram username (?u=...).', 400); } - + $innertext = null; - - foreach($html->find('script') as $script) - { - if ('' === $script->innertext) { - continue; - } - - $pos = strpos(trim($script->innertext), 'window._sharedData'); - if (0 !== $pos) - { - continue; - } - - $innertext = $script->innertext; - break; + + foreach ($html->find('script') as $script) { + if ('' === $script->innertext) { + continue; + } + + $pos = strpos(trim($script->innertext), 'window._sharedData'); + if (0 !== $pos) { + continue; + } + + $innertext = $script->innertext; + break; } - - - + $json = trim(substr($innertext, $pos+18), ' =;'); $data = json_decode($json); - + $userMedia = $data->entry_data->UserProfile[0]->userMedia; + foreach ($userMedia as $media) { + $image = $media->images->standard_resolution; - foreach($userMedia as $media) - { - $image = $media->images->standard_resolution; + $item = new \Item(); + $item->uri = $media->link; + $item->content = ''; + if (isset($media->caption)) { + $item->title = $media->caption->text; + } else { + $item->title = basename($image->url); + } + $item->timestamp = $media->created_time; + $this->items[] = $item; - $item = new \Item(); - $item->uri = $media->link; - $item->content = ''; - if (isset($media->caption)) - { - $item->title = $media->caption->text; - } else { - $item->title = basename($image->url); - } - $item->timestamp = $media->created_time; - $this->items[] = $item; - } } - public function getName(){ + public function getName() + { return (!empty($this->request) ? $this->request .' - ' : '') .'Instagram Bridge'; } - public function getURI(){ + public function getURI() + { return 'http://instagram.com/'; } - public function getCacheDuration(){ - return 3600; + public function getCacheDuration() + { + return 3600; } } diff --git a/bridges/OpenClassroomsBridge.php b/bridges/OpenClassroomsBridge.php index d2d3c4ae..5b86ac50 100644 --- a/bridges/OpenClassroomsBridge.php +++ b/bridges/OpenClassroomsBridge.php @@ -8,32 +8,36 @@ * @description Returns latest tutorials from OpenClassrooms. * @use1(u="informatique or sciences") */ -class OpenClassroomsBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class OpenClassroomsBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $link = 'http://fr.openclassrooms.com/'.$param[u].'/cours?title=&sort=updatedAt+desc'; $html = file_get_html($link) or $this->returnError('Could not request OpenClassrooms.', 404); - foreach($html->find('li.col6') as $element) { - $item = new \Item(); - $item->uri = 'http://fr.openclassrooms.com'.$element->find('a', 0)->href; - $item->title = $element->find('div.courses-content strong', 0)->innertext; - $item->content = $element->find('span.course-tags', 0)->innertext; - $this->items[] = $item; + foreach ($html->find('li.col6') as $element) { + $item = new \Item(); + $item->uri = 'http://fr.openclassrooms.com'.$element->find('a', 0)->href; + $item->title = $element->find('div.courses-content strong', 0)->innertext; + $item->content = $element->find('span.course-tags', 0)->innertext; + $this->items[] = $item; } } - public function getName(){ + public function getName() + { return 'OpenClassrooms'; } - public function getURI(){ + public function getURI() + { return 'http://fr.openclassrooms.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/bridges/PinterestBridge.php b/bridges/PinterestBridge.php index 8c24ecde..7b1e38fa 100644 --- a/bridges/PinterestBridge.php +++ b/bridges/PinterestBridge.php @@ -8,81 +8,76 @@ * @use1(u="username",b="board") * @use2(q="keyword") */ -class PinterestBridge extends BridgeAbstract{ - +class PinterestBridge extends BridgeAbstract +{ private $username; private $board; private $query; - - public function collectData(array $param){ + + public function collectData(array $param) + { $html = ''; if (isset($param['u']) && isset($param['b'])) { $this->username = $param['u']; $this->board = $param['b']; $html = file_get_html($this->getURI().'/'.urlencode($this->username).'/'.urlencode($this->board)) or $this->returnError('Could not request Pinterest.', 404); - } else if (isset($param['q'])) - { - $this->query = $param['q']; - $html = file_get_html($this->getURI().'/search/?q='.urlencode($this->query)) or $this->returnError('Could not request Pinterest.', 404); - } - - else { + } elseif (isset($param['q'])) { + $this->query = $param['q']; + $html = file_get_html($this->getURI().'/search/?q='.urlencode($this->query)) or $this->returnError('Could not request Pinterest.', 404); + } else { $this->returnError('You must specify a Pinterest username and a board name (?u=...&b=...).', 400); } - - - foreach($html->find('div.pinWrapper') as $div) - { - $a = $div->find('a.pinImageWrapper',0); - - $img = $a->find('img', 0); - - $item = new \Item(); - $item->uri = $this->getURI().$a->getAttribute('href'); - $item->content = ''; - - - if (isset($this->query)) - { - $avatar = $div->find('img.creditImg', 0); - $username = $div->find('span.creditName', 0); - $board = $div->find('span.creditTitle', 0); - - $item->username =$username->innertext; - $item->fullname = $board->innertext; - $item->avatar = $avatar->getAttribute('src'); - - $item->content .= '
'.$item->username.''; - $item->content .= '
'.$item->fullname; - } else { - - $credit = $div->find('a.creditItem',0); - $item->content .= '
'.$credit->innertext; - } - - $item->title = basename($img->getAttribute('alt')); - - //$item->timestamp = $media->created_time; - $this->items[] = $item; - + + foreach ($html->find('div.pinWrapper') as $div) { + $a = $div->find('a.pinImageWrapper',0); + + $img = $a->find('img', 0); + + $item = new \Item(); + $item->uri = $this->getURI().$a->getAttribute('href'); + $item->content = ''; + + if (isset($this->query)) { + $avatar = $div->find('img.creditImg', 0); + $username = $div->find('span.creditName', 0); + $board = $div->find('span.creditTitle', 0); + + $item->username =$username->innertext; + $item->fullname = $board->innertext; + $item->avatar = $avatar->getAttribute('src'); + + $item->content .= '
'.$item->username.''; + $item->content .= '
'.$item->fullname; + } else { + + $credit = $div->find('a.creditItem',0); + $item->content .= '
'.$credit->innertext; + } + + $item->title = basename($img->getAttribute('alt')); + + //$item->timestamp = $media->created_time; + $this->items[] = $item; + } } - public function getName(){ - - if (isset($this->query)) - { - return $this->query .' - Pinterest'; - } else { - return $this->username .' - '. $this->board.' - Pinterest'; - } + public function getName() + { + if (isset($this->query)) { + return $this->query .' - Pinterest'; + } else { + return $this->username .' - '. $this->board.' - Pinterest'; + } } - public function getURI(){ + public function getURI() + { return 'http://www.pinterest.com'; } - public function getCacheDuration(){ - return 0; + public function getCacheDuration() + { + return 0; } } diff --git a/bridges/ScmbBridge.php b/bridges/ScmbBridge.php index e58088d4..0ec26f41 100644 --- a/bridges/ScmbBridge.php +++ b/bridges/ScmbBridge.php @@ -1,49 +1,51 @@ returnError('Could not request Se Coucher Moins Bete.', 404); - - foreach($html->find('article') as $article) { - $item = new \Item(); - $item->uri = 'http://secouchermoinsbete.fr'.$article->find('p.summary a',0)->href; - $item->title = $article->find('header h1 a',0)->innertext; - - $article->find('span.read-more',0)->outertext=''; // remove text "En savoir plus" from anecdote content - $content = $article->find('p.summary a',0)->innertext; - $content =substr($content,0,strlen($content)-17); // remove superfluous spaces at the end - - // get publication date - $str_date = $article->find('time',0)->datetime; - list($date, $time) = explode(' ', $str_date); - list($y, $m, $d) = explode('-', $date); - list($h, $i) = explode(':', $time); - $timestamp = mktime($h,$i,0,$m,$d,$y); - $item->timestamp = $timestamp; - - - $item->content = $content; - $this->items[] = $item; - } + foreach ($html->find('article') as $article) { + $item = new \Item(); + $item->uri = 'http://secouchermoinsbete.fr'.$article->find('p.summary a',0)->href; + $item->title = $article->find('header h1 a',0)->innertext; + + $article->find('span.read-more',0)->outertext=''; // remove text "En savoir plus" from anecdote content + $content = $article->find('p.summary a',0)->innertext; + $content =substr($content,0,strlen($content)-17); // remove superfluous spaces at the end + + // get publication date + $str_date = $article->find('time',0)->datetime; + list($date, $time) = explode(' ', $str_date); + list($y, $m, $d) = explode('-', $date); + list($h, $i) = explode(':', $time); + $timestamp = mktime($h,$i,0,$m,$d,$y); + $item->timestamp = $timestamp; + + $item->content = $content; + $this->items[] = $item; + } } - public function getName(){ + public function getName() + { return 'Se Coucher Moins Bête Bridge'; } - public function getURI(){ + public function getURI() + { return 'http://secouchermoinsbete.fr/'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/bridges/TwitterBridge.php b/bridges/TwitterBridge.php index fcc3967b..28f38652 100644 --- a/bridges/TwitterBridge.php +++ b/bridges/TwitterBridge.php @@ -1,6 +1,6 @@ request = $param['q']; $html = file_get_html('http://twitter.com/search/realtime?q='.urlencode($this->request).'+include:retweets&src=typd') or $this->returnError('No results for this query.', 404); - } - elseif (isset($param['u'])) { /* user timeline mode */ + } elseif (isset($param['u'])) { /* user timeline mode */ $this->request = $param['u']; $html = file_get_html('http://twitter.com/'.urlencode($this->request)) or $this->returnError('Requested username can\'t be found.', 404); - } - else { + } else { $this->returnError('You must specify a keyword (?q=...) or a Twitter username (?u=...).', 400); } - foreach($html->find('div.tweet') as $tweet) { + foreach ($html->find('div.tweet') as $tweet) { $item = new \Item(); $item->username = trim(substr($tweet->find('span.username', 0)->plaintext, 1)); // extract username and sanitize $item->fullname = $tweet->getAttribute('data-name'); // extract fullname (pseudonym) @@ -40,15 +39,18 @@ class TwitterBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return (!empty($this->request) ? $this->request .' - ' : '') .'Twitter Bridge'; } - public function getURI(){ + public function getURI() + { return 'http://twitter.com'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 300; // 5 minutes } } diff --git a/bridges/WikipediaENBridge.php b/bridges/WikipediaENBridge.php index ecd2ccf5..a8294767 100755 --- a/bridges/WikipediaENBridge.php +++ b/bridges/WikipediaENBridge.php @@ -6,9 +6,10 @@ * @name Wikipedia EN "Today's Featured Article..." * @description Returns the highlighted en.wikipedia.org article. */ -class WikipediaENBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class WikipediaENBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $host = 'http://en.wikipedia.org'; // If you want HTTPS access instead, uncomment the following line: @@ -17,25 +18,28 @@ class WikipediaENBridge extends BridgeAbstract{ $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia EN.', 404); - $element = $html->find('div[id=mp-tfa]', 0); - // Clean the bottom of the featured article - $element->find('div', -1)->outertext = ''; - $item = new \Item(); - $item->uri = $host.$element->find('p', 0)->find('a', 0)->href; - $item->title = $element->find('p',0)->find('a',0)->title; - $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); - $this->items[] = $item; + $element = $html->find('div[id=mp-tfa]', 0); + // Clean the bottom of the featured article + $element->find('div', -1)->outertext = ''; + $item = new \Item(); + $item->uri = $host.$element->find('p', 0)->find('a', 0)->href; + $item->title = $element->find('p',0)->find('a',0)->title; + $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); + $this->items[] = $item; } - public function getName(){ + public function getName() + { return 'Wikipedia EN "Today\'s Featued Article"'; } - public function getURI(){ + public function getURI() + { return 'https://en.wikipedia.org/wiki/Main_Page'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 3600*4; // 4 hours } } diff --git a/bridges/WikipediaEOBridge.php b/bridges/WikipediaEOBridge.php index 19f8cee0..b34ba691 100644 --- a/bridges/WikipediaEOBridge.php +++ b/bridges/WikipediaEOBridge.php @@ -6,9 +6,10 @@ * @name Wikipedia EO "Artikolo de la semajno" * @description Returns the highlighted eo.wikipedia.org article. */ -class WikipediaEOBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class WikipediaEOBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $host = 'http://eo.wikipedia.org'; // If you want HTTPS access instead, uncomment the following line: @@ -17,25 +18,28 @@ class WikipediaEOBridge extends BridgeAbstract{ $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia EO.', 404); - $element = $html->find('div[id=mf-tfa]', 0); - // Link to article - $link = $element->find('p', -2)->find('a', 0); - $item = new \Item(); - $item->uri = $host.$link->href; - $item->title = $link->title; - $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); - $this->items[] = $item; + $element = $html->find('div[id=mf-tfa]', 0); + // Link to article + $link = $element->find('p', -2)->find('a', 0); + $item = new \Item(); + $item->uri = $host.$link->href; + $item->title = $link->title; + $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); + $this->items[] = $item; } - public function getName(){ + public function getName() + { return 'Wikipedia EO "Artikolo de la semajno"'; } - public function getURI(){ + public function getURI() + { return 'https://eo.wikipedia.org/wiki/Vikipedio:%C4%88efpa%C4%9Do'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 3600*12; // 12 hours } } diff --git a/bridges/WikipediaFRBridge.php b/bridges/WikipediaFRBridge.php index 20376da9..89875ae0 100755 --- a/bridges/WikipediaFRBridge.php +++ b/bridges/WikipediaFRBridge.php @@ -6,9 +6,10 @@ * @name Wikipedia FR "Lumière sur..." * @description Returns the highlighted fr.wikipedia.org article. */ -class WikipediaFRBridge extends BridgeAbstract{ - - public function collectData(array $param){ +class WikipediaFRBridge extends BridgeAbstract +{ + public function collectData(array $param) + { $html = ''; $host = 'http://fr.wikipedia.org'; // If you want HTTPS access instead, uncomment the following line: @@ -17,23 +18,26 @@ class WikipediaFRBridge extends BridgeAbstract{ $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia FR.', 404); - $element = $html->find('div[id=accueil-lumieresur]', 0); - $item = new \Item(); - $item->uri = $host.$element->find('p', 0)->find('a', 0)->href; - $item->title = $element->find('p',0)->find('a',0)->title; - $item->content = str_replace('href="/', 'href="'.$host.'/', $element->find('div[id=mf-lumieresur]', 0)->innertext); - $this->items[] = $item; + $element = $html->find('div[id=accueil-lumieresur]', 0); + $item = new \Item(); + $item->uri = $host.$element->find('p', 0)->find('a', 0)->href; + $item->title = $element->find('p',0)->find('a',0)->title; + $item->content = str_replace('href="/', 'href="'.$host.'/', $element->find('div[id=mf-lumieresur]', 0)->innertext); + $this->items[] = $item; } - public function getName(){ + public function getName() + { return 'Wikipedia FR "Lumière sur..."'; } - public function getURI(){ + public function getURI() + { return 'https://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Accueil_principal'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 3600*4; // 4 hours } } diff --git a/bridges/YoutubeBridge.php b/bridges/YoutubeBridge.php index 8d739251..01c6915b 100644 --- a/bridges/YoutubeBridge.php +++ b/bridges/YoutubeBridge.php @@ -1,28 +1,27 @@ request = $param['u']; $html = file_get_html('https://www.youtube.com/user/'.urlencode($this->request).'/videos') or $this->returnError('Could not request Youtube.', 404); - } - else { + } else { $this->returnError('You must specify a Youtbe username (?u=...).', 400); } - - - foreach($html->find('li.channels-content-item') as $element) { + + foreach ($html->find('li.channels-content-item') as $element) { $item = new \Item(); $item->uri = 'https://www.youtube.com'.$element->find('a',0)->href; $item->thumbnailUri = 'https:'.$element->find('img',0)->src; @@ -32,15 +31,18 @@ class YoutubeBridge extends BridgeAbstract{ } } - public function getName(){ + public function getName() + { return (!empty($this->request) ? $this->request .' - ' : '') .'Youtube Bridge'; } - public function getURI(){ + public function getURI() + { return 'https://www.youtube.com/'; } - public function getCacheDuration(){ + public function getCacheDuration() + { return 21600; // 6 hours } } diff --git a/caches/FileCache.php b/caches/FileCache.php index 594343d3..0905ddd5 100644 --- a/caches/FileCache.php +++ b/caches/FileCache.php @@ -2,17 +2,19 @@ /** * Cache with file system */ -class FileCache extends CacheAbstract{ +class FileCache extends CacheAbstract +{ protected $cacheDirCreated; // boolean to avoid always chck dir cache existance - public function loadData(){ + public function loadData() + { $this->isPrepareCache(); $datas = json_decode(file_get_contents($this->getCacheFile()),true); $items = array(); - foreach($datas as $aData){ + foreach ($datas as $aData) { $item = new \Item(); - foreach($aData as $name => $value){ + foreach ($aData as $name => $value) { $item->$name = $value; } $items[] = $item; @@ -21,7 +23,8 @@ class FileCache extends CacheAbstract{ return $items; } - public function saveData($datas){ + public function saveData($datas) + { $this->isPrepareCache(); file_put_contents($this->getCacheFile(), json_encode($datas)); @@ -29,11 +32,12 @@ class FileCache extends CacheAbstract{ return $this; } - public function getTime(){ + public function getTime() + { $this->isPrepareCache(); $cacheFile = $this->getCacheFile(); - if( file_exists($cacheFile) ){ + if ( file_exists($cacheFile) ) { return filemtime($cacheFile); } @@ -45,8 +49,9 @@ class FileCache extends CacheAbstract{ * Note : Cache name is based on request information, then cache must be prepare before use * @return \Exception|true */ - protected function isPrepareCache(){ - if( is_null($this->param) ){ + protected function isPrepareCache() + { + if ( is_null($this->param) ) { throw new \Exception('Please feed "prepare" method before try to load'); } @@ -57,11 +62,12 @@ class FileCache extends CacheAbstract{ * Return cache path (and create if not exist) * @return string Cache path */ - protected function getCachePath(){ + protected function getCachePath() + { $cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ? // FIXME : implement recursive dir creation - if( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ){ + if ( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ) { $this->cacheDirCreated = true; mkdir($cacheDir,0705); @@ -75,7 +81,8 @@ class FileCache extends CacheAbstract{ * Get the file name use for cache store * @return string Path to the file cache */ - protected function getCacheFile(){ + protected function getCacheFile() + { return $this->getCachePath() . $this->getCacheName(); } @@ -83,10 +90,12 @@ class FileCache extends CacheAbstract{ * Determines file name for store the cache * return string */ - protected function getCacheName(){ + protected function getCacheName() + { $this->isPrepareCache(); $stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param); + return hash('sha1', $stringToEncode) . '.cache'; } -} \ No newline at end of file +} diff --git a/formats/AtomFormat.php b/formats/AtomFormat.php index cdd0a9ad..768fad9c 100644 --- a/formats/AtomFormat.php +++ b/formats/AtomFormat.php @@ -5,9 +5,10 @@ * * @name Atom */ -class AtomFormat extends FormatAbstract{ - - public function stringify(){ +class AtomFormat extends FormatAbstract +{ + public function stringify() + { /* Datas preparation */ $https = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '' ); $httpHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; @@ -20,7 +21,7 @@ class AtomFormat extends FormatAbstract{ $uri = htmlspecialchars($extraInfos['uri']); $entries = ''; - foreach($this->getDatas() as $data){ + foreach ($this->getDatas() as $data) { $entryName = is_null($data->name) ? $title : $data->name; $entryAuthor = is_null($data->author) ? $uri : $data->author; $entryTitle = is_null($data->title) ? '' : $data->title; @@ -66,23 +67,25 @@ EOD; {$entries} EOD; - + // Remove invalid non-UTF8 characters // We cannot use iconv because of a bug in some versions of iconv. // See http://www.php.net/manual/fr/function.iconv.php#108643 - //$toReturn = iconv("UTF-8", "UTF-8//IGNORE", $toReturn); + //$toReturn = iconv("UTF-8", "UTF-8//IGNORE", $toReturn); // So we use mb_convert_encoding instead: ini_set('mbstring.substitute_character', 'none'); - $toReturn= mb_convert_encoding($toReturn, 'UTF-8', 'UTF-8'); + $toReturn= mb_convert_encoding($toReturn, 'UTF-8', 'UTF-8'); + return $toReturn; } - public function display(){ + public function display() + { $this ->setContentType('application/atom+xml; charset=utf8') // We force UTF-8 in ATOM output. ->callContentType(); return parent::display(); } -} \ No newline at end of file +} diff --git a/formats/HtmlFormat.php b/formats/HtmlFormat.php index c52cf963..60dd9a28 100644 --- a/formats/HtmlFormat.php +++ b/formats/HtmlFormat.php @@ -5,16 +5,17 @@ * * @name Html */ -class HtmlFormat extends FormatAbstract{ - - public function stringify(){ +class HtmlFormat extends FormatAbstract +{ + public function stringify() + { /* Datas preparation */ $extraInfos = $this->getExtraInfos(); $title = htmlspecialchars($extraInfos['name']); $uri = htmlspecialchars($extraInfos['uri']); $entries = ''; - foreach($this->getDatas() as $data){ + foreach ($this->getDatas() as $data) { $entryUri = is_null($data->uri) ? $uri : $data->uri; $entryTitle = is_null($data->title) ? '' : $this->sanitizeHtml(strip_tags($data->title)); $entryTimestamp = is_null($data->timestamp) ? '' : '' . date(DATE_ATOM, $data->timestamp) . ''; @@ -51,11 +52,12 @@ EOD; return $toReturn; } - public function display() { + public function display() + { $this ->setContentType('text/html; charset=' . $this->getCharset()) ->callContentType(); return parent::display(); } -} \ No newline at end of file +} diff --git a/formats/JsonFormat.php b/formats/JsonFormat.php index 400f91f7..79b04a82 100644 --- a/formats/JsonFormat.php +++ b/formats/JsonFormat.php @@ -5,20 +5,22 @@ * * @name Json */ -class JsonFormat extends FormatAbstract{ - - public function stringify(){ +class JsonFormat extends FormatAbstract +{ + public function stringify() + { // FIXME : sometime content can be null, transform to empty string $datas = $this->getDatas(); return json_encode($datas); } - public function display(){ + public function display() + { $this ->setContentType('application/json') ->callContentType(); return parent::display(); } -} \ No newline at end of file +} diff --git a/formats/PlaintextFormat.php b/formats/PlaintextFormat.php index 32b4e020..4f356500 100644 --- a/formats/PlaintextFormat.php +++ b/formats/PlaintextFormat.php @@ -5,18 +5,21 @@ * * @name Plaintext */ -class PlaintextFormat extends FormatAbstract{ - - public function stringify(){ +class PlaintextFormat extends FormatAbstract +{ + public function stringify() + { $datas = $this->getDatas(); + return print_r($datas, true); } - public function display(){ + public function display() + { $this ->setContentType('text/plain;charset=' . $this->getCharset()) ->callContentType(); return parent::display(); } -} \ No newline at end of file +} diff --git a/index.php b/index.php index a95fcbb4..f49daa9f 100644 --- a/index.php +++ b/index.php @@ -15,17 +15,17 @@ date_default_timezone_set('UTC'); error_reporting(0); //ini_set('display_errors','1'); error_reporting(E_ALL); // For debugging only. -try{ +try { require_once __DIR__ . '/lib/RssBridge.php'; Bridge::setDir(__DIR__ . '/bridges/'); Format::setDir(__DIR__ . '/formats/'); Cache::setDir(__DIR__ . '/caches/'); - if( isset($_REQUEST) && isset($_REQUEST['action']) ){ - switch($_REQUEST['action']){ + if ( isset($_REQUEST) && isset($_REQUEST['action']) ) { + switch ($_REQUEST['action']) { case 'display': - if( isset($_REQUEST['bridge']) ){ + if ( isset($_REQUEST['bridge']) ) { unset($_REQUEST['action']); $bridge = $_REQUEST['bridge']; unset($_REQUEST['bridge']); @@ -57,17 +57,16 @@ try{ break; } } -} -catch(HttpException $e){ +} catch (HttpException $e) { header('HTTP/1.1 ' . $e->getCode() . ' ' . Http::getMessageForCode($e->getCode())); header('Content-Type: text/plain'); die($e->getMessage()); -} -catch(\Exception $e){ +} catch (\Exception $e) { die($e->getMessage()); } -function getHelperButtonFormat($value, $name){ +function getHelperButtonFormat($value, $name) +{ return ''; } @@ -98,7 +97,7 @@ $formats = Format::searchInformation();

-

+

0 ): ?>
    @@ -114,7 +113,7 @@ $formats = Format::searchInformation(); $infos ): ?> - + @@ -125,7 +124,7 @@ $formats = Format::searchInformation(); $infos ): ?> - + @@ -133,6 +132,6 @@ $formats = Format::searchInformation(); + - \ No newline at end of file + diff --git a/lib/Bridge.php b/lib/Bridge.php index 7b6c4751..25358ad1 100644 --- a/lib/Bridge.php +++ b/lib/Bridge.php @@ -4,21 +4,24 @@ * Note : adapter are store in other place */ -interface BridgeInterface{ +interface BridgeInterface +{ public function collectData(array $param); public function getName(); public function getURI(); public function getCacheDuration(); } -abstract class BridgeAbstract implements BridgeInterface{ +abstract class BridgeAbstract implements BridgeInterface +{ protected $cache; protected $items = array(); /** * Launch probative exception */ - protected function returnError($message, $code){ + protected function returnError($message, $code) + { throw new \HttpException($message, $code); } @@ -26,7 +29,8 @@ abstract class BridgeAbstract implements BridgeInterface{ * Return datas store in the bridge * @return mixed */ - public function getDatas(){ + public function getDatas() + { return $this->items; } @@ -35,22 +39,21 @@ abstract class BridgeAbstract implements BridgeInterface{ * Note : you can defined a cache before with "setCache" * @param array $param $_REQUEST, $_GET, $_POST, or array with bridge expected paramters */ - public function setDatas(array $param){ - if( !is_null($this->cache) ){ + public function setDatas(array $param) + { + if ( !is_null($this->cache) ) { $this->cache->prepare($param); $time = $this->cache->getTime(); - } - else{ + } else { $time = false; // No cache ? No time ! } - if( $time !== false && ( time() - $this->getCacheDuration() < $time ) ){ // Cache file has not expired. Serve it. + if ( $time !== false && ( time() - $this->getCacheDuration() < $time ) ) { // Cache file has not expired. Serve it. $this->items = $this->cache->loadData(); - } - else{ + } else { $this->collectData($param); - if( !is_null($this->cache) ){ // Cache defined ? We go to refresh is memory :D + if ( !is_null($this->cache) ) { // Cache defined ? We go to refresh is memory :D $this->cache->saveData($this->getDatas()); } } @@ -59,25 +62,28 @@ abstract class BridgeAbstract implements BridgeInterface{ /** * Define default duraction for cache */ - public function getCacheDuration(){ + public function getCacheDuration() + { return 3600; } /** * Defined cache object to use */ - public function setCache(\CacheAbstract $cache){ + public function setCache(\CacheAbstract $cache) + { $this->cache = $cache; return $this; } } -class Bridge{ +class Bridge +{ + protected static $dirBridge; - static protected $dirBridge; - - public function __construct(){ + public function __construct() + { throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.'); } @@ -86,14 +92,15 @@ class Bridge{ * @param string $nameBridge Defined bridge name you want use * @return Bridge object dedicated */ - static public function create($nameBridge){ - if( !static::isValidNameBridge($nameBridge) ){ + public static function create($nameBridge) + { + if ( !static::isValidNameBridge($nameBridge) ) { throw new \InvalidArgumentException('Name bridge must be at least one uppercase follow or not by alphanumeric or dash characters.'); } $pathBridge = self::getDir() . $nameBridge . '.php'; - if( !file_exists($pathBridge) ){ + if ( !file_exists($pathBridge) ) { throw new \Exception('The bridge you looking for does not exist.'); } @@ -102,29 +109,32 @@ class Bridge{ return new $nameBridge(); } - static public function setDir($dirBridge){ - if( !is_string($dirBridge) ){ + public static function setDir($dirBridge) + { + if ( !is_string($dirBridge) ) { throw new \InvalidArgumentException('Dir bridge must be a string.'); } - if( !file_exists($dirBridge) ){ + if ( !file_exists($dirBridge) ) { throw new \Exception('Dir bridge does not exist.'); } self::$dirBridge = $dirBridge; } - static public function getDir(){ + public static function getDir() + { $dirBridge = self::$dirBridge; - if( is_null($dirBridge) ){ + if ( is_null($dirBridge) ) { throw new \LogicException(__CLASS__ . ' class need to know bridge path !'); } return $dirBridge; } - static public function isValidNameBridge($nameBridge){ + public static function isValidNameBridge($nameBridge) + { return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge); } @@ -132,7 +142,8 @@ class Bridge{ * Read bridge dir and catch informations about each bridge depending annotation * @return array Informations about each bridge */ - static public function searchInformation(){ + public static function searchInformation() + { $pathDirBridge = self::getDir(); $listBridge = array(); @@ -140,33 +151,33 @@ class Bridge{ $searchCommonPattern = array('description', 'name'); $dirFiles = scandir($pathDirBridge); - if( $dirFiles !== false ){ - foreach( $dirFiles as $fileName ){ - if( preg_match('@([^.]+)\.php@U', $fileName, $out) ){ // Is PHP file ? + if ($dirFiles !== false) { + foreach ($dirFiles as $fileName) { + if ( preg_match('@([^.]+)\.php@U', $fileName, $out) ) { // Is PHP file ? $infos = array(); // Information about the bridge $resParse = token_get_all(file_get_contents($pathDirBridge . $fileName)); // Parse PHP file - foreach($resParse as $v){ - if( is_array($v) && $v[0] == T_DOC_COMMENT ){ // Lexer node is COMMENT ? + foreach ($resParse as $v) { + if ( is_array($v) && $v[0] == T_DOC_COMMENT ) { // Lexer node is COMMENT ? $commentary = $v[1]; - foreach( $searchCommonPattern as $name){ // Catch information with common pattern + foreach ($searchCommonPattern as $name) { // Catch information with common pattern preg_match('#@' . preg_quote($name, '#') . '\s+(.+)#', $commentary, $outComment); - if( isset($outComment[1]) ){ + if ( isset($outComment[1]) ) { $infos[$name] = $outComment[1]; } } preg_match_all('#@use(?[1-9][0-9]*)\s?\((?.+)\)(?:\r|\n)#', $commentary, $outComment); // Catch specific information about "use". - if( isset($outComment['args']) && is_array($outComment['args']) ){ + if ( isset($outComment['args']) && is_array($outComment['args']) ) { $infos['use'] = array(); - foreach($outComment['args'] as $num => $args){ // Each use + foreach ($outComment['args'] as $num => $args) { // Each use preg_match_all('#(?[a-z]+)="(?.*)"(?:,|$)#U', $args, $outArg); // Catch arguments for current use - if( isset($outArg['name']) ){ + if ( isset($outArg['name']) ) { $usePos = $outComment['num'][$num]; // Current use name - if( !isset($infos['use'][$usePos]) ){ // Not information actually for this "use" ? + if ( !isset($infos['use'][$usePos]) ) { // Not information actually for this "use" ? $infos['use'][$usePos] = array(); } - foreach($outArg['name'] as $numArg => $name){ // Each arguments + foreach ($outArg['name'] as $numArg => $name) { // Each arguments $infos['use'][$usePos][$name] = $outArg['value'][$numArg]; } } @@ -175,7 +186,7 @@ class Bridge{ } } - if( isset($infos['name']) ){ // If informations containt at least a name + if ( isset($infos['name']) ) { // If informations containt at least a name $listBridge[$out[1]] = $infos; } } @@ -184,4 +195,4 @@ class Bridge{ return $listBridge; } -} \ No newline at end of file +} diff --git a/lib/Cache.php b/lib/Cache.php index 9bf8ffa8..3f3dbb88 100644 --- a/lib/Cache.php +++ b/lib/Cache.php @@ -4,38 +4,43 @@ * Note : adapter are store in other place */ -interface CacheInterface{ +interface CacheInterface +{ public function loadData(); public function saveData($datas); public function getTime(); } -abstract class CacheAbstract implements CacheInterface{ +abstract class CacheAbstract implements CacheInterface +{ protected $param; - public function prepare(array $param){ + public function prepare(array $param) + { $this->param = $param; return $this; } } -class Cache{ +class Cache +{ + protected static $dirCache; - static protected $dirCache; - - public function __construct(){ + public function __construct() + { throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.'); } - static public function create($nameCache){ - if( !static::isValidNameCache($nameCache) ){ + public static function create($nameCache) + { + if ( !static::isValidNameCache($nameCache) ) { throw new \InvalidArgumentException('Name cache must be at least one uppercase follow or not by alphanumeric or dash characters.'); } $pathCache = self::getDir() . $nameCache . '.php'; - if( !file_exists($pathCache) ){ + if ( !file_exists($pathCache) ) { throw new \Exception('The cache you looking for does not exist.'); } @@ -44,29 +49,32 @@ class Cache{ return new $nameCache(); } - static public function setDir($dirCache){ - if( !is_string($dirCache) ){ + public static function setDir($dirCache) + { + if ( !is_string($dirCache) ) { throw new \InvalidArgumentException('Dir cache must be a string.'); } - if( !file_exists($dirCache) ){ + if ( !file_exists($dirCache) ) { throw new \Exception('Dir cache does not exist.'); } self::$dirCache = $dirCache; } - static public function getDir(){ + public static function getDir() + { $dirCache = self::$dirCache; - if( is_null($dirCache) ){ + if ( is_null($dirCache) ) { throw new \LogicException(__CLASS__ . ' class need to know cache path !'); } return $dirCache; } - static public function isValidNameCache($nameCache){ + public static function isValidNameCache($nameCache) + { return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameCache); } -} \ No newline at end of file +} diff --git a/lib/Exceptions.php b/lib/Exceptions.php index 202060f6..d49d1a32 100644 --- a/lib/Exceptions.php +++ b/lib/Exceptions.php @@ -4,15 +4,16 @@ class HttpException extends \Exception{} /** * Not real http implementation but only utils stuff */ -class Http{ - +class Http +{ /** * Return message corresponding to Http code */ - static public function getMessageForCode($code){ + public static function getMessageForCode($code) + { $codes = self::getCodes(); - if( isset($codes[$code]) ){ + if ( isset($codes[$code]) ) { return $codes[$code]; } @@ -22,7 +23,8 @@ class Http{ /** * List of common Http code */ - static public function getCodes(){ + public static function getCodes() + { return array( 200 => 'OK', 201 => 'Created', @@ -58,4 +60,4 @@ class Http{ 508 => 'Loop detected', ); } -} \ No newline at end of file +} diff --git a/lib/Format.php b/lib/Format.php index a2ede6d0..e588313c 100644 --- a/lib/Format.php +++ b/lib/Format.php @@ -4,58 +4,66 @@ * Note : adapter are store in other place */ -interface FormatInterface{ +interface FormatInterface +{ public function stringify(); public function display(); public function setDatas(array $bridge); } -abstract class FormatAbstract implements FormatInterface{ +abstract class FormatAbstract implements FormatInterface +{ const DEFAULT_CHARSET = 'UTF-8'; - protected - $contentType, + protected $contentType, $charset, $datas, $extraInfos ; - public function setCharset($charset){ + public function setCharset($charset) + { $this->charset = $charset; return $this; } - public function getCharset(){ + public function getCharset() + { $charset = $this->charset; return is_null($charset) ? self::DEFAULT_CHARSET : $charset; } - protected function setContentType($contentType){ + protected function setContentType($contentType) + { $this->contentType = $contentType; return $this; } - protected function callContentType(){ + protected function callContentType() + { header('Content-Type: ' . $this->contentType); } - public function display(){ + public function display() + { echo $this->stringify(); return $this; } - public function setDatas(array $datas){ + public function setDatas(array $datas) + { $this->datas = $datas; return $this; } - public function getDatas(){ - if( !is_array($this->datas) ){ + public function getDatas() + { + if ( !is_array($this->datas) ) { throw new \LogicException('Feed the ' . get_class($this) . ' with "setDatas" method before !'); } @@ -67,9 +75,10 @@ abstract class FormatAbstract implements FormatInterface{ * @param array $extraInfos array with know informations (there isn't merge !!!) * @return this */ - public function setExtraInfos(array $extraInfos = array()){ - foreach(array('name', 'uri') as $infoName){ - if( !isset($extraInfos[$infoName]) ){ + public function setExtraInfos(array $extraInfos = array()) + { + foreach (array('name', 'uri') as $infoName) { + if ( !isset($extraInfos[$infoName]) ) { $extraInfos[$infoName] = ''; } } @@ -83,14 +92,15 @@ abstract class FormatAbstract implements FormatInterface{ * Return extra infos * @return array See "setExtraInfos" detail method to know what extra are disponibles */ - public function getExtraInfos(){ - if( is_null($this->extraInfos) ){ // No extra info ? + public function getExtraInfos() + { + if ( is_null($this->extraInfos) ) { // No extra info ? $this->setExtraInfos(); // Define with default value } return $this->extraInfos; } - + /** * Sanitized html while leaving it functionnal. * The aim is to keep html as-is (with clickable hyperlinks) @@ -109,22 +119,24 @@ abstract class FormatAbstract implements FormatInterface{ } } -class Format{ +class Format +{ + protected static $dirFormat; - static protected $dirFormat; - - public function __construct(){ + public function __construct() + { throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.'); } - static public function create($nameFormat){ - if( !static::isValidNameFormat($nameFormat) ){ + public static function create($nameFormat) + { + if ( !static::isValidNameFormat($nameFormat) ) { throw new \InvalidArgumentException('Name format must be at least one uppercase follow or not by alphabetic characters.'); } $pathFormat = self::getDir() . $nameFormat . '.php'; - if( !file_exists($pathFormat) ){ + if ( !file_exists($pathFormat) ) { throw new \Exception('The format you looking for does not exist.'); } @@ -133,29 +145,32 @@ class Format{ return new $nameFormat(); } - static public function setDir($dirFormat){ - if( !is_string($dirFormat) ){ + public static function setDir($dirFormat) + { + if ( !is_string($dirFormat) ) { throw new \InvalidArgumentException('Dir format must be a string.'); } - if( !file_exists($dirFormat) ){ + if ( !file_exists($dirFormat) ) { throw new \Exception('Dir format does not exist.'); } self::$dirFormat = $dirFormat; } - static public function getDir(){ + public static function getDir() + { $dirFormat = self::$dirFormat; - if( is_null($dirFormat) ){ + if ( is_null($dirFormat) ) { throw new \LogicException(__CLASS__ . ' class need to know format path !'); } return $dirFormat; } - static public function isValidNameFormat($nameFormat){ + public static function isValidNameFormat($nameFormat) + { return preg_match('@^[A-Z][a-zA-Z]*$@', $nameFormat); } @@ -163,7 +178,8 @@ class Format{ * Read format dir and catch informations about each format depending annotation * @return array Informations about each format */ - static public function searchInformation(){ + public static function searchInformation() + { $pathDirFormat = self::getDir(); $listFormat = array(); @@ -171,24 +187,24 @@ class Format{ $searchCommonPattern = array('name'); $dirFiles = scandir($pathDirFormat); - if( $dirFiles !== false ){ - foreach( $dirFiles as $fileName ){ - if( preg_match('@([^.]+)\.php@U', $fileName, $out) ){ // Is PHP file ? + if ($dirFiles !== false) { + foreach ($dirFiles as $fileName) { + if ( preg_match('@([^.]+)\.php@U', $fileName, $out) ) { // Is PHP file ? $infos = array(); // Information about the bridge $resParse = token_get_all(file_get_contents($pathDirFormat . $fileName)); // Parse PHP file - foreach($resParse as $v){ - if( is_array($v) && $v[0] == T_DOC_COMMENT ){ // Lexer node is COMMENT ? + foreach ($resParse as $v) { + if ( is_array($v) && $v[0] == T_DOC_COMMENT ) { // Lexer node is COMMENT ? $commentary = $v[1]; - foreach( $searchCommonPattern as $name){ // Catch information with common pattern + foreach ($searchCommonPattern as $name) { // Catch information with common pattern preg_match('#@' . preg_quote($name, '#') . '\s+(.+)#', $commentary, $outComment); - if( isset($outComment[1]) ){ + if ( isset($outComment[1]) ) { $infos[$name] = $outComment[1]; } } } } - if( isset($infos['name']) ){ // If informations containt at least a name + if ( isset($infos['name']) ) { // If informations containt at least a name $listFormat[$out[1]] = $infos; } } @@ -197,4 +213,4 @@ class Format{ return $listFormat; } -} \ No newline at end of file +} diff --git a/lib/Item.php b/lib/Item.php index 806ecca8..6e16c931 100644 --- a/lib/Item.php +++ b/lib/Item.php @@ -5,12 +5,15 @@ interface ItemInterface{} * Object to store datas collect informations * FIXME : not sur this logic is the good, I think recast all is necessary */ -class Item implements ItemInterface{ - public function __set($name, $value){ +class Item implements ItemInterface +{ + public function __set($name, $value) + { $this->$name = $value; } - public function __get($name){ + public function __get($name) + { return isset($this->$name) ? $this->$name : null; } -} \ No newline at end of file +} diff --git a/lib/RssBridge.php b/lib/RssBridge.php index d2952806..f1113291 100644 --- a/lib/RssBridge.php +++ b/lib/RssBridge.php @@ -14,13 +14,13 @@ require __DIR__ . '/Bridge.php'; require __DIR__ . '/Cache.php'; $vendorLibSimpleHtmlDom = __DIR__ . PATH_VENDOR . '/simplehtmldom/simple_html_dom.php'; -if( !file_exists($vendorLibSimpleHtmlDom) ){ +if ( !file_exists($vendorLibSimpleHtmlDom) ) { throw new \HttpException('"PHP Simple HTML DOM Parser" library is missing. Get it from http://simplehtmldom.sourceforge.net and place the script "simple_html_dom.php" in '.substr(PATH_VENDOR,4) . '/simplehtmldom/', 500); } require_once $vendorLibSimpleHtmlDom; /* Example use - + require_once __DIR__ . '/lib/RssBridge.php'; // Data retrieval @@ -39,4 +39,4 @@ require_once $vendorLibSimpleHtmlDom; )) ->display(); -*/ \ No newline at end of file +*/ From 092831894347cc369249740e9fe4d4a29e409833 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Benoit=2ES=20=C2=AB=C2=A0Benpro=C2=A0=C2=BB?= Date: Thu, 6 Feb 2014 11:54:26 +0100 Subject: [PATCH 2/2] Fix bridges FSBridge & GuruMedBridge due to PSR-2: "Visibility MUST be declared on all methods." --- bridges/FSBridge.php | 36 +++++++++++++++++++----------------- bridges/GuruMedBridge.php | 36 +++++++++++++++++++----------------- 2 files changed, 38 insertions(+), 34 deletions(-) diff --git a/bridges/FSBridge.php b/bridges/FSBridge.php index 51c0e9b0..1e7b175a 100644 --- a/bridges/FSBridge.php +++ b/bridges/FSBridge.php @@ -8,33 +8,35 @@ */ class FSBridge extends BridgeAbstract { + public function FS_StripCDATA($string) + { + $string = str_replace('', '', $string); + + return $string; + } + + public function FS_ExtractContent($url) + { + $html2 = file_get_html($url); + $text = $html2->find('div.fiche-actualite', 0)->innertext; + + return $text; + } + public function collectData(array $param) { - public function FS_StripCDATA($string) - { - $string = str_replace('', '', $string); - return $string; - } - - public function FS_ExtractContent($url) - { - $html2 = file_get_html($url); - $text = $html2->find('div.fiche-actualite', 0)->innertext; - - return $text; - } $html = file_get_html('http://www.futura-sciences.com/rss/actualites.xml') or $this->returnError('Could not request Futura Sciences.', 404); $limit = 0; foreach ($html->find('item') as $element) { if ($limit < 20) { $item = new \Item(); - $item->title = FS_StripCDATA($element->find('title', 0)->innertext); - $item->uri = FS_StripCDATA($element->find('guid', 0)->plaintext); + $item->title = $this->FS_StripCDATA($element->find('title', 0)->innertext); + $item->uri = $this->FS_StripCDATA($element->find('guid', 0)->plaintext); $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); - $item->content = FS_ExtractContent($item->uri); + $item->content = $this->FS_ExtractContent($item->uri); $this->items[] = $item; $limit++; } diff --git a/bridges/GuruMedBridge.php b/bridges/GuruMedBridge.php index b7f2268e..fffaa95a 100644 --- a/bridges/GuruMedBridge.php +++ b/bridges/GuruMedBridge.php @@ -8,33 +8,35 @@ */ class GuruMedBridge extends BridgeAbstract { + public function GurumedStripCDATA($string) + { + $string = str_replace('', '', $string); + + return $string; + } + + public function GurumedExtractContent($url) + { + $html2 = file_get_html($url); + $text = $html2->find('div.entry', 0)->innertext; + + return $text; + } + public function collectData(array $param) { - public function GurumedStripCDATA($string) - { - $string = str_replace('', '', $string); - return $string; - } - - public function GurumedExtractContent($url) - { - $html2 = file_get_html($url); - $text = $html2->find('div.entry', 0)->innertext; - - return $text; - } $html = file_get_html('http://gurumed.org/feed') or $this->returnError('Could not request Gurumed.', 404); $limit = 0; foreach ($html->find('item') as $element) { if ($limit < 10) { $item = new \Item(); - $item->title = GurumedStripCDATA($element->find('title', 0)->innertext); - $item->uri = GurumedStripCDATA($element->find('guid', 0)->plaintext); + $item->title = $this->GurumedStripCDATA($element->find('title', 0)->innertext); + $item->uri = $this->GurumedStripCDATA($element->find('guid', 0)->plaintext); $item->timestamp = strtotime($element->find('pubDate', 0)->plaintext); - $item->content = GurumedExtractContent($item->uri); + $item->content = $this->GurumedExtractContent($item->uri); $this->items[] = $item; $limit++; }