]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - plugins/Facebook/FacebookPlugin.php
cf6781cfaf8d85a0c807e12f18442c916d6b96c5
[quix0rs-gnu-social.git] / plugins / Facebook / FacebookPlugin.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Plugin to add a StatusNet Facebook application
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    Zach Copley <zach@status.net>
25  * @copyright 2009 StatusNet, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://status.net/
28  */
29
30 if (!defined('STATUSNET')) {
31     exit(1);
32 }
33
34 define("FACEBOOK_CONNECT_SERVICE", 3);
35
36 require_once INSTALLDIR . '/plugins/Facebook/facebookutil.php';
37 require_once INSTALLDIR . '/plugins/Facebook/FBConnectAuth.php';
38 require_once INSTALLDIR . '/plugins/Facebook/FBConnectLogin.php';
39 require_once INSTALLDIR . '/plugins/Facebook/FBConnectSettings.php';
40 require_once INSTALLDIR . '/plugins/Facebook/FBCLoginGroupNav.php';
41 require_once INSTALLDIR . '/plugins/Facebook/FBCSettingsNav.php';
42 require_once INSTALLDIR . '/plugins/Facebook/FBC_XDReceiver.php';
43
44 /**
45  * Facebook plugin to add a StatusNet Facebook application
46  *
47  * @category Plugin
48  * @package  StatusNet
49  * @author   Zach Copley <zach@status.net>
50  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
51  * @link     http://status.net/
52  */
53
54 class FacebookPlugin extends Plugin
55 {
56
57     /**
58      * Add Facebook app actions to the router table
59      *
60      * Hook for RouterInitialized event.
61      *
62      * @param Net_URL_Mapper &$m path-to-action mapper
63      *
64      * @return boolean hook return
65      */
66
67     function onRouterInitialized(&$m)
68     {
69
70         // Facebook App stuff
71
72         $m->connect('facebook', array('action' => 'facebookhome'));
73         $m->connect('facebook/index.php', array('action' => 'facebookhome'));
74         $m->connect('facebook/settings.php', array('action' => 'facebooksettings'));
75         $m->connect('facebook/invite.php', array('action' => 'facebookinvite'));
76         $m->connect('facebook/remove', array('action' => 'facebookremove'));
77
78         // Facebook Connect stuff
79
80         $m->connect('main/facebookconnect', array('action' => 'FBConnectAuth'));
81         $m->connect('main/facebooklogin', array('action' => 'FBConnectLogin'));
82         $m->connect('settings/facebook', array('action' => 'FBConnectSettings'));
83         $m->connect('xd_receiver.html', array('action' => 'FBC_XDReceiver'));
84
85         return true;
86     }
87
88     /**
89      * Automatically load the actions and libraries used by the Facebook app
90      *
91      * @param Class $cls the class
92      *
93      * @return boolean hook return
94      *
95      */
96     function onAutoload($cls)
97     {
98         switch ($cls) {
99         case 'FacebookAction':
100         case 'FacebookhomeAction':
101         case 'FacebookinviteAction':
102         case 'FacebookremoveAction':
103         case 'FacebooksettingsAction':
104             include_once INSTALLDIR . '/plugins/Facebook/' .
105               strtolower(mb_substr($cls, 0, -6)) . '.php';
106             return false;
107         default:
108             return true;
109         }
110     }
111
112         // Add in xmlns:fb
113     function onStartShowHTML($action)
114     {
115
116         if ($this->reqFbScripts($action)) {
117
118             // XXX: Horrible hack to make Safari, FF2, and Chrome work with
119             // Facebook Connect. These browser cannot use Facebook's
120             // DOM parsing routines unless the mime type of the page is
121             // text/html even though Facebook Connect uses XHTML.  This is
122             // A bug in Facebook Connect, and this is a temporary solution
123             // until they fix their JavaScript libs.
124             header('Content-Type: text/html');
125
126             $action->extraHeaders();
127
128             $action->startXML('html');
129
130             $language = $action->getLanguage();
131
132             $action->elementStart('html',
133                 array('xmlns'  => 'http://www.w3.org/1999/xhtml',
134                       'xmlns:fb' => 'http://www.facebook.com/2008/fbml',
135                       'xml:lang' => $language,
136                       'lang'     => $language));
137
138             return false;
139
140         } else {
141
142             return true;
143         }
144     }
145
146         // Note: this script needs to appear in the <body>
147
148     function onEndShowScripts($action)
149     {
150         if ($this->reqFbScripts($action)) {
151
152             $apikey = common_config('facebook', 'apikey');
153             $plugin_path = common_path('plugins/Facebook');
154
155             $login_url = common_local_url('FBConnectAuth');
156             $logout_url = common_local_url('logout');
157
158             // XXX: Facebook says we don't need this FB_RequireFeatures(),
159             // but we actually do, for IE and Safari. Gar.
160
161             $js =  '<script type="text/javascript">';
162             $js .= '    $(document).ready(function () {';
163             $js .= '         FB_RequireFeatures(';
164             $js .= '             ["XFBML"], function() {';
165             $js .= '                 FB.init("%1$s", "../xd_receiver.html");';
166             $js .= '             }';
167             $js .= '         );';
168             $js .= '    });';
169
170             $js .= '    function goto_login() {';
171             $js .= '        window.location = "%2$s";';
172             $js .= '    }';
173
174             // The below function alters the logout link so that it logs the user out
175             // of Facebook Connect as well as the site.  However, for some pages
176             // (FB Connect Settings) we need to output the FB Connect scripts (to
177             // show an existing FB connection even if the user isn't authenticated
178             // with Facebook connect) but NOT alter the logout link. And the only
179             // way to reliably do that is with the FB Connect .js libs.  Crazy.
180
181             $js .= '    FB.ensureInit(function() {';
182             $js .= '        FB.Connect.ifUserConnected(';
183             $js .= '            function() { ';
184             $js .= '                $(\'#nav_logout a\').attr(\'href\', \'#\');';
185             $js .= '                $(\'#nav_logout a\').click(function() {';
186             $js .= '                   FB.Connect.logoutAndRedirect(\'%3$s\');';
187             $js .= '                   return false;';
188             $js .= '                })';
189             $js .= '            },';
190             $js .= '            function() {';
191             $js .= '                return false;';
192             $js .= '            }';
193             $js .= '        );';
194             $js .= '     });';
195             $js .= '</script>';
196
197             $js = sprintf($js, $apikey, $login_url, $logout_url);
198
199             // Compress the bugger down a bit
200             $js = str_replace('  ', '', $js);
201
202             $action->raw("  $js");  // leading two spaces to make it line up
203         }
204
205     }
206
207         // Note: this script needs to appear as close as possible to </body>
208
209     function onEndShowFooter($action)
210     {
211         if ($this->reqFbScripts($action)) {
212             $action->script('http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php');
213         }
214     }
215
216     function onEndShowStatusNetStyles($action)
217     {
218         if ($this->reqFbScripts($action)) {
219             $action->cssLink('plugins/Facebook/FBConnect.css');
220         }
221     }
222
223         /**
224      * Does the Action we're plugged into require the FB Scripts?  We only
225      * want to output FB namespace, scripts, CSS, etc. on the pages that
226      * really need them.
227      *
228      * @param Action the action in question
229      *
230      * @return boolean true
231      */
232
233     function reqFbScripts($action) {
234
235         // If you're logged in w/FB Connect, you always need the FB stuff
236
237         $fbuid = $this->loggedIn();
238
239         if (!empty($fbuid)) {
240             return true;
241         }
242
243         // List of actions that require FB stuff
244
245         $needy = array('FBConnectLoginAction',
246                        'FBConnectauthAction',
247                        'FBConnectSettingsAction');
248
249         if (in_array(get_class($action), $needy)) {
250             return true;
251         }
252
253         return false;
254
255     }
256
257     /**
258      * Is the user currently logged in with FB Connect?
259      *
260      * @return mixed $fbuid the Facebook ID of the logged in user, or null
261      */
262
263     function loggedIn()
264     {
265         $user = common_current_user();
266
267         if (!empty($user)) {
268
269             $flink = Foreign_link::getByUserId($user->id,
270                 FACEBOOK_CONNECT_SERVICE);
271             $fbuid = 0;
272
273             if (!empty($flink)) {
274
275                 try {
276
277                     $facebook = getFacebook();
278                     $fbuid    = $facebook->get_loggedin_user();
279
280                 } catch (Exception $e) {
281                     common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
282                         'Problem getting Facebook user: ' .
283                             $e->getMessage());
284                 }
285
286                 if ($fbuid > 0) {
287                     return $fbuid;
288                 }
289             }
290         }
291
292         return null;
293     }
294
295     function onStartPrimaryNav($action)
296     {
297
298         $user = common_current_user();
299         $connect = 'FBConnectSettings';
300         if (common_config('xmpp', 'enabled')) {
301             $connect = 'imsettings';
302         } else if (common_config('sms', 'enabled')) {
303             $connect = 'smssettings';
304         } else if (common_config('twitter', 'enabled')) {
305             $connect = 'twittersettings';
306         }
307
308         if (!empty($user)) {
309
310             $fbuid = $this->loggedIn();
311
312             if (!empty($fbuid)) {
313
314                 /* Default FB silhouette pic for FB users who haven't
315                    uploaded a profile pic yet. */
316
317                 $silhouetteUrl =
318                     'http://static.ak.fbcdn.net/pics/q_silhouette.gif';
319
320                 $url = $this->getProfilePicURL($fbuid);
321
322                 $action->elementStart('li', array('id' => 'nav_fb'));
323
324                 $action->element('img', array('id' => 'fbc_profile-pic',
325                     'src' => (!empty($url)) ? $url : $silhouetteUrl,
326                     'alt' => 'Facebook Connect User',
327                     'width' => '16'), '');
328
329                 $iconurl =  common_path('plugins/Facebook/fbfavicon.ico');
330                 $action->element('img', array('id' => 'fb_favicon',
331                     'src' => $iconurl));
332
333                 $action->elementEnd('li');
334
335             }
336         }
337
338         return true;
339     }
340
341     function onStartShowLocalNavBlock($action)
342     {
343         $action_name   = get_class($action);
344
345         $login_actions = array('LoginAction', 'RegisterAction',
346             'OpenidloginAction', 'FBConnectLoginAction');
347
348         if (in_array($action_name, $login_actions)) {
349             $nav = new FBCLoginGroupNav($action);
350             $nav->show();
351             return false;
352         }
353
354         $connect_actions = array('SmssettingsAction', 'ImsettingsAction',
355             'TwittersettingsAction', 'FBConnectSettingsAction');
356
357         if (in_array($action_name, $connect_actions)) {
358             $nav = new FBCSettingsNav($action);
359             $nav->show();
360             return false;
361         }
362
363         return true;
364     }
365
366     function onStartLogout($action)
367     {
368         $action->logout();
369         $fbuid = $this->loggedIn();
370
371         if (!empty($fbuid)) {
372             try {
373                 $facebook = getFacebook();
374                 $facebook->expire_session();
375             } catch (Exception $e) {
376                 common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
377                            'Could\'t logout of Facebook: ' .
378                            $e->getMessage());
379             }
380         }
381
382         return true;
383     }
384
385     function getProfilePicURL($fbuid)
386     {
387
388         $facebook = getFacebook();
389         $url      = null;
390
391         try {
392
393             $fqry = 'SELECT pic_square FROM user WHERE uid = %s';
394
395             $result = $facebook->api_client->fql_query(sprintf($fqry, $fbuid));
396
397             if (!empty($result)) {
398                 $url = $result[0]['pic_square'];
399             }
400
401         } catch (Exception $e) {
402             common_log(LOG_WARNING, 'Facebook Connect Plugin - ' .
403                        "Facebook client failure requesting profile pic!");
404         }
405
406        return $url;
407
408     }
409
410     /**
411      * Add a Facebook queue item for each notice
412      *
413      * @param Notice $notice      the notice
414      * @param array  &$transports the list of transports (queues)
415      *
416      * @return boolean hook return
417      */
418     function onStartEnqueueNotice($notice, &$transports)
419     {
420         array_push($transports, 'facebook');
421         return true;
422     }
423
424     /**
425      * broadcast the message when not using queuehandler
426      *
427      * @param Notice &$notice the notice
428      * @param array  $queue   destination queue
429      *
430      * @return boolean hook return
431      */
432     function onUnqueueHandleNotice(&$notice, $queue)
433     {
434         if (($queue == 'facebook') && ($this->_isLocal($notice))) {
435             facebookBroadcastNotice($notice);
436             return false;
437         }
438         return true;
439     }
440
441     /**
442      * Determine whether the notice was locally created
443      *
444      * @param Notice $notice
445      *
446      * @return boolean locality
447      */
448     function _isLocal($notice)
449     {
450         return ($notice->is_local == Notice::LOCAL_PUBLIC ||
451                 $notice->is_local == Notice::LOCAL_NONPUBLIC);
452     }
453
454     /**
455      * Add Facebook queuehandler to the list of daemons to start
456      *
457      * @param array $daemons the list fo daemons to run
458      *
459      * @return boolean hook return
460      *
461      */
462     function onGetValidDaemons($daemons)
463     {
464         array_push($daemons, INSTALLDIR .
465                    '/plugins/Facebook/facebookqueuehandler.php');
466         return true;
467     }
468
469 }