This commit is contained in:
Benoît.S 2014-02-06 12:06:26 +01:00
commit cf82036886
29 changed files with 608 additions and 505 deletions

View File

@ -8,9 +8,10 @@
* @description Returns the N most recent documents. * @description Returns the N most recent documents.
* @use1(n="number") * @use1(n="number")
*/ */
class CryptomeBridge extends BridgeAbstract{ class CryptomeBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$num = 90; $num = 90;
$link = 'http://cryptome.org/'; $link = 'http://cryptome.org/';
@ -22,8 +23,8 @@ class CryptomeBridge extends BridgeAbstract{
$num = min(max(1, $param['n']+0), $num); $num = min(max(1, $param['n']+0), $num);
} }
foreach($html->find('pre') as $element) { foreach ($html->find('pre') as $element) {
for ( $i = 0; $i < $num; ++$i ) { for ($i = 0; $i < $num; ++$i) {
$item = new \Item(); $item = new \Item();
$item->uri = $link.substr($element->find('a', $i)->href, 20); $item->uri = $link.substr($element->find('a', $i)->href, 20);
$item->title = substr($element->find('b', $i)->plaintext, 22); $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'; return 'Cryptome';
} }
public function getURI(){ public function getURI()
{
return 'https://secure.netsolhost.com/cryptome.org/'; return 'https://secure.netsolhost.com/cryptome.org/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -7,32 +7,36 @@
* @name DansTonChat Bridge * @name DansTonChat Bridge
* @description Returns latest quotes from DansTonChat. * @description Returns latest quotes from DansTonChat.
*/ */
class DansTonChatBridge extends BridgeAbstract{ class DansTonChatBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$link = 'http://danstonchat.com/latest.html'; $link = 'http://danstonchat.com/latest.html';
$html = file_get_html($link) or $this->returnError('Could not request DansTonChat.', 404); $html = file_get_html($link) or $this->returnError('Could not request DansTonChat.', 404);
foreach($html->find('div.item') as $element) { foreach ($html->find('div.item') as $element) {
$item = new \Item(); $item = new \Item();
$item->uri = $element->find('a', 0)->href; $item->uri = $element->find('a', 0)->href;
$item->title = 'DansTonChat '.$element->find('a', 1)->plaintext; $item->title = 'DansTonChat '.$element->find('a', 1)->plaintext;
$item->content = $element->find('a', 0)->innertext; $item->content = $element->find('a', 0)->innertext;
$this->items[] = $item; $this->items[] = $item;
} }
} }
public function getName(){ public function getName()
{
return 'DansTonChat'; return 'DansTonChat';
} }
public function getURI(){ public function getURI()
{
return 'http://danstonchat.com'; return 'http://danstonchat.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -8,32 +8,36 @@
* @description Returns most recent results from DuckDuckGo. * @description Returns most recent results from DuckDuckGo.
* @use1(u="keyword") * @use1(u="keyword")
*/ */
class DuckDuckGoBridge extends BridgeAbstract{ class DuckDuckGoBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$link = 'https://duckduckgo.com/html/?q='.$param[u].'+sort:date'; $link = 'https://duckduckgo.com/html/?q='.$param[u].'+sort:date';
$html = file_get_html($link) or $this->returnError('Could not request DuckDuckGo.', 404); $html = file_get_html($link) or $this->returnError('Could not request DuckDuckGo.', 404);
foreach($html->find('div.results_links') as $element) { foreach ($html->find('div.results_links') as $element) {
$item = new \Item(); $item = new \Item();
$item->uri = $element->find('a', 0)->href; $item->uri = $element->find('a', 0)->href;
$item->title = $element->find('a', 1)->innertext; $item->title = $element->find('a', 1)->innertext;
$item->content = $element->find('div.snippet', 0)->plaintext; $item->content = $element->find('div.snippet', 0)->plaintext;
$this->items[] = $item; $this->items[] = $item;
} }
} }
public function getName(){ public function getName()
{
return 'DuckDuckGo'; return 'DuckDuckGo';
} }
public function getURI(){ public function getURI()
{
return 'https://duckduckgo.com'; return 'https://duckduckgo.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -6,50 +6,55 @@
* @name Futurasciences * @name Futurasciences
* @description Returns the 20 newest posts from FS (full text) * @description Returns the 20 newest posts from FS (full text)
*/ */
class FSBridge extends BridgeAbstract{ class FSBridge extends BridgeAbstract
{
public function FS_StripCDATA($string)
{
$string = str_replace('<![CDATA[', '', $string);
$string = str_replace(']]>', '', $string);
return $string;
public function collectData(array $param){
function FS_StripCDATA($string) {
$string = str_replace('<![CDATA[', '', $string);
$string = str_replace(']]>', '', $string);
return $string;
} }
function FS_ExtractContent($url) {
$html2 = file_get_html($url); public function FS_ExtractContent($url)
$text = $html2->find('div.fiche-actualite', 0)->innertext; {
return $text; $html2 = file_get_html($url);
$text = $html2->find('div.fiche-actualite', 0)->innertext;
return $text;
} }
public function collectData(array $param)
{
$html = file_get_html('http://www.futura-sciences.com/rss/actualites.xml') or $this->returnError('Could not request Futura Sciences.', 404); $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 = $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 = $this->FS_ExtractContent($item->uri);
$this->items[] = $item;
$limit++;
}
}
} }
public function getName(){ public function getName()
{
return 'Futura Sciences'; return 'Futura Sciences';
} }
public function getURI(){ public function getURI()
{
return 'http://www.futura-sciences.com/'; return 'http://www.futura-sciences.com/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
// return 3600; // 1 hour // return 3600; // 1 hour
return 0; // 1 hour return 0; // 1 hour
} }

View File

@ -6,12 +6,13 @@
* @name Flickr Explore * @name Flickr Explore
* @description Returns the latest interesting images from Flickr * @description Returns the latest interesting images from Flickr
*/ */
class FlickrExploreBridge extends BridgeAbstract{ class FlickrExploreBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = file_get_html('http://www.flickr.com/explore') or $this->returnError('Could not request Flickr.', 404); $html = file_get_html('http://www.flickr.com/explore') or $this->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 = new \Item();
$item->uri = 'http://flickr.com'.$element->find('a',0)->href; $item->uri = 'http://flickr.com'.$element->find('a',0)->href;
$item->thumbnailUri = $element->find('img',0)->getAttribute('data-defer-src'); $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'; return 'Flickr Explore';
} }
public function getURI(){ public function getURI()
{
return 'http://www.flickr.com/explore'; return 'http://www.flickr.com/explore';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -13,24 +13,24 @@
* @description Returns most recent results from Google search. * @description Returns most recent results from Google search.
* @use1(q="keyword") * @use1(q="keyword")
*/ */
class GoogleSearchBridge extends BridgeAbstract{ class GoogleSearchBridge extends BridgeAbstract
{
private $request; private $request;
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
if (isset($param['q'])) { /* keyword search mode */ if (isset($param['q'])) { /* keyword search mode */
$this->request = $param['q']; $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); $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); $this->returnError('You must specify a keyword (?q=...).', 400);
} }
$emIsRes = $html->find('div[id=ires]',0); $emIsRes = $html->find('div[id=ires]',0);
if( !is_null($emIsRes) ){ if ( !is_null($emIsRes) ) {
foreach($emIsRes->find('li[class=g]') as $element) { foreach ($emIsRes->find('li[class=g]') as $element) {
$item = new Item(); $item = new Item();
// Extract direct URL from google href (eg. /url?q=...) // Extract direct URL from google href (eg. /url?q=...)
@ -45,15 +45,18 @@ class GoogleSearchBridge extends BridgeAbstract{
} }
} }
public function getName(){ public function getName()
{
return (!empty($this->request) ? $this->request .' - ' : '') .'Google search'; return (!empty($this->request) ? $this->request .' - ' : '') .'Google search';
} }
public function getURI(){ public function getURI()
{
return 'http://google.com'; return 'http://google.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 1800; // 30 minutes return 1800; // 30 minutes
} }
} }

View File

@ -6,50 +6,55 @@
* @name GuruMed * @name GuruMed
* @description Returns the 20 newest posts from Gurumed (full text) * @description Returns the 20 newest posts from Gurumed (full text)
*/ */
class GuruMedBridge extends BridgeAbstract{ class GuruMedBridge extends BridgeAbstract
{
public function GurumedStripCDATA($string)
{
$string = str_replace('<![CDATA[', '', $string);
$string = str_replace(']]>', '', $string);
return $string;
public function collectData(array $param){
function GurumedStripCDATA($string) {
$string = str_replace('<![CDATA[', '', $string);
$string = str_replace(']]>', '', $string);
return $string;
} }
function GurumedExtractContent($url) {
$html2 = file_get_html($url); public function GurumedExtractContent($url)
$text = $html2->find('div.entry', 0)->innertext; {
return $text; $html2 = file_get_html($url);
$text = $html2->find('div.entry', 0)->innertext;
return $text;
} }
public function collectData(array $param)
{
$html = file_get_html('http://gurumed.org/feed') or $this->returnError('Could not request Gurumed.', 404); $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 = $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 = $this->GurumedExtractContent($item->uri);
$this->items[] = $item;
$limit++;
}
}
} }
public function getName(){ public function getName()
{
return 'Gurumed'; return 'Gurumed';
} }
public function getURI(){ public function getURI()
{
return 'http://gurumed.org/'; return 'http://gurumed.org/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600; // 1 hour return 3600; // 1 hour
} }
} }

View File

@ -6,21 +6,21 @@
* @description Returns user timelines * @description Returns user timelines
* @use1(u="username") * @use1(u="username")
*/ */
class IdenticaBridge extends BridgeAbstract{ class IdenticaBridge extends BridgeAbstract
{
private $request;
private $request; public function collectData(array $param)
{
public function collectData(array $param){
$html = ''; $html = '';
if (isset($param['u'])) { /* user timeline mode */ if (isset($param['u'])) { /* user timeline mode */
$this->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); $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); $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 = new \Item();
$item->uri = html_entity_decode($dent->find('a', 0)->href); // get dent link $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 $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'; return (!empty($this->request) ? $this->request .' - ' : '') .'Identica Bridge';
} }
public function getURI(){ public function getURI()
{
return 'https://identica.com'; return 'https://identica.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 300; // 5 minutes return 300; // 5 minutes
} }
} }

View File

@ -7,74 +7,70 @@
* @description Returns the newest images * @description Returns the newest images
* @use1(u="username") * @use1(u="username")
*/ */
class InstagramBridge extends BridgeAbstract{ class InstagramBridge extends BridgeAbstract
{
private $request; private $request;
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
if (isset($param['u'])) { /* user timeline mode */ if (isset($param['u'])) { /* user timeline mode */
$this->request = $param['u']; $this->request = $param['u'];
$html = file_get_html('http://instagram.com/'.urlencode($this->request)) or $this->returnError('Could not request Instagram.', 404); $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); $this->returnError('You must specify a Instagram username (?u=...).', 400);
} }
$innertext = null; $innertext = null;
foreach($html->find('script') as $script) foreach ($html->find('script') as $script) {
{ if ('' === $script->innertext) {
if ('' === $script->innertext) { continue;
continue; }
}
$pos = strpos(trim($script->innertext), 'window._sharedData'); $pos = strpos(trim($script->innertext), 'window._sharedData');
if (0 !== $pos) if (0 !== $pos) {
{ continue;
continue; }
}
$innertext = $script->innertext; $innertext = $script->innertext;
break; break;
} }
$json = trim(substr($innertext, $pos+18), ' =;'); $json = trim(substr($innertext, $pos+18), ' =;');
$data = json_decode($json); $data = json_decode($json);
$userMedia = $data->entry_data->UserProfile[0]->userMedia; $userMedia = $data->entry_data->UserProfile[0]->userMedia;
foreach ($userMedia as $media) {
$image = $media->images->standard_resolution;
foreach($userMedia as $media) $item = new \Item();
{ $item->uri = $media->link;
$image = $media->images->standard_resolution; $item->content = '<img src="' . htmlentities($image->url) . '" width="'.htmlentities($image->width).'" height="'.htmlentities($image->height).'" />';
if (isset($media->caption)) {
$item = new \Item(); $item->title = $media->caption->text;
$item->uri = $media->link; } else {
$item->content = '<img src="' . htmlentities($image->url) . '" width="'.htmlentities($image->width).'" height="'.htmlentities($image->height).'" />'; $item->title = basename($image->url);
if (isset($media->caption)) }
{ $item->timestamp = $media->created_time;
$item->title = $media->caption->text; $this->items[] = $item;
} 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'; return (!empty($this->request) ? $this->request .' - ' : '') .'Instagram Bridge';
} }
public function getURI(){ public function getURI()
{
return 'http://instagram.com/'; return 'http://instagram.com/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600; return 3600;
} }
} }

View File

@ -8,32 +8,36 @@
* @description Returns latest tutorials from OpenClassrooms. * @description Returns latest tutorials from OpenClassrooms.
* @use1(u="informatique or sciences") * @use1(u="informatique or sciences")
*/ */
class OpenClassroomsBridge extends BridgeAbstract{ class OpenClassroomsBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$link = 'http://fr.openclassrooms.com/'.$param[u].'/cours?title=&sort=updatedAt+desc'; $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); $html = file_get_html($link) or $this->returnError('Could not request OpenClassrooms.', 404);
foreach($html->find('li.col6') as $element) { foreach ($html->find('li.col6') as $element) {
$item = new \Item(); $item = new \Item();
$item->uri = 'http://fr.openclassrooms.com'.$element->find('a', 0)->href; $item->uri = 'http://fr.openclassrooms.com'.$element->find('a', 0)->href;
$item->title = $element->find('div.courses-content strong', 0)->innertext; $item->title = $element->find('div.courses-content strong', 0)->innertext;
$item->content = $element->find('span.course-tags', 0)->innertext; $item->content = $element->find('span.course-tags', 0)->innertext;
$this->items[] = $item; $this->items[] = $item;
} }
} }
public function getName(){ public function getName()
{
return 'OpenClassrooms'; return 'OpenClassrooms';
} }
public function getURI(){ public function getURI()
{
return 'http://fr.openclassrooms.com'; return 'http://fr.openclassrooms.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -8,81 +8,76 @@
* @use1(u="username",b="board") * @use1(u="username",b="board")
* @use2(q="keyword") * @use2(q="keyword")
*/ */
class PinterestBridge extends BridgeAbstract{ class PinterestBridge extends BridgeAbstract
{
private $username; private $username;
private $board; private $board;
private $query; private $query;
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
if (isset($param['u']) && isset($param['b'])) { if (isset($param['u']) && isset($param['b'])) {
$this->username = $param['u']; $this->username = $param['u'];
$this->board = $param['b']; $this->board = $param['b'];
$html = file_get_html($this->getURI().'/'.urlencode($this->username).'/'.urlencode($this->board)) or $this->returnError('Could not request Pinterest.', 404); $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'])) } elseif (isset($param['q'])) {
{ $this->query = $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);
$html = file_get_html($this->getURI().'/search/?q='.urlencode($this->query)) or $this->returnError('Could not request Pinterest.', 404); } else {
}
else {
$this->returnError('You must specify a Pinterest username and a board name (?u=...&b=...).', 400); $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);
foreach($html->find('div.pinWrapper') as $div) $img = $a->find('img', 0);
{
$a = $div->find('a.pinImageWrapper',0);
$img = $a->find('img', 0); $item = new \Item();
$item->uri = $this->getURI().$a->getAttribute('href');
$item->content = '<img src="' . htmlentities($img->getAttribute('src')) . '" alt="" />';
$item = new \Item(); if (isset($this->query)) {
$item->uri = $this->getURI().$a->getAttribute('href'); $avatar = $div->find('img.creditImg', 0);
$item->content = '<img src="' . htmlentities($img->getAttribute('src')) . '" alt="" />'; $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');
if (isset($this->query)) $item->content .= '<br /><img align="left" style="margin: 2px 4px;" src="'.htmlentities($item->avatar).'" /> <strong>'.$item->username.'</strong>';
{ $item->content .= '<br />'.$item->fullname;
$avatar = $div->find('img.creditImg', 0); } else {
$username = $div->find('span.creditName', 0);
$board = $div->find('span.creditTitle', 0);
$item->username =$username->innertext; $credit = $div->find('a.creditItem',0);
$item->fullname = $board->innertext; $item->content .= '<br />'.$credit->innertext;
$item->avatar = $avatar->getAttribute('src'); }
$item->content .= '<br /><img align="left" style="margin: 2px 4px;" src="'.htmlentities($item->avatar).'" /> <strong>'.$item->username.'</strong>'; $item->title = basename($img->getAttribute('alt'));
$item->content .= '<br />'.$item->fullname;
} else {
$credit = $div->find('a.creditItem',0); //$item->timestamp = $media->created_time;
$item->content .= '<br />'.$credit->innertext; $this->items[] = $item;
}
$item->title = basename($img->getAttribute('alt'));
//$item->timestamp = $media->created_time;
$this->items[] = $item;
} }
} }
public function getName(){ public function getName()
{
if (isset($this->query)) if (isset($this->query)) {
{ return $this->query .' - Pinterest';
return $this->query .' - Pinterest'; } else {
} else { return $this->username .' - '. $this->board.' - Pinterest';
return $this->username .' - '. $this->board.' - Pinterest'; }
}
} }
public function getURI(){ public function getURI()
{
return 'http://www.pinterest.com'; return 'http://www.pinterest.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 0; return 0;
} }
} }

View File

@ -6,44 +6,46 @@
* @name Se Coucher Moins Bête Bridge * @name Se Coucher Moins Bête Bridge
* @description Returns the newest anecdotes. * @description Returns the newest anecdotes.
*/ */
class ScmbBridge extends BridgeAbstract{ class ScmbBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$html = file_get_html('http://secouchermoinsbete.fr/') or $this->returnError('Could not request Se Coucher Moins Bete.', 404); $html = file_get_html('http://secouchermoinsbete.fr/') or $this->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;
foreach($html->find('article') as $article) { $article->find('span.read-more',0)->outertext=''; // remove text "En savoir plus" from anecdote content
$item = new \Item(); $content = $article->find('p.summary a',0)->innertext;
$item->uri = 'http://secouchermoinsbete.fr'.$article->find('p.summary a',0)->href; $content =substr($content,0,strlen($content)-17); // remove superfluous spaces at the end
$item->title = $article->find('header h1 a',0)->innertext;
$article->find('span.read-more',0)->outertext=''; // remove text "En savoir plus" from anecdote content // get publication date
$content = $article->find('p.summary a',0)->innertext; $str_date = $article->find('time',0)->datetime;
$content =substr($content,0,strlen($content)-17); // remove superfluous spaces at the end 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;
// get publication date $item->content = $content;
$str_date = $article->find('time',0)->datetime; $this->items[] = $item;
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'; return 'Se Coucher Moins Bête Bridge';
} }
public function getURI(){ public function getURI()
{
return 'http://secouchermoinsbete.fr/'; return 'http://secouchermoinsbete.fr/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -8,25 +8,24 @@
* @use1(q="keyword or #hashtag") * @use1(q="keyword or #hashtag")
* @use2(u="username") * @use2(u="username")
*/ */
class TwitterBridge extends BridgeAbstract{ class TwitterBridge extends BridgeAbstract
{
private $request; private $request;
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
if (isset($param['q'])) { /* keyword search mode */ if (isset($param['q'])) { /* keyword search mode */
$this->request = $param['q']; $this->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); $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']; $this->request = $param['u'];
$html = file_get_html('http://twitter.com/'.urlencode($this->request)) or $this->returnError('Requested username can\'t be found.', 404); $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); $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 = new \Item();
$item->username = trim(substr($tweet->find('span.username', 0)->plaintext, 1)); // extract username and sanitize $item->username = trim(substr($tweet->find('span.username', 0)->plaintext, 1)); // extract username and sanitize
$item->fullname = $tweet->getAttribute('data-name'); // extract fullname (pseudonym) $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'; return (!empty($this->request) ? $this->request .' - ' : '') .'Twitter Bridge';
} }
public function getURI(){ public function getURI()
{
return 'http://twitter.com'; return 'http://twitter.com';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 300; // 5 minutes return 300; // 5 minutes
} }
} }

View File

@ -6,9 +6,10 @@
* @name Wikipedia EN "Today's Featured Article..." * @name Wikipedia EN "Today's Featured Article..."
* @description Returns the highlighted en.wikipedia.org article. * @description Returns the highlighted en.wikipedia.org article.
*/ */
class WikipediaENBridge extends BridgeAbstract{ class WikipediaENBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$host = 'http://en.wikipedia.org'; $host = 'http://en.wikipedia.org';
// If you want HTTPS access instead, uncomment the following line: // 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); $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia EN.', 404);
$element = $html->find('div[id=mp-tfa]', 0); $element = $html->find('div[id=mp-tfa]', 0);
// Clean the bottom of the featured article // Clean the bottom of the featured article
$element->find('div', -1)->outertext = ''; $element->find('div', -1)->outertext = '';
$item = new \Item(); $item = new \Item();
$item->uri = $host.$element->find('p', 0)->find('a', 0)->href; $item->uri = $host.$element->find('p', 0)->find('a', 0)->href;
$item->title = $element->find('p',0)->find('a',0)->title; $item->title = $element->find('p',0)->find('a',0)->title;
$item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext);
$this->items[] = $item; $this->items[] = $item;
} }
public function getName(){ public function getName()
{
return 'Wikipedia EN "Today\'s Featued Article"'; return 'Wikipedia EN "Today\'s Featued Article"';
} }
public function getURI(){ public function getURI()
{
return 'https://en.wikipedia.org/wiki/Main_Page'; return 'https://en.wikipedia.org/wiki/Main_Page';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600*4; // 4 hours return 3600*4; // 4 hours
} }
} }

View File

@ -6,9 +6,10 @@
* @name Wikipedia EO "Artikolo de la semajno" * @name Wikipedia EO "Artikolo de la semajno"
* @description Returns the highlighted eo.wikipedia.org article. * @description Returns the highlighted eo.wikipedia.org article.
*/ */
class WikipediaEOBridge extends BridgeAbstract{ class WikipediaEOBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$host = 'http://eo.wikipedia.org'; $host = 'http://eo.wikipedia.org';
// If you want HTTPS access instead, uncomment the following line: // 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); $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia EO.', 404);
$element = $html->find('div[id=mf-tfa]', 0); $element = $html->find('div[id=mf-tfa]', 0);
// Link to article // Link to article
$link = $element->find('p', -2)->find('a', 0); $link = $element->find('p', -2)->find('a', 0);
$item = new \Item(); $item = new \Item();
$item->uri = $host.$link->href; $item->uri = $host.$link->href;
$item->title = $link->title; $item->title = $link->title;
$item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext); $item->content = str_replace('href="/', 'href="'.$host.'/', $element->innertext);
$this->items[] = $item; $this->items[] = $item;
} }
public function getName(){ public function getName()
{
return 'Wikipedia EO "Artikolo de la semajno"'; return 'Wikipedia EO "Artikolo de la semajno"';
} }
public function getURI(){ public function getURI()
{
return 'https://eo.wikipedia.org/wiki/Vikipedio:%C4%88efpa%C4%9Do'; return 'https://eo.wikipedia.org/wiki/Vikipedio:%C4%88efpa%C4%9Do';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600*12; // 12 hours return 3600*12; // 12 hours
} }
} }

View File

@ -6,9 +6,10 @@
* @name Wikipedia FR "Lumière sur..." * @name Wikipedia FR "Lumière sur..."
* @description Returns the highlighted fr.wikipedia.org article. * @description Returns the highlighted fr.wikipedia.org article.
*/ */
class WikipediaFRBridge extends BridgeAbstract{ class WikipediaFRBridge extends BridgeAbstract
{
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
$host = 'http://fr.wikipedia.org'; $host = 'http://fr.wikipedia.org';
// If you want HTTPS access instead, uncomment the following line: // 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); $html = file_get_html($host.$link) or $this->returnError('Could not request Wikipedia FR.', 404);
$element = $html->find('div[id=accueil-lumieresur]', 0); $element = $html->find('div[id=accueil-lumieresur]', 0);
$item = new \Item(); $item = new \Item();
$item->uri = $host.$element->find('p', 0)->find('a', 0)->href; $item->uri = $host.$element->find('p', 0)->find('a', 0)->href;
$item->title = $element->find('p',0)->find('a',0)->title; $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); $item->content = str_replace('href="/', 'href="'.$host.'/', $element->find('div[id=mf-lumieresur]', 0)->innertext);
$this->items[] = $item; $this->items[] = $item;
} }
public function getName(){ public function getName()
{
return 'Wikipedia FR "Lumière sur..."'; return 'Wikipedia FR "Lumière sur..."';
} }
public function getURI(){ public function getURI()
{
return 'https://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Accueil_principal'; return 'https://fr.wikipedia.org/wiki/Wikip%C3%A9dia:Accueil_principal';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600*4; // 4 hours return 3600*4; // 4 hours
} }
} }

View File

@ -7,22 +7,21 @@
* @description Returns the newest videos * @description Returns the newest videos
* @use1(u="username") * @use1(u="username")
*/ */
class YoutubeBridge extends BridgeAbstract{ class YoutubeBridge extends BridgeAbstract
{
private $request; private $request;
public function collectData(array $param){ public function collectData(array $param)
{
$html = ''; $html = '';
if (isset($param['u'])) { /* user timeline mode */ if (isset($param['u'])) { /* user timeline mode */
$this->request = $param['u']; $this->request = $param['u'];
$html = file_get_html('https://www.youtube.com/user/'.urlencode($this->request).'/videos') or $this->returnError('Could not request Youtube.', 404); $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); $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 = new \Item();
$item->uri = 'https://www.youtube.com'.$element->find('a',0)->href; $item->uri = 'https://www.youtube.com'.$element->find('a',0)->href;
$item->thumbnailUri = 'https:'.$element->find('img',0)->src; $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'; return (!empty($this->request) ? $this->request .' - ' : '') .'Youtube Bridge';
} }
public function getURI(){ public function getURI()
{
return 'https://www.youtube.com/'; return 'https://www.youtube.com/';
} }
public function getCacheDuration(){ public function getCacheDuration()
{
return 21600; // 6 hours return 21600; // 6 hours
} }
} }

View File

@ -2,17 +2,19 @@
/** /**
* Cache with file system * Cache with file system
*/ */
class FileCache extends CacheAbstract{ class FileCache extends CacheAbstract
{
protected $cacheDirCreated; // boolean to avoid always chck dir cache existance protected $cacheDirCreated; // boolean to avoid always chck dir cache existance
public function loadData(){ public function loadData()
{
$this->isPrepareCache(); $this->isPrepareCache();
$datas = json_decode(file_get_contents($this->getCacheFile()),true); $datas = json_decode(file_get_contents($this->getCacheFile()),true);
$items = array(); $items = array();
foreach($datas as $aData){ foreach ($datas as $aData) {
$item = new \Item(); $item = new \Item();
foreach($aData as $name => $value){ foreach ($aData as $name => $value) {
$item->$name = $value; $item->$name = $value;
} }
$items[] = $item; $items[] = $item;
@ -21,7 +23,8 @@ class FileCache extends CacheAbstract{
return $items; return $items;
} }
public function saveData($datas){ public function saveData($datas)
{
$this->isPrepareCache(); $this->isPrepareCache();
file_put_contents($this->getCacheFile(), json_encode($datas)); file_put_contents($this->getCacheFile(), json_encode($datas));
@ -29,11 +32,12 @@ class FileCache extends CacheAbstract{
return $this; return $this;
} }
public function getTime(){ public function getTime()
{
$this->isPrepareCache(); $this->isPrepareCache();
$cacheFile = $this->getCacheFile(); $cacheFile = $this->getCacheFile();
if( file_exists($cacheFile) ){ if ( file_exists($cacheFile) ) {
return filemtime($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 * Note : Cache name is based on request information, then cache must be prepare before use
* @return \Exception|true * @return \Exception|true
*/ */
protected function isPrepareCache(){ protected function isPrepareCache()
if( is_null($this->param) ){ {
if ( is_null($this->param) ) {
throw new \Exception('Please feed "prepare" method before try to load'); 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 cache path (and create if not exist)
* @return string Cache path * @return string Cache path
*/ */
protected function getCachePath(){ protected function getCachePath()
{
$cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ? $cacheDir = __DIR__ . '/../cache/'; // FIXME : configuration ?
// FIXME : implement recursive dir creation // FIXME : implement recursive dir creation
if( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ){ if ( is_null($this->cacheDirCreated) && !is_dir($cacheDir) ) {
$this->cacheDirCreated = true; $this->cacheDirCreated = true;
mkdir($cacheDir,0705); mkdir($cacheDir,0705);
@ -75,7 +81,8 @@ class FileCache extends CacheAbstract{
* Get the file name use for cache store * Get the file name use for cache store
* @return string Path to the file cache * @return string Path to the file cache
*/ */
protected function getCacheFile(){ protected function getCacheFile()
{
return $this->getCachePath() . $this->getCacheName(); return $this->getCachePath() . $this->getCacheName();
} }
@ -83,10 +90,12 @@ class FileCache extends CacheAbstract{
* Determines file name for store the cache * Determines file name for store the cache
* return string * return string
*/ */
protected function getCacheName(){ protected function getCacheName()
{
$this->isPrepareCache(); $this->isPrepareCache();
$stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param); $stringToEncode = $_SERVER['REQUEST_URI'] . http_build_query($this->param);
return hash('sha1', $stringToEncode) . '.cache'; return hash('sha1', $stringToEncode) . '.cache';
} }
} }

View File

@ -5,9 +5,10 @@
* *
* @name Atom * @name Atom
*/ */
class AtomFormat extends FormatAbstract{ class AtomFormat extends FormatAbstract
{
public function stringify(){ public function stringify()
{
/* Datas preparation */ /* Datas preparation */
$https = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '' ); $https = ( isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] == 'on' ? 's' : '' );
$httpHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : ''; $httpHost = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : '';
@ -20,7 +21,7 @@ class AtomFormat extends FormatAbstract{
$uri = htmlspecialchars($extraInfos['uri']); $uri = htmlspecialchars($extraInfos['uri']);
$entries = ''; $entries = '';
foreach($this->getDatas() as $data){ foreach ($this->getDatas() as $data) {
$entryName = is_null($data->name) ? $title : $data->name; $entryName = is_null($data->name) ? $title : $data->name;
$entryAuthor = is_null($data->author) ? $uri : $data->author; $entryAuthor = is_null($data->author) ? $uri : $data->author;
$entryTitle = is_null($data->title) ? '' : $data->title; $entryTitle = is_null($data->title) ? '' : $data->title;
@ -75,10 +76,12 @@ EOD;
// So we use mb_convert_encoding instead: // So we use mb_convert_encoding instead:
ini_set('mbstring.substitute_character', 'none'); 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; return $toReturn;
} }
public function display(){ public function display()
{
$this $this
->setContentType('application/atom+xml; charset=utf8') // We force UTF-8 in ATOM output. ->setContentType('application/atom+xml; charset=utf8') // We force UTF-8 in ATOM output.
->callContentType(); ->callContentType();

View File

@ -5,16 +5,17 @@
* *
* @name Html * @name Html
*/ */
class HtmlFormat extends FormatAbstract{ class HtmlFormat extends FormatAbstract
{
public function stringify(){ public function stringify()
{
/* Datas preparation */ /* Datas preparation */
$extraInfos = $this->getExtraInfos(); $extraInfos = $this->getExtraInfos();
$title = htmlspecialchars($extraInfos['name']); $title = htmlspecialchars($extraInfos['name']);
$uri = htmlspecialchars($extraInfos['uri']); $uri = htmlspecialchars($extraInfos['uri']);
$entries = ''; $entries = '';
foreach($this->getDatas() as $data){ foreach ($this->getDatas() as $data) {
$entryUri = is_null($data->uri) ? $uri : $data->uri; $entryUri = is_null($data->uri) ? $uri : $data->uri;
$entryTitle = is_null($data->title) ? '' : $this->sanitizeHtml(strip_tags($data->title)); $entryTitle = is_null($data->title) ? '' : $this->sanitizeHtml(strip_tags($data->title));
$entryTimestamp = is_null($data->timestamp) ? '' : '<small>' . date(DATE_ATOM, $data->timestamp) . '</small>'; $entryTimestamp = is_null($data->timestamp) ? '' : '<small>' . date(DATE_ATOM, $data->timestamp) . '</small>';
@ -51,7 +52,8 @@ EOD;
return $toReturn; return $toReturn;
} }
public function display() { public function display()
{
$this $this
->setContentType('text/html; charset=' . $this->getCharset()) ->setContentType('text/html; charset=' . $this->getCharset())
->callContentType(); ->callContentType();

View File

@ -5,16 +5,18 @@
* *
* @name Json * @name Json
*/ */
class JsonFormat extends FormatAbstract{ class JsonFormat extends FormatAbstract
{
public function stringify(){ public function stringify()
{
// FIXME : sometime content can be null, transform to empty string // FIXME : sometime content can be null, transform to empty string
$datas = $this->getDatas(); $datas = $this->getDatas();
return json_encode($datas); return json_encode($datas);
} }
public function display(){ public function display()
{
$this $this
->setContentType('application/json') ->setContentType('application/json')
->callContentType(); ->callContentType();

View File

@ -5,14 +5,17 @@
* *
* @name Plaintext * @name Plaintext
*/ */
class PlaintextFormat extends FormatAbstract{ class PlaintextFormat extends FormatAbstract
{
public function stringify(){ public function stringify()
{
$datas = $this->getDatas(); $datas = $this->getDatas();
return print_r($datas, true); return print_r($datas, true);
} }
public function display(){ public function display()
{
$this $this
->setContentType('text/plain;charset=' . $this->getCharset()) ->setContentType('text/plain;charset=' . $this->getCharset())
->callContentType(); ->callContentType();

View File

@ -15,17 +15,17 @@ date_default_timezone_set('UTC');
error_reporting(0); error_reporting(0);
//ini_set('display_errors','1'); error_reporting(E_ALL); // For debugging only. //ini_set('display_errors','1'); error_reporting(E_ALL); // For debugging only.
try{ try {
require_once __DIR__ . '/lib/RssBridge.php'; require_once __DIR__ . '/lib/RssBridge.php';
Bridge::setDir(__DIR__ . '/bridges/'); Bridge::setDir(__DIR__ . '/bridges/');
Format::setDir(__DIR__ . '/formats/'); Format::setDir(__DIR__ . '/formats/');
Cache::setDir(__DIR__ . '/caches/'); Cache::setDir(__DIR__ . '/caches/');
if( isset($_REQUEST) && isset($_REQUEST['action']) ){ if ( isset($_REQUEST) && isset($_REQUEST['action']) ) {
switch($_REQUEST['action']){ switch ($_REQUEST['action']) {
case 'display': case 'display':
if( isset($_REQUEST['bridge']) ){ if ( isset($_REQUEST['bridge']) ) {
unset($_REQUEST['action']); unset($_REQUEST['action']);
$bridge = $_REQUEST['bridge']; $bridge = $_REQUEST['bridge'];
unset($_REQUEST['bridge']); unset($_REQUEST['bridge']);
@ -57,17 +57,16 @@ try{
break; break;
} }
} }
} } catch (HttpException $e) {
catch(HttpException $e){
header('HTTP/1.1 ' . $e->getCode() . ' ' . Http::getMessageForCode($e->getCode())); header('HTTP/1.1 ' . $e->getCode() . ' ' . Http::getMessageForCode($e->getCode()));
header('Content-Type: text/plain'); header('Content-Type: text/plain');
die($e->getMessage()); die($e->getMessage());
} } catch (\Exception $e) {
catch(\Exception $e){
die($e->getMessage()); die($e->getMessage());
} }
function getHelperButtonFormat($value, $name){ function getHelperButtonFormat($value, $name)
{
return '<button type="submit" name="format" value="' . $value . '">' . $name . '</button>'; return '<button type="submit" name="format" value="' . $value . '">' . $name . '</button>';
} }
@ -114,7 +113,7 @@ $formats = Format::searchInformation();
<input id="<?php echo $idArg ?>" type="text" value="" placeholder="<?php echo $argDescription; ?>" name="<?php echo $argName ?>" placeholder="<?php echo $argDescription ?>" /> <input id="<?php echo $idArg ?>" type="text" value="" placeholder="<?php echo $argDescription; ?>" name="<?php echo $argName ?>" placeholder="<?php echo $argDescription ?>" />
<?php endforeach; ?> <?php endforeach; ?>
<?php foreach( $formats as $name => $infos ): ?> <?php foreach( $formats as $name => $infos ): ?>
<?php if( isset($infos['name']) ){ echo getHelperButtonFormat($name, $infos['name']); } ?> <?php if ( isset($infos['name']) ) { echo getHelperButtonFormat($name, $infos['name']); } ?>
<?php endforeach; ?> <?php endforeach; ?>
</form> </form>
</li> </li>
@ -125,7 +124,7 @@ $formats = Format::searchInformation();
<input type="hidden" name="action" value="display" /> <input type="hidden" name="action" value="display" />
<input type="hidden" name="bridge" value="<?php echo $bridgeReference ?>" /> <input type="hidden" name="bridge" value="<?php echo $bridgeReference ?>" />
<?php foreach( $formats as $name => $infos ): ?> <?php foreach( $formats as $name => $infos ): ?>
<?php if( isset($infos['name']) ){ echo getHelperButtonFormat($name, $infos['name']); } ?> <?php if ( isset($infos['name']) ) { echo getHelperButtonFormat($name, $infos['name']); } ?>
<?php endforeach; ?> <?php endforeach; ?>
</form> </form>
<?php endif; ?> <?php endif; ?>

View File

@ -4,21 +4,24 @@
* Note : adapter are store in other place * Note : adapter are store in other place
*/ */
interface BridgeInterface{ interface BridgeInterface
{
public function collectData(array $param); public function collectData(array $param);
public function getName(); public function getName();
public function getURI(); public function getURI();
public function getCacheDuration(); public function getCacheDuration();
} }
abstract class BridgeAbstract implements BridgeInterface{ abstract class BridgeAbstract implements BridgeInterface
{
protected $cache; protected $cache;
protected $items = array(); protected $items = array();
/** /**
* Launch probative exception * Launch probative exception
*/ */
protected function returnError($message, $code){ protected function returnError($message, $code)
{
throw new \HttpException($message, $code); throw new \HttpException($message, $code);
} }
@ -26,7 +29,8 @@ abstract class BridgeAbstract implements BridgeInterface{
* Return datas store in the bridge * Return datas store in the bridge
* @return mixed * @return mixed
*/ */
public function getDatas(){ public function getDatas()
{
return $this->items; return $this->items;
} }
@ -35,22 +39,21 @@ abstract class BridgeAbstract implements BridgeInterface{
* Note : you can defined a cache before with "setCache" * Note : you can defined a cache before with "setCache"
* @param array $param $_REQUEST, $_GET, $_POST, or array with bridge expected paramters * @param array $param $_REQUEST, $_GET, $_POST, or array with bridge expected paramters
*/ */
public function setDatas(array $param){ public function setDatas(array $param)
if( !is_null($this->cache) ){ {
if ( !is_null($this->cache) ) {
$this->cache->prepare($param); $this->cache->prepare($param);
$time = $this->cache->getTime(); $time = $this->cache->getTime();
} } else {
else{
$time = false; // No cache ? No time ! $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(); $this->items = $this->cache->loadData();
} } else {
else{
$this->collectData($param); $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()); $this->cache->saveData($this->getDatas());
} }
} }
@ -59,25 +62,28 @@ abstract class BridgeAbstract implements BridgeInterface{
/** /**
* Define default duraction for cache * Define default duraction for cache
*/ */
public function getCacheDuration(){ public function getCacheDuration()
{
return 3600; return 3600;
} }
/** /**
* Defined cache object to use * Defined cache object to use
*/ */
public function setCache(\CacheAbstract $cache){ public function setCache(\CacheAbstract $cache)
{
$this->cache = $cache; $this->cache = $cache;
return $this; 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.'); 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 * @param string $nameBridge Defined bridge name you want use
* @return Bridge object dedicated * @return Bridge object dedicated
*/ */
static public function create($nameBridge){ public static function create($nameBridge)
if( !static::isValidNameBridge($nameBridge) ){ {
if ( !static::isValidNameBridge($nameBridge) ) {
throw new \InvalidArgumentException('Name bridge must be at least one uppercase follow or not by alphanumeric or dash characters.'); throw new \InvalidArgumentException('Name bridge must be at least one uppercase follow or not by alphanumeric or dash characters.');
} }
$pathBridge = self::getDir() . $nameBridge . '.php'; $pathBridge = self::getDir() . $nameBridge . '.php';
if( !file_exists($pathBridge) ){ if ( !file_exists($pathBridge) ) {
throw new \Exception('The bridge you looking for does not exist.'); throw new \Exception('The bridge you looking for does not exist.');
} }
@ -102,29 +109,32 @@ class Bridge{
return new $nameBridge(); return new $nameBridge();
} }
static public function setDir($dirBridge){ public static function setDir($dirBridge)
if( !is_string($dirBridge) ){ {
if ( !is_string($dirBridge) ) {
throw new \InvalidArgumentException('Dir bridge must be a string.'); 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.'); throw new \Exception('Dir bridge does not exist.');
} }
self::$dirBridge = $dirBridge; self::$dirBridge = $dirBridge;
} }
static public function getDir(){ public static function getDir()
{
$dirBridge = self::$dirBridge; $dirBridge = self::$dirBridge;
if( is_null($dirBridge) ){ if ( is_null($dirBridge) ) {
throw new \LogicException(__CLASS__ . ' class need to know bridge path !'); throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
} }
return $dirBridge; return $dirBridge;
} }
static public function isValidNameBridge($nameBridge){ public static function isValidNameBridge($nameBridge)
{
return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $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 * Read bridge dir and catch informations about each bridge depending annotation
* @return array Informations about each bridge * @return array Informations about each bridge
*/ */
static public function searchInformation(){ public static function searchInformation()
{
$pathDirBridge = self::getDir(); $pathDirBridge = self::getDir();
$listBridge = array(); $listBridge = array();
@ -140,33 +151,33 @@ class Bridge{
$searchCommonPattern = array('description', 'name'); $searchCommonPattern = array('description', 'name');
$dirFiles = scandir($pathDirBridge); $dirFiles = scandir($pathDirBridge);
if( $dirFiles !== false ){ if ($dirFiles !== false) {
foreach( $dirFiles as $fileName ){ foreach ($dirFiles as $fileName) {
if( preg_match('@([^.]+)\.php@U', $fileName, $out) ){ // Is PHP file ? if ( preg_match('@([^.]+)\.php@U', $fileName, $out) ) { // Is PHP file ?
$infos = array(); // Information about the bridge $infos = array(); // Information about the bridge
$resParse = token_get_all(file_get_contents($pathDirBridge . $fileName)); // Parse PHP file $resParse = token_get_all(file_get_contents($pathDirBridge . $fileName)); // Parse PHP file
foreach($resParse as $v){ foreach ($resParse as $v) {
if( is_array($v) && $v[0] == T_DOC_COMMENT ){ // Lexer node is COMMENT ? if ( is_array($v) && $v[0] == T_DOC_COMMENT ) { // Lexer node is COMMENT ?
$commentary = $v[1]; $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); preg_match('#@' . preg_quote($name, '#') . '\s+(.+)#', $commentary, $outComment);
if( isset($outComment[1]) ){ if ( isset($outComment[1]) ) {
$infos[$name] = $outComment[1]; $infos[$name] = $outComment[1];
} }
} }
preg_match_all('#@use(?<num>[1-9][0-9]*)\s?\((?<args>.+)\)(?:\r|\n)#', $commentary, $outComment); // Catch specific information about "use". preg_match_all('#@use(?<num>[1-9][0-9]*)\s?\((?<args>.+)\)(?:\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(); $infos['use'] = array();
foreach($outComment['args'] as $num => $args){ // Each use foreach ($outComment['args'] as $num => $args) { // Each use
preg_match_all('#(?<name>[a-z]+)="(?<value>.*)"(?:,|$)#U', $args, $outArg); // Catch arguments for current use preg_match_all('#(?<name>[a-z]+)="(?<value>.*)"(?:,|$)#U', $args, $outArg); // Catch arguments for current use
if( isset($outArg['name']) ){ if ( isset($outArg['name']) ) {
$usePos = $outComment['num'][$num]; // Current use 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(); $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]; $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; $listBridge[$out[1]] = $infos;
} }
} }

View File

@ -4,38 +4,43 @@
* Note : adapter are store in other place * Note : adapter are store in other place
*/ */
interface CacheInterface{ interface CacheInterface
{
public function loadData(); public function loadData();
public function saveData($datas); public function saveData($datas);
public function getTime(); public function getTime();
} }
abstract class CacheAbstract implements CacheInterface{ abstract class CacheAbstract implements CacheInterface
{
protected $param; protected $param;
public function prepare(array $param){ public function prepare(array $param)
{
$this->param = $param; $this->param = $param;
return $this; 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.'); throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
} }
static public function create($nameCache){ public static function create($nameCache)
if( !static::isValidNameCache($nameCache) ){ {
if ( !static::isValidNameCache($nameCache) ) {
throw new \InvalidArgumentException('Name cache must be at least one uppercase follow or not by alphanumeric or dash characters.'); throw new \InvalidArgumentException('Name cache must be at least one uppercase follow or not by alphanumeric or dash characters.');
} }
$pathCache = self::getDir() . $nameCache . '.php'; $pathCache = self::getDir() . $nameCache . '.php';
if( !file_exists($pathCache) ){ if ( !file_exists($pathCache) ) {
throw new \Exception('The cache you looking for does not exist.'); throw new \Exception('The cache you looking for does not exist.');
} }
@ -44,29 +49,32 @@ class Cache{
return new $nameCache(); return new $nameCache();
} }
static public function setDir($dirCache){ public static function setDir($dirCache)
if( !is_string($dirCache) ){ {
if ( !is_string($dirCache) ) {
throw new \InvalidArgumentException('Dir cache must be a string.'); 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.'); throw new \Exception('Dir cache does not exist.');
} }
self::$dirCache = $dirCache; self::$dirCache = $dirCache;
} }
static public function getDir(){ public static function getDir()
{
$dirCache = self::$dirCache; $dirCache = self::$dirCache;
if( is_null($dirCache) ){ if ( is_null($dirCache) ) {
throw new \LogicException(__CLASS__ . ' class need to know cache path !'); throw new \LogicException(__CLASS__ . ' class need to know cache path !');
} }
return $dirCache; return $dirCache;
} }
static public function isValidNameCache($nameCache){ public static function isValidNameCache($nameCache)
{
return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameCache); return preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameCache);
} }
} }

View File

@ -4,15 +4,16 @@ class HttpException extends \Exception{}
/** /**
* Not real http implementation but only utils stuff * Not real http implementation but only utils stuff
*/ */
class Http{ class Http
{
/** /**
* Return message corresponding to Http code * Return message corresponding to Http code
*/ */
static public function getMessageForCode($code){ public static function getMessageForCode($code)
{
$codes = self::getCodes(); $codes = self::getCodes();
if( isset($codes[$code]) ){ if ( isset($codes[$code]) ) {
return $codes[$code]; return $codes[$code];
} }
@ -22,7 +23,8 @@ class Http{
/** /**
* List of common Http code * List of common Http code
*/ */
static public function getCodes(){ public static function getCodes()
{
return array( return array(
200 => 'OK', 200 => 'OK',
201 => 'Created', 201 => 'Created',

View File

@ -4,58 +4,66 @@
* Note : adapter are store in other place * Note : adapter are store in other place
*/ */
interface FormatInterface{ interface FormatInterface
{
public function stringify(); public function stringify();
public function display(); public function display();
public function setDatas(array $bridge); public function setDatas(array $bridge);
} }
abstract class FormatAbstract implements FormatInterface{ abstract class FormatAbstract implements FormatInterface
{
const DEFAULT_CHARSET = 'UTF-8'; const DEFAULT_CHARSET = 'UTF-8';
protected protected $contentType,
$contentType,
$charset, $charset,
$datas, $datas,
$extraInfos $extraInfos
; ;
public function setCharset($charset){ public function setCharset($charset)
{
$this->charset = $charset; $this->charset = $charset;
return $this; return $this;
} }
public function getCharset(){ public function getCharset()
{
$charset = $this->charset; $charset = $this->charset;
return is_null($charset) ? self::DEFAULT_CHARSET : $charset; return is_null($charset) ? self::DEFAULT_CHARSET : $charset;
} }
protected function setContentType($contentType){ protected function setContentType($contentType)
{
$this->contentType = $contentType; $this->contentType = $contentType;
return $this; return $this;
} }
protected function callContentType(){ protected function callContentType()
{
header('Content-Type: ' . $this->contentType); header('Content-Type: ' . $this->contentType);
} }
public function display(){ public function display()
{
echo $this->stringify(); echo $this->stringify();
return $this; return $this;
} }
public function setDatas(array $datas){ public function setDatas(array $datas)
{
$this->datas = $datas; $this->datas = $datas;
return $this; return $this;
} }
public function getDatas(){ public function getDatas()
if( !is_array($this->datas) ){ {
if ( !is_array($this->datas) ) {
throw new \LogicException('Feed the ' . get_class($this) . ' with "setDatas" method before !'); 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 !!!) * @param array $extraInfos array with know informations (there isn't merge !!!)
* @return this * @return this
*/ */
public function setExtraInfos(array $extraInfos = array()){ public function setExtraInfos(array $extraInfos = array())
foreach(array('name', 'uri') as $infoName){ {
if( !isset($extraInfos[$infoName]) ){ foreach (array('name', 'uri') as $infoName) {
if ( !isset($extraInfos[$infoName]) ) {
$extraInfos[$infoName] = ''; $extraInfos[$infoName] = '';
} }
} }
@ -83,8 +92,9 @@ abstract class FormatAbstract implements FormatInterface{
* Return extra infos * Return extra infos
* @return array See "setExtraInfos" detail method to know what extra are disponibles * @return array See "setExtraInfos" detail method to know what extra are disponibles
*/ */
public function getExtraInfos(){ public function getExtraInfos()
if( is_null($this->extraInfos) ){ // No extra info ? {
if ( is_null($this->extraInfos) ) { // No extra info ?
$this->setExtraInfos(); // Define with default value $this->setExtraInfos(); // Define with default value
} }
@ -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.'); throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
} }
static public function create($nameFormat){ public static function create($nameFormat)
if( !static::isValidNameFormat($nameFormat) ){ {
if ( !static::isValidNameFormat($nameFormat) ) {
throw new \InvalidArgumentException('Name format must be at least one uppercase follow or not by alphabetic characters.'); throw new \InvalidArgumentException('Name format must be at least one uppercase follow or not by alphabetic characters.');
} }
$pathFormat = self::getDir() . $nameFormat . '.php'; $pathFormat = self::getDir() . $nameFormat . '.php';
if( !file_exists($pathFormat) ){ if ( !file_exists($pathFormat) ) {
throw new \Exception('The format you looking for does not exist.'); throw new \Exception('The format you looking for does not exist.');
} }
@ -133,29 +145,32 @@ class Format{
return new $nameFormat(); return new $nameFormat();
} }
static public function setDir($dirFormat){ public static function setDir($dirFormat)
if( !is_string($dirFormat) ){ {
if ( !is_string($dirFormat) ) {
throw new \InvalidArgumentException('Dir format must be a string.'); 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.'); throw new \Exception('Dir format does not exist.');
} }
self::$dirFormat = $dirFormat; self::$dirFormat = $dirFormat;
} }
static public function getDir(){ public static function getDir()
{
$dirFormat = self::$dirFormat; $dirFormat = self::$dirFormat;
if( is_null($dirFormat) ){ if ( is_null($dirFormat) ) {
throw new \LogicException(__CLASS__ . ' class need to know format path !'); throw new \LogicException(__CLASS__ . ' class need to know format path !');
} }
return $dirFormat; return $dirFormat;
} }
static public function isValidNameFormat($nameFormat){ public static function isValidNameFormat($nameFormat)
{
return preg_match('@^[A-Z][a-zA-Z]*$@', $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 * Read format dir and catch informations about each format depending annotation
* @return array Informations about each format * @return array Informations about each format
*/ */
static public function searchInformation(){ public static function searchInformation()
{
$pathDirFormat = self::getDir(); $pathDirFormat = self::getDir();
$listFormat = array(); $listFormat = array();
@ -171,24 +187,24 @@ class Format{
$searchCommonPattern = array('name'); $searchCommonPattern = array('name');
$dirFiles = scandir($pathDirFormat); $dirFiles = scandir($pathDirFormat);
if( $dirFiles !== false ){ if ($dirFiles !== false) {
foreach( $dirFiles as $fileName ){ foreach ($dirFiles as $fileName) {
if( preg_match('@([^.]+)\.php@U', $fileName, $out) ){ // Is PHP file ? if ( preg_match('@([^.]+)\.php@U', $fileName, $out) ) { // Is PHP file ?
$infos = array(); // Information about the bridge $infos = array(); // Information about the bridge
$resParse = token_get_all(file_get_contents($pathDirFormat . $fileName)); // Parse PHP file $resParse = token_get_all(file_get_contents($pathDirFormat . $fileName)); // Parse PHP file
foreach($resParse as $v){ foreach ($resParse as $v) {
if( is_array($v) && $v[0] == T_DOC_COMMENT ){ // Lexer node is COMMENT ? if ( is_array($v) && $v[0] == T_DOC_COMMENT ) { // Lexer node is COMMENT ?
$commentary = $v[1]; $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); preg_match('#@' . preg_quote($name, '#') . '\s+(.+)#', $commentary, $outComment);
if( isset($outComment[1]) ){ if ( isset($outComment[1]) ) {
$infos[$name] = $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; $listFormat[$out[1]] = $infos;
} }
} }

View File

@ -5,12 +5,15 @@ interface ItemInterface{}
* Object to store datas collect informations * Object to store datas collect informations
* FIXME : not sur this logic is the good, I think recast all is necessary * FIXME : not sur this logic is the good, I think recast all is necessary
*/ */
class Item implements ItemInterface{ class Item implements ItemInterface
public function __set($name, $value){ {
public function __set($name, $value)
{
$this->$name = $value; $this->$name = $value;
} }
public function __get($name){ public function __get($name)
{
return isset($this->$name) ? $this->$name : null; return isset($this->$name) ? $this->$name : null;
} }
} }

View File

@ -14,7 +14,7 @@ require __DIR__ . '/Bridge.php';
require __DIR__ . '/Cache.php'; require __DIR__ . '/Cache.php';
$vendorLibSimpleHtmlDom = __DIR__ . PATH_VENDOR . '/simplehtmldom/simple_html_dom.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); 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; require_once $vendorLibSimpleHtmlDom;