Bridge.php 12 KB

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