]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/facebookutil.php
FacebookPlugin: Fix up FBML canvas app so it keeps working after
[quix0rs-gnu-social.git] / plugins / Facebook / facebookutil.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('STATUSNET')) {
21     exit(1);
22 }
23
24 require_once INSTALLDIR . '/plugins/Facebook/facebook/facebook.php';
25 require_once INSTALLDIR . '/plugins/Facebook/facebookaction.php';
26 require_once INSTALLDIR . '/lib/noticelist.php';
27
28 define("FACEBOOK_SERVICE", 2); // Facebook is foreign_service ID 2
29 define("FACEBOOK_NOTICE_PREFIX", 1);
30 define("FACEBOOK_PROMPTED_UPDATE_PREF", 2);
31
32 function getFacebook()
33 {
34     static $facebook = null;
35
36     $apikey = common_config('facebook', 'apikey');
37     $secret = common_config('facebook', 'secret');
38
39     if ($facebook === null) {
40         $facebook = new Facebook($apikey, $secret);
41     }
42
43     if (empty($facebook)) {
44         common_log(LOG_ERR, 'Could not make new Facebook client obj!',
45             __FILE__);
46     }
47
48     return $facebook;
49 }
50
51 function isFacebookBound($notice, $flink) {
52     if (empty($flink)) {
53         common_debug("QQQQQ empty flink");
54         return false;
55     }
56
57     // Avoid a loop
58     if ($notice->source == 'Facebook') {
59         common_log(LOG_INFO, "Skipping notice $notice->id because its " .
60                    'source is Facebook.');
61         return false;
62     }
63
64     // If the user does not want to broadcast to Facebook, move along
65     if (!($flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
66         common_log(LOG_INFO, "Skipping notice $notice->id " .
67             'because user has FOREIGN_NOTICE_SEND bit off.');
68         return false;
69     }
70
71     // If it's not a reply, or if the user WANTS to send @-replies,
72     // then, yeah, it can go to Facebook.
73     if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $notice->content) ||
74         ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
75         return true;
76     }
77
78     return false;
79 }
80
81 function facebookBroadcastNotice($notice)
82 {
83     $facebook = getFacebook();
84     $flink = Foreign_link::getByUserID(
85         $notice->profile_id,
86         FACEBOOK_SERVICE
87     );
88
89     if (isFacebookBound($notice, $flink)) {
90         // Okay, we're good to go, update the FB status
91         $fbuid = $flink->foreign_id;
92         $user = $flink->getUser();
93
94         try {
95             // Check permissions
96             common_debug(
97                 'FacebookPlugin - checking for publish_stream permission for user '
98                 . "$user->nickname ($user->id), Facebook UID: $fbuid"
99             );
100
101             // NOTE: $facebook->api_client->users_hasAppPermission('publish_stream', $fbuid)
102             // has been returning bogus results, so we're using FQL to check for
103             // publish_stream permission now
104             $fql = "SELECT publish_stream FROM permissions WHERE uid = $fbuid";
105             $result = $facebook->api_client->fql_query($fql);
106
107             $canPublish = 0;
108
109             if (!empty($result)) {
110                 $canPublish = $result[0]['publish_stream'];
111             }
112
113             if ($canPublish == 1) {
114                 common_debug(
115                     "FacebookPlugin - $user->nickname ($user->id), Facebook UID: $fbuid "
116                     . 'has publish_stream permission.'
117                 );
118             } else {
119                 common_debug(
120                     "FacebookPlugin - $user->nickname ($user->id), Facebook UID: $fbuid "
121                     . 'does NOT have publish_stream permission. Facebook '
122                     . 'returned: ' . var_export($result, true)
123                 );
124             }
125
126             common_debug(
127                 'FacebookPlugin - checking for status_update permission for user '
128                 . "$user->nickname ($user->id), Facebook UID: $fbuid. "
129             );
130
131             $canUpdate = $facebook->api_client->users_hasAppPermission(
132                 'status_update',
133                 $fbuid
134             );
135
136             if ($canUpdate == 1) {
137                 common_debug(
138                     "FacebookPlugin - $user->nickname ($user->id), Facebook UID: $fbuid "
139                     . 'has status_update permission.'
140                 );
141             } else {
142                 common_debug(
143                     "FacebookPlugin - $user->nickname ($user->id), Facebook UID: $fbuid "
144                     .'does NOT have status_update permission. Facebook '
145                     . 'returned: ' . var_export($canPublish, true)
146                 );
147             }
148
149             // Post to Facebook
150             if ($notice->hasAttachments() && $canPublish == 1) {
151                 publishStream($notice, $user, $fbuid);
152             } elseif ($canUpdate == 1 || $canPublish == 1) {
153                 statusUpdate($notice, $user, $fbuid);
154             } else {
155                 $msg = "FacebookPlugin - Not sending notice $notice->id to Facebook " .
156                   "because user $user->nickname has not given the " .
157                   'Facebook app \'status_update\' or \'publish_stream\' permission.';
158                 common_log(LOG_WARNING, $msg);
159             }
160
161         } catch (FacebookRestClientException $e) {
162             return handleFacebookError($e, $notice, $flink);
163         }
164     }
165
166     return true;
167 }
168
169 function handleFacebookError($e, $notice, $flink)
170 {
171     $fbuid  = $flink->foreign_id;
172     $user   = $flink->getUser();
173     $code   = $e->getCode();
174     $errmsg = $e->getMessage();
175
176     // XXX: Check for any others?
177     switch($code) {
178      case 100: // Invalid parameter
179         $msg = "FacebookPlugin - Facebook claims notice %d was posted with an invalid parameter (error code 100):"
180             . "\"%s\" (Notice details: nickname=%s, user ID=%d, Facebook ID=%d, notice content=\"%s\"). "
181             . "Removing notice from the Facebook queue for safety.";
182         common_log(
183             LOG_ERR, sprintf(
184                 $msg,
185                 $notice->id,
186                 $errmsg,
187                 $user->nickname,
188                 $user->id,
189                 $fbuid,
190                 $notice->content
191             )
192         );
193         return true;
194         break;
195      case 200: // Permissions error
196      case 250: // Updating status requires the extended permission status_update
197         remove_facebook_app($flink);
198         return true; // dequeue
199         break;
200      case 341: // Feed action request limit reached
201             $msg = "FacebookPlugin - User %s (User ID=%d, Facebook ID=%d) has exceeded "
202                    . "his/her limit for posting notices to Facebook today. Dequeuing "
203                    . "notice %d.";
204             common_log(
205                 LOG_INFO, sprintf(
206                     $msg,
207                     $user->nickname,
208                     $user->id,
209                     $fbuid,
210                     $notice->id
211                 )
212             );
213         // @fixme: We want to rety at a later time when the throttling has expired
214         // instead of just giving up.
215         return true;
216         break;
217      default:
218         $msg = "FacebookPlugin - Facebook returned an error we don't know how to deal with while trying to "
219             . "post notice %d. Error code: %d, error message: \"%s\". (Notice details: "
220             . "nickname=%s, user ID=%d, Facebook ID=%d, notice content=\"%s\"). Removing notice "
221             . "from the Facebook queue for safety.";
222         common_log(
223             LOG_ERR, sprintf(
224                 $msg,
225                 $notice->id,
226                 $code,
227                 $errmsg,
228                 $user->nickname,
229                 $user->id,
230                 $fbuid,
231                 $notice->content
232             )
233         );
234         return true; // dequeue
235         break;
236     }
237 }
238
239 function statusUpdate($notice, $user, $fbuid)
240 {
241     common_debug(
242         "FacebookPlugin - Attempting to post notice $notice->id "
243         . "as a status update for $user->nickname ($user->id), "
244         . "Facebook UID: $fbuid"
245     );
246
247     $facebook = getFacebook();
248     $result = $facebook->api_client->users_setStatus(
249          $notice->content,
250          $fbuid,
251          false,
252          true
253     );
254
255     common_debug('Facebook returned: ' . var_export($result, true));
256
257     common_log(
258         LOG_INFO,
259         "FacebookPlugin - Posted notice $notice->id as a status "
260         . "update for $user->nickname ($user->id), "
261         . "Facebook UID: $fbuid"
262     );
263 }
264
265 function publishStream($notice, $user, $fbuid)
266 {
267     common_debug(
268         "FacebookPlugin - Attempting to post notice $notice->id "
269         . "as stream item with attachment for $user->nickname ($user->id), "
270         . "Facebook UID: $fbuid"
271     );
272
273     $fbattachment = format_attachments($notice->attachments());
274
275     $facebook = getFacebook();
276     $facebook->api_client->stream_publish(
277         $notice->content,
278         $fbattachment,
279         null,
280         null,
281         $fbuid
282     );
283
284     common_log(
285         LOG_INFO,
286         "FacebookPlugin - Posted notice $notice->id as a stream "
287         . "item with attachment for $user->nickname ($user->id), "
288         . "Facebook UID: $fbuid"
289     );
290 }
291
292 function format_attachments($attachments)
293 {
294     $fbattachment          = array();
295     $fbattachment['media'] = array();
296
297     foreach($attachments as $attachment)
298     {
299         if($enclosure = $attachment->getEnclosure()){
300             $fbmedia = get_fbmedia_for_attachment($enclosure);
301         }else{
302             $fbmedia = get_fbmedia_for_attachment($attachment);
303         }
304         if($fbmedia){
305             $fbattachment['media'][]=$fbmedia;
306         }else{
307             $fbattachment['name'] = ($attachment->title ?
308                                   $attachment->title : $attachment->url);
309             $fbattachment['href'] = $attachment->url;
310         }
311     }
312     if(count($fbattachment['media'])>0){
313         unset($fbattachment['name']);
314         unset($fbattachment['href']);
315     }
316     return $fbattachment;
317 }
318
319 /**
320 * given an File objects, returns an associative array suitable for Facebook media
321 */
322 function get_fbmedia_for_attachment($attachment)
323 {
324     $fbmedia    = array();
325
326     if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
327         $fbmedia['type']         = 'image';
328         $fbmedia['src']          = $attachment->url;
329         $fbmedia['href']         = $attachment->url;
330     } else if ($attachment->mimetype == 'audio/mpeg') {
331         $fbmedia['type']         = 'mp3';
332         $fbmedia['src']          = $attachment->url;
333     }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
334         $fbmedia['type']         = 'flash';
335
336         // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
337         // says that imgsrc is required... but we have no value to put in it
338         // $fbmedia['imgsrc']='';
339
340         $fbmedia['swfsrc']       = $attachment->url;
341     }else{
342         return false;
343     }
344     return $fbmedia;
345 }
346
347 function remove_facebook_app($flink)
348 {
349
350     $user = $flink->getUser();
351
352     common_log(LOG_INFO, 'Removing Facebook App Foreign link for ' .
353         "user $user->nickname (user id: $user->id).");
354
355     $result = $flink->delete();
356
357     if (empty($result)) {
358         common_log(LOG_ERR, 'Could not remove Facebook App ' .
359             "Foreign_link for $user->nickname (user id: $user->id)!");
360         common_log_db_error($flink, 'DELETE', __FILE__);
361     }
362
363     // Notify the user that we are removing their FB app access
364
365     $result = mail_facebook_app_removed($user);
366
367     if (!$result) {
368
369         $msg = 'Unable to send email to notify ' .
370             "$user->nickname (user id: $user->id) " .
371             'that their Facebook app link was ' .
372             'removed!';
373
374         common_log(LOG_WARNING, $msg);
375     }
376 }
377
378 /**
379  * Send a mail message to notify a user that her Facebook Application
380  * access has been removed.
381  *
382  * @param User $user   user whose Facebook app link has been removed
383  *
384  * @return boolean success flag
385  */
386 function mail_facebook_app_removed($user)
387 {
388     $profile = $user->getProfile();
389
390     $site_name = common_config('site', 'name');
391
392     common_switch_locale($user->language);
393
394     $subject = sprintf(
395         _m('Your %1$s Facebook application access has been disabled.',
396             $site_name));
397
398     $body = sprintf(_m("Hi, %1\$s. We're sorry to inform you that we are " .
399         'unable to update your Facebook status from %2$s, and have disabled ' .
400         'the Facebook application for your account. This may be because ' .
401         'you have removed the Facebook application\'s authorization, or ' .
402         'have deleted your Facebook account.  You can re-enable the ' .
403         'Facebook application and automatic status updating by ' .
404         "re-installing the %2\$s Facebook application.\n\nRegards,\n\n%2\$s"),
405         $user->nickname, $site_name);
406
407     common_switch_locale();
408     return mail_to_user($user, $subject, $body);
409 }