]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FacebookBridge/lib/facebookclient.php
5b512dfdff6cb5ca70ea660601cb38582dab08ac
[quix0rs-gnu-social.git] / plugins / FacebookBridge / lib / facebookclient.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Class for communicating with Facebook
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  Plugin
23  * @package   StatusNet
24  * @author    Craig Andrews <candrews@integralblue.com>
25  * @author    Zach Copley <zach@status.net>
26  * @copyright 2009-2011 StatusNet, Inc.
27  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
28  * @link      http://status.net/
29  */
30
31 if (!defined('STATUSNET')) {
32     exit(1);
33 }
34
35 /**
36  * Class for communication with Facebook
37  *
38  * @category Plugin
39  * @package  StatusNet
40  * @author   Zach Copley <zach@status.net>
41  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
42  * @link     http://status.net/
43  */
44 class Facebookclient
45 {
46     protected $facebook      = null; // Facebook Graph client obj
47     protected $flink         = null; // Foreign_link StatusNet -> Facebook
48     protected $notice        = null; // The user's notice
49     protected $user          = null; // Sender of the notice
50
51     /**
52      *
53      * @param Notice $notice the notice to manipulate
54      * @param Profile $profile local user to act as; if left empty, the notice's poster will be used.
55      */
56     function __construct($notice, $profile=null)
57     {
58         $this->facebook = self::getFacebook();
59
60         if (empty($this->facebook)) {
61             throw new FacebookApiException(
62                 "Could not create Facebook client! Bad application ID or secret?"
63             );
64         }
65
66         $this->notice = $notice;
67
68         $profile_id = $profile ? $profile->id : $notice->profile_id;
69         $this->flink = Foreign_link::getByUserID(
70             $profile_id,
71             FACEBOOK_SERVICE
72         );
73
74         if (!empty($this->flink)) {
75             $this->user = $this->flink->getUser();
76         }
77     }
78
79     /*
80      * Get an instance of the Facebook Graph SDK object
81      *
82      * @param string $appId     Application
83      * @param string $secret    Facebook API secret
84      *
85      * @return Facebook A Facebook SDK obj
86      */
87     static function getFacebook($appId = null, $secret = null)
88     {
89         // Check defaults and configuration for application ID and secret
90         if (empty($appId)) {
91             $appId = common_config('facebook', 'appid');
92         }
93
94         if (empty($secret)) {
95             $secret = common_config('facebook', 'secret');
96         }
97
98         // If there's no app ID and secret set in the local config, look
99         // for a global one
100         if (empty($appId) || empty($secret)) {
101             $appId  = common_config('facebook', 'global_appid');
102             $secret = common_config('facebook', 'global_secret');
103         }
104
105         if (empty($appId)) {
106             common_log(
107                 LOG_WARNING,
108                 "Couldn't find Facebook application ID!",
109                 __FILE__
110             );
111         }
112
113         if (empty($secret)) {
114             common_log(
115                 LOG_WARNING,
116                 "Couldn't find Facebook application ID!",
117                 __FILE__
118             );
119         }
120
121         return new Facebook(
122             array(
123                'appId'  => $appId,
124                'secret' => $secret,
125                'cookie' => true
126             )
127         );
128     }
129
130     /*
131      * Broadcast a notice to Facebook
132      *
133      * @param Notice $notice    the notice to send
134      */
135     static function facebookBroadcastNotice($notice)
136     {
137         $client = new Facebookclient($notice);
138         return $client->sendNotice();
139     }
140
141     /*
142      * Should the notice go to Facebook?
143      */
144     function isFacebookBound() {
145
146         if (empty($this->flink)) {
147             // User hasn't setup bridging
148             return false;
149         }
150
151         // Avoid a loop
152         if ($this->notice->source == 'Facebook') {
153             common_log(
154                 LOG_INFO,
155                 sprintf(
156                     'Skipping notice %d because its source is Facebook.',
157                     $this->notice->id
158                 ),
159                 __FILE__
160             );
161             return false;
162         }
163
164         // If the user does not want to broadcast to Facebook, move along
165         if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
166             common_log(
167                 LOG_INFO,
168                 sprintf(
169                     'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
170                     $this->notice->id
171                 ),
172                 __FILE__
173             );
174             return false;
175         }
176
177         // If it's not a reply, or if the user WANTS to send @-replies,
178         // then, yeah, it can go to Facebook.
179
180         if (empty($this->notice->reply_to) ||
181             ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
182             return true;
183         }
184
185         return false;
186     }
187
188     /*
189      * Determine whether we should send this notice using the Graph API or the
190      * old REST API and then dispatch
191      */
192     function sendNotice()
193     {
194         // If there's nothing in the credentials field try to send via
195         // the Old Rest API
196
197         if ($this->isFacebookBound()) {
198             common_debug("notice is facebook bound", __FILE__);
199             if (empty($this->flink->credentials)) {
200                 return $this->sendOldRest();
201             } else {
202
203                 // Otherwise we most likely have an access token
204                 return $this->sendGraph();
205             }
206         }
207
208         // dequeue
209         return true;
210     }
211
212     /*
213      * Send a notice to Facebook using the Graph API
214      */
215     function sendGraph()
216     {
217         try {
218
219             $fbuid = $this->flink->foreign_id;
220
221             common_debug(
222                 sprintf(
223                     "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
224                     $this->notice->id,
225                     $this->user->nickname,
226                     $this->user->id,
227                     $fbuid
228                 ),
229                 __FILE__
230             );
231
232             $params = array(
233                 'access_token' => $this->flink->credentials,
234                 // XXX: Need to worrry about length of the message?
235                 'message'      => $this->notice->content
236             );
237
238             $attachments = $this->notice->attachments();
239
240             if (!empty($attachments)) {
241
242                 // We can only send one attachment with the Graph API :(
243
244                 $first = array_shift($attachments);
245
246                 if (substr($first->mimetype, 0, 6) == 'image/'
247                     || in_array(
248                         $first->mimetype,
249                         array('application/x-shockwave-flash', 'audio/mpeg' ))) {
250
251                    $params['picture'] = $first->url;
252                    $params['caption'] = 'Click for full size';
253                    $params['source']  = $first->url;
254                 }
255
256             }
257
258             $result = $this->facebook->api(
259                 sprintf('/%s/feed', $fbuid), 'post', $params
260             );
261
262             // Save a mapping
263             Notice_to_item::saveNew($this->notice->id, $result['id']);
264
265             common_log(
266                 LOG_INFO,
267                 sprintf(
268                     "Posted notice %d as a stream item for %s (%d), fbuid %d",
269                     $this->notice->id,
270                     $this->user->nickname,
271                     $this->user->id,
272                     $fbuid
273                 ),
274                 __FILE__
275             );
276
277         } catch (FacebookApiException $e) {
278             return $this->handleFacebookError($e);
279         }
280
281         return true;
282     }
283
284     /*
285      * Send a notice to Facebook using the deprecated Old REST API. We need this
286      * for backwards compatibility. Users who signed up for Facebook bridging
287      * using the old Facebook Canvas application do not have an OAuth 2.0
288      * access token.
289      */
290     function sendOldRest()
291     {
292         try {
293
294             $canPublish = $this->checkPermission('publish_stream');
295             $canUpdate  = $this->checkPermission('status_update');
296
297             // We prefer to use stream.publish, because it can handle
298             // attachments and returns the ID of the published item
299
300             if ($canPublish == 1) {
301                 $this->restPublishStream();
302             } else if ($canUpdate == 1) {
303                 // as a last resort we can just update the user's "status"
304                 $this->restStatusUpdate();
305             } else {
306
307                 $msg = 'Not sending notice %d to Facebook because user %s '
308                      . '(%d), fbuid %d,  does not have \'status_update\' '
309                      . 'or \'publish_stream\' permission.';
310
311                 common_log(
312                     LOG_WARNING,
313                     sprintf(
314                         $msg,
315                         $this->notice->id,
316                         $this->user->nickname,
317                         $this->user->id,
318                         $this->flink->foreign_id
319                     ),
320                     __FILE__
321                 );
322             }
323
324         } catch (FacebookApiException $e) {
325             return $this->handleFacebookError($e);
326         }
327
328         return true;
329     }
330
331     /*
332      * Query Facebook to to see if a user has permission
333      *
334      *
335      *
336      * @param $permission the permission to check for - must be either
337      *                    public_stream or status_update
338      *
339      * @return boolean result
340      */
341     function checkPermission($permission)
342     {
343         if (!in_array($permission, array('publish_stream', 'status_update'))) {
344              // TRANS: Server exception thrown when permission check fails.
345              throw new ServerException(_('No such permission!'));
346         }
347
348         $fbuid = $this->flink->foreign_id;
349
350         common_debug(
351             sprintf(
352                 'Checking for %s permission for user %s (%d), fbuid %d',
353                 $permission,
354                 $this->user->nickname,
355                 $this->user->id,
356                 $fbuid
357             ),
358             __FILE__
359         );
360
361         $hasPermission = $this->facebook->api(
362             array(
363                 'method'   => 'users.hasAppPermission',
364                 'ext_perm' => $permission,
365                 'uid'      => $fbuid
366             )
367         );
368
369         if ($hasPermission == 1) {
370
371             common_debug(
372                 sprintf(
373                     '%s (%d), fbuid %d has %s permission',
374                     $permission,
375                     $this->user->nickname,
376                     $this->user->id,
377                     $fbuid
378                 ),
379                 __FILE__
380             );
381
382             return true;
383
384         } else {
385
386             $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
387                     . 'Facebook returned: %s';
388
389             common_debug(
390                 sprintf(
391                     $logMsg,
392                     $this->user->nickname,
393                     $this->user->id,
394                     $permission,
395                     $fbuid,
396                     var_export($result, true)
397                 ),
398                 __FILE__
399             );
400
401             return false;
402         }
403     }
404
405     /*
406      * Handle a Facebook API Exception
407      *
408      * @param FacebookApiException $e the exception
409      *
410      */
411     function handleFacebookError($e)
412     {
413         $fbuid  = $this->flink->foreign_id;
414         $errmsg = $e->getMessage();
415         $code   = $e->getCode();
416
417         // The Facebook PHP SDK seems to always set the code attribute
418         // of the Exception to 0; they put the real error code in
419         // the message. Gar!
420         if ($code == 0) {
421             preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
422             $code = $matches['code'];
423         }
424
425         // XXX: Check for any others?
426         switch($code) {
427          case 100: // Invalid parameter
428             $msg = 'Facebook claims notice %d was posted with an invalid '
429                  . 'parameter (error code 100 - %s) Notice details: '
430                  . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
431                  . 'Dequeing.';
432             common_log(
433                 LOG_ERR, sprintf(
434                     $msg,
435                     $this->notice->id,
436                     $errmsg,
437                     $this->user->nickname,
438                     $this->user->id,
439                     $fbuid,
440                     $this->notice->content
441                 ),
442                 __FILE__
443             );
444             return true;
445             break;
446          case 200: // Permissions error
447          case 250: // Updating status requires the extended permission status_update
448             $this->disconnect();
449             return true; // dequeue
450             break;
451          case 341: // Feed action request limit reached
452                 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
453                      . 'for posting notices to Facebook today. Dequeuing '
454                      . 'notice %d';
455                 common_log(
456                     LOG_INFO, sprintf(
457                         $msg,
458                         $user->nickname,
459                         $user->id,
460                         $fbuid,
461                         $this->notice->id
462                     ),
463                     __FILE__
464                 );
465             // @todo FIXME: We want to rety at a later time when the throttling has expired
466             // instead of just giving up.
467             return true;
468             break;
469          default:
470             $msg = 'Facebook returned an error we don\'t know how to deal with '
471                  . 'when posting notice %d. Error code: %d, error message: "%s"'
472                  . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
473                  . 'notice content="%s"]. Dequeing.';
474             common_log(
475                 LOG_ERR, sprintf(
476                     $msg,
477                     $this->notice->id,
478                     $code,
479                     $errmsg,
480                     $this->user->nickname,
481                     $this->user->id,
482                     $fbuid,
483                     $this->notice->content
484                 ),
485                 __FILE__
486             );
487             return true; // dequeue
488             break;
489         }
490     }
491
492     /*
493      * Publish a notice to Facebook as a status update
494      *
495      * This is the least preferable way to send a notice to Facebook because
496      * it doesn't support attachments and the API method doesn't return
497      * the ID of the post on Facebook.
498      *
499      */
500     function restStatusUpdate()
501     {
502         $fbuid = $this->flink->foreign_id;
503
504         common_debug(
505             sprintf(
506                 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
507                 $this->notice->id,
508                 $this->user->nickname,
509                 $this->user->id,
510                 $fbuid
511             ),
512             __FILE__
513         );
514
515         $result = $this->facebook->api(
516             array(
517                 'method'               => 'users.setStatus',
518                 'status'               => $this->formatMessage(),
519                 'status_includes_verb' => true,
520                 'uid'                  => $fbuid
521             )
522         );
523
524         if ($result == 1) { // 1 is success
525
526             common_log(
527                 LOG_INFO,
528                 sprintf(
529                     "Posted notice %s as a status update for %s (%d), fbuid %d",
530                     $this->notice->id,
531                     $this->user->nickname,
532                     $this->user->id,
533                     $fbuid
534                 ),
535                 __FILE__
536             );
537
538             // There is no item ID returned for status update so we can't
539             // save a Notice_to_item mapping
540
541         } else {
542
543             $msg = sprintf(
544                 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
545                 $this->notice->id,
546                 $this->user->nickname,
547                 $this->user->id,
548                 $fbuid,
549                 $result // will contain 0, or an error
550             );
551
552             throw new FacebookApiException($msg, $result);
553         }
554     }
555
556     /*
557      * Publish a notice to a Facebook user's stream using the old REST API
558      */
559     function restPublishStream()
560     {
561         $fbuid = $this->flink->foreign_id;
562
563         common_debug(
564             sprintf(
565                 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
566                 $this->notice->id,
567                 $this->user->nickname,
568                 $this->user->id,
569                 $fbuid
570             ),
571             __FILE__
572         );
573
574         $fbattachment = $this->formatAttachments();
575
576         $result = $this->facebook->api(
577             array(
578                 'method'     => 'stream.publish',
579                 'message'    => $this->formatMessage(),
580                 'attachment' => $fbattachment,
581                 'uid'        => $fbuid
582             )
583         );
584
585         if (!empty($result)) { // result will contain the item ID
586             // Save a mapping
587             Notice_to_item::saveNew($this->notice->id, $result);
588
589             common_log(
590                 LOG_INFO,
591                 sprintf(
592                     'Posted notice %d as a %s for %s (%d), fbuid %d',
593                     $this->notice->id,
594                     empty($fbattachment) ? 'stream item' : 'stream item with attachment',
595                     $this->user->nickname,
596                     $this->user->id,
597                     $fbuid
598                 ),
599                 __FILE__
600             );
601         } else {
602
603             $msg = sprintf(
604                 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
605                 $this->notice->id,
606                 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
607                 $this->user->nickname,
608                 $this->user->id,
609                 $result, // result will contain an error code
610                 $fbuid
611             );
612
613             throw new FacebookApiException($msg, $result);
614         }
615     }
616
617     /*
618      * Format the text message of a stream item so it's appropriate for
619      * sending to Facebook. If the notice is too long, truncate it, and
620      * add a linkback to the original notice at the end.
621      *
622      * @return String $txt the formated message
623      */
624     function formatMessage()
625     {
626         // Start with the plaintext source of this notice...
627         $txt = $this->notice->content;
628
629         // Facebook has a 420-char hardcoded max.
630         if (mb_strlen($statustxt) > 420) {
631             $noticeUrl = common_shorten_url($this->notice->getUrl());
632             $urlLen = mb_strlen($noticeUrl);
633             $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' â€¦ ' . $noticeUrl;
634         }
635
636         return $txt;
637     }
638
639     /*
640      * Format attachments for the old REST API stream.publish method
641      *
642      * Note: Old REST API supports multiple attachments per post
643      *
644      */
645     function formatAttachments()
646     {
647         $attachments = $this->notice->attachments();
648
649         $fbattachment          = array();
650         $fbattachment['media'] = array();
651
652         foreach($attachments as $attachment)
653         {
654             try {
655                 $enclosure = $attachment->getEnclosure();
656                 $fbmedia = $this->getFacebookMedia($enclosure);
657             } catch (ServerException $e) {
658                 $fbmedia = $this->getFacebookMedia($attachment);
659             }
660             if($fbmedia){
661                 $fbattachment['media'][]=$fbmedia;
662             }else{
663                 $fbattachment['name'] = ($attachment->title ?
664                                       $attachment->title : $attachment->url);
665                 $fbattachment['href'] = $attachment->url;
666             }
667         }
668         if(count($fbattachment['media'])>0){
669             unset($fbattachment['name']);
670             unset($fbattachment['href']);
671         }
672         return $fbattachment;
673     }
674
675     /**
676      * given a File objects, returns an associative array suitable for Facebook media
677      */
678     function getFacebookMedia($attachment)
679     {
680         $fbmedia    = array();
681
682         if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
683             $fbmedia['type']         = 'image';
684             $fbmedia['src']          = $attachment->url;
685             $fbmedia['href']         = $attachment->url;
686         } else if ($attachment->mimetype == 'audio/mpeg') {
687             $fbmedia['type']         = 'mp3';
688             $fbmedia['src']          = $attachment->url;
689         }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
690             $fbmedia['type']         = 'flash';
691
692             // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
693             // says that imgsrc is required... but we have no value to put in it
694             // $fbmedia['imgsrc']='';
695
696             $fbmedia['swfsrc']       = $attachment->url;
697         }else{
698             return false;
699         }
700         return $fbmedia;
701     }
702
703     /*
704      * Disconnect a user from Facebook by deleting his Foreign_link.
705      * Notifies the user his account has been disconnected by email.
706      */
707     function disconnect()
708     {
709         $fbuid = $this->flink->foreign_id;
710
711         common_log(
712             LOG_INFO,
713             sprintf(
714                 'Removing Facebook link for %s (%d), fbuid %d',
715                 $this->user->nickname,
716                 $this->user->id,
717                 $fbuid
718             ),
719             __FILE__
720         );
721
722         $result = $this->flink->delete();
723
724         if (empty($result)) {
725             common_log(
726                 LOG_ERR,
727                 sprintf(
728                     'Could not remove Facebook link for %s (%d), fbuid %d',
729                     $this->user->nickname,
730                     $this->user->id,
731                     $fbuid
732                 ),
733                 __FILE__
734             );
735             common_log_db_error($flink, 'DELETE', __FILE__);
736         }
737
738         // Notify the user that we are removing their Facebook link
739         if (!empty($this->user->email)) {
740             $result = $this->mailFacebookDisconnect();
741
742             if (!$result) {
743                 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
744                      . 'about his/her Facebook link being removed.';
745
746                 common_log(
747                     LOG_WARNING,
748                     sprintf(
749                         $msg,
750                         $this->user->nickname,
751                         $this->user->id,
752                         $fbuid
753                     ),
754                     __FILE__
755                 );
756             }
757         } else {
758             $msg = 'Unable to send email to notify %s (%d), fbuid %d '
759                  . 'about his/her Facebook link being removed because the '
760                  . 'user has not set an email address.';
761
762             common_log(
763                 LOG_WARNING,
764                 sprintf(
765                     $msg,
766                     $this->user->nickname,
767                     $this->user->id,
768                     $fbuid
769                 ),
770                 __FILE__
771             );
772         }
773     }
774
775     /**
776      * Send a mail message to notify a user that her Facebook link
777      * has been terminated.
778      *
779      * @return boolean success flag
780      */
781     function mailFacebookDisconnect()
782     {
783         $profile = $this->user->getProfile();
784
785         $siteName = common_config('site', 'name');
786
787         common_switch_locale($this->user->language);
788
789         // TRANS: E-mail subject.
790         $subject = _m('Your Facebook connection has been removed');
791
792         // TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
793         $msg = _m("Hi %1\$s,\n\n".
794                   "We are sorry to inform you we are unable to publish your notice to\n".
795                   "Facebook, and have removed the connection between your %2\$s account and\n".
796                   "Facebook.\n\n".
797                   "This may have happened because you have removed permission for %2\$s\n".
798                   "to post on your behalf, or perhaps you have deactivated your Facebook\n".
799                   "account. You can reconnect your %2\$s account to Facebook at any time by\n".
800                   "logging in with Facebook again.\n\n".
801                   "Sincerely,\n\n".
802                   "%2\$s\n");
803
804         $body = sprintf(
805             $msg,
806             $this->user->nickname,
807             $siteName
808         );
809
810         common_switch_locale();
811
812         $result = mail_to_user($this->user, $subject, $body);
813
814         if (empty($this->user->password)) {
815             $result = self::emailWarn($this->user);
816         }
817
818         return $result;
819     }
820
821     /*
822      * Send the user an email warning that their account has been
823      * disconnected and he/she has no way to login and must contact
824      * the site administrator for help.
825      *
826      * @param User $user the deauthorizing user
827      *
828      */
829     static function emailWarn($user)
830     {
831         $profile = $user->getProfile();
832
833         $siteName  = common_config('site', 'name');
834         $siteEmail = common_config('site', 'email');
835
836         if (empty($siteEmail)) {
837             common_log(
838                 LOG_WARNING,
839                     "No site email address configured. Please set one."
840             );
841         }
842
843         common_switch_locale($user->language);
844
845         // TRANS: E-mail subject. %s is the StatusNet sitename.
846         $subject = _m('Contact the %s administrator to retrieve your account');
847
848         // TRANS: E-mail body. %1$s is a username,
849         // TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail address.
850         $msg = _m("Hi %1\$s,\n\n".
851                   "We have noticed you have deauthorized the Facebook connection for your\n".
852                   "%2\$s account.  You have not set a password for your %2\$s account yet, so\n".
853                   "you will not be able to login. If you wish to continue using your %2\$s\n".
854                   "account, please contact the site administrator (%3\$s) to set a password.\n\n".
855                   "Sincerely,\n\n".
856                   "%2\$s\n");
857
858         $body = sprintf(
859             $msg,
860             $user->nickname,
861             $siteName,
862             $siteEmail
863         );
864
865         common_switch_locale();
866
867         if (mail_to_user($user, $subject, $body)) {
868             common_log(
869                 LOG_INFO,
870                 sprintf(
871                     'Sent account lockout warning to %s (%d)',
872                     $user->nickname,
873                     $user->id
874                 ),
875                 __FILE__
876             );
877         } else {
878             common_log(
879                 LOG_WARNING,
880                 sprintf(
881                     'Unable to send account lockout warning to %s (%d)',
882                     $user->nickname,
883                     $user->id
884                 ),
885                 __FILE__
886             );
887         }
888     }
889
890     /*
891      * Check to see if we have a mapping to a copy of this notice
892      * on Facebook
893      *
894      * @param Notice $notice the notice to check
895      *
896      * @return mixed null if it can't find one, or the id of the Facebook
897      *               stream item
898      */
899     static function facebookStatusId($notice)
900     {
901         $n2i = Notice_to_item::getKV('notice_id', $notice->id);
902
903         if (empty($n2i)) {
904             return null;
905         } else {
906             return $n2i->item_id;
907         }
908     }
909
910     /*
911      * Save a Foreign_user record of a Facebook user
912      *
913      * @param object $fbuser a Facebook Graph API user obj
914      *                       See: http://developers.facebook.com/docs/reference/api/user
915      * @return mixed $result Id or key
916      *
917      */
918     static function addFacebookUser($fbuser)
919     {
920         // remove any existing, possibly outdated, record
921         $luser = Foreign_user::getForeignUser($fbuser->id, FACEBOOK_SERVICE);
922
923         if (!empty($luser)) {
924
925             $result = $luser->delete();
926
927             if ($result != false) {
928                 common_log(
929                     LOG_INFO,
930                     sprintf(
931                         'Removed old Facebook user: %s, fbuid %d',
932                         $fbuid->name,
933                         $fbuid->id
934                     ),
935                     __FILE__
936                 );
937             }
938         }
939
940         $fuser = new Foreign_user();
941
942         $fuser->nickname = $fbuser->username;
943         $fuser->uri      = $fbuser->link;
944         $fuser->id       = $fbuser->id;
945         $fuser->service  = FACEBOOK_SERVICE;
946         $fuser->created  = common_sql_now();
947
948         $result = $fuser->insert();
949
950         if (empty($result)) {
951             common_log(
952                 LOG_WARNING,
953                     sprintf(
954                         'Failed to add new Facebook user: %s, fbuid %d',
955                         $fbuser->username,
956                         $fbuser->id
957                     ),
958                     __FILE__
959             );
960
961             common_log_db_error($fuser, 'INSERT', __FILE__);
962         } else {
963             common_log(
964                 LOG_INFO,
965                 sprintf(
966                     'Added new Facebook user: %s, fbuid %d',
967                     $fbuser->name,
968                     $fbuser->id
969                 ),
970                 __FILE__
971             );
972         }
973
974         return $result;
975     }
976
977     /*
978      * Remove an item from a Facebook user's feed if we have a mapping
979      * for it.
980      */
981     function streamRemove()
982     {
983         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
984
985         if (!empty($this->flink) && !empty($n2i)) {
986             try {
987                 $result = $this->facebook->api(
988                     array(
989                         'method'  => 'stream.remove',
990                         'post_id' => $n2i->item_id,
991                         'uid'     => $this->flink->foreign_id
992                     )
993                 );
994
995                 if (!empty($result) && result == true) {
996                     common_log(
997                       LOG_INFO,
998                         sprintf(
999                             'Deleted Facebook item: %s for %s (%d), fbuid %d',
1000                             $n2i->item_id,
1001                             $this->user->nickname,
1002                             $this->user->id,
1003                             $this->flink->foreign_id
1004                         ),
1005                         __FILE__
1006                     );
1007
1008                     $n2i->delete();
1009
1010                 } else {
1011                     throw new FaceboookApiException(var_export($result, true));
1012                 }
1013             } catch (FacebookApiException $e) {
1014                 common_log(
1015                   LOG_WARNING,
1016                     sprintf(
1017                         'Could not deleted Facebook item: %s for %s (%d), '
1018                             . 'fbuid %d - (API error: %s) item already deleted '
1019                             . 'on Facebook? ',
1020                         $n2i->item_id,
1021                         $this->user->nickname,
1022                         $this->user->id,
1023                         $this->flink->foreign_id,
1024                         $e
1025                     ),
1026                     __FILE__
1027                 );
1028             }
1029         }
1030     }
1031
1032     /*
1033      * Like an item in a Facebook user's feed if we have a mapping
1034      * for it.
1035      */
1036     function like()
1037     {
1038         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
1039
1040         if (!empty($this->flink) && !empty($n2i)) {
1041             try {
1042                 $result = $this->facebook->api(
1043                     array(
1044                         'method'  => 'stream.addlike',
1045                         'post_id' => $n2i->item_id,
1046                         'uid'     => $this->flink->foreign_id
1047                     )
1048                 );
1049
1050                 if (!empty($result) && result == true) {
1051                     common_log(
1052                       LOG_INFO,
1053                         sprintf(
1054                             'Added like for item: %s for %s (%d), fbuid %d',
1055                             $n2i->item_id,
1056                             $this->user->nickname,
1057                             $this->user->id,
1058                             $this->flink->foreign_id
1059                         ),
1060                         __FILE__
1061                     );
1062                 } else {
1063                     throw new FacebookApiException(var_export($result, true));
1064                 }
1065             } catch (FacebookApiException $e) {
1066                 common_log(
1067                   LOG_WARNING,
1068                     sprintf(
1069                         'Could not like Facebook item: %s for %s (%d), '
1070                             . 'fbuid %d (API error: %s)',
1071                         $n2i->item_id,
1072                         $this->user->nickname,
1073                         $this->user->id,
1074                         $this->flink->foreign_id,
1075                         $e
1076                     ),
1077                     __FILE__
1078                 );
1079             }
1080         }
1081     }
1082
1083     /*
1084      * Unlike an item in a Facebook user's feed if we have a mapping
1085      * for it.
1086      */
1087     function unLike()
1088     {
1089         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
1090
1091         if (!empty($this->flink) && !empty($n2i)) {
1092             try {
1093                 $result = $this->facebook->api(
1094                     array(
1095                         'method'  => 'stream.removeLike',
1096                         'post_id' => $n2i->item_id,
1097                         'uid'     => $this->flink->foreign_id
1098                     )
1099                 );
1100
1101                 if (!empty($result) && result == true) {
1102                     common_log(
1103                       LOG_INFO,
1104                         sprintf(
1105                             'Removed like for item: %s for %s (%d), fbuid %d',
1106                             $n2i->item_id,
1107                             $this->user->nickname,
1108                             $this->user->id,
1109                             $this->flink->foreign_id
1110                         ),
1111                         __FILE__
1112                     );
1113
1114                 } else {
1115                     throw new FacebookApiException(var_export($result, true));
1116                 }
1117             } catch (FacebookApiException $e) {
1118                   common_log(
1119                   LOG_WARNING,
1120                     sprintf(
1121                         'Could not remove like for Facebook item: %s for %s '
1122                           . '(%d), fbuid %d (API error: %s)',
1123                         $n2i->item_id,
1124                         $this->user->nickname,
1125                         $this->user->id,
1126                         $this->flink->foreign_id,
1127                         $e
1128                     ),
1129                     __FILE__
1130                 );
1131             }
1132         }
1133     }
1134 }