Bridge.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394
  1. <?php
  2. /**
  3. * All bridge logic
  4. * Note : adapter are store in other place
  5. */
  6. interface BridgeInterface{
  7. public function collectData(array $param);
  8. public function getCacheDuration();
  9. public function loadMetadatas();
  10. public function getName();
  11. public function getURI();
  12. }
  13. abstract class BridgeAbstract implements BridgeInterface{
  14. protected $cache;
  15. protected $items = array();
  16. public $name = "Unnamed bridge";
  17. public $uri = "";
  18. public $description = 'No description provided';
  19. public $maintainer = 'No maintainer';
  20. public $useProxy = true;
  21. public $parameters = array();
  22. /**
  23. * Launch probative exception
  24. */
  25. protected function returnError($message, $code){
  26. throw new \HttpException($message, $code);
  27. }
  28. protected function returnClientError($message){
  29. $this->returnError($message, 400);
  30. }
  31. protected function returnServerError($message){
  32. $this->returnError($message, 500);
  33. }
  34. /**
  35. * Return datas stored in the bridge
  36. * @return mixed
  37. */
  38. public function getDatas(){
  39. return $this->items;
  40. }
  41. /**
  42. * Defined datas with parameters depending choose bridge
  43. * Note : you can define a cache before with "setCache"
  44. * @param array $param $_REQUEST, $_GET, $_POST, or array with bridge expected paramters
  45. */
  46. public function setDatas(array $param){
  47. if( !is_null($this->cache) ){
  48. $this->cache->prepare($param);
  49. $time = $this->cache->getTime();
  50. }
  51. else{
  52. $time = false; // No cache ? No time !
  53. }
  54. if( $time !== false && ( time() - $this->getCacheDuration() < $time ) ){ // Cache file has not expired. Serve it.
  55. $this->items = $this->cache->loadData();
  56. }
  57. else{
  58. $this->collectData($param);
  59. if( !is_null($this->cache) ){ // Cache defined ? We go to refresh is memory :D
  60. $this->cache->saveData($this->getDatas());
  61. }
  62. }
  63. }
  64. /**
  65. * Define default bridge name
  66. */
  67. public function getName(){
  68. return $this->name;
  69. }
  70. /**
  71. * Define default bridge URI
  72. */
  73. public function getURI(){
  74. return $this->uri;
  75. }
  76. /**
  77. * Define default duraction for cache
  78. */
  79. public function getCacheDuration(){
  80. return 3600;
  81. }
  82. /**
  83. * Defined cache object to use
  84. */
  85. public function setCache(\CacheAbstract $cache){
  86. $this->cache = $cache;
  87. return $this;
  88. }
  89. public function message($text) {
  90. if(!file_exists('DEBUG')){
  91. return;
  92. }
  93. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  94. $calling = $backtrace[2];
  95. $message = $calling["file"].":".$calling["line"]
  96. ." class ".get_class($this)."->".$calling["function"]
  97. ." - ".$text;
  98. error_log($message);
  99. }
  100. protected function getContents($url,$use_include_path=false,$context=null,$offset=0,$maxlen=null){
  101. $contextOptions = array(
  102. 'http' => array(
  103. 'user_agent'=>ini_get('user_agent')
  104. ),
  105. );
  106. if(defined('PROXY_URL') && $this->useProxy) {
  107. $contextOptions['http']['proxy'] = PROXY_URL;
  108. $contextOptions['http']['request_fulluri'] = true;
  109. if(is_null($context)){
  110. $context = stream_context_create($contextOptions);
  111. } else {
  112. $prevContext=$context;
  113. if(!stream_context_set_option($context,$contextOptions)){
  114. $context=$prevContext;
  115. };
  116. }
  117. }
  118. if(is_null($maxlen)){
  119. $content=@file_get_contents($url, $use_include_path, $context, $offset);
  120. }else{
  121. $content=@file_get_contents($url, $use_include_path, $context, $offset,$maxlen);
  122. }
  123. if($content===false){
  124. $this->message('Cant\'t download '.$url );
  125. }
  126. return $content;
  127. }
  128. protected function getSimpleHTMLDOM($url, $use_include_path = false, $context=null, $offset = 0, $maxLen=null, $lowercase = true, $forceTagsClosed=true, $target_charset = DEFAULT_TARGET_CHARSET, $stripRN=true, $defaultBRText=DEFAULT_BR_TEXT, $defaultSpanText=DEFAULT_SPAN_TEXT){
  129. $content=$this->getContents($url,$use_include_path,$context,$offset,$maxLen);
  130. return str_get_html($content,$lowercase,$forceTagsClosed,$target_charset,$stripRN,$defaultBRText,$defaultSpanText);
  131. }
  132. }
  133. /**
  134. * Extension of BridgeAbstract allowing caching of files downloaded over http files.
  135. * This is specially useful for sites from Gawker or Liberation networks, which allow pages excerpts top be viewed together on index, while full pages have to be downloaded
  136. * separately.
  137. * This class mainly provides a get_cached method which will will download the file from its remote location.
  138. * TODO allow file cache invalidation by touching files on access, and removing files/directories which have not been touched since ... a long time
  139. * After all, rss-bridge is not respaw, isn't it ?
  140. */
  141. abstract class HttpCachingBridgeAbstract extends BridgeAbstract {
  142. /**
  143. * Maintain locally cached versions of pages to download to avoid multiple doiwnloads.
  144. * A file name is generated by replacing all "/" by "_", and the file is saved below this bridge cache
  145. * @param url url to cache
  146. * @return content of file as string
  147. */
  148. public function get_cached($url) {
  149. $simplified_url = str_replace(["http://", "https://", "?", "&", "="], ["", "", "/", "/", "/"], $url);
  150. // TODO build this from the variable given to Cache
  151. $pageCacheDir = __DIR__ . '/../cache/'."pages/";
  152. $filename = $pageCacheDir.$simplified_url;
  153. if (substr($filename, -1) == '/') {
  154. $filename = $filename."index.html";
  155. }
  156. if(file_exists($filename)) {
  157. // $this->message("loading cached file from ".$filename." for page at url ".$url);
  158. // TODO touch file and its parent, and try to do neighbour deletion
  159. $this->refresh_in_cache($pageCacheDir, $filename);
  160. $content=file_get_contents($filename);
  161. } else {
  162. // $this->message("we have no local copy of ".$url." Downloading to ".$filename);
  163. $dir = substr($filename, 0, strrpos($filename, '/'));
  164. if(!is_dir($dir)) {
  165. // $this->message("creating directories for ".$dir);
  166. mkdir($dir, 0777, true);
  167. }
  168. $content=$this->getContents($url);
  169. if($content!==false){
  170. file_put_contents($filename,$content);
  171. }
  172. }
  173. return $content;
  174. }
  175. public function get_cached_time($url) {
  176. $simplified_url = str_replace(["http://", "https://", "?", "&", "="], ["", "", "/", "/", "/"], $url);
  177. // TODO build this from the variable given to Cache
  178. $pageCacheDir = __DIR__ . '/../cache/'."pages/";
  179. $filename = $pageCacheDir.$simplified_url;
  180. if (substr($filename, -1) == '/') {
  181. $filename = $filename."index.html";
  182. }
  183. if(!file_exists($filename)) {
  184. $this->get_cached($url);
  185. }
  186. return filectime($filename);
  187. }
  188. private function refresh_in_cache($pageCacheDir, $filename) {
  189. $currentPath = $filename;
  190. while(!$pageCacheDir==$currentPath) {
  191. touch($currentPath);
  192. $currentPath = dirname($currentPath);
  193. }
  194. }
  195. public function remove_from_cache($url) {
  196. $simplified_url = str_replace(["http://", "https://", "?", "&", "="], ["", "", "/", "/", "/"], $url);
  197. // TODO build this from the variable given to Cache
  198. $pageCacheDir = __DIR__ . '/../cache/'."pages/";
  199. $filename = realpath($pageCacheDir.$simplified_url);
  200. $this->message("removing from cache \"".$filename."\" WELL, NOT REALLY");
  201. // filename is NO GOOD
  202. // unlink($filename);
  203. }
  204. }
  205. class Bridge{
  206. static protected $dirBridge;
  207. public function __construct(){
  208. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  209. }
  210. /**
  211. * Checks if a bridge is an instantiable bridge.
  212. * @param string $nameBridge name of the bridge that you want to use
  213. * @return true if it is an instantiable bridge, false otherwise.
  214. */
  215. static public function isInstantiable($nameBridge) {
  216. $re = new ReflectionClass($nameBridge);
  217. return $re->IsInstantiable();
  218. }
  219. /**
  220. * Create a new bridge object
  221. * @param string $nameBridge Defined bridge name you want use
  222. * @return Bridge object dedicated
  223. */
  224. static public function create($nameBridge){
  225. if( !preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge)){
  226. throw new \InvalidArgumentException('Name bridge must be at least one uppercase follow or not by alphanumeric or dash characters.');
  227. }
  228. $nameBridge=$nameBridge.'Bridge';
  229. $pathBridge = self::getDir() . $nameBridge . '.php';
  230. if( !file_exists($pathBridge) ){
  231. throw new \Exception('The bridge you looking for does not exist. It should be at path '.$pathBridge);
  232. }
  233. require_once $pathBridge;
  234. if(Bridge::isInstantiable($nameBridge)) {
  235. return new $nameBridge();
  236. } else {
  237. return FALSE;
  238. }
  239. }
  240. static public function setDir($dirBridge){
  241. if( !is_string($dirBridge) ){
  242. throw new \InvalidArgumentException('Dir bridge must be a string.');
  243. }
  244. if( !file_exists($dirBridge) ){
  245. throw new \Exception('Dir bridge does not exist.');
  246. }
  247. self::$dirBridge = $dirBridge;
  248. }
  249. static public function getDir(){
  250. $dirBridge = self::$dirBridge;
  251. if( is_null($dirBridge) ){
  252. throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
  253. }
  254. return $dirBridge;
  255. }
  256. /**
  257. * Lists the available bridges.
  258. * @return array List of the bridges
  259. */
  260. static public function listBridges() {
  261. $pathDirBridge = self::getDir();
  262. $listBridge = array();
  263. $dirFiles = scandir($pathDirBridge);
  264. if( $dirFiles !== false ){
  265. foreach( $dirFiles as $fileName ) {
  266. if( preg_match('@^([^.]+)Bridge\.php$@U', $fileName, $out) ){
  267. $listBridge[] = $out[1];
  268. }
  269. }
  270. }
  271. return $listBridge;
  272. }
  273. static function isWhitelisted( $whitelist, $name ) {
  274. if(in_array($name, $whitelist) or in_array($name.'.php', $whitelist) or
  275. // DEPRECATED: the nameBridge notation will be removed in future releases
  276. in_array($name.'Bridge', $whitelist) or in_array($name.'Bridge.php', $whitelist) or
  277. count($whitelist) === 1 and trim($whitelist[0]) === '*')
  278. return TRUE;
  279. else
  280. return FALSE;
  281. }
  282. }
  283. abstract class RssExpander extends HttpCachingBridgeAbstract{
  284. public $name;
  285. public $uri;
  286. public $description;
  287. public function collectExpandableDatas(array $param, $name){
  288. if (empty($name)) {
  289. $this->returnServerError('There is no $name for this RSS expander');
  290. }
  291. // $this->message("Loading from ".$param['url']);
  292. // Notice WE DO NOT use cache here on purpose : we want a fresh view of the RSS stream each time
  293. $content=$this->getContents($name) or
  294. $this->returnServerError('Could not request '.$name);
  295. $rssContent = simplexml_load_string($content);
  296. // $this->message("loaded RSS from ".$param['url']);
  297. // TODO insert RSS format detection
  298. // we suppose for now, we have some RSS 2.0
  299. $this->collect_RSS_2_0_data($rssContent);
  300. }
  301. protected function collect_RSS_2_0_data($rssContent) {
  302. $rssContent = $rssContent->channel[0];
  303. // $this->message("RSS content is ===========\n".var_export($rssContent, true)."===========");
  304. $this->load_RSS_2_0_feed_data($rssContent);
  305. foreach($rssContent->item as $item) {
  306. // $this->message("parsing item ".var_export($item, true));
  307. $this->items[] = $this->parseRSSItem($item);
  308. }
  309. }
  310. protected function RSS_2_0_time_to_timestamp($item) {
  311. return DateTime::createFromFormat('D, d M Y H:i:s e', $item->pubDate)->getTimestamp();
  312. }
  313. // TODO set title, link, description, language, and so on
  314. protected function load_RSS_2_0_feed_data($rssContent) {
  315. $this->name = trim($rssContent->title);
  316. $this->uri = trim($rssContent->link);
  317. $this->description = trim($rssContent->description);
  318. }
  319. /**
  320. * Method should return, from a source RSS item given by lastRSS, one of our Items objects
  321. * @param $item the input rss item
  322. * @return a RSS-Bridge Item, with (hopefully) the whole content)
  323. */
  324. abstract protected function parseRSSItem($item);
  325. public function getDescription() {
  326. return $this->description;
  327. }
  328. }