]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/oauthstore.php
Mass replacement of #-comments with //-comments
[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         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             return _('You have been banned from subscribing.');
483         }
484
485         $sub->subscribed = $subscribed->id;
486         $sub->subscriber = $subscriber->id;
487
488         $sub_exists = $sub->find(true);
489
490         if ($sub_exists) {
491             $orig_sub = clone($sub);
492         } else {
493             $sub->created = DB_DataObject_Cast::dateTime();
494         }
495
496         $sub->token  = $token->key;
497         $sub->secret = $token->secret;
498
499         if ($sub_exists) {
500             $result = $sub->update($orig_sub);
501         } else {
502             $result = $sub->insert();
503         }
504
505         if (!$result) {
506             common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
507             throw new Exception(_('Couldn\'t insert new subscription.'));
508             return;
509         }
510
511         /* Notify user, if necessary. */
512
513         if ($subscribed instanceof User) {
514             mail_subscribe_notify_profile($subscribed,
515                                           Profile::staticGet($subscriber->id));
516         }
517     }
518 }
519 ?>