]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/facebookutil.php
Hotpatch for Facebook mirror problems: drop messages when hitting rate limit (err...
[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 require_once INSTALLDIR . '/plugins/Facebook/facebook/facebook.php';
21 require_once INSTALLDIR . '/plugins/Facebook/facebookaction.php';
22 require_once INSTALLDIR . '/lib/noticelist.php';
23
24 define("FACEBOOK_SERVICE", 2); // Facebook is foreign_service ID 2
25 define("FACEBOOK_NOTICE_PREFIX", 1);
26 define("FACEBOOK_PROMPTED_UPDATE_PREF", 2);
27
28 function getFacebook()
29 {
30     static $facebook = null;
31
32     $apikey = common_config('facebook', 'apikey');
33     $secret = common_config('facebook', 'secret');
34
35     if ($facebook === null) {
36         $facebook = new Facebook($apikey, $secret);
37     }
38
39     if (empty($facebook)) {
40         common_log(LOG_ERR, 'Could not make new Facebook client obj!',
41             __FILE__);
42     }
43
44     return $facebook;
45 }
46
47 function isFacebookBound($notice, $flink) {
48
49     if (empty($flink)) {
50         return false;
51     }
52
53     // Avoid a loop
54
55     if ($notice->source == 'Facebook') {
56         common_log(LOG_INFO, "Skipping notice $notice->id because its " .
57                    'source is Facebook.');
58         return false;
59     }
60
61     // If the user does not want to broadcast to Facebook, move along
62
63     if (!($flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
64         common_log(LOG_INFO, "Skipping notice $notice->id " .
65             'because user has FOREIGN_NOTICE_SEND bit off.');
66         return false;
67     }
68
69     // If it's not a reply, or if the user WANTS to send @-replies,
70     // then, yeah, it can go to Facebook.
71
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
81 function facebookBroadcastNotice($notice)
82 {
83     $facebook = getFacebook();
84     $flink = Foreign_link::getByUserID($notice->profile_id, FACEBOOK_SERVICE);
85
86     if (isFacebookBound($notice, $flink)) {
87
88         // Okay, we're good to go, update the FB status
89
90         $status = null;
91         $fbuid = $flink->foreign_id;
92         $user = $flink->getUser();
93         $attachments  = $notice->attachments();
94
95         try {
96
97             // Get the status 'verb' (prefix) the user has set
98
99             // XXX: Does this call count against our per user FB request limit?
100             // If so we should consider storing verb elsewhere or not storing
101
102             $prefix = trim($facebook->api_client->data_getUserPreference(FACEBOOK_NOTICE_PREFIX,
103                                                                          $fbuid));
104
105             $status = "$prefix $notice->content";
106
107             common_debug("FacebookPlugin - checking for publish_stream permission for user $user->id");
108
109             $can_publish = $facebook->api_client->users_hasAppPermission('publish_stream',
110                                                                          $fbuid);
111
112             common_debug("FacebookPlugin - checking for status_update permission for user $user->id");
113
114             $can_update  = $facebook->api_client->users_hasAppPermission('status_update',
115                                                                          $fbuid);
116             if (!empty($attachments) && $can_publish == 1) {
117                 $fbattachment = format_attachments($attachments);
118                 $facebook->api_client->stream_publish($status, $fbattachment,
119                                                       null, null, $fbuid);
120                 common_log(LOG_INFO,
121                            "FacebookPlugin - Posted notice $notice->id w/attachment " .
122                            "to Facebook user's stream (fbuid = $fbuid).");
123             } elseif ($can_update == 1 || $can_publish == 1) {
124                 $facebook->api_client->users_setStatus($status, $fbuid, false, true);
125                 common_log(LOG_INFO,
126                            "FacebookPlugin - Posted notice $notice->id to Facebook " .
127                            "as a status update (fbuid = $fbuid).");
128             } else {
129                 $msg = "FacebookPlugin - Not sending notice $notice->id to Facebook " .
130                   "because user $user->nickname hasn't given the " .
131                   'Facebook app \'status_update\' or \'publish_stream\' permission.';
132                 common_log(LOG_WARNING, $msg);
133             }
134
135             // Finally, attempt to update the user's profile box
136
137             if ($can_publish == 1 || $can_update == 1) {
138                 updateProfileBox($facebook, $flink, $notice);
139             }
140
141         } catch (FacebookRestClientException $e) {
142
143             $code = $e->getCode();
144
145             $msg = "FacebookPlugin - Facebook returned error code $code: " .
146               $e->getMessage() . ' - ' .
147               "Unable to update Facebook status (notice $notice->id) " .
148               "for $user->nickname (user id: $user->id)!";
149
150             common_log(LOG_WARNING, $msg);
151
152             if ($code == 100 || $code == 200 || $code == 250) {
153
154                 // 100 The account is 'inactive' (probably - this is not well documented)
155                 // 200 The application does not have permission to operate on the passed in uid parameter.
156                 // 250 Updating status requires the extended permission status_update or publish_stream.
157                 // see: http://wiki.developers.facebook.com/index.php/Users.setStatus#Example_Return_XML
158
159                 remove_facebook_app($flink);
160
161             } else if ($code == 341) {
162                 // 341 Feed action request limit reached - Unable to update Facebook status
163                 // Reposting immediately probably won't work, so drop the message for now. :(
164
165                 common_log(LOG_ERR, "Facebook rate limit hit: dropping notice $notice->id");
166                 return true;
167             } else {
168
169                 // Try sending again later.
170                 //
171                 // @fixme at the moment, returning false here could lead to an infinite loop
172                 // if the error condition isn't actually transitory.
173                 //
174                 // Temporarily throwing an exception to kill the process so it'll hit our
175                 // retry limits.
176                 throw new Exception("Facebook error $code on notice $notice->id");
177
178                 return false;
179             }
180
181         }
182     }
183
184     return true;
185
186 }
187
188 function updateProfileBox($facebook, $flink, $notice) {
189     $fbaction = new FacebookAction($output = 'php://output',
190                                    $indent = null, $facebook, $flink);
191     $fbaction->updateProfileBox($notice);
192 }
193
194 function format_attachments($attachments)
195 {
196     $fbattachment          = array();
197     $fbattachment['media'] = array();
198
199     foreach($attachments as $attachment)
200     {
201         if($enclosure = $attachment->getEnclosure()){
202             $fbmedia = get_fbmedia_for_attachment($enclosure);
203         }else{
204             $fbmedia = get_fbmedia_for_attachment($attachment);
205         }
206         if($fbmedia){
207             $fbattachment['media'][]=$fbmedia;
208         }else{
209             $fbattachment['name'] = ($attachment->title ?
210                                   $attachment->title : $attachment->url);
211             $fbattachment['href'] = $attachment->url;
212         }
213     }
214     if(count($fbattachment['media'])>0){
215         unset($fbattachment['name']);
216         unset($fbattachment['href']);
217     }
218     return $fbattachment;
219 }
220
221 /**
222 * given an File objects, returns an associative array suitable for Facebook media
223 */
224 function get_fbmedia_for_attachment($attachment)
225 {
226     $fbmedia    = array();
227
228     if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
229         $fbmedia['type']         = 'image';
230         $fbmedia['src']          = $attachment->url;
231         $fbmedia['href']         = $attachment->url;
232     } else if ($attachment->mimetype == 'audio/mpeg') {
233         $fbmedia['type']         = 'mp3';
234         $fbmedia['src']          = $attachment->url;
235     }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
236         $fbmedia['type']         = 'flash';
237
238         // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
239         // says that imgsrc is required... but we have no value to put in it
240         // $fbmedia['imgsrc']='';
241
242         $fbmedia['swfsrc']       = $attachment->url;
243     }else{
244         return false;
245     }
246     return $fbmedia;
247 }
248
249 function remove_facebook_app($flink)
250 {
251
252     $user = $flink->getUser();
253
254     common_log(LOG_INFO, 'Removing Facebook App Foreign link for ' .
255         "user $user->nickname (user id: $user->id).");
256
257     $result = $flink->delete();
258
259     if (empty($result)) {
260         common_log(LOG_ERR, 'Could not remove Facebook App ' .
261             "Foreign_link for $user->nickname (user id: $user->id)!");
262         common_log_db_error($flink, 'DELETE', __FILE__);
263     }
264
265     // Notify the user that we are removing their FB app access
266
267     $result = mail_facebook_app_removed($user);
268
269     if (!$result) {
270
271         $msg = 'Unable to send email to notify ' .
272             "$user->nickname (user id: $user->id) " .
273             'that their Facebook app link was ' .
274             'removed!';
275
276         common_log(LOG_WARNING, $msg);
277     }
278
279 }
280
281 /**
282  * Send a mail message to notify a user that her Facebook Application
283  * access has been removed.
284  *
285  * @param User $user   user whose Facebook app link has been removed
286  *
287  * @return boolean success flag
288  */
289
290 function mail_facebook_app_removed($user)
291 {
292     $profile = $user->getProfile();
293
294     $site_name = common_config('site', 'name');
295
296     common_switch_locale($user->language);
297
298     $subject = sprintf(
299         _m('Your %1$s Facebook application access has been disabled.',
300             $site_name));
301
302     $body = sprintf(_m("Hi, %1\$s. We're sorry to inform you that we are " .
303         'unable to update your Facebook status from %2$s, and have disabled ' .
304         'the Facebook application for your account. This may be because ' .
305         'you have removed the Facebook application\'s authorization, or ' .
306         'have deleted your Facebook account.  You can re-enable the ' .
307         'Facebook application and automatic status updating by ' .
308         "re-installing the %2\$s Facebook application.\n\nRegards,\n\n%2\$s"),
309         $user->nickname, $site_name);
310
311     common_switch_locale();
312     return mail_to_user($user, $subject, $body);
313
314 }