FacebookBridge.php 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. <?php
  2. class FacebookBridge extends BridgeAbstract {
  3. const MAINTAINER = 'teromene';
  4. const NAME = 'Facebook';
  5. const URI = 'https://www.facebook.com/';
  6. const CACHE_TIMEOUT = 300; // 5min
  7. const DESCRIPTION = 'Input a page title or a profile log. For a profile log,
  8. please insert the parameter as follow : myExamplePage/132621766841117';
  9. const PARAMETERS = array( array(
  10. 'u' => array(
  11. 'name' => 'Username',
  12. 'required' => true
  13. ),
  14. 'media_type' => array(
  15. 'name' => 'Media type',
  16. 'type' => 'list',
  17. 'required' => false,
  18. 'values' => array(
  19. 'All' => 'all',
  20. 'Video' => 'video',
  21. 'No Video' => 'novideo'
  22. ),
  23. 'defaultValue' => 'all'
  24. )
  25. ));
  26. private $authorName = '';
  27. public function collectData(){
  28. //Extract a string using start and end delimiters
  29. function extractFromDelimiters($string, $start, $end){
  30. if(strpos($string, $start) !== false) {
  31. $section_retrieved = substr($string, strpos($string, $start) + strlen($start));
  32. $section_retrieved = substr($section_retrieved, 0, strpos($section_retrieved, $end));
  33. return $section_retrieved;
  34. }
  35. return false;
  36. }
  37. //Utility function for cleaning a Facebook link
  38. $unescape_fb_link = function($matches){
  39. if(is_array($matches) && count($matches) > 1) {
  40. $link = $matches[1];
  41. if(strpos($link, '/') === 0)
  42. $link = self::URI . $link . '"';
  43. if(strpos($link, 'facebook.com/l.php?u=') !== false)
  44. $link = urldecode(extractFromDelimiters($link, 'facebook.com/l.php?u=', '&'));
  45. return ' href="' . $link . '"';
  46. }
  47. };
  48. //Utility function for converting facebook emoticons
  49. $unescape_fb_emote = function($matches){
  50. static $facebook_emoticons = array(
  51. 'smile' => ':)',
  52. 'frown' => ':(',
  53. 'tongue' => ':P',
  54. 'grin' => ':D',
  55. 'gasp' => ':O',
  56. 'wink' => ';)',
  57. 'pacman' => ':<',
  58. 'grumpy' => '>_<',
  59. 'unsure' => ':/',
  60. 'cry' => ':\'(',
  61. 'kiki' => '^_^',
  62. 'glasses' => '8-)',
  63. 'sunglasses' => 'B-)',
  64. 'heart' => '<3',
  65. 'devil' => ']:D',
  66. 'angel' => '0:)',
  67. 'squint' => '-_-',
  68. 'confused' => 'o_O',
  69. 'upset' => 'xD',
  70. 'colonthree' => ':3',
  71. 'like' => '&#x1F44D;');
  72. $len = count($matches);
  73. if ($len > 1)
  74. for ($i = 1; $i < $len; $i++)
  75. foreach ($facebook_emoticons as $name => $emote)
  76. if ($matches[$i] === $name)
  77. return $emote;
  78. return $matches[0];
  79. };
  80. $html = null;
  81. //Handle captcha response sent by the viewer
  82. if (isset($_POST['captcha_response'])) {
  83. if (session_status() == PHP_SESSION_NONE)
  84. session_start();
  85. if (isset($_SESSION['captcha_fields'], $_SESSION['captcha_action'])) {
  86. $captcha_action = $_SESSION['captcha_action'];
  87. $captcha_fields = $_SESSION['captcha_fields'];
  88. $captcha_fields['captcha_response'] = preg_replace("/[^a-zA-Z0-9]+/", "", $_POST['captcha_response']);
  89. $http_options = array(
  90. 'http' => array(
  91. 'method' => 'POST',
  92. 'user_agent' => ini_get('user_agent'),
  93. 'header' => array("Content-type:
  94. application/x-www-form-urlencoded\r\nReferer: $captcha_action\r\nCookie: noscript=1\r\n"),
  95. 'content' => http_build_query($captcha_fields)
  96. ),
  97. );
  98. $context = stream_context_create($http_options);
  99. $html = getContents($captcha_action, false, $context);
  100. if($html === false) {
  101. returnServerError('Failed to submit captcha response back to Facebook');
  102. }
  103. unset($_SESSION['captcha_fields']);
  104. $html = str_get_html($html);
  105. }
  106. unset($_SESSION['captcha_fields']);
  107. unset($_SESSION['captcha_action']);
  108. }
  109. //Retrieve page contents
  110. if(is_null($html)) {
  111. $http_options = array(
  112. 'http' => array(
  113. 'method' => 'GET',
  114. 'user_agent' => ini_get('user_agent'),
  115. 'header' => 'Accept-Language: ' . getEnv('HTTP_ACCEPT_LANGUAGE') . "\r\n"
  116. )
  117. );
  118. $context = stream_context_create($http_options);
  119. if(!strpos($this->getInput('u'), "/")) {
  120. $html = getSimpleHTMLDOM(self::URI . urlencode($this->getInput('u')) . '?_fb_noscript=1',
  121. false,
  122. $context)
  123. or returnServerError('No results for this query.');
  124. } else {
  125. $html = getSimpleHTMLDOM(self::URI . 'pages/' . $this->getInput('u') . '?_fb_noscript=1',
  126. false,
  127. $context)
  128. or returnServerError('No results for this query.');
  129. }
  130. }
  131. //Handle captcha form?
  132. $captcha = $html->find('div.captcha_interstitial', 0);
  133. if (!is_null($captcha)) {
  134. //Save form for submitting after getting captcha response
  135. if (session_status() == PHP_SESSION_NONE)
  136. session_start();
  137. $captcha_fields = array();
  138. foreach ($captcha->find('input, button') as $input)
  139. $captcha_fields[$input->name] = $input->value;
  140. $_SESSION['captcha_fields'] = $captcha_fields;
  141. $_SESSION['captcha_action'] = $captcha->find('form', 0)->action;
  142. //Show captcha filling form to the viewer, proxying the captcha image
  143. $img = base64_encode(getContents($captcha->find('img', 0)->src));
  144. header('HTTP/1.1 500 ' . Http::getMessageForCode(500));
  145. header('Content-Type: text/html');
  146. $message = <<<EOD
  147. <form method="post" action="?{$_SERVER['QUERY_STRING']}">
  148. <h2>Facebook captcha challenge</h2>
  149. <p>Unfortunately, rss-bridge cannot fetch the requested page.<br />
  150. Facebook wants rss-bridge to resolve the following captcha:</p>
  151. <p><img src="data:image/png;base64,{$img}" /></p>
  152. <p><b>Response:</b> <input name="captcha_response" placeholder="please fill in" />
  153. <input type="submit" value="Submit!" /></p>
  154. </form>
  155. EOD;
  156. die($message);
  157. }
  158. //No captcha? We can carry on retrieving page contents :)
  159. $element = $html
  160. ->find('#pagelet_timeline_main_column')[0]
  161. ->children(0)
  162. ->children(0)
  163. ->children(0)
  164. ->next_sibling()
  165. ->children(0);
  166. if(isset($element)) {
  167. $author = str_replace(' | Facebook', '', $html->find('title#pageTitle', 0)->innertext);
  168. $profilePic = 'https://graph.facebook.com/'
  169. . $this->getInput('u')
  170. . '/picture?width=200&amp;height=200';
  171. $this->authorName = $author;
  172. foreach($element->children() as $cell) {
  173. // Manage summary posts
  174. if(strpos($cell->class, '_3xaf') !== false) {
  175. $posts = $cell->children();
  176. } else {
  177. $posts = array($cell);
  178. }
  179. foreach($posts as $post) {
  180. // Check media type
  181. switch($this->getInput('media_type')) {
  182. case 'all': break;
  183. case 'video':
  184. if(empty($post->find('[aria-label=Video]'))) continue 2;
  185. break;
  186. case 'novideo':
  187. if(!empty($post->find('[aria-label=Video]'))) continue 2;
  188. break;
  189. default: break;
  190. }
  191. $item = array();
  192. if(count($post->find('abbr')) > 0) {
  193. //Retrieve post contents
  194. $content = preg_replace(
  195. '/(?i)><div class=\"clearfix([^>]+)>(.+?)div\ class=\"userContent\"/i',
  196. '',
  197. $post);
  198. $content = preg_replace(
  199. '/(?i)><div class=\"_59tj([^>]+)>(.+?)<\/div><\/div><a/i',
  200. '',
  201. $content);
  202. $content = preg_replace(
  203. '/(?i)><div class=\"_3dp([^>]+)>(.+?)div\ class=\"[^u]+userContent\"/i',
  204. '',
  205. $content);
  206. $content = preg_replace(
  207. '/(?i)><div class=\"_4l5([^>]+)>(.+?)<\/div>/i',
  208. '',
  209. $content);
  210. //Remove html nodes, keep only img, links, basic formatting
  211. $content = strip_tags($content, '<a><img><i><u><br><p>');
  212. //Adapt link hrefs: convert relative links into absolute links and bypass external link redirection
  213. $content = preg_replace_callback('/ href=\"([^"]+)\"/i', $unescape_fb_link, $content);
  214. //Clean useless html tag properties and fix link closing tags
  215. foreach (array(
  216. 'onmouseover',
  217. 'onclick',
  218. 'target',
  219. 'ajaxify',
  220. 'tabindex',
  221. 'class',
  222. 'style',
  223. 'data-[^=]*',
  224. 'aria-[^=]*',
  225. 'role',
  226. 'rel',
  227. 'id') as $property_name)
  228. $content = preg_replace('/ ' . $property_name . '=\"[^"]*\"/i', '', $content);
  229. $content = preg_replace('/<\/a [^>]+>/i', '</a>', $content);
  230. //Convert textual representation of emoticons eg
  231. //"<i><u>smile emoticon</u></i>" back to ASCII emoticons eg ":)"
  232. $content = preg_replace_callback(
  233. '/<i><u>([^ <>]+) ([^<>]+)<\/u><\/i>/i',
  234. $unescape_fb_emote,
  235. $content
  236. );
  237. //Retrieve date of the post
  238. $date = $post->find("abbr")[0];
  239. if(isset($date) && $date->hasAttribute('data-utime')) {
  240. $date = $date->getAttribute('data-utime');
  241. } else {
  242. $date = 0;
  243. }
  244. //Build title from username and content
  245. $title = $author;
  246. if(strlen($title) > 24)
  247. $title = substr($title, 0, strpos(wordwrap($title, 24), "\n")) . '...';
  248. $title = $title . ' | ' . strip_tags($content);
  249. if(strlen($title) > 64)
  250. $title = substr($title, 0, strpos(wordwrap($title, 64), "\n")) . '...';
  251. //Build and add final item
  252. $item['uri'] = self::URI . $post->find('abbr')[0]->parent()->getAttribute('href');
  253. $item['content'] = $content;
  254. $item['title'] = $title;
  255. $item['author'] = $author;
  256. $item['timestamp'] = $date;
  257. $this->items[] = $item;
  258. }
  259. }
  260. }
  261. }
  262. }
  263. public function getName(){
  264. if(!empty($this->authorName)) {
  265. return isset($this->extraInfos['name']) ? $this->extraInfos['name'] : $this->authorName
  266. . ' - Facebook Bridge';
  267. }
  268. return parent::getName();
  269. }
  270. }