4 * This module still needs a lot of work, but is functional today.
5 * Please review this section if you upgrade because things will change.
6 * If you have issues upgrading, remove facebook from the addon list,
7 * view a page on your site, then add it back to the list. This will reset
8 * all of the plugin 'hooks'.
10 * 1. register an API key for your site from developer.facebook.com
11 * a. We'd be very happy if you include "Friendika" in the application name
12 * to increase name recognition. The Friendika icons are also present
13 * in the images directory and may be uploaded as a Facebook app icon.
14 * Use images/ff-16.jpg for the Icon and images/ff-128.jpg for the Logo.
15 * b. The url should be your site URL with a trailing slash.
16 * You may use http://portal.friendika.com/privacy as the privacy policy
17 * URL unless your site has different requirements, and
18 * http://portal.friendika.com as the Terms of Service URL unless
19 * you have different requirements. (Friendika is a software application
20 * and does not require Terms of Service, though your installation of it might).
21 * c. Set the following values in your .htconfig.php file
22 * $a->config['facebook']['appid'] = 'xxxxxxxxxxx';
23 * $a->config['facebook']['appsecret'] = 'xxxxxxxxxxxxxxx';
24 * Replace with the settings Facebook gives you.
25 * 2. Enable the facebook plugin by including it in .htconfig.php - e.g.
26 * $a->config['system']['addon'] = 'plugin1,plugin2,facebook';
27 * 3. Visit your site url + '/facebook' (e.g. http://example.com/facebook)
28 * and click 'Install Facebook posting'.
29 * 4. This will ask you to login to Facebook and grant permission to the
30 * plugin to do its stuff. Allow it to do so.
31 * 5. You're done. To turn it off visit your site's /facebook page again and
32 * 'Remove Facebook posting'.
34 * Turn logging on (see the github Friendika wiki page 'Settings') and
35 * repeat these steps if you have trouble.
36 * Vidoes and embeds will not be posted if there is no other content. Links
37 * and images will be converted to text and long posts truncated - with a link
38 * to view the full post. Posts with permission settings and comments will
39 * not be posted to Facebook.
43 define('FACEBOOK_MAXPOSTLEN', 420);
45 /* declare the facebook_module function so that /facebook url requests will land here */
47 function facebook_module() {}
51 /* If a->argv[1] is a nickname, this is a callback from Facebook oauth requests. */
53 function facebook_init(&$a) {
59 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
66 $auth_code = (($_GET['code']) ? $_GET['code'] : '');
67 $error = (($_GET['error_description']) ? $_GET['error_description'] : '');
71 logger('facebook_init: Error: ' . $error);
73 if($auth_code && $uid) {
75 $appid = get_config('facebook','appid');
76 $appsecret = get_config('facebook', 'appsecret');
78 $x = fetch_url('https://graph.facebook.com/oauth/access_token?client_id='
79 . $appid . '&client_secret=' . $appsecret . '&redirect_uri='
80 . urlencode($a->get_baseurl() . '/facebook/' . $nick)
81 . '&code=' . $auth_code);
83 logger('facebook_init: returned access token: ' . $x, LOGGER_DATA);
85 if(strpos($x,'access_token=') !== false) {
86 $token = str_replace('access_token=', '', $x);
87 if(strpos($token,'&') !== false)
88 $token = substr($token,0,strpos($token,'&'));
89 set_pconfig($uid,'facebook','access_token',$token);
90 set_pconfig($uid,'facebook','post','1');
97 // todo: is this a browser session or a server session? where do we go?
103 function fb_get_self($uid) {
104 $access_token = get_pconfig($uid,'facebook','access_token');
107 $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
109 $j = json_decode($s);
110 set_pconfig($uid,'facebook','self_id',(string) $j->id);
116 function fb_get_friends($uid) {
118 $access_token = get_pconfig($uid,'facebook','access_token');
121 $s = fetch_url('https://graph.facebook.com/me/friends?access_token=' . $access_token);
123 logger('facebook: fb_get_friends: ' . $s);
124 $j = json_decode($s);
125 logger('facebook: fb_get_friends: json: ' . print_r($j,true));
126 foreach($j->data as $person) {
127 $s = fetch_url('https://graph.facebook.com/' . $person->id . '?access_token=' . $access_token);
129 $jp = json_decode($s);
130 logger('fb_get_friends: info: ' . print_r($jp,true));
132 $jp->link = 'http://facebook.com/profile.php?id=' . $person->id;
134 // check if we already have a contact
136 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
146 // create contact record
147 $r = q("INSERT INTO `contact` ( `uid`, `created`, `url`, `addr`, `alias`, `notify`, `poll`,
148 `name`, `nick`, `photo`, `network`, `rel`, `priority`,
149 `writable`, `blocked`, `readonly`, `pending` )
150 VALUES ( %d, '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', '%s', %d, %d, %d, 0, 0, 0 ) ",
152 dbesc(datetime_convert()),
157 dbesc('facebook ' . $jp->id),
159 dbesc(($jp->nickname) ? $jp->nickname : strtolower($jp->first_name)),
160 dbesc('https://graph.facebook.com/' . $jp->id . '/picture'),
161 dbesc(NETWORK_FACEBOOK),
168 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
178 $contact_id = $r[0]['id'];
180 require_once("Photo.php");
182 $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
184 $r = q("UPDATE `contact` SET `photo` = '%s',
190 WHERE `id` = %d LIMIT 1
195 dbesc(datetime_convert()),
196 dbesc(datetime_convert()),
197 dbesc(datetime_convert()),
207 function facebook_post(&$a) {
210 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
211 set_pconfig(local_user(),'facebook','post_by_default', $value);
216 function facebook_content(&$a) {
219 notice( t('Permission denied.') . EOL);
223 if($a->argc > 1 && $a->argv[1] === 'remove') {
224 del_pconfig(local_user(),'facebook','post');
225 notice( t('Facebook disabled') . EOL);
228 $fb_installed = get_pconfig(local_user(),'facebook','post');
230 $appid = get_config('facebook','appid');
233 notice( t('Facebook API key is missing.') . EOL);
237 $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="'
238 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
240 $o .= '<h3>' . t('Facebook Connect') . '</h3>';
242 if(! $fb_installed) {
243 $o .= '<div id="facebook-enable-wrapper">';
245 $o .= '<a href="https://www.facebook.com/dialog/oauth?client_id=' . $appid . '&redirect_uri='
246 . $a->get_baseurl() . '/facebook/' . $a->user['nickname'] . '&scope=publish_stream,read_stream,offline_access">' . t('Install Facebook post connector') . '</a>';
251 $o .= '<div id="facebook-disable-wrapper">';
253 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook post connector') . '</a></div>';
255 $o .= '<div id="facebook-post-default-form">';
256 $o .= '<form action="facebook" method="post" >';
257 $post_by_default = get_pconfig(local_user(),'facebook','post_by_default');
258 $checked = (($post_by_default) ? ' checked="checked" ' : '');
259 $o .= '<input type="checkbox" name="post_by_default" value="1"' . $checked . '/>' . ' ' . t('Post to Facebook by default') . '<br />';
260 $o .= '<input type="submit" name="submit" value="' . t('Submit') . '" /></form></div>';
266 function facebook_install() {
267 register_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook');
268 register_hook('jot_networks', 'addon/facebook/facebook.php', 'facebook_jot_nets');
269 register_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
273 function facebook_uninstall() {
274 unregister_hook('post_local_end', 'addon/facebook/facebook.php', 'facebook_post_hook');
275 unregister_hook('jot_networks', 'addon/facebook/facebook.php', 'facebook_jot_nets');
276 unregister_hook('plugin_settings', 'addon/facebook/facebook.php', 'facebook_plugin_settings');
280 function facebook_plugin_settings(&$a,&$b) {
282 $b .= '<div class="settings-block">';
283 $b .= '<h3>' . t('Facebook') . '</h3>';
284 $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
289 function facebook_jot_nets(&$a,&$b) {
293 $fb_post = get_pconfig(local_user(),'facebook','post');
294 if(intval($fb_post) == 1) {
295 $fb_defpost = get_pconfig(local_user(),'facebook','post_by_default');
296 $selected = ((intval($fb_defpost) == 1) ? ' checked="checked" ' : '');
297 $b .= '<div class="profile-jot-net"><input type="checkbox" name="facebook_enable"' . $selected . 'value="1" /> '
298 . t('Post to Facebook') . '</div>';
303 function facebook_post_hook(&$a,&$b) {
306 * Post to Facebook stream
309 logger('Facebook post');
311 if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent'])) {
314 $appid = get_config('facebook', 'appid' );
315 $secret = get_config('facebook', 'appsecret' );
317 if($appid && $secret) {
319 logger('facebook: have appid+secret');
321 $fb_post = intval(get_pconfig(local_user(),'facebook','post'));
322 $fb_enable = (($fb_post && x($_POST,'facebook_enable')) ? intval($_POST['facebook_enable']) : 0);
323 $fb_token = get_pconfig(local_user(),'facebook','access_token');
325 logger('facebook: $fb_post: ' . $fb_post . ' $fb_enable: ' . $fb_enable . ' $fb_token: ' . $fb_token,LOGGER_DEBUG);
326 if($fb_post && $fb_token && $fb_enable) {
327 logger('facebook: able to post');
328 require_once('library/facebook.php');
329 require_once('include/bbcode.php');
333 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
335 // make links readable before we strip the code
337 $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 $1',$msg);
339 $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1',$msg);
341 $msg = trim(strip_tags(bbcode($msg)));
342 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
344 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
346 require_once('library/slinky.php');
348 $display_url = $a->get_baseurl() . '/display/' . $a->user['nickname'] . '/' . $b['id'];
349 $slinky = new Slinky( $display_url );
350 // setup a cascade of shortening services
351 // try to get a short link from these services
352 // in the order ur1.ca, trim, id.gd, tinyurl
353 $slinky->set_cascade( array( new Slinky_UR1ca(), new Slinky_Trim(), new Slinky_IsGd(), new Slinky_TinyURL() ) );
354 $shortlink = $slinky->short();
355 // the new message will be shortened such that "... $shortlink"
356 // will fit into the character limit
357 $msg = substr($msg, 0, FACEBOOK_MAXPOSTLEN - strlen($shortlink) - 4);
358 $msg .= '... ' . $shortlink;
363 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
366 'access_token' => $fb_token,
371 $postvars['actions'] = '{"name": "' . t('View on Friendika') . '", "link": "' . $b['plink'] . '"}';
373 $x = post_url('https://graph.facebook.com/me/feed', $postvars);
375 logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
383 function fb_consume_all($uid) {
385 require_once('include/items.php');
387 $access_token = get_pconfig($uid,'facebook','access_token');
390 $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
392 $j = json_decode($s);
393 logger('fb_consume_stream: wall: ' . print_r($j,true));
394 fb_consume_stream($uid,$j,true);
396 $s = fetch_url('https://graph.facebook.com/me/home?access_token=' . $access_token);
398 logger('fb_consume_stream: raw feed: ' . $s);
399 $j = json_decode($s);
400 logger('fb_consume_stream: feed: ' . print_r($j,true));
401 fb_consume_stream($uid,$j,false);
406 function fb_consume_stream($uid,$j,$wall = false) {
409 $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
414 $self_id = get_pconfig($uid,'facebook','self_id');
415 logger('fb_consume');
416 if(! count($j->data) || (! strlen($self_id)))
419 foreach($j->data as $entry) {
420 logger('fb_consume: entry: ' . print_r($entry,true));
423 $app = $entry->application;
424 if($app->id == get_config('facebook','appid') && $wall)
428 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `created` > '%s' AND `created` < '%s' AND `deleted` = 0 LIMIT 1",
430 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' - 1 minute')),
431 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' + 1 minute'))
435 $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `deleted` = 0 LIMIT 1",
436 dbesc('fb::' . $entry->id),
443 $top_item = $r[0]['id'];
446 $post_exists = false;
450 $datarray['gravity'] = 0;
451 $datarray['uid'] = $uid;
452 $datarray['wall'] = (($wall) ? 1 : 0);
453 $datarray['uri'] = $datarray['parent-uri'] = 'fb::' . $entry->id;
454 $from = $entry->from;
455 if($from->id == $self_id)
456 $datarray['contact-id'] = $self[0]['id'];
458 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
463 $datarray['contact-id'] = $r[0]['id'];
465 $datarray['verb'] = ACTIVITY_POST;
466 $datarray['author-name'] = $from->name;
467 $datarray['author-link'] = 'http://facebook.com/profile.php?id=' . $from->id;
468 $datarray['author-avatar'] = 'https://graph.facebook.com/' . $from->id . '/picture';
469 $datarray['body'] = $entry->message;
471 $datarray['body'] .= "\n\n" . '[img]' . $entry->picture . '[/img]';
473 $datarray['body'] .= "\n" . linkify($entry->link);
475 $datarray['body'] .= "\n" . $entry->name;
477 $datarray['body'] .= "\n" . $entry->caption;
478 if($entry->description)
479 $datarray['body'] .= "\n" . $entry->description;
480 $datarray['created'] = datetime_convert('UTC','UTC',$entry->created_time);
481 $datarray['edited'] = datetime_convert('UTC','UTC',$entry->updated_time);
483 $top_item = item_store($datarray);
484 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uid` = %d LIMIT 1",
492 $likers = $entry->likes->data;
493 $comments = $entry->comments->data;
495 if(is_array($likers)) {
496 foreach($likers as $likes) {
498 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `author-link` = '%s'
500 dbesc('fb::' . $entry->id),
502 dbesc(ACTIVITY_LIKE),
503 dbesc('http://facebook.com/profile.php?id=' . $likes->id)
509 $likedata['parent'] = $top_item;
510 $likedata['verb'] = ACTIVITY_LIKE;
513 $likedata['gravity'] = 3;
514 $likedata['uid'] = $uid;
515 $likedata['wall'] = (($wall) ? 1 : 0);
516 $likedata['uri'] = item_new_uri($a->get_baseurl(), $uid);
517 $likedata['parent-uri'] = 'fb::' . $entry->id;
518 if($likes->id == $self_id)
519 $likedata['contact-id'] = $self[0]['id'];
521 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
526 $likedata['contact-id'] = $r[0]['id'];
528 if(! x($likedata,'contact-id'))
529 $likedata['contact-id'] = $orig_post['contact-id'];
531 $likedata['verb'] = ACTIVITY_LIKE;
532 $likedata['author-name'] = $likes->name;
533 $likedata['author-link'] = 'http://facebook.com/profile.php?id=' . $likes->id;
534 $likedata['author-avatar'] = 'https://graph.facebook.com/' . $likes->id . '/picture';
535 $likedata['body'] = sprintf( t('%1$s likes %2$s\'s %3$s'), $likes->name, $orig_post['author-name'], t('post'));
536 $item = item_store($likedata);
539 if(is_array($comments)) {
540 foreach($comments as $cmnt) {
542 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
544 dbesc('fb::' . $cmnt->id)
550 $cmntdata['parent'] = $top_item;
551 $cmntdata['verb'] = ACTIVITY_POST;
552 $cmntdata['gravity'] = 6;
553 $cmntdata['uid'] = $uid;
554 $cmntdata['wall'] = (($wall) ? 1 : 0);
555 $cmntdata['uri'] = 'fb::' . $cmnt->id;
556 $cmntdata['parent-uri'] = 'fb::' . $entry->id;
557 if($cmnt->from->id == $self_id)
558 $cmntdata['contact-id'] = $self[0]['id'];
559 elseif(is_array($orig_post) && (x($orig_post,'contact-id')))
560 $cmntdata['contact-id'] = $orig_post['contact-id'];
562 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
563 dbesc($cmnt->from->id),
567 $cmntdata['contact-id'] = $r[0]['id'];
569 $cmntdata['verb'] = ACTIVITY_POST;
570 $cmntdata['author-name'] = $cmnt->from->name;
571 $cmntdata['author-link'] = 'http://facebook.com/profile.php?id=' . $cmnt->from->id;
572 $cmntdata['author-avatar'] = 'https://graph.facebook.com/' . $cmnt->from->id . '/picture';
573 $cmntdata['body'] = $cmnt->message;
574 $item = item_store($cmntdata);