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 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."
73 // XXX: It's not clear why the token is here
75 function lookup_nonce($consumer, $token, $nonce, $timestamp)
78 $n->consumer_key = $consumer->key;
79 $n->ts = common_sql_date($timestamp);
84 $n->created = DB_DataObject_Cast::dateTime();
90 function new_request_token($consumer)
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();
102 return new OAuthToken($t->tok, $t->secret);
106 // defined in OAuthDataStore, but not implemented anywhere
108 function fetch_request_token($consumer)
110 return $this->new_request_token($consumer);
113 function new_access_token($token, $consumer)
115 common_debug('new_access_token("'.$token->key.'","'.$consumer->key.'")', __FILE__);
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__);
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__);
133 common_debug('access token "'.$at->tok.'" inserted', __FILE__);
135 $orig_rt = clone($rt);
136 $rt->state = 2; // used
137 if (!$rt->update($orig_rt)) {
140 common_debug('request token "'.$rt->tok.'" updated', __FILE__);
141 // Update subscription
142 // XXX: mixing levels here
143 $sub = Subscription::staticGet('token', $rt->tok);
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)) {
154 common_debug('subscription updated to use access token', __FILE__);
155 return new OAuthToken($at->tok, $at->secret);
163 // defined in OAuthDataStore, but not implemented anywhere
165 function fetch_access_token($consumer)
167 return $this->new_access_token($consumer);
171 * Revoke specified OAuth token
173 * Revokes the authorization token specified by $token_key.
174 * Throws exceptions in case of error.
176 * @param string $token_key The token to be revoked
180 public function revoke_token($token_key) {
182 $rt->tok = $token_key;
185 if (!$rt->find(true)) {
186 throw new Exception('Tried to revoke unknown token');
188 if (!$rt->delete()) {
189 throw new Exception('Failed to delete revoked token');
194 * Authorize specified OAuth token
196 * Authorizes the authorization token specified by $token_key.
197 * Throws exceptions in case of error.
199 * @param string $token_key The token to be authorized
203 public function authorize_token($token_key) {
205 $rt->tok = $token_key;
208 if (!$rt->find(true)) {
209 throw new Exception('Tried to authorize unknown token');
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');
219 * Get profile by identifying URI
221 * Returns an OMB_Profile object representing the OMB profile identified by
223 * Returns null if there is no such OMB profile.
224 * Throws exceptions in case of other error.
226 * @param string $identifier_uri The OMB identifier URI specifying the
231 * @return OMB_Profile The corresponding profile
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');
241 require_once INSTALLDIR.'/lib/omb.php';
242 return profile_to_omb_profile($identifier_uri, $profile);
246 * Save passed profile
248 * Stores the OMB profile $profile. Overwrites an existing entry.
249 * Throws exceptions in case of error.
251 * @param OMB_Profile $profile The OMB profile which should be saved
255 public function saveProfile($omb_profile) {
256 if (common_profile_url($omb_profile->getNickname()) ==
257 $omb_profile->getProfileURL()) {
258 throw new Exception('Not implemented');
260 $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
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
271 $remote = new Remote_profile();
272 $remote->uri = $omb_profile->getIdentifierURI();
273 $profile = new Profile();
276 $profile->nickname = $omb_profile->getNickname();
277 $profile->profileurl = $omb_profile->getProfileURL();
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;
289 $profile->update($orig_profile);
291 $profile->created = DB_DataObject_Cast::dateTime(); # current time
292 $id = $profile->insert();
294 throw new Exception(_('Error inserting new profile.'));
299 $avatar_url = $omb_profile->getAvatarURL();
301 if (!$this->add_avatar($profile, $avatar_url)) {
302 throw new Exception(_('Error inserting avatar.'));
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();
316 if (!$remote->update($orig_remote)) {
317 throw new Exception(_('Error updating remote profile.'));
320 $remote->created = DB_DataObject_Cast::dateTime(); # current time
321 if (!$remote->insert()) {
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 return _('You have been banned from subscribing.');
485 $sub->subscribed = $subscribed->id;
486 $sub->subscriber = $subscriber->id;
488 $sub_exists = $sub->find(true);
491 $orig_sub = clone($sub);
493 $sub->created = DB_DataObject_Cast::dateTime();
496 $sub->token = $token->key;
497 $sub->secret = $token->secret;
500 $result = $sub->update($orig_sub);
502 $result = $sub->insert();
506 common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
507 throw new Exception(_('Couldn\'t insert new subscription.'));
511 /* Notify user, if necessary. */
513 if ($subscribed instanceof User) {
514 mail_subscribe_notify_profile($subscribed,
515 Profile::staticGet($subscriber->id));