]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oauthstore.php
Merge remote-tracking branch 'mainline/1.0.x' into people_tags_rebase
[quix0rs-gnu-social.git] / lib / oauthstore.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, 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('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 require_once 'libomb/datastore.php';
23
24 // @todo FIXME: Class documentation missing.
25 class StatusNetOAuthDataStore extends OAuthDataStore
26 {
27     // We keep a record of who's contacted us
28     function lookup_consumer($consumer_key)
29     {
30         $con = Consumer::staticGet('consumer_key', $consumer_key);
31         if (!$con) {
32             $con = new Consumer();
33             $con->consumer_key = $consumer_key;
34             $con->seed = common_good_rand(16);
35             $con->created = DB_DataObject_Cast::dateTime();
36             if (!$con->insert()) {
37                 return null;
38             }
39         }
40         return new OAuthConsumer($con->consumer_key, '');
41     }
42
43     function lookup_token($consumer, $token_type, $token_key)
44     {
45         $t = new Token();
46         if (!is_null($consumer)) {
47             $t->consumer_key = $consumer->key;
48         }
49         $t->tok = $token_key;
50         $t->type = ($token_type == 'access') ? 1 : 0;
51         if ($t->find(true)) {
52             return new OAuthToken($t->tok, $t->secret);
53         } else {
54             return null;
55         }
56     }
57
58     function getTokenByKey($token_key)
59     {
60         $t = new Token();
61         $t->tok = $token_key;
62         if ($t->find(true)) {
63             return $t;
64         } else {
65             return null;
66         }
67     }
68
69     // http://oauth.net/core/1.0/#nonce
70     // "The Consumer SHALL then generate a Nonce value that is unique for
71     // all requests with that timestamp."
72     // XXX: It's not clear why the token is here
73     function lookup_nonce($consumer, $token, $nonce, $timestamp)
74     {
75         $n = new Nonce();
76         $n->consumer_key = $consumer->key;
77         $n->ts = common_sql_date($timestamp);
78         $n->nonce = $nonce;
79         if ($n->find(true)) {
80             return true;
81         } else {
82             $n->created = DB_DataObject_Cast::dateTime();
83             $n->insert();
84             return false;
85         }
86     }
87
88     function new_request_token($consumer)
89     {
90         $t = new Token();
91         $t->consumer_key = $consumer->key;
92         $t->tok = common_good_rand(16);
93         $t->secret = common_good_rand(16);
94         $t->type = 0; // request
95         $t->state = 0; // unauthorized
96         $t->created = DB_DataObject_Cast::dateTime();
97         if (!$t->insert()) {
98             return null;
99         } else {
100             return new OAuthToken($t->tok, $t->secret);
101         }
102     }
103
104     // defined in OAuthDataStore, but not implemented anywhere
105     function fetch_request_token($consumer)
106     {
107         return $this->new_request_token($consumer);
108     }
109
110     function new_access_token($token, $consumer)
111     {
112         common_debug('new_access_token("'.$token->key.'","'.$consumer->key.'")', __FILE__);
113         $rt = new Token();
114         $rt->consumer_key = $consumer->key;
115         $rt->tok = $token->key;
116         $rt->type = 0; // request
117         if ($rt->find(true) && $rt->state == 1) { // authorized
118             common_debug('request token found.', __FILE__);
119             $at = new Token();
120             $at->consumer_key = $consumer->key;
121             $at->tok = common_good_rand(16);
122             $at->secret = common_good_rand(16);
123             $at->type = 1; // access
124             $at->created = DB_DataObject_Cast::dateTime();
125             if (!$at->insert()) {
126                 $e = $at->_lastError;
127                 common_debug('access token "'.$at->tok.'" not inserted: "'.$e->message.'"', __FILE__);
128                 return null;
129             } else {
130                 common_debug('access token "'.$at->tok.'" inserted', __FILE__);
131                 // burn the old one
132                 $orig_rt = clone($rt);
133                 $rt->state = 2; // used
134                 if (!$rt->update($orig_rt)) {
135                     return null;
136                 }
137                 common_debug('request token "'.$rt->tok.'" updated', __FILE__);
138                 // Update subscription
139                 // XXX: mixing levels here
140                 $sub = Subscription::staticGet('token', $rt->tok);
141                 if (!$sub) {
142                     return null;
143                 }
144                 common_debug('subscription for request token found', __FILE__);
145                 $orig_sub = clone($sub);
146                 $sub->token = $at->tok;
147                 $sub->secret = $at->secret;
148                 if (!$sub->update($orig_sub)) {
149                     return null;
150                 } else {
151                     common_debug('subscription updated to use access token', __FILE__);
152                     return new OAuthToken($at->tok, $at->secret);
153                 }
154             }
155         } else {
156             return null;
157         }
158     }
159
160     // defined in OAuthDataStore, but not implemented anywhere
161     function fetch_access_token($consumer)
162     {
163         return $this->new_access_token($consumer);
164     }
165
166     /**
167      * Revoke specified OAuth token
168      *
169      * Revokes the authorization token specified by $token_key.
170      * Throws exceptions in case of error.
171      *
172      * @param string $token_key The token to be revoked
173      *
174      * @access public
175      **/
176     public function revoke_token($token_key) {
177         $rt = new Token();
178         $rt->tok = $token_key;
179         $rt->type = 0;
180         $rt->state = 0;
181         if (!$rt->find(true)) {
182             throw new Exception('Tried to revoke unknown token');
183         }
184         if (!$rt->delete()) {
185             throw new Exception('Failed to delete revoked token');
186         }
187     }
188
189     /**
190      * Authorize specified OAuth token
191      *
192      * Authorizes the authorization token specified by $token_key.
193      * Throws exceptions in case of error.
194      *
195      * @param string $token_key The token to be authorized
196      *
197      * @access public
198      **/
199     public function authorize_token($token_key) {
200         $rt = new Token();
201         $rt->tok = $token_key;
202         $rt->type = 0;
203         $rt->state = 0;
204         if (!$rt->find(true)) {
205             throw new Exception('Tried to authorize unknown token');
206         }
207         $orig_rt = clone($rt);
208         $rt->state = 1; # Authorized but not used
209         if (!$rt->update($orig_rt)) {
210             throw new Exception('Failed to authorize token');
211         }
212     }
213
214     /**
215      * Get profile by identifying URI
216      *
217      * Returns an OMB_Profile object representing the OMB profile identified by
218      * $identifier_uri.
219      * Returns null if there is no such OMB profile.
220      * Throws exceptions in case of other error.
221      *
222      * @param string $identifier_uri The OMB identifier URI specifying the
223      *                               requested profile
224      *
225      * @access public
226      *
227      * @return OMB_Profile The corresponding profile
228      **/
229     public function getProfile($identifier_uri) {
230         /* getProfile is only used for remote profiles by libomb.
231            @TODO: Make it work with local ones anyway. */
232         $remote = Remote_profile::staticGet('uri', $identifier_uri);
233         if (!$remote) throw new Exception('No such remote profile');
234         $profile = Profile::staticGet('id', $remote->id);
235         if (!$profile) throw new Exception('No profile for remote user');
236
237         require_once INSTALLDIR.'/lib/omb.php';
238         return profile_to_omb_profile($identifier_uri, $profile);
239     }
240
241     /**
242      * Save passed profile
243      *
244      * Stores the OMB profile $profile. Overwrites an existing entry.
245      * Throws exceptions in case of error.
246      *
247      * @param OMB_Profile $profile   The OMB profile which should be saved
248      *
249      * @access public
250      **/
251     public function saveProfile($omb_profile) {
252         if (common_profile_url($omb_profile->getNickname()) ==
253                                                 $omb_profile->getProfileURL()) {
254             throw new Exception('Not implemented');
255         } else {
256             $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
257
258             if ($remote) {
259                 $exists = true;
260                 $profile = Profile::staticGet($remote->id);
261                 $orig_remote = clone($remote);
262                 $orig_profile = clone($profile);
263                 // XXX: compare current postNotice and updateProfile URLs to the ones
264                 // stored in the DB to avoid (possibly...) above attack
265             } else {
266                 $exists = false;
267                 $remote = new Remote_profile();
268                 $remote->uri = $omb_profile->getIdentifierURI();
269                 $profile = new Profile();
270             }
271
272             $profile->nickname = $omb_profile->getNickname();
273             $profile->profileurl = $omb_profile->getProfileURL();
274
275             $fullname = $omb_profile->getFullname();
276             $profile->fullname = is_null($fullname) ? '' : $fullname;
277             $homepage = $omb_profile->getHomepage();
278             $profile->homepage = is_null($homepage) ? '' : $homepage;
279             $bio = $omb_profile->getBio();
280             $profile->bio = is_null($bio) ? '' : $bio;
281             $location = $omb_profile->getLocation();
282             $profile->location = is_null($location) ? '' : $location;
283
284             if ($exists) {
285                 $profile->update($orig_profile);
286             } else {
287                 $profile->created = DB_DataObject_Cast::dateTime(); # current time
288                 $id = $profile->insert();
289                 if (!$id) {
290                     // TRANS: Exception thrown when creating a new profile fails in OAuth store.
291                     throw new Exception(_('Error inserting new profile.'));
292                 }
293                 $remote->id = $id;
294             }
295
296             $avatar_url = $omb_profile->getAvatarURL();
297             if ($avatar_url) {
298                 if (!$this->add_avatar($profile, $avatar_url)) {
299                     // TRANS: Exception thrown when creating a new avatar fails in OAuth store.
300                     throw new Exception(_('Error inserting avatar.'));
301                 }
302             } else {
303                 $avatar = $profile->getOriginalAvatar();
304                 if($avatar) $avatar->delete();
305                 $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
306                 if($avatar) $avatar->delete();
307                 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
308                 if($avatar) $avatar->delete();
309                 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
310                 if($avatar) $avatar->delete();
311             }
312
313             if ($exists) {
314                 if (!$remote->update($orig_remote)) {
315                     // TRANS: Exception thrown when updating a remote profile fails in OAuth store.
316                     throw new Exception(_('Error updating remote profile.'));
317                 }
318             } else {
319                 $remote->created = DB_DataObject_Cast::dateTime(); # current time
320                 if (!$remote->insert()) {
321                     // TRANS: Exception thrown when creating a remote profile fails in OAuth store.
322                     throw new Exception(_('Error inserting remote profile.'));
323                 }
324             }
325         }
326     }
327
328     function add_avatar($profile, $url)
329     {
330         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
331         try {
332             copy($url, $temp_filename);
333             $imagefile = new ImageFile($profile->id, $temp_filename);
334             $filename = Avatar::filename($profile->id,
335                                          image_type_to_extension($imagefile->type),
336                                          null,
337                                          common_timestamp());
338             rename($temp_filename, Avatar::path($filename));
339         } catch (Exception $e) {
340             unlink($temp_filename);
341             throw $e;
342         }
343         return $profile->setOriginal($filename);
344     }
345
346     /**
347      * Save passed notice
348      *
349      * Stores the OMB notice $notice. The datastore may change the passed notice.
350      * This might by neccessary for URIs depending on a database key. Note that
351      * it is the user’s duty to present a mechanism for his OMB_Datastore to
352      * appropriately change his OMB_Notice.
353      * Throws exceptions in case of error.
354      *
355      * @param OMB_Notice $notice The OMB notice which should be saved
356      *
357      * @access public
358      **/
359     public function saveNotice(&$omb_notice) {
360         if (Notice::staticGet('uri', $omb_notice->getIdentifierURI())) {
361             // TRANS: Exception thrown when a notice is denied because it has been sent before.
362             throw new Exception(_('Duplicate notice.'));
363         }
364         $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
365         common_log(LOG_DEBUG, $author_uri, __FILE__);
366         $author = Remote_profile::staticGet('uri', $author_uri);
367         if (!$author) {
368             $author = User::staticGet('uri', $author_uri);
369         }
370         if (!$author) {
371             throw new Exception('No such user.');
372         }
373
374         common_log(LOG_DEBUG, print_r($author, true), __FILE__);
375
376         $notice = Notice::saveNew($author->id,
377                                   $omb_notice->getContent(),
378                                   'omb',
379                                   array('is_local' => Notice::REMOTE_OMB,
380                                         'uri' => $omb_notice->getIdentifierURI()));
381
382     }
383
384     /**
385      * Get subscriptions of a given profile
386      *
387      * Returns an array containing subscription informations for the specified
388      * profile. Every array entry should in turn be an array with keys
389      *   'uri´: The identifier URI of the subscriber
390      *   'token´: The subscribe token
391      *   'secret´: The secret token
392      * Throws exceptions in case of error.
393      *
394      * @param string $subscribed_user_uri The OMB identifier URI specifying the
395      *                                    subscribed profile
396      *
397      * @access public
398      *
399      * @return mixed An array containing the subscriptions or 0 if no
400      *               subscription has been found.
401      **/
402     public function getSubscriptions($subscribed_user_uri) {
403         $sub = new Subscription();
404
405         $user = $this->_getAnyProfile($subscribed_user_uri);
406
407         $sub->subscribed = $user->id;
408
409         if (!$sub->find(true)) {
410             return array();
411         }
412
413         /* Since we do not use OMB_Service_Provider’s action methods, there
414            is no need to actually return the subscriptions. */
415         return 1;
416     }
417
418     private function _getAnyProfile($uri)
419     {
420         $user = Remote_profile::staticGet('uri', $uri);
421         if (!$user) {
422             $user = User::staticGet('uri', $uri);
423         }
424         if (!$user) {
425             throw new Exception('No such user.');
426         }
427         return $user;
428     }
429
430     /**
431      * Delete a subscription
432      *
433      * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
434      * Throws exceptions in case of error.
435      *
436      * @param string $subscriber_uri      The OMB identifier URI specifying the
437      *                                    subscribing profile
438      *
439      * @param string $subscribed_user_uri The OMB identifier URI specifying the
440      *                                    subscribed profile
441      *
442      * @access public
443      **/
444     public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
445     {
446         $sub = new Subscription();
447
448         $subscribed = $this->_getAnyProfile($subscribed_user_uri);
449         $subscriber = $this->_getAnyProfile($subscriber_uri);
450
451         $sub->subscribed = $subscribed->id;
452         $sub->subscriber = $subscriber->id;
453
454         $sub->delete();
455     }
456
457     /**
458      * Save a subscription
459      *
460      * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
461      * Throws exceptions in case of error.
462      *
463      * @param string     $subscriber_uri      The OMB identifier URI specifying
464      *                                        the subscribing profile
465      *
466      * @param string     $subscribed_user_uri The OMB identifier URI specifying
467      *                                        the subscribed profile
468      * @param OAuthToken $token               The access token
469      *
470      * @access public
471      **/
472     public function saveSubscription($subscriber_uri, $subscribed_user_uri,
473                                                                        $token)
474     {
475         $sub = new Subscription();
476
477         $subscribed = $this->_getAnyProfile($subscribed_user_uri);
478         $subscriber = $this->_getAnyProfile($subscriber_uri);
479
480         if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
481             common_log(LOG_INFO, __METHOD__ . ": remote subscriber banned ($subscriber_uri subbing to $subscribed_user_uri)");
482             // TRANS: Error message displayed to a banned user when they try to subscribe.
483             return _('You have been banned from subscribing.');
484         }
485
486         $sub->subscribed = $subscribed->id;
487         $sub->subscriber = $subscriber->id;
488
489         $sub_exists = $sub->find(true);
490
491         if ($sub_exists) {
492             $orig_sub = clone($sub);
493         } else {
494             $sub->created = DB_DataObject_Cast::dateTime();
495         }
496
497         $sub->token  = $token->key;
498         $sub->secret = $token->secret;
499
500         if ($sub_exists) {
501             $result = $sub->update($orig_sub);
502         } else {
503             $result = $sub->insert();
504         }
505
506         if (!$result) {
507             common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
508             // TRANS: Exception thrown when creating a new subscription fails in OAuth store.
509             throw new Exception(_('Could not insert new subscription.'));
510             return;
511         }
512
513         /* Notify user, if necessary. */
514
515         if ($subscribed instanceof User) {
516             mail_subscribe_notify_profile($subscribed,
517                                           Profile::staticGet($subscriber->id));
518         }
519     }
520 }