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::getKV('consumer_key', $consumer_key);
32 $con = new Consumer();
33 $con->consumer_key = $consumer_key;
34 $con->seed = common_random_hexstr(16);
35 $con->created = common_sql_now();
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 = common_sql_now();
77 function new_request_token($consumer)
80 $t->consumer_key = $consumer->key;
81 $t->tok = common_random_hexstr(16);
82 $t->secret = common_random_hexstr(16);
83 $t->type = 0; // request
84 $t->state = 0; // unauthorized
85 $t->created = common_sql_now();
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_random_hexstr(16);
111 $at->secret = common_random_hexstr(16);
112 $at->type = 1; // access
113 $at->created = common_sql_now();
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::getKV('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::getKV('uri', $identifier_uri);
222 if (!$remote) throw new Exception('No such remote profile');
223 $profile = Profile::getKV('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::getKV('uri', $omb_profile->getIdentifierURI());
249 $profile = Profile::getKV($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 = common_sql_now(); # 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::deleteFromProfile($profile);
296 if (!$remote->update($orig_remote)) {
297 // TRANS: Exception thrown when updating a remote profile fails in OAuth store.
298 throw new Exception(_('Error updating remote profile.'));
301 $remote->created = common_sql_now(); # current time
302 if (!$remote->insert()) {
303 // TRANS: Exception thrown when creating a remote profile fails in OAuth store.
304 throw new Exception(_('Error inserting remote profile.'));
310 function add_avatar($profile, $url)
312 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
314 copy($url, $temp_filename);
315 $imagefile = new ImageFile($profile->id, $temp_filename);
316 $filename = Avatar::filename($profile->id,
317 image_type_to_extension($imagefile->type),
320 rename($temp_filename, Avatar::path($filename));
321 } catch (Exception $e) {
322 unlink($temp_filename);
325 return $profile->setOriginal($filename);
331 * Stores the OMB notice $notice. The datastore may change the passed notice.
332 * This might by neccessary for URIs depending on a database key. Note that
333 * it is the user’s duty to present a mechanism for his OMB_Datastore to
334 * appropriately change his OMB_Notice.
335 * Throws exceptions in case of error.
337 * @param OMB_Notice $notice The OMB notice which should be saved
341 public function saveNotice(&$omb_notice) {
342 if (Notice::getKV('uri', $omb_notice->getIdentifierURI())) {
343 // TRANS: Exception thrown when a notice is denied because it has been sent before.
344 throw new Exception(_('Duplicate notice.'));
346 $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
347 common_log(LOG_DEBUG, $author_uri, __FILE__);
348 $author = Remote_profile::getKV('uri', $author_uri);
350 $author = User::getKV('uri', $author_uri);
353 throw new Exception('No such user.');
356 common_log(LOG_DEBUG, print_r($author, true), __FILE__);
358 $notice = Notice::saveNew($author->id,
359 $omb_notice->getContent(),
361 array('is_local' => Notice::REMOTE,
362 'uri' => $omb_notice->getIdentifierURI()));
367 * Get subscriptions of a given profile
369 * Returns an array containing subscription informations for the specified
370 * profile. Every array entry should in turn be an array with keys
371 * 'uri´: The identifier URI of the subscriber
372 * 'token´: The subscribe token
373 * 'secret´: The secret token
374 * Throws exceptions in case of error.
376 * @param string $subscribed_user_uri The OMB identifier URI specifying the
381 * @return mixed An array containing the subscriptions or 0 if no
382 * subscription has been found.
384 public function getSubscriptions($subscribed_user_uri) {
385 $sub = new Subscription();
387 $user = $this->_getAnyProfile($subscribed_user_uri);
389 $sub->subscribed = $user->id;
391 if (!$sub->find(true)) {
395 /* Since we do not use OMB_Service_Provider’s action methods, there
396 is no need to actually return the subscriptions. */
400 private function _getAnyProfile($uri)
402 $user = Remote_profile::getKV('uri', $uri);
404 $user = User::getKV('uri', $uri);
407 throw new Exception('No such user.');
413 * Delete a subscription
415 * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
416 * Throws exceptions in case of error.
418 * @param string $subscriber_uri The OMB identifier URI specifying the
419 * subscribing profile
421 * @param string $subscribed_user_uri The OMB identifier URI specifying the
426 public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
428 $sub = new Subscription();
430 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
431 $subscriber = $this->_getAnyProfile($subscriber_uri);
433 $sub->subscribed = $subscribed->id;
434 $sub->subscriber = $subscriber->id;
440 * Save a subscription
442 * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
443 * Throws exceptions in case of error.
445 * @param string $subscriber_uri The OMB identifier URI specifying
446 * the subscribing profile
448 * @param string $subscribed_user_uri The OMB identifier URI specifying
449 * the subscribed profile
450 * @param OAuthToken $token The access token
454 public function saveSubscription($subscriber_uri, $subscribed_user_uri,
457 $sub = new Subscription();
459 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
460 $subscriber = $this->_getAnyProfile($subscriber_uri);
462 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
463 common_log(LOG_INFO, __METHOD__ . ": remote subscriber banned ($subscriber_uri subbing to $subscribed_user_uri)");
464 // TRANS: Error message displayed to a banned user when they try to subscribe.
465 return _('You have been banned from subscribing.');
468 $sub->subscribed = $subscribed->id;
469 $sub->subscriber = $subscriber->id;
471 $sub_exists = $sub->find(true);
474 $orig_sub = clone($sub);
476 $sub->created = common_sql_now();
479 $sub->token = $token->key;
480 $sub->secret = $token->secret;
483 $result = $sub->update($orig_sub);
485 $result = $sub->insert();
489 common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
490 // TRANS: Exception thrown when creating a new subscription fails in OAuth store.
491 throw new Exception(_('Could not insert new subscription.'));
495 /* Notify user, if necessary. */
497 if ($subscribed instanceof User) {
498 mail_subscribe_notify_profile($subscribed,
499 Profile::getKV($subscriber->id));