]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FacebookBridge/lib/facebookclient.php
Merge branch 'qna' into 1.0.x
[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-2010 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         if (!preg_match('/@[a-zA-Z0-9_]{1,15}\b/u', $this->notice->content) ||
180             ($this->flink->noticesync & FOREIGN_NOTICE_SEND_REPLY)) {
181             return true;
182         }
183
184         return false;
185     }
186
187     /*
188      * Determine whether we should send this notice using the Graph API or the
189      * old REST API and then dispatch
190      */
191     function sendNotice()
192     {
193         // If there's nothing in the credentials field try to send via
194         // the Old Rest API
195
196         if ($this->isFacebookBound()) {
197             common_debug("notice is facebook bound", __FILE__);
198             if (empty($this->flink->credentials)) {
199                 return $this->sendOldRest();
200             } else {
201
202                 // Otherwise we most likely have an access token
203                 return $this->sendGraph();
204             }
205         }
206
207         // dequeue
208         return true;
209     }
210
211     /*
212      * Send a notice to Facebook using the Graph API
213      */
214     function sendGraph()
215     {
216         try {
217
218             $fbuid = $this->flink->foreign_id;
219
220             common_debug(
221                 sprintf(
222                     "Attempting use Graph API to post notice %d as a stream item for %s (%d), fbuid %d",
223                     $this->notice->id,
224                     $this->user->nickname,
225                     $this->user->id,
226                     $fbuid
227                 ),
228                 __FILE__
229             );
230
231             $params = array(
232                 'access_token' => $this->flink->credentials,
233                 // XXX: Need to worrry about length of the message?
234                 'message'      => $this->notice->content
235             );
236
237             $attachments = $this->notice->attachments();
238
239             if (!empty($attachments)) {
240
241                 // We can only send one attachment with the Graph API :(
242
243                 $first = array_shift($attachments);
244
245                 if (substr($first->mimetype, 0, 6) == 'image/'
246                     || in_array(
247                         $first->mimetype,
248                         array('application/x-shockwave-flash', 'audio/mpeg' ))) {
249
250                    $params['picture'] = $first->url;
251                    $params['caption'] = 'Click for full size';
252                    $params['source']  = $first->url;
253                 }
254
255             }
256
257             $result = $this->facebook->api(
258                 sprintf('/%s/feed', $fbuid), 'post', $params
259             );
260
261             // Save a mapping
262             Notice_to_item::saveNew($this->notice->id, $result['id']);
263
264             common_log(
265                 LOG_INFO,
266                 sprintf(
267                     "Posted notice %d as a stream item for %s (%d), fbuid %d",
268                     $this->notice->id,
269                     $this->user->nickname,
270                     $this->user->id,
271                     $fbuid
272                 ),
273                 __FILE__
274             );
275
276         } catch (FacebookApiException $e) {
277             return $this->handleFacebookError($e);
278         }
279
280         return true;
281     }
282
283     /*
284      * Send a notice to Facebook using the deprecated Old REST API. We need this
285      * for backwards compatibility. Users who signed up for Facebook bridging
286      * using the old Facebook Canvas application do not have an OAuth 2.0
287      * access token.
288      */
289     function sendOldRest()
290     {
291         try {
292
293             $canPublish = $this->checkPermission('publish_stream');
294             $canUpdate  = $this->checkPermission('status_update');
295
296             // We prefer to use stream.publish, because it can handle
297             // attachments and returns the ID of the published item
298
299             if ($canPublish == 1) {
300                 $this->restPublishStream();
301             } else if ($canUpdate == 1) {
302                 // as a last resort we can just update the user's "status"
303                 $this->restStatusUpdate();
304             } else {
305
306                 $msg = 'Not sending notice %d to Facebook because user %s '
307                      . '(%d), fbuid %d,  does not have \'status_update\' '
308                      . 'or \'publish_stream\' permission.';
309
310                 common_log(
311                     LOG_WARNING,
312                     sprintf(
313                         $msg,
314                         $this->notice->id,
315                         $this->user->nickname,
316                         $this->user->id,
317                         $this->flink->foreign_id
318                     ),
319                     __FILE__
320                 );
321             }
322
323         } catch (FacebookApiException $e) {
324             return $this->handleFacebookError($e);
325         }
326
327         return true;
328     }
329
330     /*
331      * Query Facebook to to see if a user has permission
332      *
333      *
334      *
335      * @param $permission the permission to check for - must be either
336      *                    public_stream or status_update
337      *
338      * @return boolean result
339      */
340     function checkPermission($permission)
341     {
342         if (!in_array($permission, array('publish_stream', 'status_update'))) {
343              throw new ServerException("No such permission!");
344         }
345
346         $fbuid = $this->flink->foreign_id;
347
348         common_debug(
349             sprintf(
350                 'Checking for %s permission for user %s (%d), fbuid %d',
351                 $permission,
352                 $this->user->nickname,
353                 $this->user->id,
354                 $fbuid
355             ),
356             __FILE__
357         );
358
359         $hasPermission = $this->facebook->api(
360             array(
361                 'method'   => 'users.hasAppPermission',
362                 'ext_perm' => $permission,
363                 'uid'      => $fbuid
364             )
365         );
366
367         if ($hasPermission == 1) {
368
369             common_debug(
370                 sprintf(
371                     '%s (%d), fbuid %d has %s permission',
372                     $permission,
373                     $this->user->nickname,
374                     $this->user->id,
375                     $fbuid
376                 ),
377                 __FILE__
378             );
379
380             return true;
381
382         } else {
383
384             $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
385                     . 'Facebook returned: %s';
386
387             common_debug(
388                 sprintf(
389                     $logMsg,
390                     $this->user->nickname,
391                     $this->user->id,
392                     $permission,
393                     $fbuid,
394                     var_export($result, true)
395                 ),
396                 __FILE__
397             );
398
399             return false;
400
401         }
402     }
403
404     /*
405      * Handle a Facebook API Exception
406      *
407      * @param FacebookApiException $e the exception
408      *
409      */
410     function handleFacebookError($e)
411     {
412         $fbuid  = $this->flink->foreign_id;
413         $errmsg = $e->getMessage();
414         $code   = $e->getCode();
415
416         // The Facebook PHP SDK seems to always set the code attribute
417         // of the Exception to 0; they put the real error code in
418         // the message. Gar!
419         if ($code == 0) {
420             preg_match('/^\(#(?<code>\d+)\)/', $errmsg, $matches);
421             $code = $matches['code'];
422         }
423
424         // XXX: Check for any others?
425         switch($code) {
426          case 100: // Invalid parameter
427             $msg = 'Facebook claims notice %d was posted with an invalid '
428                  . 'parameter (error code 100 - %s) Notice details: '
429                  . '[nickname=%s, user id=%d, fbuid=%d, content="%s"]. '
430                  . 'Dequeing.';
431             common_log(
432                 LOG_ERR, sprintf(
433                     $msg,
434                     $this->notice->id,
435                     $errmsg,
436                     $this->user->nickname,
437                     $this->user->id,
438                     $fbuid,
439                     $this->notice->content
440                 ),
441                 __FILE__
442             );
443             return true;
444             break;
445          case 200: // Permissions error
446          case 250: // Updating status requires the extended permission status_update
447             $this->disconnect();
448             return true; // dequeue
449             break;
450          case 341: // Feed action request limit reached
451                 $msg = '%s (userid=%d, fbuid=%d) has exceeded his/her limit '
452                      . 'for posting notices to Facebook today. Dequeuing '
453                      . 'notice %d';
454                 common_log(
455                     LOG_INFO, sprintf(
456                         $msg,
457                         $user->nickname,
458                         $user->id,
459                         $fbuid,
460                         $this->notice->id
461                     ),
462                     __FILE__
463                 );
464             // @fixme: We want to rety at a later time when the throttling has expired
465             // instead of just giving up.
466             return true;
467             break;
468          default:
469             $msg = 'Facebook returned an error we don\'t know how to deal with '
470                  . 'when posting notice %d. Error code: %d, error message: "%s"'
471                  . ' Notice details: [nickname=%s, user id=%d, fbuid=%d, '
472                  . 'notice content="%s"]. Dequeing.';
473             common_log(
474                 LOG_ERR, sprintf(
475                     $msg,
476                     $this->notice->id,
477                     $code,
478                     $errmsg,
479                     $this->user->nickname,
480                     $this->user->id,
481                     $fbuid,
482                     $this->notice->content
483                 ),
484                 __FILE__
485             );
486             return true; // dequeue
487             break;
488         }
489     }
490
491     /*
492      * Publish a notice to Facebook as a status update
493      *
494      * This is the least preferable way to send a notice to Facebook because
495      * it doesn't support attachments and the API method doesn't return
496      * the ID of the post on Facebook.
497      *
498      */
499     function restStatusUpdate()
500     {
501         $fbuid = $this->flink->foreign_id;
502
503         common_debug(
504             sprintf(
505                 "Attempting to post notice %d as a status update for %s (%d), fbuid %d",
506                 $this->notice->id,
507                 $this->user->nickname,
508                 $this->user->id,
509                 $fbuid
510             ),
511             __FILE__
512         );
513
514         $result = $this->facebook->api(
515             array(
516                 'method'               => 'users.setStatus',
517                 'status'               => $this->formatMessage(),
518                 'status_includes_verb' => true,
519                 'uid'                  => $fbuid
520             )
521         );
522
523         if ($result == 1) { // 1 is success
524
525             common_log(
526                 LOG_INFO,
527                 sprintf(
528                     "Posted notice %s as a status update for %s (%d), fbuid %d",
529                     $this->notice->id,
530                     $this->user->nickname,
531                     $this->user->id,
532                     $fbuid
533                 ),
534                 __FILE__
535             );
536
537             // There is no item ID returned for status update so we can't
538             // save a Notice_to_item mapping
539
540         } else {
541
542             $msg = sprintf(
543                 "Error posting notice %s as a status update for %s (%d), fbuid %d - error code: %s",
544                 $this->notice->id,
545                 $this->user->nickname,
546                 $this->user->id,
547                 $fbuid,
548                 $result // will contain 0, or an error
549             );
550
551             throw new FacebookApiException($msg, $result);
552         }
553     }
554
555     /*
556      * Publish a notice to a Facebook user's stream using the old REST API
557      */
558     function restPublishStream()
559     {
560         $fbuid = $this->flink->foreign_id;
561
562         common_debug(
563             sprintf(
564                 'Attempting to post notice %d as stream item for %s (%d) fbuid %d',
565                 $this->notice->id,
566                 $this->user->nickname,
567                 $this->user->id,
568                 $fbuid
569             ),
570             __FILE__
571         );
572
573         $fbattachment = $this->formatAttachments();
574
575         $result = $this->facebook->api(
576             array(
577                 'method'     => 'stream.publish',
578                 'message'    => $this->formatMessage(),
579                 'attachment' => $fbattachment,
580                 'uid'        => $fbuid
581             )
582         );
583
584         if (!empty($result)) { // result will contain the item ID
585
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
602         } else {
603
604             $msg = sprintf(
605                 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
606                 $this->notice->id,
607                 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
608                 $this->user->nickname,
609                 $this->user->id,
610                 $result, // result will contain an error code
611                 $fbuid
612             );
613
614             throw new FacebookApiException($msg, $result);
615         }
616     }
617
618     /*
619      * Format the text message of a stream item so it's appropriate for
620      * sending to Facebook. If the notice is too long, truncate it, and
621      * add a linkback to the original notice at the end.
622      *
623      * @return String $txt the formated message
624      */
625     function formatMessage()
626     {
627         // Start with the plaintext source of this notice...
628         $txt = $this->notice->content;
629
630         // Facebook has a 420-char hardcoded max.
631         if (mb_strlen($statustxt) > 420) {
632             $noticeUrl = common_shorten_url($this->notice->uri);
633             $urlLen = mb_strlen($noticeUrl);
634             $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' â€¦ ' . $noticeUrl;
635         }
636
637         return $txt;
638     }
639
640     /*
641      * Format attachments for the old REST API stream.publish method
642      *
643      * Note: Old REST API supports multiple attachments per post
644      *
645      */
646     function formatAttachments()
647     {
648         $attachments = $this->notice->attachments();
649
650         $fbattachment          = array();
651         $fbattachment['media'] = array();
652
653         foreach($attachments as $attachment)
654         {
655             if($enclosure = $attachment->getEnclosure()){
656                 $fbmedia = $this->getFacebookMedia($enclosure);
657             }else{
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
744                 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
745                      . 'about his/her Facebook link being removed.';
746
747                 common_log(
748                     LOG_WARNING,
749                     sprintf(
750                         $msg,
751                         $this->user->nickname,
752                         $this->user->id,
753                         $fbuid
754                     ),
755                     __FILE__
756                 );
757             }
758
759         } else {
760
761             $msg = 'Unable to send email to notify %s (%d), fbuid %d '
762                  . 'about his/her Facebook link being removed because the '
763                  . 'user has not set an email address.';
764
765             common_log(
766                 LOG_WARNING,
767                 sprintf(
768                     $msg,
769                     $this->user->nickname,
770                     $this->user->id,
771                     $fbuid
772                 ),
773                 __FILE__
774             );
775         }
776     }
777
778     /**
779      * Send a mail message to notify a user that her Facebook link
780      * has been terminated.
781      *
782      * @return boolean success flag
783      */
784     function mailFacebookDisconnect()
785     {
786         $profile = $this->user->getProfile();
787
788         $siteName = common_config('site', 'name');
789
790         common_switch_locale($this->user->language);
791
792         $subject = _m('Your Facebook connection has been removed');
793
794         $msg = <<<BODY
795 Hi %1$s,
796
797 We're sorry to inform you we are unable to publish your notice to
798 Facebook, and have removed the connection between your %2$s account and
799 Facebook.
800
801 This may have happened because you have removed permission for %2$s
802 to post on your behalf, or perhaps you have deactivated your Facebook
803 account. You can reconnect your %s account to Facebook at any time by
804 logging in with Facebook again.
805
806 Sincerely,
807
808 %2$s
809 BODY;
810         $body = sprintf(
811             _m($msg),
812             $this->user->nickname,
813             $siteName
814         );
815
816         common_switch_locale();
817
818         $result = mail_to_user($this->user, $subject, $body);
819
820         if (empty($this->user->password)) {
821             $result = self::emailWarn($this->user);
822         }
823
824         return $result;
825     }
826
827     /*
828      * Send the user an email warning that their account has been
829      * disconnected and he/she has no way to login and must contact
830      * the site administrator for help.
831      *
832      * @param User $user the deauthorizing user
833      *
834      */
835     static function emailWarn($user)
836     {
837         $profile = $user->getProfile();
838
839         $siteName  = common_config('site', 'name');
840         $siteEmail = common_config('site', 'email');
841
842         if (empty($siteEmail)) {
843             common_log(
844                 LOG_WARNING,
845                     "No site email address configured. Please set one."
846             );
847         }
848
849         common_switch_locale($user->language);
850
851         $subject = _m('Contact the %s administrator to retrieve your account');
852
853         $msg = <<<BODY
854 Hi %1$s,
855
856 We've noticed you have deauthorized the Facebook connection for your
857 %2$s account.  You have not set a password for your %2$s account yet, so
858 you will not be able to login. If you wish to continue using your %2$s
859 account, please contact the site administrator (%3$s) to set a password.
860
861 Sincerely,
862
863 %2$s
864 BODY;
865         $body = sprintf(
866             _m($msg),
867             $user->nickname,
868             $siteName,
869             $siteEmail
870         );
871
872         common_switch_locale();
873
874         if (mail_to_user($user, $subject, $body)) {
875             common_log(
876                 LOG_INFO,
877                 sprintf(
878                     'Sent account lockout warning to %s (%d)',
879                     $user->nickname,
880                     $user->id
881                 ),
882                 __FILE__
883             );
884         } else {
885             common_log(
886                 LOG_WARNING,
887                 sprintf(
888                     'Unable to send account lockout warning to %s (%d)',
889                     $user->nickname,
890                     $user->id
891                 ),
892                 __FILE__
893             );
894         }
895     }
896
897     /*
898      * Check to see if we have a mapping to a copy of this notice
899      * on Facebook
900      *
901      * @param Notice $notice the notice to check
902      *
903      * @return mixed null if it can't find one, or the id of the Facebook
904      *               stream item
905      */
906     static function facebookStatusId($notice)
907     {
908         $n2i = Notice_to_item::staticGet('notice_id', $notice->id);
909
910         if (empty($n2i)) {
911             return null;
912         } else {
913             return $n2i->item_id;
914         }
915     }
916
917     /*
918      * Save a Foreign_user record of a Facebook user
919      *
920      * @param object $fbuser a Facebook Graph API user obj
921      *                       See: http://developers.facebook.com/docs/reference/api/user
922      * @return mixed $result Id or key
923      *
924      */
925     static function addFacebookUser($fbuser)
926     {
927         // remove any existing, possibly outdated, record
928         $luser = Foreign_user::getForeignUser($fbuser['id'], FACEBOOK_SERVICE);
929
930         if (!empty($luser)) {
931
932             $result = $luser->delete();
933
934             if ($result != false) {
935                 common_log(
936                     LOG_INFO,
937                     sprintf(
938                         'Removed old Facebook user: %s, fbuid %d',
939                         $fbuid['name'],
940                         $fbuid['id']
941                     ),
942                     __FILE__
943                 );
944             }
945         }
946
947         $fuser = new Foreign_user();
948
949         $fuser->nickname = $fbuser['name'];
950         $fuser->uri      = $fbuser['link'];
951         $fuser->id       = $fbuser['id'];
952         $fuser->service  = FACEBOOK_SERVICE;
953         $fuser->created  = common_sql_now();
954
955         $result = $fuser->insert();
956
957         if (empty($result)) {
958             common_log(
959                 LOG_WARNING,
960                     sprintf(
961                         'Failed to add new Facebook user: %s, fbuid %d',
962                         $fbuser['name'],
963                         $fbuser['id']
964                     ),
965                     __FILE__
966             );
967
968             common_log_db_error($fuser, 'INSERT', __FILE__);
969         } else {
970             common_log(
971                 LOG_INFO,
972                 sprintf(
973                     'Added new Facebook user: %s, fbuid %d',
974                     $fbuser['name'],
975                     $fbuser['id']
976                 ),
977                 __FILE__
978             );
979         }
980
981         return $result;
982     }
983
984     /*
985      * Remove an item from a Facebook user's feed if we have a mapping
986      * for it.
987      */
988     function streamRemove()
989     {
990         $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
991
992         if (!empty($this->flink) && !empty($n2i)) {
993
994             try {
995
996                 $result = $this->facebook->api(
997                     array(
998                         'method'  => 'stream.remove',
999                         'post_id' => $n2i->item_id,
1000                         'uid'     => $this->flink->foreign_id
1001                     )
1002                 );
1003
1004                 if (!empty($result) && result == true) {
1005
1006                     common_log(
1007                       LOG_INFO,
1008                         sprintf(
1009                             'Deleted Facebook item: %s for %s (%d), fbuid %d',
1010                             $n2i->item_id,
1011                             $this->user->nickname,
1012                             $this->user->id,
1013                             $this->flink->foreign_id
1014                         ),
1015                         __FILE__
1016                     );
1017
1018                     $n2i->delete();
1019
1020                 } else {
1021                     throw new FaceboookApiException(var_export($result, true));
1022                 }
1023
1024             } catch (FacebookApiException $e) {
1025                 common_log(
1026                   LOG_WARNING,
1027                     sprintf(
1028                         'Could not deleted Facebook item: %s for %s (%d), '
1029                             . 'fbuid %d - (API error: %s) item already deleted '
1030                             . 'on Facebook? ',
1031                         $n2i->item_id,
1032                         $this->user->nickname,
1033                         $this->user->id,
1034                         $this->flink->foreign_id,
1035                         $e
1036                     ),
1037                     __FILE__
1038                 );
1039             }
1040         }
1041     }
1042
1043     /*
1044      * Like an item in a Facebook user's feed if we have a mapping
1045      * for it.
1046      */
1047     function like()
1048     {
1049         $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1050
1051         if (!empty($this->flink) && !empty($n2i)) {
1052
1053             try {
1054
1055                 $result = $this->facebook->api(
1056                     array(
1057                         'method'  => 'stream.addlike',
1058                         'post_id' => $n2i->item_id,
1059                         'uid'     => $this->flink->foreign_id
1060                     )
1061                 );
1062
1063                 if (!empty($result) && result == true) {
1064
1065                     common_log(
1066                       LOG_INFO,
1067                         sprintf(
1068                             'Added like for item: %s for %s (%d), fbuid %d',
1069                             $n2i->item_id,
1070                             $this->user->nickname,
1071                             $this->user->id,
1072                             $this->flink->foreign_id
1073                         ),
1074                         __FILE__
1075                     );
1076
1077                 } else {
1078                     throw new FacebookApiException(var_export($result, true));
1079                 }
1080
1081             } catch (FacebookApiException $e) {
1082                 common_log(
1083                   LOG_WARNING,
1084                     sprintf(
1085                         'Could not like Facebook item: %s for %s (%d), '
1086                             . 'fbuid %d (API error: %s)',
1087                         $n2i->item_id,
1088                         $this->user->nickname,
1089                         $this->user->id,
1090                         $this->flink->foreign_id,
1091                         $e
1092                     ),
1093                     __FILE__
1094                 );
1095             }
1096         }
1097     }
1098
1099     /*
1100      * Unlike an item in a Facebook user's feed if we have a mapping
1101      * for it.
1102      */
1103     function unLike()
1104     {
1105         $n2i = Notice_to_item::staticGet('notice_id', $this->notice->id);
1106
1107         if (!empty($this->flink) && !empty($n2i)) {
1108
1109             try {
1110
1111                 $result = $this->facebook->api(
1112                     array(
1113                         'method'  => 'stream.removeLike',
1114                         'post_id' => $n2i->item_id,
1115                         'uid'     => $this->flink->foreign_id
1116                     )
1117                 );
1118
1119                 if (!empty($result) && result == true) {
1120
1121                     common_log(
1122                       LOG_INFO,
1123                         sprintf(
1124                             'Removed like for item: %s for %s (%d), fbuid %d',
1125                             $n2i->item_id,
1126                             $this->user->nickname,
1127                             $this->user->id,
1128                             $this->flink->foreign_id
1129                         ),
1130                         __FILE__
1131                     );
1132
1133                 } else {
1134                     throw new FacebookApiException(var_export($result, true));
1135                 }
1136
1137             } catch (FacebookApiException $e) {
1138                   common_log(
1139                   LOG_WARNING,
1140                     sprintf(
1141                         'Could not remove like for Facebook item: %s for %s '
1142                           . '(%d), fbuid %d (API error: %s)',
1143                         $n2i->item_id,
1144                         $this->user->nickname,
1145                         $this->user->id,
1146                         $this->flink->foreign_id,
1147                         $e
1148                     ),
1149                     __FILE__
1150                 );
1151             }
1152         }
1153     }
1154
1155 }