-
Notifications
You must be signed in to change notification settings - Fork 1
/
facebook.php
480 lines (407 loc) · 11.3 KB
/
facebook.php
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
<?php
/*
Plugin Name: Facebook integration
Description: Facebook integration that doesn't make John want to gouge his eyeballs out
Author: John Du Hart
*/
class WpFacebook {
private static $footerInits = array();
/**
* Registers filters
*/
public static function init() {
add_filter( 'language_attributes', array( __CLASS__, 'langAtrributes' ) );
add_filter( 'init', array( __CLASS__, 'channelFile' ) );
add_filter( 'wp_footer', array( __CLASS__, 'footer' ), 20 );
add_filter( 'admin_print_footer_scripts', array( __CLASS__, 'footer' ), 20 );
add_filter( 'wp_head', array( __CLASS__, 'pageMeta' ), 20 );
add_filter( 'personal_options', array( __CLASS__, 'profilePageConnect' ) );
add_filter( 'wp_ajax_facebook_login', array( __CLASS__, 'profilePageLoginAjax' ) );
add_filter( 'wp_ajax_facebook_disconnect', array( __CLASS__, 'profilePageDisconnectAjax' ) );
add_action( 'transition_post_status', array( __CLASS__, 'onPostStatusTransition' ), 10, 3 );
}
/**
* Adds the facebook tag namespace to <html>
*
* @param $lang
* @return string
*/
public static function langAtrributes( $lang ) {
return ' xmlns:fb="http://ogp.me/ns/fb#" xmlns:og="http://ogp.me/ns#" ' . $lang;
}
/**
* Outputs the weird channel file for cross-domain support
*/
public static function channelFile() {
if ( isset( $_GET['fb-channel-file'] ) ) {
$cache_expire = 60*60*24*365;
header( "Pragma: public" );
header( "Cache-Control: max-age=" . $cache_expire);
header( 'Expires: ' . gmdate( 'D, d M Y H:i:s', time() + $cache_expire ) . ' GMT');
echo '<script src="//connect.facebook.net/en_US/all.js"></script>';
exit;
}
}
/**
* Adds the javascript SDK to the footer
*
* @param array $args
*/
public static function footer( $args = array() ) {
$defaults = array(
'appId' => FB_APP_ID,
'channelUrl' => home_url( '?fb-channel-file' ),
'status' => true,
'cookie' => true,
'xfbml' => true,
'oauth' => true,
);
$args = wp_parse_args( $args, $defaults );
?>
<div id="fb-root"></div>
<script type="text/javascript">
window.fbAsyncInit = function() {
FB.init( <?php echo json_encode( $args ) ?> );
<?php self::footerInit() ?>
};
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>
<?php
}
/**
* Calls all the queued footer inits
*/
private static function footerInit() {
foreach ( self::$footerInits as $func ) {
call_user_func( array( __CLASS__, $func ) );
}
}
/**
* Adds a function to the footer queue
*
* @param $function
*/
private static function footerInitRegister( $function ) {
self::$footerInits[] = $function;
}
/**
* Base64 encoding that doesn't need to be urlencode()ed.
* Exactly the same as base64_encode except it uses
* - instead of +
* _ instead of /
*
* @param string $input base64UrlEncoded string
* @return string
*/
private static function base64UrlDecode( $input ) {
return base64_decode( strtr( $input, '-_', '+/' ) );
}
/**
* Parses a signed_request and validates the signature.
*
* @param string $signed_request A signed token
* @return array The payload inside it or null if the sig is wrong
*/
protected static function parseSignedRequest( $signed_request ) {
list( $encoded_sig, $payload ) = explode( '.', $signed_request, 2 );
// decode the data
$sig = self::base64UrlDecode( $encoded_sig );
$data = json_decode( self::base64UrlDecode( $payload ), true );
if ( strtoupper( $data['algorithm'] ) !== 'HMAC-SHA256' ) {
return null;
}
// check sig
$expected_sig = hash_hmac( 'sha256', $payload,
FB_APP_SECRET, $raw = true );
if ( $sig !== $expected_sig ) {
return null;
}
return $data;
}
protected static function firstImage() {
global $post;
$output = preg_match_all( '/<img.+src=[\'"]([^\'"]+)[\'"].*>/i', $post->post_content, $matches );
if ( $output === 0 || $output === false ) {
return false;
}
$image = $matches[1][0];
// if no base url in image path lets make one
if ( !preg_match( '/^https?:\/\//', $image ) ) {
if ( $image[0] != '/' ) {
$image = '/' . $image;
}
$image = home_url() . $image;
}
return $image;
}
/*
* Page header and <meta> magic
*/
public static function pageMeta() {
$meta = array();
if ( is_singular() ) {
// Single post (article)
global $wp_query;
$post = $wp_query->get_queried_object();
if ( has_excerpt( $post->ID ) ) {
$description = esc_attr( strip_tags( get_the_excerpt( $post->ID ) ) );
} else {
$description = esc_attr( str_replace( "\r\n", ' ', substr(
strip_tags( strip_shortcodes( $post->post_content ) ), 0, 160 ) ) );
}
if ( has_post_thumbnail( $post->ID ) ) {
list( $image ) = wp_get_attachment_image_src( get_post_thumbnail_id( $post->ID ), 'thumbnail' );
} elseif ( self::firstImage() !== false ) {
$image = self::firstImage();
}
$link = get_permalink( $post->ID );
$title = get_the_title( $post->ID );
$type = 'article';
$meta['og:site_name'] = get_bloginfo( 'name' );
} else {
if ( is_home() || is_front_page() ) {
$link = get_bloginfo( 'url' );
} else {
// TODO: HTTP hardcode
$link = 'http://' . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
}
$title = get_bloginfo( 'name' );
$description = get_bloginfo( 'description' );
$type = 'website';
}
if ( !isset( $image ) ) {
// TODO: Get a better default image
$image = 'http://wmkscopedotcom.files.wordpress.com/2011/11/logo-just-kscope-resized.png';
}
$meta = array_merge( array(
'fb:app_id' => FB_APP_ID,
'og:locale' => 'en_US',
'og:title' => $title,
'og:type' => $type,
'og:url' => $link,
'og:description' => $description,
'og:image' => $image,
), $meta );
foreach ( $meta as $prop => $content ) {
?><meta property="<?php echo $prop ?>" content="<?php echo $content ?>">
<?php
}
}
/**
* Returns a facebook data object
*
* @param $userId
* @return WpFacebookData|null
*/
public function getUserFacebookData( $userId ) {
$data = get_user_meta( $userId, 'facebook', true );
if ( $data instanceof WpFacebookData ) {
return $data;
}
return null;
}
/*
* Login stuff
*/
/**
* Add the connect link to the profile page
*
* @todo Add a link on other profile pages
* @param $user WP_User
*/
public static function profilePageConnect( $user ) {
$data = get_user_meta( $user->ID, 'facebook', true );
// Check to see if we already have tokens
if ( $data instanceof WpFacebookData || !defined( 'IS_PROFILE_PAGE' ) || !IS_PROFILE_PAGE ) {
self::footerInitRegister( 'profilePageFooter' );
} else {
self::footerInitRegister( 'profilePageLoginFooter' );
}
?>
<tr>
<th><label>Facebook Connect</label></th>
<td><p>
<?php if ( $data instanceof WpFacebookData ) {
$id = $data->userId;
?>
<img id="fb-profile-pic" src="https://graph.facebook.com/<?php echo $id ?>/picture?type=square" />
Connected as
<a id="fb-profile-link" href="#" fb-id="<?php echo $id ?>"></a>
( <a href="#" id="fb-disconnect-link">Disconnect</a> )
<?php } elseif ( defined( 'IS_PROFILE_PAGE' ) && IS_PROFILE_PAGE ) { ?>
<fb:login-button scope="email,publish_actions" show-faces="false">Connect this WordPress account to Facebook</fb:login-button>
<?php } else { ?>
Account Not connected
<?php } ?>
</p></td>
</tr>
<?php
}
/**
* AJAX for connecting to a facebook account
*/
public static function profilePageLoginAjax() {
// Make sure the token is there
if ( !isset( $_POST['token'] ) ) {
exit;
}
// Get the extended token
$response = wp_remote_get( 'https://graph.facebook.com/oauth/access_token?client_id=' . FB_APP_ID
. '&client_secret=' . FB_APP_SECRET . '&grant_type=fb_exchange_token'
. '&fb_exchange_token=' . $_POST['token'] );
parse_str( $response['body'], $params );
$cookie = self::parseSignedRequest( $_COOKIE['fbsr_' . FB_APP_ID] );
$data = new WpFacebookData;
$data->userId = $cookie['user_id'];
$data->token = $params['access_token'];
$data->expires = time() + $params['expires'];
$data->update();
// Save the meta and exit
update_user_meta( wp_get_current_user()->ID, 'facebook', $data );
exit;
}
/**
* AJAX for disconnecting the facebook account
*/
public static function profilePageDisconnectAjax() {
$data = get_user_meta( wp_get_current_user()->ID, 'facebook', true );
// Make sure it's a data instance
if ( !( $data instanceof WpFacebookData ) ) {
exit;
}
// Make a request to delete the authorization
$response = wp_remote_request( 'https://graph.facebook.com/'
. $data->userId . '/permissions?access_token=' . $data->token,
array( 'method' => 'DELETE' ) );
$response = json_decode( $response['body'] );
// TODO: Care about the output
delete_user_meta( wp_get_current_user()->ID, 'facebook' );
exit;
}
/**
* JavaScript to handle logins
*/
private static function profilePageLoginFooter() {
echo <<<JAVASCRIPT
function fbLogin( response ) {
if ( response.status !== 'connected' ) {
return;
}
jQuery.post( ajaxurl, {
action: 'facebook_login',
token: response.authResponse.accessToken
}, function () {
location.reload();
} );
}
// Login and reload the page
FB.Event.subscribe( 'auth.statusChange', fbLogin );
JAVASCRIPT;
}
private static function profilePageFooter() {
echo <<<JAVASCRIPT
var id = jQuery( '#fb-profile-link' ).attr( 'fb-id' );
FB.api( '/' + id, function ( response ) {
jQuery( '#fb-profile-link' )
.attr( 'href', 'https://www.facebook.com/' + id )
.text( response.name );
} );
jQuery( '#fb-disconnect-link' ).click( function () {
jQuery.post( ajaxurl, {
action: 'facebook_disconnect'
}, function () {
location.reload();
} );
return false;
} );
JAVASCRIPT;
}
/*
* Publishing
*/
/**
* Makes the post to the user's timeline
*
* @param $new
* @param $old
* @param $post
* @return mixed
*/
public function onPostStatusTransition( $new, $old, $post ) {
if ( $new != 'publish' || $old == 'publish' ) {
return;
}
// Cycle for each user
if ( function_exists( 'get_coauthors' ) ) {
foreach ( get_coauthors( $post->ID ) as $user ) {
self::publishWriteAction( $user->ID, $post->ID );
}
} else {
self::publishWriteAction( $post->post_author, $post->ID );
}
}
/**
* Publish a wmkscope:write action
*
* @param $userId
* @param $postId
* @return mixed
*/
private function publishWriteAction( $userId, $postId ) {
$data = self::getUserFacebookData( $userId );
if ( $data === null ) {
// No user data. ugh.
return;
}
$params = array(
'access_token' => $data->token,
'article' => get_permalink( $postId ),
);
wp_remote_post(
'https://graph.facebook.com/' . $data->userId . '/wmkscope:write',
array( 'body' => $params )
);
}
}
/**
* Serialized class
*/
class WpFacebookData {
/**
* Facebook user id
*
* @var int
*/
public $userId;
/**
* Access token
*
* @var string
*/
public $token;
/**
* Expiration timestamp
*
* @var int
*/
public $expires;
/**
* Day number of last update
*
* @var string
*/
public $lastUpdate;
/**
* Helper function to update the date
*/
public function update() {
$this->lastUpdate = date( 'd' );
}
}
WpFacebook::init();