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