summaryrefslogtreecommitdiff
path: root/bridges/FacebookBridge.php
blob: 08b3a38a97f49d01da0fd138be468feabfa4f9c7 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
<?php
class FacebookBridge extends BridgeAbstract {

	const MAINTAINER = 'teromene, logmanoriginal';
	const NAME = 'Facebook Bridge';
	const URI = 'https://www.facebook.com/';
	const CACHE_TIMEOUT = 300; // 5min
	const DESCRIPTION = 'Input a page title or a profile log. For a profile log,
 please insert the parameter as follow : myExamplePage/132621766841117';

	const PARAMETERS = array(
		'User' => array(
			'u' => array(
				'name' => 'Username',
				'required' => true
			),
			'media_type' => array(
				'name' => 'Media type',
				'type' => 'list',
				'required' => false,
				'values' => array(
					'All' => 'all',
					'Video' => 'video',
					'No Video' => 'novideo'
				),
				'defaultValue' => 'all'
			),
			'skip_reviews' => array(
				'name' => 'Skip reviews',
				'type' => 'checkbox',
				'required' => false,
				'defaultValue' => false,
				'title' => 'Feed includes reviews when checked'
			)
		),
		'Group' => array(
			'g' => array(
				'name' => 'Group',
				'type' => 'text',
				'required' => true,
				'exampleValue' => 'https://www.facebook.com/groups/743149642484225',
				'title' => 'Insert group name or facebook group URL'
			)
		),
		'global' => array(
			'limit' => array(
				'name' => 'Limit',
				'type' => 'number',
				'required' => false,
				'title' => 'Specify the number of items to return (default: -1)',
				'defaultValue' => -1
			)
		)
	);

	private $authorName = '';
	private $groupName = '';

	public function getIcon() {
		return 'https://static.xx.fbcdn.net/rsrc.php/yo/r/iRmz9lCMBD2.ico';
	}

	public function getName(){

		switch($this->queriedContext) {

			case 'User':
				if(!empty($this->authorName)) {
					return isset($this->extraInfos['name']) ? $this->extraInfos['name'] : $this->authorName
					. ' - ' . static::NAME;
				}
				break;

			case 'Group':
				if(!empty($this->groupName)) {
					return $this->groupName . ' - ' . static::NAME;
				}
				break;

		}

		return parent::getName();
	}

	public function getURI() {
		$uri = self::URI;

		switch($this->queriedContext) {

			case 'Group':
				// Discover groups via	https://www.facebook.com/groups/
				// Example group:		https://www.facebook.com/groups/sailors.worldwide
				$uri .= 'groups/' . $this->sanitizeGroup(filter_var($this->getInput('g'), FILTER_SANITIZE_URL));
				break;

			case 'User':
				// Example user 1:		https://www.facebook.com/artetv/
				// Example user 2:		artetv
				$user = $this->sanitizeUser($this->getInput('u'));

				if(!strpos($user, '/')) {
					$uri .= urlencode($user) . '/posts';
				} else {
					$uri .= 'pages/' . $user;
				}

				break;

		}

		// Request the mobile version to reduce page size (no javascript)
		// More information: https://stackoverflow.com/a/11103592
		return $uri .= '?_fb_noscript=1';
	}

	public function collectData() {

		switch($this->queriedContext) {

			case 'Group':
				$this->collectGroupData();
				break;

			case 'User':
				$this->collectUserData();
				break;

			default:
				returnClientError('Unknown context: "' . $this->queriedContext . '"!');

		}

		$limit = $this->getInput('limit') ?: -1;

		if($limit > 0 && count($this->items) > $limit) {
			$this->items = array_slice($this->items, 0, $limit);
		}

	}

	#region Group

	private function collectGroupData() {

		if(getEnv('HTTP_ACCEPT_LANGUAGE')) {
			$header = array('Accept-Language: ' . getEnv('HTTP_ACCEPT_LANGUAGE'));
		} else {
			$header = array();
		}

		$html = getSimpleHTMLDOM($this->getURI(), $header)
			or returnServerError('Failed loading facebook page: ' . $this->getURI());

		if(!$this->isPublicGroup($html)) {
			returnClientError('This group is not public! RSS-Bridge only supports public groups!');
		}

		defaultLinkTo($html, substr(self::URI, 0, strlen(self::URI) - 1));

		$this->groupName = $this->extractGroupName($html);

		$posts = $html->find('div.userContentWrapper')
			or returnServerError('Failed finding posts!');

		foreach($posts as $post) {

			$item = array();

			$item['uri'] = $this->extractGroupURI($post);
			$item['title'] = $this->extractGroupTitle($post);
			$item['author'] = $this->extractGroupAuthor($post);
			$item['content'] = $this->extractGroupContent($post);
			$item['timestamp'] = $this->extractGroupTimestamp($post);
			$item['enclosures'] = $this->extractGroupEnclosures($post);

			$this->items[] = $item;

		}

	}

	private function sanitizeGroup($group) {

		if(filter_var(
			$group,
			FILTER_VALIDATE_URL, FILTER_FLAG_PATH_REQUIRED)) {
			// User provided a URL

			$urlparts = parse_url($group);

			if($urlparts['host'] !== parse_url(self::URI)['host']
			&& 'www.' . $urlparts['host'] !== parse_url(self::URI)['host']) {

				returnClientError('The host you provided is invalid! Received "'
				. $urlparts['host']
				. '", expected "'
				. parse_url(self::URI)['host']
				. '"!');

			}

			return explode('/', $urlparts['path'])[2];

		} elseif(strpos($group, '/') !== false) {
			returnClientError('The group you provided is invalid: ' . $group);
		} else {
			return $group;
		}

	}

	private function isPublicGroup($html) {

		// Facebook redirects to the groups about page for non-public groups
		$about = $html->find('#pagelet_group_about', 0);

		return !($about);

	}

	private function extractGroupName($html) {

		$ogtitle = $html->find('meta[property="og:title"]', 0)
			or returnServerError('Unable to find group title!');

		return html_entity_decode($ogtitle->content, ENT_QUOTES);
	}

	private function extractGroupURI($post) {

		$elements = $post->find('a')
			or returnServerError('Unable to find URI!');

		foreach($elements as $anchor) {

			// Find the one that is a permalink
			if(strpos($anchor->href, 'permalink') !== false) {
				return $anchor->href;
			}

		}

		return null;

	}

	private function extractGroupContent($post) {

		$content = $post->find('div.userContent', 0)
			or returnServerError('Unable to find user content!');

		return $content->innertext . $content->next_sibling()->innertext;

	}

	private function extractGroupTimestamp($post) {

		$element = $post->find('abbr[data-utime]', 0)
			or returnServerError('Unable to find timestamp!');

		return $element->getAttribute('data-utime');

	}

	private function extractGroupAuthor($post) {

		$element = $post->find('img', 0)
			or returnServerError('Unable to find author information!');

		return $element->{'aria-label'};

	}

	private function extractGroupEnclosures($post) {

		$elements = $post->find('div.userContent', 0)->next_sibling()->find('img');

		$enclosures = array();

		foreach($elements as $enclosure) {
			$enclosures[] = $enclosure->src;
		}

		return empty($enclosures) ? null : $enclosures;

	}

	private function extractGroupTitle($post) {

		$element = $post->find('h5', 0)
			or returnServerError('Unable to find title!');

		if(strpos($element->plaintext, 'shared') === false) {

			$content = strip_tags($this->extractGroupContent($post));

			return $this->extractGroupAuthor($post)
			. ' posted: '
			. substr(
					$content,
					0,
					strpos(wordwrap($content, 64), "\n")
				)
			. '...';

		}

		return $element->plaintext;

	}

	#endregion (Group)

	#region User

	/**
	 * Checks if $user is a valid username or URI and returns the username
	 */
	private function sanitizeUser($user) {
		if (filter_var($user, FILTER_VALIDATE_URL)) {

			$urlparts = parse_url($user);

			if($urlparts['host'] !== parse_url(self::URI)['host']) {
				returnClientError('The host you provided is invalid! Received "'
				. $urlparts['host']
				. '", expected "'
				. parse_url(self::URI)['host']
				. '"!');
			}

			if(!array_key_exists('path', $urlparts)
			|| $urlparts['path'] === '/') {
				returnClientError('The URL you provided doesn\'t contain the user name!');
			}

			return explode('/', $urlparts['path'])[1];

		} else {

			// First character cannot be a forward slash
			if(strpos($user, '/') === 0) {
				returnClientError('Remove leading slash "/" from the username!');
			}

			return $user;

		}
	}

	/**
	 * Bypass external link redirection
	 */
	private function unescape_fb_link($content){
		return preg_replace_callback('/ href=\"([^"]+)\"/i', function($matches){
			if(is_array($matches) && count($matches) > 1) {

				$link = $matches[1];

				if(strpos($link, 'facebook.com/l.php?u=') !== false)
					$link = urldecode(extractFromDelimiters($link, 'facebook.com/l.php?u=', '&'));

				return ' href="' . $link . '"';

			}
		}, $content);
	}

	/**
	 * Remove Facebook's tracking code
	 */
	private function remove_tracking_codes($content){
		return preg_replace_callback('/ href=\"([^"]+)\"/i', function($matches){
			if(is_array($matches) && count($matches) > 1) {

				$link = $matches[1];

				if(strpos($link, 'facebook.com') !== false) {
					if(strpos($link, '?') !== false) {
						$link = substr($link, 0, strpos($link, '?'));
					}
				}
				return ' href="' . $link . '"';

			}
		}, $content);
	}

	/**
	 * Convert textual representation of emoticons back to ASCII emoticons.
	 * i.e. "<i><u>smile emoticon</u></i>" => ":)"
	 */
	private function unescape_fb_emote($content){
		return preg_replace_callback('/<i><u>([^ <>]+) ([^<>]+)<\/u><\/i>/i', function($matches){
				static $facebook_emoticons = array(
					'smile' => ':)',
					'frown' => ':(',
					'tongue' => ':P',
					'grin' => ':D',
					'gasp' => ':O',
					'wink' => ';)',
					'pacman' => ':<',
					'grumpy' => '>_<',
					'unsure' => ':/',
					'cry' => ':\'(',
					'kiki' => '^_^',
					'glasses' => '8-)',
					'sunglasses' => 'B-)',
					'heart' => '<3',
					'devil' => ']:D',
					'angel' => '0:)',
					'squint' => '-_-',
					'confused' => 'o_O',
					'upset' => 'xD',
					'colonthree' => ':3',
					'like' => '&#x1F44D;');

				$len = count($matches);

				if ($len > 1)
					for ($i = 1; $i < $len; $i++)
						foreach ($facebook_emoticons as $name => $emote)
							if ($matches[$i] === $name)
								return $emote;

				return $matches[0];
			}, $content);
	}

	/**
	 * Returns the captcha message for the given captcha
	 */
	private function returnCaptchaMessage($captcha) {
		// Save form for submitting after getting captcha response
		if (session_status() == PHP_SESSION_NONE) {
			session_start();
		}

		$captcha_fields = array();

		foreach ($captcha->find('input, button') as $input) {
			$captcha_fields[$input->name] = $input->value;
		}

		$_SESSION['captcha_fields'] = $captcha_fields;
		$_SESSION['captcha_action'] = $captcha->find('form', 0)->action;

		// Show captcha filling form to the viewer, proxying the captcha image
		$img = base64_encode(getContents($captcha->find('img', 0)->src));

		header('Content-Type: text/html', true, 500);

		$message = <<<EOD
<form method="post" action="?{$_SERVER['QUERY_STRING']}">
<h2>Facebook captcha challenge</h2>
<p>Unfortunately, rss-bridge cannot fetch the requested page.<br />
Facebook wants rss-bridge to resolve the following captcha:</p>
<p><img src="data:image/png;base64,{$img}" /></p>
<p><b>Response:</b> <input name="captcha_response" placeholder="please fill in" />
<input type="submit" value="Submit!" /></p>
</form>
EOD;

		die($message);
	}

	/**
	 * Checks if a capture response was received and tries to load the contents
	 * @return mixed null if no capture response was received, simplhtmldom document otherwise
	 */
	private function handleCaptchaResponse() {
		if (isset($_POST['captcha_response'])) {
			if (session_status() == PHP_SESSION_NONE)
				session_start();

			if (isset($_SESSION['captcha_fields'], $_SESSION['captcha_action'])) {
				$captcha_action = $_SESSION['captcha_action'];
				$captcha_fields = $_SESSION['captcha_fields'];
				$captcha_fields['captcha_response'] = preg_replace('/[^a-zA-Z0-9]+/', '', $_POST['captcha_response']);

				$header = array(
					'Content-type: application/x-www-form-urlencoded',
					'Referer: ' . $captcha_action,
					'Cookie: noscript=1'
				);

				$opts = array(
					CURLOPT_POST => 1,
					CURLOPT_POSTFIELDS => http_build_query($captcha_fields)
				);

				$html = getSimpleHTMLDOM($captcha_action, $header, $opts)
					or returnServerError('Failed to submit captcha response back to Facebook');

				return $html;
			}

			unset($_SESSION['captcha_fields']);
			unset($_SESSION['captcha_action']);
		}

		return null;
	}

	private function collectUserData(){

		$html = $this->handleCaptchaResponse();

		// Retrieve page contents
		if(is_null($html)) {

			if(getEnv('HTTP_ACCEPT_LANGUAGE')) {
				$header = array('Accept-Language: ' . getEnv('HTTP_ACCEPT_LANGUAGE'));
			} else {
				$header = array();
			}

			$html = getSimpleHTMLDOM($this->getURI(), $header)
				or returnServerError('No results for this query.');

		}

		// Handle captcha form?
		$captcha = $html->find('div.captcha_interstitial', 0);

		if (!is_null($captcha)) {
			$this->returnCaptchaMessage($captcha);
		}

		// No captcha? We can carry on retrieving page contents :)
		// First, we check wether the page is public or not
		$loginForm = $html->find('._585r', 0);

		if($loginForm != null) {
			returnServerError('You must be logged in to view this page. This is not supported by RSS-Bridge.');
		}

		$element = $html
		->find('#pagelet_timeline_main_column')[0]
		->children(0)
		->children(0)
		->next_sibling()
		->children(0);

		if(isset($element)) {

			$author = str_replace(' - Posts | Facebook', '', $html->find('title#pageTitle', 0)->innertext);

			$profilePic = $html->find('meta[property="og:image"]', 0)->content;

			$this->authorName = $author;

			foreach($element->children() as $cell) {
				// Manage summary posts
				if(strpos($cell->class, '_3xaf') !== false) {
					$posts = $cell->children();
				} else {
					$posts = array($cell);
				}

				// Optionally skip reviews
				if($this->getInput('skip_reviews')
				&& !is_null($cell->find('#review_composer_container', 0))) {
					continue;
				}

				foreach($posts as $post) {
					// Check media type
					switch($this->getInput('media_type')) {
						case 'all': break;
						case 'video':
							if(empty($post->find('[aria-label=Video]'))) continue 2;
							break;
						case 'novideo':
							if(!empty($post->find('[aria-label=Video]'))) continue 2;
							break;
						default: break;
					}

					$item = array();

					if(count($post->find('abbr')) > 0) {

						$content = $post->find('.userContentWrapper', 0);

						// This array specifies filters applied to all posts in order of appearance
						$content_filters = array(
							'._5mly', // Remove embedded videos (the preview image remains)
							'._2ezg', // Remove "Views ..."
							'.hidden_elem', // Remove hidden elements (they are hidden anyway)
							'.timestampContent', // Remove relative timestamp
							'._6spk', // Remove redundant separator
						);

						foreach($content_filters as $filter) {
							foreach($content->find($filter) as $subject) {
								$subject->outertext = '';
							}
						}

						// Change origin tag for embedded media from div to paragraph
						foreach($content->find('._59tj') as $subject) {
							$subject->outertext = '<p>' . $subject->innertext . '</p>';
						}

						// Change title tag for embedded media from anchor to paragraph
						foreach($content->find('._3n1k a') as $anchor) {
							$anchor->outertext = '<p>' . $anchor->innertext . '</p>';
						}

						$content = preg_replace(
							'/(?i)><div class=\"_3dp([^>]+)>(.+?)div\ class=\"[^u]+userContent\"/i',
							'',
							$content);

						$content = preg_replace(
							'/(?i)><div class=\"_4l5([^>]+)>(.+?)<\/div>/i',
							'',
							$content);

						// Remove "SpSonsSoriSsés"
						$content = preg_replace(
							'/(?iU)<a [^>]+ href="#" role="link" [^>}]+>.+<\/a>/iU',
							'',
							$content);

						// Remove html nodes, keep only img, links, basic formatting
						$content = strip_tags($content, '<a><img><i><u><br><p>');

						$content = $this->unescape_fb_link($content);

						// Clean useless html tag properties and fix link closing tags
						foreach (array(
							'onmouseover',
							'onclick',
							'target',
							'ajaxify',
							'tabindex',
							'class',
							'style',
							'data-[^=]*',
							'aria-[^=]*',
							'role',
							'rel',
							'id') as $property_name) {
							$content = preg_replace('/ ' . $property_name . '=\"[^"]*\"/i', '', $content);
						}

						$content = preg_replace('/<\/a [^>]+>/i', '</a>', $content);

						$this->unescape_fb_emote($content);

						// Restore links in the post before further parsing
						$post = defaultLinkTo($post, self::URI);

						// Restore links in the content before adding to the item
						$content = defaultLinkTo($content, self::URI);

						$content = $this->remove_tracking_codes($content);

						// Retrieve date of the post
						$date = $post->find('abbr')[0];

						if(isset($date) && $date->hasAttribute('data-utime')) {
							$date = $date->getAttribute('data-utime');
						} else {
							$date = 0;
						}

						// Build title from content
						$title = strip_tags($post->find('.userContent', 0)->innertext);
						if(strlen($title) > 64)
							$title = substr($title, 0, strpos(wordwrap($title, 64), "\n")) . '...';

						$uri = $post->find('abbr')[0]->parent()->getAttribute('href');

						if (false !== strpos($uri, '?')) {
							$uri = substr($uri, 0, strpos($uri, '?'));
						}

						//Build and add final item
						$item['uri'] = htmlspecialchars_decode($uri, ENT_QUOTES);
						$item['content'] = htmlspecialchars_decode($content, ENT_QUOTES);
						$item['title'] = htmlspecialchars_decode($title, ENT_QUOTES);
						$item['author'] = htmlspecialchars_decode($author, ENT_QUOTES);
						$item['timestamp'] = $date;

						if(strpos($item['content'], '<img') === false) {
							$item['enclosures'] = array($profilePic);
						}

						$this->items[] = $item;
					}
				}
			}
		}
	}
	#endregion (User)

}