3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
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.
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.
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/>.
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
22 require_once 'libomb/datastore.php';
24 // @todo FIXME: Class documentation missing.
25 class StatusNetOAuthDataStore extends OAuthDataStore
27 // We keep a record of who's contacted us
28 function lookup_consumer($consumer_key)
30 $con = Consumer::staticGet('consumer_key', $consumer_key);
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()) {
40 return new OAuthConsumer($con->consumer_key, '');
43 function lookup_token($consumer, $token_type, $token_key)
46 if (!is_null($consumer)) {
47 $t->consumer_key = $consumer->key;
50 $t->type = ($token_type == 'access') ? 1 : 0;
52 return new OAuthToken($t->tok, $t->secret);
58 function getTokenByKey($token_key)
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)
76 $n->consumer_key = $consumer->key;
77 $n->ts = common_sql_date($timestamp);
82 $n->created = DB_DataObject_Cast::dateTime();
88 function new_request_token($consumer)
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();
100 return new OAuthToken($t->tok, $t->secret);
104 // defined in OAuthDataStore, but not implemented anywhere
105 function fetch_request_token($consumer)
107 return $this->new_request_token($consumer);
110 function new_access_token($token, $consumer)
112 common_debug('new_access_token("'.$token->key.'","'.$consumer->key.'")', __FILE__);
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__);
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__);
130 common_debug('access token "'.$at->tok.'" inserted', __FILE__);
132 $orig_rt = clone($rt);
133 $rt->state = 2; // used
134 if (!$rt->update($orig_rt)) {
137 common_debug('request token "'.$rt->tok.'" updated', __FILE__);
138 // Update subscription
139 // XXX: mixing levels here
140 $sub = Subscription::staticGet('token', $rt->tok);
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)) {
151 common_debug('subscription updated to use access token', __FILE__);
152 return new OAuthToken($at->tok, $at->secret);
160 // defined in OAuthDataStore, but not implemented anywhere
161 function fetch_access_token($consumer)
163 return $this->new_access_token($consumer);
167 * Revoke specified OAuth token
169 * Revokes the authorization token specified by $token_key.
170 * Throws exceptions in case of error.
172 * @param string $token_key The token to be revoked
176 public function revoke_token($token_key) {
178 $rt->tok = $token_key;
181 if (!$rt->find(true)) {
182 throw new Exception('Tried to revoke unknown token');
184 if (!$rt->delete()) {
185 throw new Exception('Failed to delete revoked token');
190 * Authorize specified OAuth token
192 * Authorizes the authorization token specified by $token_key.
193 * Throws exceptions in case of error.
195 * @param string $token_key The token to be authorized
199 public function authorize_token($token_key) {
201 $rt->tok = $token_key;
204 if (!$rt->find(true)) {
205 throw new Exception('Tried to authorize unknown token');
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');
215 * Get profile by identifying URI
217 * Returns an OMB_Profile object representing the OMB profile identified by
219 * Returns null if there is no such OMB profile.
220 * Throws exceptions in case of other error.
222 * @param string $identifier_uri The OMB identifier URI specifying the
227 * @return OMB_Profile The corresponding profile
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');
237 require_once INSTALLDIR.'/lib/omb.php';
238 return profile_to_omb_profile($identifier_uri, $profile);
242 * Save passed profile
244 * Stores the OMB profile $profile. Overwrites an existing entry.
245 * Throws exceptions in case of error.
247 * @param OMB_Profile $profile The OMB profile which should be saved
251 public function saveProfile($omb_profile) {
252 if (common_profile_url($omb_profile->getNickname()) ==
253 $omb_profile->getProfileURL()) {
254 throw new Exception('Not implemented');
256 $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
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
267 $remote = new Remote_profile();
268 $remote->uri = $omb_profile->getIdentifierURI();
269 $profile = new Profile();
272 $profile->nickname = $omb_profile->getNickname();
273 $profile->profileurl = $omb_profile->getProfileURL();
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;
285 $profile->update($orig_profile);
287 $profile->created = DB_DataObject_Cast::dateTime(); # current time
288 $id = $profile->insert();
290 // TRANS: Exception thrown when creating a new profile fails in OAuth store.
291 throw new Exception(_('Error inserting new profile.'));
296 $avatar_url = $omb_profile->getAvatarURL();
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.'));
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();
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.'));
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.'));
328 function add_avatar($profile, $url)
330 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
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),
338 rename($temp_filename, Avatar::path($filename));
339 } catch (Exception $e) {
340 unlink($temp_filename);
343 return $profile->setOriginal($filename);
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.
355 * @param OMB_Notice $notice The OMB notice which should be saved
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.'));
364 $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
365 common_log(LOG_DEBUG, $author_uri, __FILE__);
366 $author = Remote_profile::staticGet('uri', $author_uri);
368 $author = User::staticGet('uri', $author_uri);
371 throw new Exception('No such user.');
374 common_log(LOG_DEBUG, print_r($author, true), __FILE__);
376 $notice = Notice::saveNew($author->id,
377 $omb_notice->getContent(),
379 array('is_local' => Notice::REMOTE_OMB,
380 'uri' => $omb_notice->getIdentifierURI()));
385 * Get subscriptions of a given profile
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.
394 * @param string $subscribed_user_uri The OMB identifier URI specifying the
399 * @return mixed An array containing the subscriptions or 0 if no
400 * subscription has been found.
402 public function getSubscriptions($subscribed_user_uri) {
403 $sub = new Subscription();
405 $user = $this->_getAnyProfile($subscribed_user_uri);
407 $sub->subscribed = $user->id;
409 if (!$sub->find(true)) {
413 /* Since we do not use OMB_Service_Provider’s action methods, there
414 is no need to actually return the subscriptions. */
418 private function _getAnyProfile($uri)
420 $user = Remote_profile::staticGet('uri', $uri);
422 $user = User::staticGet('uri', $uri);
425 throw new Exception('No such user.');
431 * Delete a subscription
433 * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
434 * Throws exceptions in case of error.
436 * @param string $subscriber_uri The OMB identifier URI specifying the
437 * subscribing profile
439 * @param string $subscribed_user_uri The OMB identifier URI specifying the
444 public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
446 $sub = new Subscription();
448 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
449 $subscriber = $this->_getAnyProfile($subscriber_uri);
451 $sub->subscribed = $subscribed->id;
452 $sub->subscriber = $subscriber->id;
458 * Save a subscription
460 * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
461 * Throws exceptions in case of error.
463 * @param string $subscriber_uri The OMB identifier URI specifying
464 * the subscribing profile
466 * @param string $subscribed_user_uri The OMB identifier URI specifying
467 * the subscribed profile
468 * @param OAuthToken $token The access token
472 public function saveSubscription($subscriber_uri, $subscribed_user_uri,
475 $sub = new Subscription();
477 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
478 $subscriber = $this->_getAnyProfile($subscriber_uri);
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.');
486 $sub->subscribed = $subscribed->id;
487 $sub->subscriber = $subscriber->id;
489 $sub_exists = $sub->find(true);
492 $orig_sub = clone($sub);
494 $sub->created = DB_DataObject_Cast::dateTime();
497 $sub->token = $token->key;
498 $sub->secret = $token->secret;
501 $result = $sub->update($orig_sub);
503 $result = $sub->insert();
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.'));
513 /* Notify user, if necessary. */
515 if ($subscribed instanceof User) {
516 mail_subscribe_notify_profile($subscribed,
517 Profile::staticGet($subscriber->id));