]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oauthstore.php
Merge remote branch 'laconica/0.8.x' 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 = $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     /**
161      * Revoke specified OAuth token
162      *
163      * Revokes the authorization token specified by $token_key.
164      * Throws exceptions in case of error.
165      *
166      * @param string $token_key The token to be revoked
167      *
168      * @access public
169      **/
170     public function revoke_token($token_key) {
171         $rt = new Token();
172         $rt->tok = $token_key;
173         $rt->type = 0;
174         $rt->state = 0;
175         if (!$rt->find(true)) {
176             throw new Exception('Tried to revoke unknown token');
177         }
178         if (!$rt->delete()) {
179             throw new Exception('Failed to delete revoked token');
180         }
181     }
182
183     /**
184      * Authorize specified OAuth token
185      *
186      * Authorizes the authorization token specified by $token_key.
187      * Throws exceptions in case of error.
188      *
189      * @param string $token_key The token to be authorized
190      *
191      * @access public
192      **/
193     public function authorize_token($token_key) {
194         $rt = new Token();
195         $rt->tok = $token_key;
196         $rt->type = 0;
197         $rt->state = 0;
198         if (!$rt->find(true)) {
199             throw new Exception('Tried to authorize unknown token');
200         }
201         $orig_rt = clone($rt);
202         $rt->state = 1; # Authorized but not used
203         if (!$rt->update($orig_rt)) {
204             throw new Exception('Failed to authorize token');
205         }
206     }
207
208     /**
209      * Get profile by identifying URI
210      *
211      * Returns an OMB_Profile object representing the OMB profile identified by
212      * $identifier_uri.
213      * Returns null if there is no such OMB profile.
214      * Throws exceptions in case of other error.
215      *
216      * @param string $identifier_uri The OMB identifier URI specifying the
217      *                               requested profile
218      *
219      * @access public
220      *
221      * @return OMB_Profile The corresponding profile
222      **/
223     public function getProfile($identifier_uri) {
224         /* getProfile is only used for remote profiles by libomb.
225            TODO: Make it work with local ones anyway. */
226         $remote = Remote_profile::staticGet('uri', $identifier_uri);
227         if (!$remote) throw new Exception('No such remote profile');
228         $profile = Profile::staticGet('id', $remote->id);
229         if (!$profile) throw new Exception('No profile for remote user');
230
231         require_once INSTALLDIR.'/lib/omb.php';
232         return profile_to_omb_profile($identifier_uri, $profile);
233     }
234
235     /**
236      * Save passed profile
237      *
238      * Stores the OMB profile $profile. Overwrites an existing entry.
239      * Throws exceptions in case of error.
240      *
241      * @param OMB_Profile $profile   The OMB profile which should be saved
242      *
243      * @access public
244      **/
245     public function saveProfile($omb_profile) {
246         if (common_profile_url($omb_profile->getNickname()) ==
247                                                 $omb_profile->getProfileURL()) {
248             throw new Exception('Not implemented');
249         } else {
250             $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
251
252             if ($remote) {
253                 $exists = true;
254                 $profile = Profile::staticGet($remote->id);
255                 $orig_remote = clone($remote);
256                 $orig_profile = clone($profile);
257                 # XXX: compare current postNotice and updateProfile URLs to the ones
258                 # stored in the DB to avoid (possibly...) above attack
259             } else {
260                 $exists = false;
261                 $remote = new Remote_profile();
262                 $remote->uri = $omb_profile->getIdentifierURI();
263                 $profile = new Profile();
264             }
265
266             $profile->nickname = $omb_profile->getNickname();
267             $profile->profileurl = $omb_profile->getProfileURL();
268
269             $fullname = $omb_profile->getFullname();
270             $profile->fullname = is_null($fullname) ? '' : $fullname;
271             $homepage = $omb_profile->getHomepage();
272             $profile->homepage = is_null($homepage) ? '' : $homepage;
273             $bio = $omb_profile->getBio();
274             $profile->bio = is_null($bio) ? '' : $bio;
275             $location = $omb_profile->getLocation();
276             $profile->location = is_null($location) ? '' : $location;
277
278             if ($exists) {
279                 $profile->update($orig_profile);
280             } else {
281                 $profile->created = DB_DataObject_Cast::dateTime(); # current time
282                 $id = $profile->insert();
283                 if (!$id) {
284                     throw new Exception(_('Error inserting new profile'));
285                 }
286                 $remote->id = $id;
287             }
288
289             $avatar_url = $omb_profile->getAvatarURL();
290             if ($avatar_url) {
291                 if (!$this->add_avatar($profile, $avatar_url)) {
292                     throw new Exception(_('Error inserting avatar'));
293                 }
294             } else {
295                 $avatar = $profile->getOriginalAvatar();
296                 if($avatar) $avatar->delete();
297                 $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
298                 if($avatar) $avatar->delete();
299                 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
300                 if($avatar) $avatar->delete();
301                 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
302                 if($avatar) $avatar->delete();
303             }
304
305             if ($exists) {
306                 if (!$remote->update($orig_remote)) {
307                     throw new Exception(_('Error updating remote profile'));
308                 }
309             } else {
310                 $remote->created = DB_DataObject_Cast::dateTime(); # current time
311                 if (!$remote->insert()) {
312                     throw new Exception(_('Error inserting remote profile'));
313                 }
314             }
315         }
316     }
317
318     function add_avatar($profile, $url)
319     {
320         $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
321         copy($url, $temp_filename);
322         $imagefile = new ImageFile($profile->id, $temp_filename);
323         $filename = Avatar::filename($profile->id,
324                                      image_type_to_extension($imagefile->type),
325                                      null,
326                                      common_timestamp());
327         rename($temp_filename, Avatar::path($filename));
328         return $profile->setOriginal($filename);
329     }
330
331     /**
332      * Save passed notice
333      *
334      * Stores the OMB notice $notice. The datastore may change the passed notice.
335      * This might by neccessary for URIs depending on a database key. Note that
336      * it is the user’s duty to present a mechanism for his OMB_Datastore to
337      * appropriately change his OMB_Notice.
338      * Throws exceptions in case of error.
339      *
340      * @param OMB_Notice $notice The OMB notice which should be saved
341      *
342      * @access public
343      **/
344     public function saveNotice(&$omb_notice) {
345         if (Notice::staticGet('uri', $omb_notice->getIdentifierURI())) {
346             throw new Exception(_('Duplicate notice'));
347         }
348         $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
349         common_log(LOG_DEBUG, $author_uri, __FILE__);
350         $author = Remote_profile::staticGet('uri', $author_uri);
351         if (!$author) {
352             $author = User::staticGet('uri', $author_uri);
353         }
354         if (!$author) {
355             throw new Exception('No such user');
356         }
357
358         common_log(LOG_DEBUG, print_r($author, true), __FILE__);
359
360         $notice = Notice::saveNew($author->id,
361                                   $omb_notice->getContent(),
362                                   'omb',
363                                   false,
364                                   null,
365                                   $omb_notice->getIdentifierURI());
366         if (is_string($notice)) {
367             throw new Exception($notice);
368         }
369         common_broadcast_notice($notice, true);
370     }
371
372     /**
373      * Get subscriptions of a given profile
374      *
375      * Returns an array containing subscription informations for the specified
376      * profile. Every array entry should in turn be an array with keys
377      *   'uri´: The identifier URI of the subscriber
378      *   'token´: The subscribe token
379      *   'secret´: The secret token
380      * Throws exceptions in case of error.
381      *
382      * @param string $subscribed_user_uri The OMB identifier URI specifying the
383      *                                    subscribed profile
384      *
385      * @access public
386      *
387      * @return mixed An array containing the subscriptions or 0 if no
388      *               subscription has been found.
389      **/
390     public function getSubscriptions($subscribed_user_uri) {
391         $sub = new Subscription();
392
393         $user = $this->_getAnyProfile($subscribed_user_uri);
394
395         $sub->subscribed = $user->id;
396
397         if (!$sub->find(true)) {
398             return 0;
399         }
400
401         /* Since we do not use OMB_Service_Provider’s action methods, there
402            is no need to actually return the subscriptions. */
403         return 1;
404     }
405
406     private function _getAnyProfile($uri)
407     {
408         $user = Remote_profile::staticGet('uri', $uri);
409         if (!$user) {
410             $user = User::staticGet('uri', $uri);
411         }
412         if (!$user) {
413             throw new Exception('No such user');
414         }
415         return $user;
416     }
417
418     /**
419      * Delete a subscription
420      *
421      * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
422      * Throws exceptions in case of error.
423      *
424      * @param string $subscriber_uri      The OMB identifier URI specifying the
425      *                                    subscribing profile
426      *
427      * @param string $subscribed_user_uri The OMB identifier URI specifying the
428      *                                    subscribed profile
429      *
430      * @access public
431      **/
432     public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
433     {
434         $sub = new Subscription();
435
436         $subscribed = $this->_getAnyProfile($subscribed_user_uri);
437         $subscriber = $this->_getAnyProfile($subscriber_uri);
438
439         $sub->subscribed = $subscribed->id;
440         $sub->subscriber = $subscriber->id;
441
442         $sub->delete();
443     }
444
445     /**
446      * Save a subscription
447      *
448      * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
449      * Throws exceptions in case of error.
450      *
451      * @param string     $subscriber_uri      The OMB identifier URI specifying
452      *                                        the subscribing profile
453      *
454      * @param string     $subscribed_user_uri The OMB identifier URI specifying
455      *                                        the subscribed profile
456      * @param OAuthToken $token               The access token
457      *
458      * @access public
459      **/
460     public function saveSubscription($subscriber_uri, $subscribed_user_uri,
461                                                                        $token)
462     {
463         $sub = new Subscription();
464
465         $subscribed = $this->_getAnyProfile($subscribed_user_uri);
466         $subscriber = $this->_getAnyProfile($subscriber_uri);
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 ?>