Bridge.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401
  1. <?php
  2. class Bridge {
  3. static protected $dirBridge;
  4. public function __construct(){
  5. throw new \LogicException('Please use ' . __CLASS__ . '::create for new object.');
  6. }
  7. /**
  8. * Checks if a bridge is an instantiable bridge.
  9. * @param string $nameBridge name of the bridge that you want to use
  10. * @return true if it is an instantiable bridge, false otherwise.
  11. */
  12. static public function isInstantiable($nameBridge){
  13. $re = new ReflectionClass($nameBridge);
  14. return $re->IsInstantiable();
  15. }
  16. /**
  17. * Create a new bridge object
  18. * @param string $nameBridge Defined bridge name you want use
  19. * @return Bridge object dedicated
  20. */
  21. static public function create($nameBridge){
  22. if(!preg_match('@^[A-Z][a-zA-Z0-9-]*$@', $nameBridge)){
  23. $message = <<<EOD
  24. 'nameBridge' must start with one uppercase character followed or not by
  25. alphanumeric or dash characters!
  26. EOD;
  27. throw new \InvalidArgumentException($message);
  28. }
  29. $nameBridge = $nameBridge . 'Bridge';
  30. $pathBridge = self::getDir() . $nameBridge . '.php';
  31. if(!file_exists($pathBridge)){
  32. throw new \Exception('The bridge you looking for does not exist. It should be at path ' . $pathBridge);
  33. }
  34. require_once $pathBridge;
  35. if(Bridge::isInstantiable($nameBridge)){
  36. return new $nameBridge();
  37. } else {
  38. return false;
  39. }
  40. }
  41. static public function setDir($dirBridge){
  42. if(!is_string($dirBridge)){
  43. throw new \InvalidArgumentException('Dir bridge must be a string.');
  44. }
  45. if(!file_exists($dirBridge)){
  46. throw new \Exception('Dir bridge does not exist.');
  47. }
  48. self::$dirBridge = $dirBridge;
  49. }
  50. static public function getDir(){
  51. $dirBridge = self::$dirBridge;
  52. if(is_null($dirBridge)){
  53. throw new \LogicException(__CLASS__ . ' class need to know bridge path !');
  54. }
  55. return $dirBridge;
  56. }
  57. /**
  58. * Lists the available bridges.
  59. * @return array List of the bridges
  60. */
  61. static public function listBridges(){
  62. $pathDirBridge = self::getDir();
  63. $listBridge = array();
  64. $dirFiles = scandir($pathDirBridge);
  65. if($dirFiles !== false){
  66. foreach($dirFiles as $fileName){
  67. if(preg_match('@^([^.]+)Bridge\.php$@U', $fileName, $out)){
  68. $listBridge[] = $out[1];
  69. }
  70. }
  71. }
  72. return $listBridge;
  73. }
  74. static public function isWhitelisted($whitelist, $name){
  75. if(in_array($name, $whitelist)
  76. or in_array($name . '.php', $whitelist)
  77. or in_array($name . 'Bridge', $whitelist) // DEPRECATED
  78. or in_array($name . 'Bridge.php', $whitelist) // DEPRECATED
  79. or count($whitelist) === 1 and trim($whitelist[0]) === '*'){
  80. return true;
  81. } else {
  82. return false;
  83. }
  84. }
  85. }
  86. interface BridgeInterface {
  87. public function collectData(array $param);
  88. public function getCacheDuration();
  89. public function loadMetadatas();
  90. public function getName();
  91. public function getURI();
  92. }
  93. abstract class BridgeAbstract implements BridgeInterface {
  94. protected $cache;
  95. protected $items = array();
  96. public $name = 'Unnamed bridge';
  97. public $uri = '';
  98. public $description = 'No description provided';
  99. public $maintainer = 'No maintainer';
  100. public $useProxy = true;
  101. public $parameters = array();
  102. protected function returnError($message, $code){
  103. throw new \HttpException($message, $code);
  104. }
  105. protected function returnClientError($message){
  106. $this->returnError($message, 400);
  107. }
  108. protected function returnServerError($message){
  109. $this->returnError($message, 500);
  110. }
  111. /**
  112. * Return items stored in the bridge
  113. * @return mixed
  114. */
  115. public function getDatas(){
  116. return $this->items;
  117. }
  118. /**
  119. * Defined datas with parameters depending choose bridge
  120. * Note : you can define a cache with "setCache"
  121. * @param array $param $_REQUEST, $_GET, $_POST, or array with expected
  122. * bridge paramters
  123. */
  124. public function setDatas(array $param){
  125. if(!is_null($this->cache)){
  126. $this->cache->prepare($param);
  127. $time = $this->cache->getTime();
  128. } else {
  129. $time = false;
  130. }
  131. if($time !== false && (time() - $this->getCacheDuration() < $time)){
  132. $this->items = $this->cache->loadData();
  133. } else {
  134. $this->collectData($param);
  135. if(!is_null($this->cache)){
  136. $this->cache->saveData($this->getDatas());
  137. }
  138. }
  139. }
  140. public function getName(){
  141. return $this->name;
  142. }
  143. public function getURI(){
  144. return $this->uri;
  145. }
  146. public function getCacheDuration(){
  147. return 3600;
  148. }
  149. public function setCache(\CacheAbstract $cache){
  150. $this->cache = $cache;
  151. }
  152. public function debugMessage($text){
  153. if(!file_exists('DEBUG')) {
  154. return;
  155. }
  156. $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS, 3);
  157. $calling = $backtrace[2];
  158. $message = $calling['file'] . ':'
  159. . $calling['line'] . ' class '
  160. . get_class($this) . '->'
  161. . $calling['function'] . ' - '
  162. . $text;
  163. error_log($message);
  164. }
  165. protected function getContents($url
  166. , $use_include_path = false
  167. , $context = null
  168. , $offset = 0
  169. , $maxlen = null){
  170. $contextOptions = array(
  171. 'http' => array(
  172. 'user_agent' => ini_get('user_agent')
  173. ),
  174. );
  175. if(defined('PROXY_URL') && $this->useProxy){
  176. $contextOptions['http']['proxy'] = PROXY_URL;
  177. $contextOptions['http']['request_fulluri'] = true;
  178. if(is_null($context)){
  179. $context = stream_context_create($contextOptions);
  180. } else {
  181. $prevContext=$context;
  182. if(!stream_context_set_option($context, $contextOptions)){
  183. $context = $prevContext;
  184. }
  185. }
  186. }
  187. if(is_null($maxlen)){
  188. $content = @file_get_contents($url, $use_include_path, $context, $offset);
  189. } else {
  190. $content = @file_get_contents($url, $use_include_path, $context, $offset, $maxlen);
  191. }
  192. if($content === false)
  193. $this->debugMessage('Cant\'t download ' . $url);
  194. return $content;
  195. }
  196. protected function getSimpleHTMLDOM($url
  197. , $use_include_path = false
  198. , $context = null
  199. , $offset = 0
  200. , $maxLen = null
  201. , $lowercase = true
  202. , $forceTagsClosed = true
  203. , $target_charset = DEFAULT_TARGET_CHARSET
  204. , $stripRN = true
  205. , $defaultBRText = DEFAULT_BR_TEXT
  206. , $defaultSpanText = DEFAULT_SPAN_TEXT){
  207. $content = $this->getContents($url, $use_include_path, $context, $offset, $maxLen);
  208. return str_get_html($content
  209. , $lowercase
  210. , $forceTagsClosed
  211. , $target_charset
  212. , $stripRN
  213. , $defaultBRText
  214. , $defaultSpanText);
  215. }
  216. }
  217. /**
  218. * Extension of BridgeAbstract allowing caching of files downloaded over http.
  219. * TODO allow file cache invalidation by touching files on access, and removing
  220. * files/directories which have not been touched since ... a long time
  221. */
  222. abstract class HttpCachingBridgeAbstract extends BridgeAbstract {
  223. /**
  224. * Maintain locally cached versions of pages to download, to avoid multiple downloads.
  225. * @param url url to cache
  226. * @return content of the file as string
  227. */
  228. public function get_cached($url){
  229. // TODO build this from the variable given to Cache
  230. $cacheDir = __DIR__ . '/../cache/pages/';
  231. $filepath = $this->buildCacheFilePath($url, $cacheDir);
  232. if(file_exists($filepath)){
  233. $this->debugMessage('loading cached file from ' . $filepath . ' for page at url ' . $url);
  234. // TODO touch file and its parent, and try to do neighbour deletion
  235. $this->refresh_in_cache($cacheDir, $filepath);
  236. $content = file_get_contents($filepath);
  237. } else {
  238. $this->debugMessage('we have no local copy of ' . $url . ' Downloading to ' . $filepath);
  239. $dir = substr($filepath, 0, strrpos($filepath, '/'));
  240. if(!is_dir($dir)){
  241. $this->debugMessage('creating directories for ' . $dir);
  242. mkdir($dir, 0777, true);
  243. }
  244. $content = $this->getContents($url);
  245. if($content !== false){
  246. file_put_contents($filepath, $content);
  247. }
  248. }
  249. return $content;
  250. }
  251. public function get_cached_time($url){
  252. // TODO build this from the variable given to Cache
  253. $cacheDir = __DIR__ . '/../cache/pages/';
  254. $filepath = $this->buildCacheFilePath($url, $cacheDir);
  255. if(!file_exists($filepath)){
  256. $this->get_cached($url);
  257. }
  258. return filectime($filepath);
  259. }
  260. private function refresh_in_cache($cacheDir, $filepath){
  261. $currentPath = $filepath;
  262. while(!$cacheDir == $currentPath){
  263. touch($currentPath);
  264. $currentPath = dirname($currentPath);
  265. }
  266. }
  267. private function buildCacheFilePath($url, $cacheDir){
  268. $simplified_url = str_replace(
  269. ['http://', 'https://', '?', '&', '='],
  270. ['', '', '/', '/', '/'],
  271. $url);
  272. if(substr($cacheDir, -1) !== '/'){
  273. $cacheDir .= '/';
  274. }
  275. $filepath = $cacheDir . $simplified_url;
  276. if(substr($filepath, -1) === '/'){
  277. $filepath .= 'index.html';
  278. }
  279. return $filepath;
  280. }
  281. public function remove_from_cache($url){
  282. // TODO build this from the variable given to Cache
  283. $cacheDir = __DIR__ . '/../cache/pages/';
  284. $filepath = $this->buildCacheFilePath($url, $cacheDir);
  285. $this->debugMessage('removing from cache \'' . $filepath . '\' WELL, NOT REALLY');
  286. // unlink($filepath);
  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. }