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