]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/twittersettings.php
Twitter OAuth server dance working
[quix0rs-gnu-social.git] / actions / twittersettings.php
1 <?php
2 /**
3  * Laconica, the distributed open-source microblogging tool
4  *
5  * Settings for Twitter integration
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  Settings
23  * @package   Laconica
24  * @author    Evan Prodromou <evan@controlyourself.ca>
25  * @copyright 2008-2009 Control Yourself, Inc.
26  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
27  * @link      http://laconi.ca/
28  */
29
30 if (!defined('LACONICA')) {
31     exit(1);
32 }
33
34 require_once INSTALLDIR.'/lib/connectsettingsaction.php';
35 require_once INSTALLDIR.'/lib/twitter.php';
36
37 define('SUBSCRIPTIONS', 80);
38
39 /**
40  * Settings for Twitter integration
41  *
42  * @category Settings
43  * @package  Laconica
44  * @author   Evan Prodromou <evan@controlyourself.ca>
45  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
46  * @link     http://laconi.ca/
47  *
48  * @see      SettingsAction
49  */
50
51 class TwittersettingsAction extends ConnectSettingsAction
52 {
53     /**
54      * Title of the page
55      *
56      * @return string Title of the page
57      */
58
59     function title()
60     {
61         return _('Twitter settings');
62     }
63
64     /**
65      * Instructions for use
66      *
67      * @return instructions for use
68      */
69
70     function getInstructions()
71     {
72         return _('Connect your Twitter account to share your updates ' .
73          'with your Twitter friends and vice-versa.');
74     }
75
76     /**
77      * Content area of the page
78      *
79      * Shows a form for associating a Twitter account with this
80      * Laconica account. Also lets the user set preferences.
81      *
82      * @return void
83      */
84
85     function showContent()
86     {
87         $user = common_current_user();
88
89         $profile = $user->getProfile();
90
91         $fuser = null;
92
93         $flink = Foreign_link::getByUserID($user->id, TWITTER_SERVICE);
94
95         if (!empty($flink)) {
96             $fuser = $flink->getForeignUser();
97         }
98
99         $this->elementStart('form', array('method' => 'post',
100                                           'id' => 'form_settings_twitter',
101                                           'class' => 'form_settings',
102                                           'action' =>
103                                           common_local_url('twittersettings')));
104
105         $this->hidden('token', common_session_token());
106
107
108         if (empty($fuser)) {
109
110             $this->elementStart('fieldset', array('id' => 'settings_twitter_account'));
111             $this->elementStart('ul', 'form_data');
112             $this->elementStart('li', array('id' => 'settings_twitter_login_button'));
113             $this->element('a', array('href' => common_local_url('twitterauthorization')),
114                 'Connect my Twitter account');
115                 $this->elementEnd('li');
116             $this->elementEnd('ul');
117             $this->elementEnd('fieldset');
118
119         } else {
120
121             $this->elementStart('fieldset',
122                                 array('id' => 'settings_twitter_preferences'));
123             $this->element('legend', null, _('Preferences'));
124
125             $this->elementStart('ul', 'form_data');
126             $this->elementStart('li');
127             $this->checkbox('noticesend',
128                     _('Automatically send my notices to Twitter.'),
129                     ($flink) ?
130                     ($flink->noticesync & FOREIGN_NOTICE_SEND) :
131                     true);
132             $this->elementEnd('li');
133             $this->elementStart('li');
134             $this->checkbox('replysync',
135                     _('Send local "@" replies to Twitter.'),
136                     ($flink) ?
137                     ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) :
138                     true);
139             $this->elementEnd('li');
140             $this->elementStart('li');
141             $this->checkbox('friendsync',
142                     _('Subscribe to my Twitter friends here.'),
143                     ($flink) ?
144                     ($flink->friendsync & FOREIGN_FRIEND_RECV) :
145                     false);
146             $this->elementEnd('li');
147
148             if (common_config('twitterbridge','enabled')) {
149             $this->elementStart('li');
150             $this->checkbox('noticerecv',
151                     _('Import my Friends Timeline.'),
152                     ($flink) ?
153                     ($flink->noticesync & FOREIGN_NOTICE_RECV) :
154                     false);
155             $this->elementEnd('li');
156
157             // preserve setting even if bidrection bridge toggled off
158
159             if ($flink && ($flink->noticesync & FOREIGN_NOTICE_RECV)) {
160                 $this->hidden('noticerecv', true, 'noticerecv');
161             }
162         }
163
164         $this->elementEnd('ul');
165
166         if ($flink) {
167             $this->submit('save', _('Save'));
168         } else {
169             $this->submit('add', _('Add'));
170         }
171
172         $this->elementEnd('fieldset');
173     }
174
175     $this->showTwitterSubscriptions();
176
177     $this->elementEnd('form');
178     }
179
180     /**
181      * Gets some of the user's Twitter friends
182      *
183      * Gets the number of Twitter friends that are on this
184      * instance of Laconica.
185      *
186      * @return array array of User objects
187      */
188
189     function subscribedTwitterUsers()
190     {
191
192         $current_user = common_current_user();
193
194         $qry = 'SELECT "user".* ' .
195           'FROM subscription ' .
196           'JOIN "user" ON subscription.subscribed = "user".id ' .
197           'JOIN foreign_link ON foreign_link.user_id = "user".id ' .
198           'WHERE subscriber = %d ' .
199           'ORDER BY "user".nickname';
200
201         $user = new User();
202
203         $user->query(sprintf($qry, $current_user->id));
204
205         $users = array();
206
207         while ($user->fetch()) {
208
209             // Don't include the user's own self-subscription
210             if ($user->id != $current_user->id) {
211                 $users[] = clone($user);
212             }
213         }
214
215         return $users;
216     }
217
218     /**
219      * Show user's Twitter friends
220      *
221      * Gets the number of Twitter friends that are on this
222      * instance of Laconica, and shows their mini-avatars.
223      *
224      * @return void
225      */
226
227     function showTwitterSubscriptions()
228     {
229
230         $friends = $this->subscribedTwitterUsers();
231
232         $friends_count = count($friends);
233
234         if ($friends_count > 0) {
235             $this->elementStart('div', array('id' => 'entity_subscriptions',
236                                              'class' => 'section'));
237             $this->element('h2', null, _('Twitter Friends'));
238             $this->elementStart('ul', 'entities users xoxo');
239
240             for ($i = 0; $i < min($friends_count, SUBSCRIPTIONS); $i++) {
241
242                 $other = Profile::staticGet($friends[$i]->id);
243
244                 if (!$other) {
245                     common_log_db_error($subs, 'SELECT', __FILE__);
246                     continue;
247                 }
248
249                 $this->elementStart('li', 'vcard');
250                 $this->elementStart('a', array('title' => ($other->fullname) ?
251                                                $other->fullname :
252                                                $other->nickname,
253                                                'href' => $other->profileurl,
254                                                'class' => 'url'));
255
256                 $avatar = $other->getAvatar(AVATAR_MINI_SIZE);
257
258                 $avatar_url = ($avatar) ?
259                   $avatar->displayUrl() :
260                   Avatar::defaultImage(AVATAR_MINI_SIZE);
261
262                 $this->element('img', array('src' => $avatar_url,
263                                             'width' => AVATAR_MINI_SIZE,
264                                             'height' => AVATAR_MINI_SIZE,
265                                             'class' => 'avatar photo',
266                                             'alt' =>  ($other->fullname) ?
267                                             $other->fullname :
268                                             $other->nickname));
269
270                 $this->element('span', 'fn nickname', $other->nickname);
271                 $this->elementEnd('a');
272                 $this->elementEnd('li');
273
274             }
275
276             $this->elementEnd('ul');
277             $this->elementEnd('div');
278
279         }
280     }
281
282     /**
283      * Handle posts to this form
284      *
285      * Based on the button that was pressed, muxes out to other functions
286      * to do the actual task requested.
287      *
288      * All sub-functions reload the form with a message -- success or failure.
289      *
290      * @return void
291      */
292
293     function handlePost()
294     {
295
296         // CSRF protection
297         $token = $this->trimmed('token');
298         if (!$token || $token != common_session_token()) {
299             $this->showForm(_('There was a problem with your session token. '.
300                               'Try again, please.'));
301             return;
302         }
303
304         if ($this->arg('save')) {
305             $this->savePreferences();
306         } else if ($this->arg('add')) {
307             $this->addTwitterAccount();
308         } else if ($this->arg('remove')) {
309             $this->removeTwitterAccount();
310         } else {
311             $this->showForm(_('Unexpected form submission.'));
312         }
313     }
314
315     /**
316      * Associate a Twitter account with the user's account
317      *
318      * Validates post input; verifies it against Twitter; and if
319      * successful stores in the database.
320      *
321      * @return void
322      */
323
324     function addTwitterAccount()
325     {
326         $screen_name = $this->trimmed('twitter_username');
327         $password    = $this->trimmed('twitter_password');
328         $noticesend  = $this->boolean('noticesend');
329         $noticerecv  = $this->boolean('noticerecv');
330         $replysync   = $this->boolean('replysync');
331         $friendsync  = $this->boolean('friendsync');
332
333         if (!Validate::string($screen_name,
334                               array('min_length' => 1,
335                                     'max_length' => 15,
336                                     'format' => VALIDATE_NUM.VALIDATE_ALPHA.'_'))) {
337             $this->showForm(_('Username must have only numbers, '.
338                               'upper- and lowercase letters, '.
339                               'and underscore (_). 15 chars max.'));
340             return;
341         }
342
343         if (!$this->verifyCredentials($screen_name, $password)) {
344             $this->showForm(_('Could not verify your Twitter credentials!'));
345             return;
346         }
347
348         $twit_user = twitter_user_info($screen_name, $password);
349
350         if (!$twit_user) {
351             $this->showForm(sprintf(_('Unable to retrieve account information '.
352                                       'For "%s" from Twitter.'),
353                                     $screen_name));
354             return;
355         }
356
357         if (!save_twitter_user($twit_user->id, $screen_name)) {
358             $this->showForm(_('Unable to save your Twitter settings!'));
359             return;
360         }
361
362         $user = common_current_user();
363
364         $flink = new Foreign_link();
365
366         $flink->user_id     = $user->id;
367         $flink->foreign_id  = $twit_user->id;
368         $flink->service     = TWITTER_SERVICE;
369         $flink->credentials = $password;
370         $flink->created     = common_sql_now();
371
372         $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync);
373
374         $flink_id = $flink->insert();
375
376         if (!$flink_id) {
377             common_log_db_error($flink, 'INSERT', __FILE__);
378             $this->showForm(_('Unable to save your Twitter settings!'));
379             return;
380         }
381
382         if ($friendsync) {
383             save_twitter_friends($user, $twit_user->id, $screen_name, $password);
384             $flink->last_friendsync = common_sql_now();
385             $flink->update();
386         }
387
388         $this->showForm(_('Twitter settings saved.'), true);
389     }
390
391     /**
392      * Disassociate an existing Twitter account from this account
393      *
394      * @return void
395      */
396
397     function removeTwitterAccount()
398     {
399         $user = common_current_user();
400
401         $flink = Foreign_link::getByUserID($user->id, 1);
402
403         $flink_foreign_id = $this->arg('flink_foreign_id');
404
405         // Maybe an old tab open...?
406         if ($flink->foreign_id != $flink_foreign_id) {
407             $this->showForm(_('That is not your Twitter account.'));
408             return;
409         }
410
411         $result = $flink->delete();
412
413         if (!$result) {
414             common_log_db_error($flink, 'DELETE', __FILE__);
415             $this->serverError(_('Couldn\'t remove Twitter user.'));
416             return;
417         }
418
419         $this->showForm(_('Twitter account removed.'), true);
420     }
421
422     /**
423      * Save user's Twitter-bridging preferences
424      *
425      * @return void
426      */
427
428     function savePreferences()
429     {
430         $noticesend = $this->boolean('noticesend');
431         $noticerecv = $this->boolean('noticerecv');
432         $friendsync = $this->boolean('friendsync');
433         $replysync  = $this->boolean('replysync');
434
435         $user = common_current_user();
436
437         $flink = Foreign_link::getByUserID($user->id, 1);
438
439         if (!$flink) {
440             common_log_db_error($flink, 'SELECT', __FILE__);
441             $this->showForm(_('Couldn\'t save Twitter preferences.'));
442             return;
443         }
444
445         $twitter_id = $flink->foreign_id;
446         $password   = $flink->credentials;
447
448         $fuser = $flink->getForeignUser();
449
450         if (!$fuser) {
451             common_log_db_error($fuser, 'SELECT', __FILE__);
452             $this->showForm(_('Couldn\'t save Twitter preferences.'));
453             return;
454         }
455
456         $screen_name = $fuser->nickname;
457
458         $original = clone($flink);
459
460         $flink->set_flags($noticesend, $noticerecv, $replysync, $friendsync);
461
462         $result = $flink->update($original);
463
464         if ($result === false) {
465             common_log_db_error($flink, 'UPDATE', __FILE__);
466             $this->showForm(_('Couldn\'t save Twitter preferences.'));
467             return;
468         }
469
470         if ($friendsync) {
471             save_twitter_friends($user, $flink->foreign_id, $screen_name, $password);
472         }
473
474         $this->showForm(_('Twitter preferences saved.'), true);
475     }
476
477     /**
478      * Verifies a username and password against Twitter's API
479      *
480      * @param string $screen_name Twitter user name
481      * @param string $password    Twitter password
482      *
483      * @return boolean success flag
484      */
485
486     function verifyCredentials($screen_name, $password)
487     {
488         $uri = 'http://twitter.com/account/verify_credentials.json';
489
490         $data = get_twitter_data($uri, $screen_name, $password);
491
492         if (!$data) {
493             return false;
494         }
495
496         $user = json_decode($data);
497
498         if (!$user) {
499             return false;
500         }
501
502         $twitter_id = $user->id;
503
504         if ($twitter_id) {
505             return $twitter_id;
506         }
507
508         return false;
509     }
510
511 }