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