]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/FacebookBridge/lib/facebookclient.php
Merge branch 'nightly' of git.gnu.io:gnu/gnu-social into nightly
[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         try {
70             $this->flink = Foreign_link::getByUserID($profile_id, FACEBOOK_SERVICE);
71             $this->user = $this->flink->getUser();
72         } catch (NoResultException $e) {
73             // at least $this->flink could've gotten set to something,
74             // but the logic that was here before didn't care, so let's not care either
75         }
76     }
77
78     /*
79      * Get an instance of the Facebook Graph SDK object
80      *
81      * @param string $appId     Application
82      * @param string $secret    Facebook API secret
83      *
84      * @return Facebook A Facebook SDK obj
85      */
86     static function getFacebook($appId = null, $secret = null)
87     {
88         // Check defaults and configuration for application ID and secret
89         if (empty($appId)) {
90             $appId = common_config('facebook', 'appid');
91         }
92
93         if (empty($secret)) {
94             $secret = common_config('facebook', 'secret');
95         }
96
97         // If there's no app ID and secret set in the local config, look
98         // for a global one
99         if (empty($appId) || empty($secret)) {
100             $appId  = common_config('facebook', 'global_appid');
101             $secret = common_config('facebook', 'global_secret');
102         }
103
104         if (empty($appId)) {
105             common_log(
106                 LOG_WARNING,
107                 "Couldn't find Facebook application ID!",
108                 __FILE__
109             );
110         }
111
112         if (empty($secret)) {
113             common_log(
114                 LOG_WARNING,
115                 "Couldn't find Facebook application ID!",
116                 __FILE__
117             );
118         }
119
120         return new Facebook(
121             array(
122                'appId'  => $appId,
123                'secret' => $secret,
124                'cookie' => true
125             )
126         );
127     }
128
129     /*
130      * Broadcast a notice to Facebook
131      *
132      * @param Notice $notice    the notice to send
133      */
134     static function facebookBroadcastNotice($notice)
135     {
136         $client = new Facebookclient($notice);
137         return $client->sendNotice();
138     }
139
140     /*
141      * Should the notice go to Facebook?
142      */
143     function isFacebookBound() {
144
145         if (empty($this->flink)) {
146             // User hasn't setup bridging
147             return false;
148         }
149
150         // Avoid a loop
151         if ($this->notice->source == 'Facebook') {
152             common_log(
153                 LOG_INFO,
154                 sprintf(
155                     'Skipping notice %d because its source is Facebook.',
156                     $this->notice->id
157                 ),
158                 __FILE__
159             );
160             return false;
161         }
162
163         // If the user does not want to broadcast to Facebook, move along
164         if (!($this->flink->noticesync & FOREIGN_NOTICE_SEND == FOREIGN_NOTICE_SEND)) {
165             common_log(
166                 LOG_INFO,
167                 sprintf(
168                     'Skipping notice %d because user has FOREIGN_NOTICE_SEND bit off.',
169                     $this->notice->id
170                 ),
171                 __FILE__
172             );
173             return false;
174         }
175
176         // If it's not a reply, or if the user WANTS to send @-replies,
177         // then, yeah, it can go to Facebook.
178
179         if (empty($this->notice->reply_to) ||
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              // TRANS: Server exception thrown when permission check fails.
344              throw new ServerException(_('No such permission!'));
345         }
346
347         $fbuid = $this->flink->foreign_id;
348
349         common_debug(
350             sprintf(
351                 'Checking for %s permission for user %s (%d), fbuid %d',
352                 $permission,
353                 $this->user->nickname,
354                 $this->user->id,
355                 $fbuid
356             ),
357             __FILE__
358         );
359
360         $hasPermission = $this->facebook->api(
361             array(
362                 'method'   => 'users.hasAppPermission',
363                 'ext_perm' => $permission,
364                 'uid'      => $fbuid
365             )
366         );
367
368         if ($hasPermission == 1) {
369
370             common_debug(
371                 sprintf(
372                     '%s (%d), fbuid %d has %s permission',
373                     $permission,
374                     $this->user->nickname,
375                     $this->user->id,
376                     $fbuid
377                 ),
378                 __FILE__
379             );
380
381             return true;
382
383         } else {
384
385             $logMsg = '%s (%d), fbuid $fbuid does NOT have %s permission.'
386                     . 'Facebook returned: %s';
387
388             common_debug(
389                 sprintf(
390                     $logMsg,
391                     $this->user->nickname,
392                     $this->user->id,
393                     $permission,
394                     $fbuid,
395                     var_export($result, true)
396                 ),
397                 __FILE__
398             );
399
400             return false;
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             // @todo 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             // Save a mapping
586             Notice_to_item::saveNew($this->notice->id, $result);
587
588             common_log(
589                 LOG_INFO,
590                 sprintf(
591                     'Posted notice %d as a %s for %s (%d), fbuid %d',
592                     $this->notice->id,
593                     empty($fbattachment) ? 'stream item' : 'stream item with attachment',
594                     $this->user->nickname,
595                     $this->user->id,
596                     $fbuid
597                 ),
598                 __FILE__
599             );
600         } else {
601
602             $msg = sprintf(
603                 'Could not post notice %d as a %s for %s (%d), fbuid %d - error code: %s',
604                 $this->notice->id,
605                 empty($fbattachment) ? 'stream item' : 'stream item with attachment',
606                 $this->user->nickname,
607                 $this->user->id,
608                 $result, // result will contain an error code
609                 $fbuid
610             );
611
612             throw new FacebookApiException($msg, $result);
613         }
614     }
615
616     /*
617      * Format the text message of a stream item so it's appropriate for
618      * sending to Facebook. If the notice is too long, truncate it, and
619      * add a linkback to the original notice at the end.
620      *
621      * @return String $txt the formated message
622      */
623     function formatMessage()
624     {
625         // Start with the plaintext source of this notice...
626         $txt = $this->notice->content;
627
628         // Facebook has a 420-char hardcoded max.
629         if (mb_strlen($statustxt) > 420) {
630             $noticeUrl = common_shorten_url($this->notice->getUrl());
631             $urlLen = mb_strlen($noticeUrl);
632             $txt = mb_substr($statustxt, 0, 420 - ($urlLen + 3)) . ' â€¦ ' . $noticeUrl;
633         }
634
635         return $txt;
636     }
637
638     /*
639      * Format attachments for the old REST API stream.publish method
640      *
641      * Note: Old REST API supports multiple attachments per post
642      *
643      */
644     function formatAttachments()
645     {
646         $attachments = $this->notice->attachments();
647
648         $fbattachment          = array();
649         $fbattachment['media'] = array();
650
651         foreach($attachments as $attachment)
652         {
653             try {
654                 $enclosure = $attachment->getEnclosure();
655                 $fbmedia = $this->getFacebookMedia($enclosure);
656             } catch (ServerException $e) {
657                 $fbmedia = $this->getFacebookMedia($attachment);
658             }
659             if($fbmedia){
660                 $fbattachment['media'][]=$fbmedia;
661             }else{
662                 $fbattachment['name'] = ($attachment->title ?
663                                       $attachment->title : $attachment->url);
664                 $fbattachment['href'] = $attachment->url;
665             }
666         }
667         if(count($fbattachment['media'])>0){
668             unset($fbattachment['name']);
669             unset($fbattachment['href']);
670         }
671         return $fbattachment;
672     }
673
674     /**
675      * given a File objects, returns an associative array suitable for Facebook media
676      */
677     function getFacebookMedia($attachment)
678     {
679         $fbmedia    = array();
680
681         if (strncmp($attachment->mimetype, 'image/', strlen('image/')) == 0) {
682             $fbmedia['type']         = 'image';
683             $fbmedia['src']          = $attachment->url;
684             $fbmedia['href']         = $attachment->url;
685         } else if ($attachment->mimetype == 'audio/mpeg') {
686             $fbmedia['type']         = 'mp3';
687             $fbmedia['src']          = $attachment->url;
688         }else if ($attachment->mimetype == 'application/x-shockwave-flash') {
689             $fbmedia['type']         = 'flash';
690
691             // http://wiki.developers.facebook.com/index.php/Attachment_%28Streams%29
692             // says that imgsrc is required... but we have no value to put in it
693             // $fbmedia['imgsrc']='';
694
695             $fbmedia['swfsrc']       = $attachment->url;
696         }else{
697             return false;
698         }
699         return $fbmedia;
700     }
701
702     /*
703      * Disconnect a user from Facebook by deleting his Foreign_link.
704      * Notifies the user his account has been disconnected by email.
705      */
706     function disconnect()
707     {
708         $fbuid = $this->flink->foreign_id;
709
710         common_log(
711             LOG_INFO,
712             sprintf(
713                 'Removing Facebook link for %s (%d), fbuid %d',
714                 $this->user->nickname,
715                 $this->user->id,
716                 $fbuid
717             ),
718             __FILE__
719         );
720
721         $result = $this->flink->delete();
722
723         if (empty($result)) {
724             common_log(
725                 LOG_ERR,
726                 sprintf(
727                     'Could not remove Facebook link for %s (%d), fbuid %d',
728                     $this->user->nickname,
729                     $this->user->id,
730                     $fbuid
731                 ),
732                 __FILE__
733             );
734             common_log_db_error($flink, 'DELETE', __FILE__);
735         }
736
737         // Notify the user that we are removing their Facebook link
738         if (!empty($this->user->email)) {
739             $result = $this->mailFacebookDisconnect();
740
741             if (!$result) {
742                 $msg = 'Unable to send email to notify %s (%d), fbuid %d '
743                      . 'about his/her Facebook link being removed.';
744
745                 common_log(
746                     LOG_WARNING,
747                     sprintf(
748                         $msg,
749                         $this->user->nickname,
750                         $this->user->id,
751                         $fbuid
752                     ),
753                     __FILE__
754                 );
755             }
756         } else {
757             $msg = 'Unable to send email to notify %s (%d), fbuid %d '
758                  . 'about his/her Facebook link being removed because the '
759                  . 'user has not set an email address.';
760
761             common_log(
762                 LOG_WARNING,
763                 sprintf(
764                     $msg,
765                     $this->user->nickname,
766                     $this->user->id,
767                     $fbuid
768                 ),
769                 __FILE__
770             );
771         }
772     }
773
774     /**
775      * Send a mail message to notify a user that her Facebook link
776      * has been terminated.
777      *
778      * @return boolean success flag
779      */
780     function mailFacebookDisconnect()
781     {
782         $profile = $this->user->getProfile();
783
784         $siteName = common_config('site', 'name');
785
786         common_switch_locale($this->user->language);
787
788         // TRANS: E-mail subject.
789         $subject = _m('Your Facebook connection has been removed');
790
791         // TRANS: E-mail body. %1$s is a username, %2$s is the StatusNet sitename.
792         $msg = _m("Hi %1\$s,\n\n".
793                   "We are sorry to inform you we are unable to publish your notice to\n".
794                   "Facebook, and have removed the connection between your %2\$s account and\n".
795                   "Facebook.\n\n".
796                   "This may have happened because you have removed permission for %2\$s\n".
797                   "to post on your behalf, or perhaps you have deactivated your Facebook\n".
798                   "account. You can reconnect your %2\$s account to Facebook at any time by\n".
799                   "logging in with Facebook again.\n\n".
800                   "Sincerely,\n\n".
801                   "%2\$s\n");
802
803         $body = sprintf(
804             $msg,
805             $this->user->nickname,
806             $siteName
807         );
808
809         common_switch_locale();
810
811         $result = mail_to_user($this->user, $subject, $body);
812
813         if (empty($this->user->password)) {
814             $result = self::emailWarn($this->user);
815         }
816
817         return $result;
818     }
819
820     /*
821      * Send the user an email warning that their account has been
822      * disconnected and he/she has no way to login and must contact
823      * the site administrator for help.
824      *
825      * @param User $user the deauthorizing user
826      *
827      */
828     static function emailWarn($user)
829     {
830         $profile = $user->getProfile();
831
832         $siteName  = common_config('site', 'name');
833         $siteEmail = common_config('site', 'email');
834
835         if (empty($siteEmail)) {
836             common_log(
837                 LOG_WARNING,
838                     "No site email address configured. Please set one."
839             );
840         }
841
842         common_switch_locale($user->language);
843
844         // TRANS: E-mail subject. %s is the StatusNet sitename.
845         $subject = _m('Contact the %s administrator to retrieve your account');
846
847         // TRANS: E-mail body. %1$s is a username,
848         // TRANS: %2$s is the StatusNet sitename, %3$s is the site contact e-mail address.
849         $msg = _m("Hi %1\$s,\n\n".
850                   "We have noticed you have deauthorized the Facebook connection for your\n".
851                   "%2\$s account.  You have not set a password for your %2\$s account yet, so\n".
852                   "you will not be able to login. If you wish to continue using your %2\$s\n".
853                   "account, please contact the site administrator (%3\$s) to set a password.\n\n".
854                   "Sincerely,\n\n".
855                   "%2\$s\n");
856
857         $body = sprintf(
858             $msg,
859             $user->nickname,
860             $siteName,
861             $siteEmail
862         );
863
864         common_switch_locale();
865
866         if (mail_to_user($user, $subject, $body)) {
867             common_log(
868                 LOG_INFO,
869                 sprintf(
870                     'Sent account lockout warning to %s (%d)',
871                     $user->nickname,
872                     $user->id
873                 ),
874                 __FILE__
875             );
876         } else {
877             common_log(
878                 LOG_WARNING,
879                 sprintf(
880                     'Unable to send account lockout warning to %s (%d)',
881                     $user->nickname,
882                     $user->id
883                 ),
884                 __FILE__
885             );
886         }
887     }
888
889     /*
890      * Check to see if we have a mapping to a copy of this notice
891      * on Facebook
892      *
893      * @param Notice $notice the notice to check
894      *
895      * @return mixed null if it can't find one, or the id of the Facebook
896      *               stream item
897      */
898     static function facebookStatusId($notice)
899     {
900         $n2i = Notice_to_item::getKV('notice_id', $notice->id);
901
902         if (empty($n2i)) {
903             return null;
904         } else {
905             return $n2i->item_id;
906         }
907     }
908
909     /*
910      * Save a Foreign_user record of a Facebook user
911      *
912      * @param object $fbuser a Facebook Graph API user obj
913      *                       See: http://developers.facebook.com/docs/reference/api/user
914      * @return mixed $result Id or key
915      *
916      */
917     static function addFacebookUser($fbuser)
918     {
919         // remove any existing, possibly outdated, record
920         try {
921             $fuser = Foreign_user::getForeignUser($fbuser->id, FACEBOOK_SERVICE);
922             $result = $fuser->delete();
923             if ($result != false) {
924                 common_log(
925                     LOG_INFO,
926                     sprintf(
927                         'Removed old Facebook user: %s, fbuid %d',
928                         $fbuid->name,
929                         $fbuid->id
930                     ),
931                     __FILE__
932                 );
933             }
934         } catch (NoResultException $e) {
935             // no old foreign users exist for this id
936         }
937
938         $fuser = new Foreign_user();
939
940         $fuser->nickname = $fbuser->username;
941         $fuser->uri      = $fbuser->link;
942         $fuser->id       = $fbuser->id;
943         $fuser->service  = FACEBOOK_SERVICE;
944         $fuser->created  = common_sql_now();
945
946         $result = $fuser->insert();
947
948         if (empty($result)) {
949             common_log(
950                 LOG_WARNING,
951                     sprintf(
952                         'Failed to add new Facebook user: %s, fbuid %d',
953                         $fbuser->username,
954                         $fbuser->id
955                     ),
956                     __FILE__
957             );
958
959             common_log_db_error($fuser, 'INSERT', __FILE__);
960         } else {
961             common_log(
962                 LOG_INFO,
963                 sprintf(
964                     'Added new Facebook user: %s, fbuid %d',
965                     $fbuser->name,
966                     $fbuser->id
967                 ),
968                 __FILE__
969             );
970         }
971
972         return $result;
973     }
974
975     /*
976      * Remove an item from a Facebook user's feed if we have a mapping
977      * for it.
978      */
979     function streamRemove()
980     {
981         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
982
983         if (!empty($this->flink) && !empty($n2i)) {
984             try {
985                 $result = $this->facebook->api(
986                     array(
987                         'method'  => 'stream.remove',
988                         'post_id' => $n2i->item_id,
989                         'uid'     => $this->flink->foreign_id
990                     )
991                 );
992
993                 if (!empty($result) && result == true) {
994                     common_log(
995                       LOG_INFO,
996                         sprintf(
997                             'Deleted Facebook item: %s for %s (%d), fbuid %d',
998                             $n2i->item_id,
999                             $this->user->nickname,
1000                             $this->user->id,
1001                             $this->flink->foreign_id
1002                         ),
1003                         __FILE__
1004                     );
1005
1006                     $n2i->delete();
1007
1008                 } else {
1009                     throw new FaceboookApiException(var_export($result, true));
1010                 }
1011             } catch (FacebookApiException $e) {
1012                 common_log(
1013                   LOG_WARNING,
1014                     sprintf(
1015                         'Could not deleted Facebook item: %s for %s (%d), '
1016                             . 'fbuid %d - (API error: %s) item already deleted '
1017                             . 'on Facebook? ',
1018                         $n2i->item_id,
1019                         $this->user->nickname,
1020                         $this->user->id,
1021                         $this->flink->foreign_id,
1022                         $e
1023                     ),
1024                     __FILE__
1025                 );
1026             }
1027         }
1028     }
1029
1030     /*
1031      * Like an item in a Facebook user's feed if we have a mapping
1032      * for it.
1033      */
1034     function like()
1035     {
1036         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
1037
1038         if (!empty($this->flink) && !empty($n2i)) {
1039             try {
1040                 $result = $this->facebook->api(
1041                     array(
1042                         'method'  => 'stream.addlike',
1043                         'post_id' => $n2i->item_id,
1044                         'uid'     => $this->flink->foreign_id
1045                     )
1046                 );
1047
1048                 if (!empty($result) && result == true) {
1049                     common_log(
1050                       LOG_INFO,
1051                         sprintf(
1052                             'Added like for item: %s for %s (%d), fbuid %d',
1053                             $n2i->item_id,
1054                             $this->user->nickname,
1055                             $this->user->id,
1056                             $this->flink->foreign_id
1057                         ),
1058                         __FILE__
1059                     );
1060                 } else {
1061                     throw new FacebookApiException(var_export($result, true));
1062                 }
1063             } catch (FacebookApiException $e) {
1064                 common_log(
1065                   LOG_WARNING,
1066                     sprintf(
1067                         'Could not like Facebook item: %s for %s (%d), '
1068                             . 'fbuid %d (API error: %s)',
1069                         $n2i->item_id,
1070                         $this->user->nickname,
1071                         $this->user->id,
1072                         $this->flink->foreign_id,
1073                         $e
1074                     ),
1075                     __FILE__
1076                 );
1077             }
1078         }
1079     }
1080
1081     /*
1082      * Unlike an item in a Facebook user's feed if we have a mapping
1083      * for it.
1084      */
1085     function unLike()
1086     {
1087         $n2i = Notice_to_item::getKV('notice_id', $this->notice->id);
1088
1089         if (!empty($this->flink) && !empty($n2i)) {
1090             try {
1091                 $result = $this->facebook->api(
1092                     array(
1093                         'method'  => 'stream.removeLike',
1094                         'post_id' => $n2i->item_id,
1095                         'uid'     => $this->flink->foreign_id
1096                     )
1097                 );
1098
1099                 if (!empty($result) && result == true) {
1100                     common_log(
1101                       LOG_INFO,
1102                         sprintf(
1103                             'Removed like for item: %s for %s (%d), fbuid %d',
1104                             $n2i->item_id,
1105                             $this->user->nickname,
1106                             $this->user->id,
1107                             $this->flink->foreign_id
1108                         ),
1109                         __FILE__
1110                     );
1111
1112                 } else {
1113                     throw new FacebookApiException(var_export($result, true));
1114                 }
1115             } catch (FacebookApiException $e) {
1116                   common_log(
1117                   LOG_WARNING,
1118                     sprintf(
1119                         'Could not remove like for Facebook item: %s for %s '
1120                           . '(%d), fbuid %d (API error: %s)',
1121                         $n2i->item_id,
1122                         $this->user->nickname,
1123                         $this->user->id,
1124                         $this->flink->foreign_id,
1125                         $e
1126                     ),
1127                     __FILE__
1128                 );
1129             }
1130         }
1131     }
1132 }