]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/twittersettings.php
1115708a5cd9387e4e6305c4b541626f990186fe
[quix0rs-gnu-social.git] / actions / twittersettings.php
1 <?php
2 /*
3  * Laconica - a distributed open-source microblogging tool
4  * Copyright (C) 2008, Controlez-Vous, Inc.
5  *
6  * This program is free software: you can redistribute it and/or modify
7  * it under the terms of the GNU Affero General Public License as published by
8  * the Free Software Foundation, either version 3 of the License, or
9  * (at your option) any later version.
10  *
11  * This program is distributed in the hope that it will be useful,
12  * but WITHOUT ANY WARRANTY; without even the implied warranty of
13  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
14  * GNU Affero General Public License for more details.
15  *
16  * You should have received a copy of the GNU Affero General Public License
17  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
18  */
19
20 if (!defined('LACONICA')) { exit(1); }
21
22 require_once(INSTALLDIR.'/lib/settingsaction.php');
23
24 class TwittersettingsAction extends SettingsAction {
25
26         function get_instructions() {
27                 return _('Add your Twitter account to automatically send your notices to Twitter, ' .
28                         'and subscribe to Twitter friends already here.');
29         }
30
31         function show_form($msg=NULL, $success=false) {
32                 $user = common_current_user();
33                 $profile = $user->getProfile();
34                 $fuser = NULL;
35                 $flink = Foreign_link::getForeignLink($user->id, 1); // 1 == Twitter
36
37                 if ($flink) {
38                         $fuser = Foreign_user::getForeignUser($flink->foreign_id, 1);
39                 }
40
41                 $this->form_header(_('Twitter settings'), $msg, $success);
42                 common_element_start('form', array('method' => 'post',
43                                                                                    'id' => 'twittersettings',
44                                                                                    'action' =>
45                                                                                    common_local_url('twittersettings')));
46                 common_hidden('token', common_session_token());
47
48                 common_element('h2', NULL, _('Twitter Account'));
49
50                 if ($fuser) {
51                         common_element_start('p');
52
53                         common_element('span', 'twitter_user', $fuser->nickname);
54                         common_element('a', array('href' => $fuser->uri),  $fuser->uri);
55                         common_element('span', 'input_instructions',
56                                        _('Current verified Twitter account.'));
57                         common_hidden('flink_foreign_id', $flink->foreign_id);
58                         common_element_end('p');
59                         common_submit('remove', _('Remove'));
60                 } else {
61
62                         // XXX: Should we make an educated guess as to the twitter acct name? -- Zach
63                         common_input('twitter_username', _('Twitter Username'),
64                                                  ($this->arg('twitter_username')) ? $this->arg('twitter_username') : $profile->nickname,
65                                                  _('No spaces, please.')); // hey, it's what Twitter says
66
67                         common_password('twitter_password', _('Twitter Password'));
68                 }
69
70                 common_element('h2', NULL, _('Preferences'));
71
72                 common_checkbox('noticesync', _('Automatically send my notices to Twitter.'),
73                                                 ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND) : true);
74
75                 common_checkbox('replysync', _('Send local "@" replies to Twitter.'),
76                                                 ($flink) ? ($flink->noticesync & FOREIGN_NOTICE_SEND_REPLY) : true);
77
78                 common_checkbox('friendsync', _('Subscribe to my Twitter friends here.'),
79                                                 ($flink) ? ($flink->friendsync & FOREIGN_FRIEND_RECV) : false,
80                                                 NULL, 'true', true);
81
82                 if ($flink) {
83                         common_submit('save', _('Save'));
84                 } else {
85                         common_submit('add', _('Add'));
86                 }
87
88                 common_element_end('form');
89                 common_show_footer();
90         }
91
92         function handle_post() {
93
94                 # CSRF protection
95                 $token = $this->trimmed('token');
96                 if (!$token || $token != common_session_token()) {
97                         $this->show_form(_('There was a problem with your session token. Try again, please.'));
98                         return;
99                 }
100
101                 if ($this->arg('save')) {
102                         $this->save_preferences();
103                 } else if ($this->arg('add')) {
104                         $this->add_twitter_acct();
105                 } else if ($this->arg('remove')) {
106                         $this->remove_twitter_acct();
107                 } else {
108                         $this->show_form(_('Unexpected form submission.'));
109                 }
110         }
111
112         function add_twitter_acct() {
113                 $twitter_username = $this->trimmed('twitter_username');
114                 $twitter_password = $this->trimmed('twitter_password');
115                 $noticesync = $this->boolean('noticesync');
116                 $replysync = $this->boolean('replysync');
117                 $friendsync = $this->boolean('friendsync');
118
119                 if (!Validate::string($twitter_username, array('min_length' => 1,
120                                                                                                            'max_length' => 15,
121                                                                                                            'format' => VALIDATE_NUM . VALIDATE_ALPHA . '_'))) {
122                         $this->show_form(_('Username must have only numbers, upper- and lowercase letters, and underscore (_). 15 chars max.'));
123                         return;
124                 }
125
126                 // Verify this is a real Twitter user.
127                 if (!$this->verify_credentials($twitter_username, $twitter_password)) {
128                         $this->show_form(_('Could not verify your Twitter credentials!'));
129                         return;
130                 }
131
132                 // Now that we have a valid Twitter user, we have to make another api call to
133                 // find its Twitter ID.  Dumb, but true.
134                 $twitter_id = $this->get_twitter_id($twitter_username, $twitter_password);
135
136                 if (!$twitter_id) {
137                         $this->show_form(sprintf(_('Unable to retrieve account information for "%s" from Twitter.'), $twitter_username));
138                         return;
139                 }
140
141                 $fuser = null;
142                 $result = null;
143
144                 // Check to see whether the Twitter user is already in the system,
145                 // and update its username and uri if so.
146                 $fuser = Foreign_User::getForeignUser($twitter_id, 1);
147
148                 if ($fuser) {
149
150                         $original = clone($fuser);
151
152                         $fuser->nickname = $twitter_username;
153                         $fuser->uri = "http://www.twitter.com/$twitter_username";
154
155                         $result = $fuser->updateKeys($original);
156
157                         if (!$result) {
158                                 common_log_db_error($fuser, 'UPDATE', __FILE__);
159                         }
160
161                 } else {
162
163                         // Otherwise, add the Twitter user
164                         $fuser = DB_DataObject::factory('foreign_user');
165
166                         $fuser->nickname = $twitter_username;
167                         $fuser->uri = "http://www.twitter.com/$twitter_username";
168                         $fuser->id = $twitter_id;
169                         $fuser->service = 1; // Twitter
170                         $fuser->created = common_sql_now();
171                         $result = $fuser->insert();
172
173                         if (!$result) {
174                                 common_log_db_error($fuser, 'INSERT', __FILE__);
175                         }
176
177                 }
178
179                 if (!$result) {
180                         $this->show_form(_('Unable to save your Twitter settings!'));
181                         return;
182                 }
183
184                 $user = common_current_user();
185
186                 $flink = DB_DataObject::factory('foreign_link');
187                 $flink->user_id = $user->id;
188                 $flink->foreign_id = $fuser->id;
189                 $flink->service = 1; // Twitter
190                 $flink->credentials = $twitter_password;
191                 $flink->created = common_sql_now();
192
193                 $this->set_flags($flink, $noticesync, $replysync, $friendsync);
194
195                 $flink_id = $flink->insert();
196
197                 if (!$flink_id) {
198                         common_log_db_error($flink, 'INSERT', __FILE__);
199                         $this->show_form(_('Unable to save your Twitter settings!'));
200                         return;
201                 }
202
203                 $this->show_form(_('Twitter settings saved.'), true);
204         }
205
206         function remove_twitter_acct() {
207                 $user = common_current_user();
208
209                 // For now we assume one Twitter acct per Laconica acct
210                 $flink = Foreign_link::getForeignLink($user->id, 1);
211                 $flink_foreign_id = $this->arg('flink_foreign_id');
212
213                 if (!$flink) {
214                         common_debug("couldn't get flink");
215                 }
216
217                 # Maybe an old tab open...?
218                 if ($flink->foreign_id != $flink_foreign_id) {
219                         common_debug("flink user_id = " . $flink->user_id);
220                     $this->show_form(_('That is not your Twitter account.'));
221                     return;
222                 }
223
224                 $result = $flink->delete();
225
226                 if (!$result) {
227                         common_log_db_error($flink, 'DELETE', __FILE__);
228                         common_server_error(_('Couldn\'t remove Twitter user.'));
229                         return;
230                 }
231
232                 $this->show_form(_('Twitter account removed.'), TRUE);
233         }
234
235         function save_preferences() {
236                 $noticesync = $this->boolean('noticesync');
237                 $friendsync = $this->boolean('friendsync');
238                 $replysync = $this->boolean('replysync');
239
240                 $user = common_current_user();
241                 $flink = Foreign_link::getForeignLink($user->id, 1);
242
243                 if (!$flink) {
244                         common_log_db_error($flink, 'SELECT', __FILE__);
245                         $this->show_form(_('Couldn\'t save Twitter preferences.'));
246                         return;
247                 }
248
249                 $flink->query('BEGIN');
250
251                 $original = clone($flink);
252
253                 $this->set_flags($flink, $noticesync, $replysync, $friendsync);
254
255                 $result = $flink->update($original);
256
257                 if ($result === FALSE) {
258                         common_log_db_error($flink, 'UPDATE', __FILE__);
259                         $this->show_form(_('Couldn\'t save Twitter preferences.'));
260                         return;
261                 }
262
263                 $flink->query('COMMIT');
264
265                 $this->show_form(_('Twitter preferences saved.'));
266
267                 return;
268         }
269
270         function get_twitter_id($user, $password) {
271                 $uri = "http://twitter.com/users/show/$user.json";
272                 $data = $this->get_twitter_data($uri, $user, $password);
273
274                 if (!$data) {
275                         return NULL;
276                 }
277
278                 $user = json_decode($data);
279
280                 if (!$user) {
281                         return NULL;
282                 }
283
284                 return $user->id;
285         }
286
287         function verify_credentials($user, $password) {
288                 $uri = 'http://twitter.com/account/verify_credentials.json';
289                 $data = $this->get_twitter_data($uri, $user, $password);
290
291                 if (!$data) {
292                         return false;
293                 }
294
295                 $creds = json_decode($data);
296
297                 if (!$creds) {
298                         return false;
299                 }
300
301                 if ($creds->authorized == 1) {
302                         return true;
303                 }
304
305                 return false;
306         }
307
308         // PHP's cURL the best thing to use here? -- Zach
309         function get_twitter_data($uri, $user=NULL, $password=NULL) {
310                 $options = array(
311                                 CURLOPT_USERPWD => "$user:$password",
312                                 CURLOPT_RETURNTRANSFER  => true,
313                                 CURLOPT_FAILONERROR             => true,
314                                 CURLOPT_HEADER                  => false,
315                                 CURLOPT_FOLLOWLOCATION  => true,
316                                 // CURLOPT_USERAGENT            => "identi.ca",
317                                 CURLOPT_CONNECTTIMEOUT  => 120,
318                                 CURLOPT_TIMEOUT                 => 120
319                 );
320
321                 $ch = curl_init($uri);
322             curl_setopt_array($ch, $options);
323             $data = curl_exec($ch);
324             $errmsg = curl_error($ch);
325
326                 if ($errmsg) {
327                         common_debug("cURL error: $errmsg - trying to load: $uri with user $user.", __FILE__);
328                 }
329
330                 curl_close($ch);
331
332                 return $data;
333         }
334
335         function set_flags(&$flink, $noticesync, $replysync, $friendsync) {
336                 if ($noticesync) {
337                         $flink->noticesync |= FOREIGN_NOTICE_SEND;
338                 } else {
339                         $flink->noticesync &= ~FOREIGN_NOTICE_SEND;
340                 }
341
342                 if ($replysync) {
343                         $flink->noticesync |= FOREIGN_NOTICE_SEND_REPLY;
344                 } else {
345                         $flink->noticesync &= ~FOREIGN_NOTICE_SEND_REPLY;
346                 }
347
348                 if ($friendsync) {
349                         $flink->friendsync |= FOREIGN_FRIEND_RECV;
350                 } else {
351                         $flink->friendsync &= ~FOREIGN_FRIEND_RECV;
352                 }
353
354                 $flink->profilesync = 0; // XXX: leave as default?
355         }
356 }