3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008-2011 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 dirname(__FILE__) . '/../extlib/libomb/datastore.php';
24 // @todo FIXME: Class documentation missing.
25 class OMBOAuthDataStore 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 // 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 // XXX: It's not clear why the token is here
62 function lookup_nonce($consumer, $token, $nonce, $timestamp)
65 $n->consumer_key = $consumer->key;
66 $n->ts = common_sql_date($timestamp);
71 $n->created = DB_DataObject_Cast::dateTime();
77 function new_request_token($consumer)
80 $t->consumer_key = $consumer->key;
81 $t->tok = common_good_rand(16);
82 $t->secret = common_good_rand(16);
83 $t->type = 0; // request
84 $t->state = 0; // unauthorized
85 $t->created = DB_DataObject_Cast::dateTime();
89 return new OAuthToken($t->tok, $t->secret);
93 // defined in OAuthDataStore, but not implemented anywhere
94 function fetch_request_token($consumer)
96 return $this->new_request_token($consumer);
99 function new_access_token($token, $consumer)
101 common_debug('new_access_token("'.$token->key.'","'.$consumer->key.'")', __FILE__);
103 $rt->consumer_key = $consumer->key;
104 $rt->tok = $token->key;
105 $rt->type = 0; // request
106 if ($rt->find(true) && $rt->state == 1) { // authorized
107 common_debug('request token found.', __FILE__);
109 $at->consumer_key = $consumer->key;
110 $at->tok = common_good_rand(16);
111 $at->secret = common_good_rand(16);
112 $at->type = 1; // access
113 $at->created = DB_DataObject_Cast::dateTime();
114 if (!$at->insert()) {
115 $e = $at->_lastError;
116 common_debug('access token "'.$at->tok.'" not inserted: "'.$e->message.'"', __FILE__);
119 common_debug('access token "'.$at->tok.'" inserted', __FILE__);
121 $orig_rt = clone($rt);
122 $rt->state = 2; // used
123 if (!$rt->update($orig_rt)) {
126 common_debug('request token "'.$rt->tok.'" updated', __FILE__);
127 // Update subscription
128 // XXX: mixing levels here
129 $sub = Subscription::staticGet('token', $rt->tok);
133 common_debug('subscription for request token found', __FILE__);
134 $orig_sub = clone($sub);
135 $sub->token = $at->tok;
136 $sub->secret = $at->secret;
137 if (!$sub->update($orig_sub)) {
140 common_debug('subscription updated to use access token', __FILE__);
141 return new OAuthToken($at->tok, $at->secret);
149 // defined in OAuthDataStore, but not implemented anywhere
150 function fetch_access_token($consumer)
152 return $this->new_access_token($consumer);
156 * Revoke specified OAuth token
158 * Revokes the authorization token specified by $token_key.
159 * Throws exceptions in case of error.
161 * @param string $token_key The token to be revoked
165 public function revoke_token($token_key) {
167 $rt->tok = $token_key;
170 if (!$rt->find(true)) {
171 throw new Exception('Tried to revoke unknown token');
173 if (!$rt->delete()) {
174 throw new Exception('Failed to delete revoked token');
179 * Authorize specified OAuth token
181 * Authorizes the authorization token specified by $token_key.
182 * Throws exceptions in case of error.
184 * @param string $token_key The token to be authorized
188 public function authorize_token($token_key) {
190 $rt->tok = $token_key;
193 if (!$rt->find(true)) {
194 throw new Exception('Tried to authorize unknown token');
196 $orig_rt = clone($rt);
197 $rt->state = 1; # Authorized but not used
198 if (!$rt->update($orig_rt)) {
199 throw new Exception('Failed to authorize token');
204 * Get profile by identifying URI
206 * Returns an OMB_Profile object representing the OMB profile identified by
208 * Returns null if there is no such OMB profile.
209 * Throws exceptions in case of other error.
211 * @param string $identifier_uri The OMB identifier URI specifying the
216 * @return OMB_Profile The corresponding profile
218 public function getProfile($identifier_uri) {
219 /* getProfile is only used for remote profiles by libomb.
220 @TODO: Make it work with local ones anyway. */
221 $remote = Remote_profile::staticGet('uri', $identifier_uri);
222 if (!$remote) throw new Exception('No such remote profile');
223 $profile = Profile::staticGet('id', $remote->id);
224 if (!$profile) throw new Exception('No profile for remote user');
226 require_once dirname(__FILE__) . '/omb.php';
227 return profile_to_omb_profile($identifier_uri, $profile);
231 * Save passed profile
233 * Stores the OMB profile $profile. Overwrites an existing entry.
234 * Throws exceptions in case of error.
236 * @param OMB_Profile $profile The OMB profile which should be saved
240 public function saveProfile($omb_profile) {
241 if (common_profile_url($omb_profile->getNickname()) ==
242 $omb_profile->getProfileURL()) {
243 throw new Exception('Not implemented');
245 $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
249 $profile = Profile::staticGet($remote->id);
250 $orig_remote = clone($remote);
251 $orig_profile = clone($profile);
252 // XXX: compare current postNotice and updateProfile URLs to the ones
253 // stored in the DB to avoid (possibly...) above attack
256 $remote = new Remote_profile();
257 $remote->uri = $omb_profile->getIdentifierURI();
258 $profile = new Profile();
261 $profile->nickname = $omb_profile->getNickname();
262 $profile->profileurl = $omb_profile->getProfileURL();
264 $fullname = $omb_profile->getFullname();
265 $profile->fullname = is_null($fullname) ? '' : $fullname;
266 $homepage = $omb_profile->getHomepage();
267 $profile->homepage = is_null($homepage) ? '' : $homepage;
268 $bio = $omb_profile->getBio();
269 $profile->bio = is_null($bio) ? '' : $bio;
270 $location = $omb_profile->getLocation();
271 $profile->location = is_null($location) ? '' : $location;
274 $profile->update($orig_profile);
276 $profile->created = DB_DataObject_Cast::dateTime(); # current time
277 $id = $profile->insert();
279 // TRANS: Exception thrown when creating a new profile fails in OAuth store.
280 throw new Exception(_('Error inserting new profile.'));
285 $avatar_url = $omb_profile->getAvatarURL();
287 if (!$this->add_avatar($profile, $avatar_url)) {
288 // TRANS: Exception thrown when creating a new avatar fails in OAuth store.
289 throw new Exception(_('Error inserting avatar.'));
292 $avatar = $profile->getOriginalAvatar();
293 if($avatar) $avatar->delete();
294 $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
295 if($avatar) $avatar->delete();
296 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
297 if($avatar) $avatar->delete();
298 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
299 if($avatar) $avatar->delete();
303 if (!$remote->update($orig_remote)) {
304 // TRANS: Exception thrown when updating a remote profile fails in OAuth store.
305 throw new Exception(_('Error updating remote profile.'));
308 $remote->created = DB_DataObject_Cast::dateTime(); # current time
309 if (!$remote->insert()) {
310 // TRANS: Exception thrown when creating a remote profile fails in OAuth store.
311 throw new Exception(_('Error inserting remote profile.'));
317 function add_avatar($profile, $url)
319 $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),
327 rename($temp_filename, Avatar::path($filename));
328 } catch (Exception $e) {
329 unlink($temp_filename);
332 return $profile->setOriginal($filename);
338 * Stores the OMB notice $notice. The datastore may change the passed notice.
339 * This might by neccessary for URIs depending on a database key. Note that
340 * it is the user’s duty to present a mechanism for his OMB_Datastore to
341 * appropriately change his OMB_Notice.
342 * Throws exceptions in case of error.
344 * @param OMB_Notice $notice The OMB notice which should be saved
348 public function saveNotice(&$omb_notice) {
349 if (Notice::staticGet('uri', $omb_notice->getIdentifierURI())) {
350 // TRANS: Exception thrown when a notice is denied because it has been sent before.
351 throw new Exception(_('Duplicate notice.'));
353 $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
354 common_log(LOG_DEBUG, $author_uri, __FILE__);
355 $author = Remote_profile::staticGet('uri', $author_uri);
357 $author = User::staticGet('uri', $author_uri);
360 throw new Exception('No such user.');
363 common_log(LOG_DEBUG, print_r($author, true), __FILE__);
365 $notice = Notice::saveNew($author->id,
366 $omb_notice->getContent(),
368 array('is_local' => Notice::REMOTE,
369 'uri' => $omb_notice->getIdentifierURI()));
374 * Get subscriptions of a given profile
376 * Returns an array containing subscription informations for the specified
377 * profile. Every array entry should in turn be an array with keys
378 * 'uri´: The identifier URI of the subscriber
379 * 'token´: The subscribe token
380 * 'secret´: The secret token
381 * Throws exceptions in case of error.
383 * @param string $subscribed_user_uri The OMB identifier URI specifying the
388 * @return mixed An array containing the subscriptions or 0 if no
389 * subscription has been found.
391 public function getSubscriptions($subscribed_user_uri) {
392 $sub = new Subscription();
394 $user = $this->_getAnyProfile($subscribed_user_uri);
396 $sub->subscribed = $user->id;
398 if (!$sub->find(true)) {
402 /* Since we do not use OMB_Service_Provider’s action methods, there
403 is no need to actually return the subscriptions. */
407 private function _getAnyProfile($uri)
409 $user = Remote_profile::staticGet('uri', $uri);
411 $user = User::staticGet('uri', $uri);
414 throw new Exception('No such user.');
420 * Delete a subscription
422 * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
423 * Throws exceptions in case of error.
425 * @param string $subscriber_uri The OMB identifier URI specifying the
426 * subscribing profile
428 * @param string $subscribed_user_uri The OMB identifier URI specifying the
433 public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
435 $sub = new Subscription();
437 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
438 $subscriber = $this->_getAnyProfile($subscriber_uri);
440 $sub->subscribed = $subscribed->id;
441 $sub->subscriber = $subscriber->id;
447 * Save a subscription
449 * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
450 * Throws exceptions in case of error.
452 * @param string $subscriber_uri The OMB identifier URI specifying
453 * the subscribing profile
455 * @param string $subscribed_user_uri The OMB identifier URI specifying
456 * the subscribed profile
457 * @param OAuthToken $token The access token
461 public function saveSubscription($subscriber_uri, $subscribed_user_uri,
464 $sub = new Subscription();
466 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
467 $subscriber = $this->_getAnyProfile($subscriber_uri);
469 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
470 common_log(LOG_INFO, __METHOD__ . ": remote subscriber banned ($subscriber_uri subbing to $subscribed_user_uri)");
471 // TRANS: Error message displayed to a banned user when they try to subscribe.
472 return _('You have been banned from subscribing.');
475 $sub->subscribed = $subscribed->id;
476 $sub->subscriber = $subscriber->id;
478 $sub_exists = $sub->find(true);
481 $orig_sub = clone($sub);
483 $sub->created = DB_DataObject_Cast::dateTime();
486 $sub->token = $token->key;
487 $sub->secret = $token->secret;
490 $result = $sub->update($orig_sub);
492 $result = $sub->insert();
496 common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
497 // TRANS: Exception thrown when creating a new subscription fails in OAuth store.
498 throw new Exception(_('Could not insert new subscription.'));
502 /* Notify user, if necessary. */
504 if ($subscribed instanceof User) {
505 mail_subscribe_notify_profile($subscribed,
506 Profile::staticGet($subscriber->id));