]> git.mxchange.org Git - friendica.git/blob - addon/facebook/facebook.php
facebook poll
[friendica.git] / addon / facebook / facebook.php
1 <?php
2
3 /**
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'. 
9  *
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'.
33  *
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. 
40  *
41  */
42
43 define('FACEBOOK_MAXPOSTLEN', 420);
44
45 /* declare the facebook_module function so that /facebook url requests will land here */
46
47 function facebook_module() {}
48
49
50
51 /* If a->argv[1] is a nickname, this is a callback from Facebook oauth requests. */
52
53 function facebook_init(&$a) {
54
55         if($a->argc != 2)
56                 return;
57         $nick = $a->argv[1];
58         if(strlen($nick))
59                 $r = q("SELECT `uid` FROM `user` WHERE `nickname` = '%s' LIMIT 1",
60                                 dbesc($nick)
61                 );
62         if(! count($r))
63                 return;
64
65         $uid           = $r[0]['uid'];
66         $auth_code     = (($_GET['code']) ? $_GET['code'] : '');
67         $error         = (($_GET['error_description']) ? $_GET['error_description'] : '');
68
69
70         if($error)
71                 logger('facebook_init: Error: ' . $error);
72
73         if($auth_code && $uid) {
74
75                 $appid = get_config('facebook','appid');
76                 $appsecret = get_config('facebook', 'appsecret');
77
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);
82
83                 logger('facebook_init: returned access token: ' . $x, LOGGER_DATA);
84
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');
91                         fb_get_self($uid);
92                         fb_get_friends($uid);
93                         fb_consume_all($uid);
94
95                 }
96
97                 // todo: is this a browser session or a server session? where do we go? 
98         }
99
100 }
101
102
103 function fb_get_self($uid) {
104         $access_token = get_pconfig($uid,'facebook','access_token');
105         if(! $access_token)
106                 return;
107         $s = fetch_url('https://graph.facebook.com/me/?access_token=' . $access_token);
108         if($s) {
109                 $j = json_decode($s);
110                 set_pconfig($uid,'facebook','self_id',(string) $j->id);
111         }
112 }
113
114
115
116 function fb_get_friends($uid) {
117
118         $access_token = get_pconfig($uid,'facebook','access_token');
119         if(! $access_token)
120                 return;
121         $s = fetch_url('https://graph.facebook.com/me/friends?access_token=' . $access_token);
122         if($s) {
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);
128                         if($s) {
129                                 $jp = json_decode($s);
130                                 logger('fb_get_friends: info: ' . print_r($jp,true));
131                                 if(! $jp->link)
132                                         $jp->link = 'http://facebook.com/profile.php?id=' . $person->id;
133
134                                 // check if we already have a contact
135
136                                 $r = q("SELECT * FROM `contact` WHERE `uid` = %d AND `url` = '%s' LIMIT 1",
137                                         intval($uid),
138                                         dbesc($jp->link)
139                                 );                      
140
141                                 if(count($r)) {
142                                         continue;
143                                 }
144                                 else {
145
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 ) ",
151                                                 intval($uid),
152                                                 dbesc(datetime_convert()),
153                                                 dbesc($jp->link),
154                                                 dbesc(''),
155                                                 dbesc(''),
156                                                 dbesc($jp->id),
157                                                 dbesc('facebook ' . $jp->id),
158                                                 dbesc($jp->name),
159                                                 dbesc(($jp->nickname) ? $jp->nickname : strtolower($jp->first_name)),
160                                                 dbesc('https://graph.facebook.com/' . $jp->id . '/picture'),
161                                                 dbesc(NETWORK_FACEBOOK),
162                                                 intval(REL_BUD),
163                                                 intval(1),
164                                                 intval(1)
165                                         );
166                                 }
167
168                                 $r = q("SELECT * FROM `contact` WHERE `url` = '%s' AND `uid` = %d LIMIT 1",
169                                         dbesc($jp->link),
170                                         intval($uid)
171                                 );
172
173                                 if(! count($r)) {
174                                         continue;
175                                 }
176
177                                 $contact = $r[0];
178                                 $contact_id  = $r[0]['id'];
179
180                                 require_once("Photo.php");
181
182                                 $photos = import_profile_photo($r[0]['photo'],$uid,$contact_id);
183
184                                 $r = q("UPDATE `contact` SET `photo` = '%s', 
185                                         `thumb` = '%s',
186                                         `micro` = '%s', 
187                                         `name-date` = '%s', 
188                                         `uri-date` = '%s', 
189                                         `avatar-date` = '%s'
190                                         WHERE `id` = %d LIMIT 1
191                                 ",
192                                         dbesc($photos[0]),
193                                         dbesc($photos[1]),
194                                         dbesc($photos[2]),
195                                         dbesc(datetime_convert()),
196                                         dbesc(datetime_convert()),
197                                         dbesc(datetime_convert()),
198                                         intval($contact_id)
199                                 );                      
200
201                         }
202                 }
203         }
204 }
205
206
207 function facebook_post(&$a) {
208
209         if(local_user()){
210                 $value = ((x($_POST,'post_by_default')) ? intval($_POST['post_by_default']) : 0);
211                 set_pconfig(local_user(),'facebook','post_by_default', $value);
212         } 
213         return;         
214 }
215
216 function facebook_content(&$a) {
217
218         if(! local_user()) {
219                 notice( t('Permission denied.') . EOL);
220                 return '';
221         }
222
223         if($a->argc > 1 && $a->argv[1] === 'remove') {
224                 del_pconfig(local_user(),'facebook','post');
225                 notice( t('Facebook disabled') . EOL);
226         }
227
228         $fb_installed = get_pconfig(local_user(),'facebook','post');
229
230         $appid = get_config('facebook','appid');
231
232         if(! $appid) {
233                 notice( t('Facebook API key is missing.') . EOL);
234                 return '';
235         }
236
237         $a->page['htmlhead'] .= '<link rel="stylesheet" type="text/css" href="' 
238                 . $a->get_baseurl() . '/addon/facebook/facebook.css' . '" media="all" />' . "\r\n";
239
240         $o .= '<h3>' . t('Facebook Connect') . '</h3>';
241
242         if(! $fb_installed) { 
243                 $o .= '<div id="facebook-enable-wrapper">';
244
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>';
247                 $o .= '</div>';
248         }
249
250         if($fb_installed) {
251                 $o .= '<div id="facebook-disable-wrapper">';
252
253                 $o .= '<a href="' . $a->get_baseurl() . '/facebook/remove' . '">' . t('Remove Facebook post connector') . '</a></div>';
254         
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>';
261         }
262
263         return $o;
264 }
265
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');
270 }
271
272
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');
277 }
278
279
280 function facebook_plugin_settings(&$a,&$b) {
281
282         $b .= '<div class="settings-block">';
283         $b .= '<h3>' . t('Facebook') . '</h3>';
284         $b .= '<a href="facebook">' . t('Facebook Connector Settings') . '</a><br />';
285         $b .= '</div>';
286
287 }
288
289 function facebook_jot_nets(&$a,&$b) {
290         if(! local_user())
291                 return;
292
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>';     
299         }
300 }
301
302
303 function facebook_post_hook(&$a,&$b) {
304
305         /**
306          * Post to Facebook stream
307          */
308
309         logger('Facebook post');
310
311         if((local_user()) && (local_user() == $b['uid']) && (! $b['private']) && (! $b['parent'])) {
312
313
314                 $appid  = get_config('facebook', 'appid'  );
315                 $secret = get_config('facebook', 'appsecret' );
316
317                 if($appid && $secret) {
318
319                         logger('facebook: have appid+secret');
320
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');
324
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');     
330
331                                 $msg = $b['body'];
332
333                                 logger('Facebook post: original msg=' . $msg, LOGGER_DATA);
334
335                                 // make links readable before we strip the code
336
337                                 $msg = preg_replace("/\[url=(.+?)\](.+?)\[\/url\]/is",'$2 $1',$msg);
338
339                                 $msg = preg_replace("/\[img\](.+?)\[\/img\]/is", t('Image: ') . '$1',$msg);
340
341                                 $msg = trim(strip_tags(bbcode($msg)));
342                                 $msg = html_entity_decode($msg,ENT_QUOTES,'UTF-8');
343
344                                 if (strlen($msg) > FACEBOOK_MAXPOSTLEN) {
345                                         $shortlink = "";
346                                         require_once('library/slinky.php');
347
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;
359                                 }
360                                 if(! strlen($msg))
361                                         return;
362
363                                 logger('Facebook post: msg=' . $msg, LOGGER_DATA);
364
365                                 $postvars = array(
366                                         'access_token' => $fb_token, 
367                                         'message' => $msg
368                                 );
369  
370                                 if($b['plink'])
371                                         $postvars['actions'] = '{"name": "' . t('View on Friendika') . '", "link": "' .  $b['plink'] . '"}';
372
373                                 $x = post_url('https://graph.facebook.com/me/feed', $postvars);
374                                 
375                                 logger('Facebook post returns: ' . $x, LOGGER_DEBUG);
376
377                         }
378                 }
379         }
380 }
381
382
383 function fb_consume_all($uid) {
384
385         require_once('include/items.php');
386
387         $access_token = get_pconfig($uid,'facebook','access_token');
388         if(! $access_token)
389                 return;
390         $s = fetch_url('https://graph.facebook.com/me/feed?access_token=' . $access_token);
391         if($s) {
392                 $j = json_decode($s);
393 logger('fb_consume_stream: wall: ' . print_r($j,true));
394                 fb_consume_stream($uid,$j,true);
395         }
396         $s = fetch_url('https://graph.facebook.com/me/home?access_token=' . $access_token);
397         if($s) {
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);
402         }
403
404 }
405
406 function fb_consume_stream($uid,$j,$wall = false) {
407         $a = get_app();
408
409         $self = q("SELECT * FROM `contact` WHERE `self` = 1 AND `uid` = %d LIMIT 1",
410                 intval($uid)
411         );
412
413
414         $self_id = get_pconfig($uid,'facebook','self_id');
415 logger('fb_consume'); 
416         if(! count($j->data) || (! strlen($self_id)))
417                 return;
418
419         foreach($j->data as $entry) {
420 logger('fb_consume: entry: ' . print_r($entry,true));
421                 $datarray = array();
422                 $we_posted = false;
423                 $app = $entry->application;
424                 if($app->id == get_config('facebook','appid') && $wall)
425                         $we_posted = true;
426
427                 if($we_posted) {
428                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `created` > '%s' AND `created` < '%s' AND `deleted` = 0 LIMIT 1",
429                                 intval($uid),
430                                 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' - 1 minute')),
431                                 dbesc(datetime_convert('UTC','UTC',$entry->created_time . ' + 1 minute'))
432                         );
433                 }
434                 else {
435                         $r = q("SELECT * FROM `item` WHERE `uri` = '%s' AND `uid` = %d AND `deleted` = 0 LIMIT 1",
436                                 dbesc('fb::' . $entry->id),
437                                 intval($uid)
438                         );
439                 }
440                 if(count($r)) {
441                         $post_exists = true;
442                         $orig_post = $r[0];
443                         $top_item = $r[0]['id'];
444                 }
445                 else {
446                         $post_exists = false;
447                         $orig_post = null;
448                 }
449                 if(! $orig_post) {
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'];
457                         else {
458                                 $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
459                                         dbesc($from->id),
460                                         intval($uid)
461                                 );
462                                 if(count($r))
463                                         $datarray['contact-id'] = $r[0]['id'];
464                         }
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;
470                         if($entry->picture)
471                                 $datarray['body'] .= "\n\n" . '[img]' . $entry->picture . '[/img]';
472                         if($entry->link)
473                                 $datarray['body'] .= "\n" . linkify($entry->link);
474                         if($entry->name)
475                                 $datarray['body'] .= "\n" . $entry->name;
476                         if($entry->caption)
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);
482
483                         $top_item = item_store($datarray);
484                         $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uid` = %d LIMIT 1",
485                                 intval($top_item),
486                                 intval($uid)
487                         );                      
488                         if(count($r))
489                                 $orig_post = $r[0];
490
491                 }
492                 $likers = $entry->likes->data;
493                 $comments = $entry->comments->data;
494
495                 if(is_array($likers)) {
496                         foreach($likers as $likes) {
497
498                                 $r = q("SELECT * FROM `item` WHERE `parent-uri` = '%s' AND `uid` = %d AND `verb` = '%s' AND `author-link` = '%s'
499                                         LIMIT 1",
500                                         dbesc('fb::' . $entry->id),
501                                         intval($uid),
502                                         dbesc(ACTIVITY_LIKE),
503                                         dbesc('http://facebook.com/profile.php?id=' . $likes->id)
504                                 );
505                                 if(count($r))
506                                         continue;
507                                         
508                                 $likedata = array();
509                                 $likedata['parent'] = $top_item;
510                                 $likedata['verb'] = ACTIVITY_LIKE;
511
512
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'];
520                                 else {
521                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
522                                                 dbesc($likes->id),
523                                                 intval($uid)
524                                         );
525                                         if(count($r))
526                                                 $likedata['contact-id'] = $r[0]['id'];
527                                 }
528                                 if(! x($likedata,'contact-id'))
529                                         $likedata['contact-id'] = $orig_post['contact-id'];
530
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);                  
537                         }
538                 }
539                 if(is_array($comments)) {
540                         foreach($comments as $cmnt) {
541
542                                 $r = q("SELECT * FROM `item` WHERE `uid` = %d AND `uri` = '%s' LIMIT 1",
543                                         intval($uid),
544                                         dbesc('fb::' . $cmnt->id)
545                                 );
546                                 if(count($r))
547                                         continue;
548
549                                 $cmntdata = array();
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'];
561                                 else {
562                                         $r = q("SELECT * FROM `contact` WHERE `notify` = '%s' AND `uid` = %d LIMIT 1",
563                                                 dbesc($cmnt->from->id),
564                                                 intval($uid)
565                                         );
566                                         if(count($r))
567                                                 $cmntdata['contact-id'] = $r[0]['id'];
568                                 }
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);                  
575                         }
576
577
578                 }
579
580         }
581
582
583
584
585
586 }