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 // 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."
62 // XXX: It's not clear why the token is here
64 function lookup_nonce($consumer, $token, $nonce, $timestamp)
67 $n->consumer_key = $consumer->key;
73 $n->created = DB_DataObject_Cast::dateTime();
79 function new_request_token($consumer)
82 $t->consumer_key = $consumer->key;
83 $t->tok = common_good_rand(16);
84 $t->secret = common_good_rand(16);
85 $t->type = 0; // request
86 $t->state = 0; // unauthorized
87 $t->created = DB_DataObject_Cast::dateTime();
91 return new OAuthToken($t->tok, $t->secret);
95 // defined in OAuthDataStore, but not implemented anywhere
97 function fetch_request_token($consumer)
99 return $this->new_request_token($consumer);
102 function new_access_token($token, $consumer)
104 common_debug('new_access_token("'.$token->key.'","'.$consumer->key.'")', __FILE__);
106 $rt->consumer_key = $consumer->key;
107 $rt->tok = $token->key;
108 $rt->type = 0; // request
109 if ($rt->find(true) && $rt->state == 1) { // authorized
110 common_debug('request token found.', __FILE__);
112 $at->consumer_key = $consumer->key;
113 $at->tok = common_good_rand(16);
114 $at->secret = common_good_rand(16);
115 $at->type = 1; // access
116 $at->created = DB_DataObject_Cast::dateTime();
117 if (!$at->insert()) {
118 $e = $at->_lastError;
119 common_debug('access token "'.$at->tok.'" not inserted: "'.$e->message.'"', __FILE__);
122 common_debug('access token "'.$at->tok.'" inserted', __FILE__);
124 $orig_rt = clone($rt);
125 $rt->state = 2; // used
126 if (!$rt->update($orig_rt)) {
129 common_debug('request token "'.$rt->tok.'" updated', __FILE__);
130 // Update subscription
131 // XXX: mixing levels here
132 $sub = Subscription::staticGet('token', $rt->tok);
136 common_debug('subscription for request token found', __FILE__);
137 $orig_sub = clone($sub);
138 $sub->token = $at->tok;
139 $sub->secret = $at->secret;
140 if (!$sub->update($orig_sub)) {
143 common_debug('subscription updated to use access token', __FILE__);
144 return new OAuthToken($at->tok, $at->secret);
152 // defined in OAuthDataStore, but not implemented anywhere
154 function fetch_access_token($consumer)
156 return $this->new_access_token($consumer);
160 * Revoke specified OAuth token
162 * Revokes the authorization token specified by $token_key.
163 * Throws exceptions in case of error.
165 * @param string $token_key The token to be revoked
169 public function revoke_token($token_key) {
171 $rt->tok = $token_key;
174 if (!$rt->find(true)) {
175 throw new Exception('Tried to revoke unknown token');
177 if (!$rt->delete()) {
178 throw new Exception('Failed to delete revoked token');
183 * Authorize specified OAuth token
185 * Authorizes the authorization token specified by $token_key.
186 * Throws exceptions in case of error.
188 * @param string $token_key The token to be authorized
192 public function authorize_token($token_key) {
194 $rt->tok = $token_key;
197 if (!$rt->find(true)) {
198 throw new Exception('Tried to authorize unknown token');
200 $orig_rt = clone($rt);
201 $rt->state = 1; # Authorized but not used
202 if (!$rt->update($orig_rt)) {
203 throw new Exception('Failed to authorize token');
208 * Get profile by identifying URI
210 * Returns an OMB_Profile object representing the OMB profile identified by
212 * Returns null if there is no such OMB profile.
213 * Throws exceptions in case of other error.
215 * @param string $identifier_uri The OMB identifier URI specifying the
220 * @return OMB_Profile The corresponding profile
222 public function getProfile($identifier_uri) {
223 /* getProfile is only used for remote profiles by libomb.
224 TODO: Make it work with local ones anyway. */
225 $remote = Remote_profile::staticGet('uri', $identifier_uri);
226 if (!$remote) throw new Exception('No such remote profile');
227 $profile = Profile::staticGet('id', $remote->id);
228 if (!$profile) throw new Exception('No profile for remote user');
230 require_once INSTALLDIR.'/lib/omb.php';
231 return profile_to_omb_profile($identifier_uri, $profile);
235 * Save passed profile
237 * Stores the OMB profile $profile. Overwrites an existing entry.
238 * Throws exceptions in case of error.
240 * @param OMB_Profile $profile The OMB profile which should be saved
244 public function saveProfile($omb_profile) {
245 if (common_profile_url($omb_profile->getNickname()) ==
246 $omb_profile->getProfileURL()) {
247 throw new Exception('Not implemented');
249 $remote = Remote_profile::staticGet('uri', $omb_profile->getIdentifierURI());
253 $profile = Profile::staticGet($remote->id);
254 $orig_remote = clone($remote);
255 $orig_profile = clone($profile);
256 # XXX: compare current postNotice and updateProfile URLs to the ones
257 # stored in the DB to avoid (possibly...) above attack
260 $remote = new Remote_profile();
261 $remote->uri = $omb_profile->getIdentifierURI();
262 $profile = new Profile();
265 $profile->nickname = $omb_profile->getNickname();
266 $profile->profileurl = $omb_profile->getProfileURL();
268 $fullname = $omb_profile->getFullname();
269 $profile->fullname = is_null($fullname) ? '' : $fullname;
270 $homepage = $omb_profile->getHomepage();
271 $profile->homepage = is_null($homepage) ? '' : $homepage;
272 $bio = $omb_profile->getBio();
273 $profile->bio = is_null($bio) ? '' : $bio;
274 $location = $omb_profile->getLocation();
275 $profile->location = is_null($location) ? '' : $location;
278 $profile->update($orig_profile);
280 $profile->created = DB_DataObject_Cast::dateTime(); # current time
281 $id = $profile->insert();
283 throw new Exception(_('Error inserting new profile'));
288 $avatar_url = $omb_profile->getAvatarURL();
290 if (!$this->add_avatar($profile, $avatar_url)) {
291 throw new Exception(_('Error inserting avatar'));
294 $avatar = $profile->getOriginalAvatar();
295 if($avatar) $avatar->delete();
296 $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
297 if($avatar) $avatar->delete();
298 $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
299 if($avatar) $avatar->delete();
300 $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
301 if($avatar) $avatar->delete();
305 if (!$remote->update($orig_remote)) {
306 throw new Exception(_('Error updating remote profile'));
309 $remote->created = DB_DataObject_Cast::dateTime(); # current time
310 if (!$remote->insert()) {
311 throw new Exception(_('Error inserting remote profile'));
317 function add_avatar($profile, $url)
319 $temp_filename = tempnam(sys_get_temp_dir(), 'listener_avatar');
320 copy($url, $temp_filename);
321 $imagefile = new ImageFile($profile->id, $temp_filename);
322 $filename = Avatar::filename($profile->id,
323 image_type_to_extension($imagefile->type),
326 rename($temp_filename, Avatar::path($filename));
327 return $profile->setOriginal($filename);
333 * Stores the OMB notice $notice. The datastore may change the passed notice.
334 * This might by neccessary for URIs depending on a database key. Note that
335 * it is the user’s duty to present a mechanism for his OMB_Datastore to
336 * appropriately change his OMB_Notice.
337 * Throws exceptions in case of error.
339 * @param OMB_Notice $notice The OMB notice which should be saved
343 public function saveNotice(&$omb_notice) {
344 if (Notice::staticGet('uri', $omb_notice->getIdentifierURI())) {
345 throw new Exception(_('Duplicate notice'));
347 $author_uri = $omb_notice->getAuthor()->getIdentifierURI();
348 common_log(LOG_DEBUG, $author_uri, __FILE__);
349 $author = Remote_profile::staticGet('uri', $author_uri);
351 $author = User::staticGet('uri', $author_uri);
354 throw new Exception('No such user.');
357 common_log(LOG_DEBUG, print_r($author, true), __FILE__);
359 $notice = Notice::saveNew($author->id,
360 $omb_notice->getContent(),
364 $omb_notice->getIdentifierURI());
366 common_broadcast_notice($notice, true);
370 * Get subscriptions of a given profile
372 * Returns an array containing subscription informations for the specified
373 * profile. Every array entry should in turn be an array with keys
374 * 'uri´: The identifier URI of the subscriber
375 * 'token´: The subscribe token
376 * 'secret´: The secret token
377 * Throws exceptions in case of error.
379 * @param string $subscribed_user_uri The OMB identifier URI specifying the
384 * @return mixed An array containing the subscriptions or 0 if no
385 * subscription has been found.
387 public function getSubscriptions($subscribed_user_uri) {
388 $sub = new Subscription();
390 $user = $this->_getAnyProfile($subscribed_user_uri);
392 $sub->subscribed = $user->id;
394 if (!$sub->find(true)) {
398 /* Since we do not use OMB_Service_Provider’s action methods, there
399 is no need to actually return the subscriptions. */
403 private function _getAnyProfile($uri)
405 $user = Remote_profile::staticGet('uri', $uri);
407 $user = User::staticGet('uri', $uri);
410 throw new Exception('No such user.');
416 * Delete a subscription
418 * Deletes the subscription from $subscriber_uri to $subscribed_user_uri.
419 * Throws exceptions in case of error.
421 * @param string $subscriber_uri The OMB identifier URI specifying the
422 * subscribing profile
424 * @param string $subscribed_user_uri The OMB identifier URI specifying the
429 public function deleteSubscription($subscriber_uri, $subscribed_user_uri)
431 $sub = new Subscription();
433 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
434 $subscriber = $this->_getAnyProfile($subscriber_uri);
436 $sub->subscribed = $subscribed->id;
437 $sub->subscriber = $subscriber->id;
443 * Save a subscription
445 * Saves the subscription from $subscriber_uri to $subscribed_user_uri.
446 * Throws exceptions in case of error.
448 * @param string $subscriber_uri The OMB identifier URI specifying
449 * the subscribing profile
451 * @param string $subscribed_user_uri The OMB identifier URI specifying
452 * the subscribed profile
453 * @param OAuthToken $token The access token
457 public function saveSubscription($subscriber_uri, $subscribed_user_uri,
460 $sub = new Subscription();
462 $subscribed = $this->_getAnyProfile($subscribed_user_uri);
463 $subscriber = $this->_getAnyProfile($subscriber_uri);
465 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
466 return _('You have been banned from subscribing.');
469 $sub->subscribed = $subscribed->id;
470 $sub->subscriber = $subscriber->id;
472 $sub_exists = $sub->find(true);
475 $orig_sub = clone($sub);
477 $sub->created = DB_DataObject_Cast::dateTime();
480 $sub->token = $token->key;
481 $sub->secret = $token->secret;
484 $result = $sub->update($orig_sub);
486 $result = $sub->insert();
490 common_log_db_error($sub, ($sub_exists) ? 'UPDATE' : 'INSERT', __FILE__);
491 throw new Exception(_('Couldn\'t insert new subscription.'));
495 /* Notify user, if necessary. */
497 if ($subscribed instanceof User) {
498 mail_subscribe_notify_profile($subscribed,
499 Profile::staticGet($subscriber->id));