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