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