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); }
23 * Table Definition for subscription
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
27 class Subscription extends Managed_DataObject
29 const CACHE_WINDOW = 201;
33 /* the code below is auto generated do not remove the above tag */
35 public $__table = 'subscription'; // table name
36 public $subscriber; // int(4) primary_key not_null
37 public $subscribed; // int(4) primary_key not_null
38 public $jabber; // tinyint(1) default_1
39 public $sms; // tinyint(1) default_1
40 public $token; // varchar(255)
41 public $secret; // varchar(255)
42 public $uri; // varchar(255)
43 public $created; // datetime() not_null
44 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
46 public static function schemaDef()
50 'subscriber' => array('type' => 'int', 'not null' => true, 'description' => 'profile listening'),
51 'subscribed' => array('type' => 'int', 'not null' => true, 'description' => 'profile being listened to'),
52 'jabber' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver jabber messages'),
53 'sms' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver sms messages'),
54 'token' => array('type' => 'varchar', 'length' => 255, 'description' => 'authorization token'),
55 'secret' => array('type' => 'varchar', 'length' => 255, 'description' => 'token secret'),
56 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier'),
57 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
58 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
60 'primary key' => array('subscriber', 'subscribed'),
61 'unique keys' => array(
62 'subscription_uri_key' => array('uri'),
65 'subscription_subscriber_idx' => array('subscriber', 'created'),
66 'subscription_subscribed_idx' => array('subscribed', 'created'),
67 'subscription_token_idx' => array('token'),
72 /* the code above is auto generated do not remove the tag below */
77 return Memcached_DataObject::pkeyGet('Subscription', $kv);
81 * Make a new subscription
83 * @param Profile $subscriber party to receive new notices
84 * @param Profile $other party sending notices; publisher
85 * @param bool $force pass Subscription::FORCE to override local subscription approval
87 * @return mixed Subscription or Subscription_queue: new subscription info
90 static function start($subscriber, $other, $force=false)
92 // @fixme should we enforce this as profiles in callers instead?
93 if ($subscriber instanceof User) {
94 $subscriber = $subscriber->getProfile();
96 if ($other instanceof User) {
97 $other = $other->getProfile();
100 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
101 // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
102 throw new Exception(_('You have been banned from subscribing.'));
105 if (self::exists($subscriber, $other)) {
106 // TRANS: Exception thrown when trying to subscribe while already subscribed.
107 throw new Exception(_('Already subscribed!'));
110 if ($other->hasBlocked($subscriber)) {
111 // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
112 throw new Exception(_('User has blocked you.'));
115 if (Event::handle('StartSubscribe', array($subscriber, $other))) {
116 $otherUser = User::staticGet('id', $other->id);
117 if ($otherUser && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
118 $sub = Subscription_queue::saveNew($subscriber, $other);
121 $sub = self::saveNew($subscriber->id, $other->id);
124 self::blow('user:notices_with_friends:%d', $subscriber->id);
126 self::blow('subscription:by-subscriber:'.$subscriber->id);
127 self::blow('subscription:by-subscribed:'.$other->id);
129 $subscriber->blowSubscriptionCount();
130 $other->blowSubscriberCount();
132 if (!empty($otherUser) &&
133 $otherUser->autosubscribe &&
134 !self::exists($other, $subscriber) &&
135 !$subscriber->hasBlocked($other)) {
138 self::start($other, $subscriber);
139 } catch (Exception $e) {
140 common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
145 Event::handle('EndSubscribe', array($subscriber, $other));
152 * Low-level subscription save.
153 * Outside callers should use Subscription::start()
155 protected function saveNew($subscriber_id, $other_id)
157 $sub = new Subscription();
159 $sub->subscriber = $subscriber_id;
160 $sub->subscribed = $other_id;
163 $sub->created = common_sql_now();
164 $sub->uri = self::newURI($sub->subscriber,
168 $result = $sub->insert();
171 common_log_db_error($sub, 'INSERT', __FILE__);
172 // TRANS: Exception thrown when a subscription could not be stored on the server.
173 throw new Exception(_('Could not save subscription.'));
181 // XXX: add other notifications (Jabber, SMS) here
182 // XXX: queue this and handle it offline
183 // XXX: Whatever happens, do it in Twitter-like API, too
185 $this->notifyEmail();
188 function notifyEmail()
190 $subscribedUser = User::staticGet('id', $this->subscribed);
192 if (!empty($subscribedUser)) {
194 $subscriber = Profile::staticGet('id', $this->subscriber);
196 mail_subscribe_notify_profile($subscribedUser, $subscriber);
201 * Cancel a subscription
204 function cancel($subscriber, $other)
206 if (!self::exists($subscriber, $other)) {
207 // TRANS: Exception thrown when trying to unsibscribe without a subscription.
208 throw new Exception(_('Not subscribed!'));
211 // Don't allow deleting self subs
213 if ($subscriber->id == $other->id) {
214 // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
215 throw new Exception(_('Could not delete self-subscription.'));
218 if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
220 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
221 'subscribed' => $other->id));
223 // note we checked for existence above
225 assert(!empty($sub));
227 $result = $sub->delete();
230 common_log_db_error($sub, 'DELETE', __FILE__);
231 // TRANS: Exception thrown when a subscription could not be deleted on the server.
232 throw new Exception(_('Could not delete subscription.'));
235 self::blow('user:notices_with_friends:%d', $subscriber->id);
237 self::blow('subscription:by-subscriber:'.$subscriber->id);
238 self::blow('subscription:by-subscribed:'.$other->id);
240 $subscriber->blowSubscriptionCount();
241 $other->blowSubscriberCount();
243 Event::handle('EndUnsubscribe', array($subscriber, $other));
249 function exists($subscriber, $other)
251 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
252 'subscribed' => $other->id));
253 return (empty($sub)) ? false : true;
256 function asActivity()
258 $subscriber = Profile::staticGet('id', $this->subscriber);
259 $subscribed = Profile::staticGet('id', $this->subscribed);
261 if (empty($subscriber)) {
262 throw new Exception(sprintf(_('No profile for the subscriber: %d'), $this->subscriber));
265 if (empty($subscribed)) {
266 throw new Exception(sprintf(_('No profile for the subscribed: %d'), $this->subscribed));
269 $act = new Activity();
271 $act->verb = ActivityVerb::FOLLOW;
273 // XXX: rationalize this with the URL
275 $act->id = $this->getURI();
277 $act->time = strtotime($this->created);
278 // TRANS: Activity title when subscribing to another person.
279 $act->title = _m('TITLE','Follow');
280 // TRANS: Notification given when one person starts following another.
281 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
282 $act->content = sprintf(_('%1$s is now following %2$s.'),
283 $subscriber->getBestName(),
284 $subscribed->getBestName());
286 $act->actor = ActivityObject::fromProfile($subscriber);
287 $act->objects[] = ActivityObject::fromProfile($subscribed);
289 $url = common_local_url('AtomPubShowSubscription',
290 array('subscriber' => $subscriber->id,
291 'subscribed' => $subscribed->id));
293 $act->selfLink = $url;
294 $act->editLink = $url;
300 * Stream of subscriptions with the same subscriber
302 * Useful for showing pages that list subscriptions in reverse
303 * chronological order. Has offset & limit to make paging
306 * @param integer $subscriberId Profile ID of the subscriber
307 * @param integer $offset Offset from latest
308 * @param integer $limit Maximum number to fetch
310 * @return Subscription stream of subscriptions; use fetch() to iterate
312 static function bySubscriber($subscriberId,
314 $limit = PROFILES_PER_PAGE)
316 if ($offset + $limit > self::CACHE_WINDOW) {
317 return new ArrayWrapper(self::realBySubscriber($subscriberId,
321 $key = 'subscription:by-subscriber:'.$subscriberId;
322 $window = self::cacheGet($key);
323 if ($window === false) {
324 $window = self::realBySubscriber($subscriberId,
327 self::cacheSet($key, $window);
329 return new ArrayWrapper(array_slice($window,
335 private static function realBySubscriber($subscriberId,
339 $sub = new Subscription();
341 $sub->subscriber = $subscriberId;
343 $sub->whereAdd('subscribed != ' . $subscriberId);
345 $sub->orderBy('created DESC');
346 $sub->limit($offset, $limit);
352 while ($sub->fetch()) {
353 $subs[] = clone($sub);
360 * Stream of subscriptions with the same subscribed profile
362 * Useful for showing pages that list subscribers in reverse
363 * chronological order. Has offset & limit to make paging
366 * @param integer $subscribedId Profile ID of the subscribed
367 * @param integer $offset Offset from latest
368 * @param integer $limit Maximum number to fetch
370 * @return Subscription stream of subscriptions; use fetch() to iterate
372 static function bySubscribed($subscribedId,
374 $limit = PROFILES_PER_PAGE)
376 if ($offset + $limit > self::CACHE_WINDOW) {
377 return new ArrayWrapper(self::realBySubscribed($subscribedId,
381 $key = 'subscription:by-subscribed:'.$subscribedId;
382 $window = self::cacheGet($key);
383 if ($window === false) {
384 $window = self::realBySubscribed($subscribedId,
387 self::cacheSet($key, $window);
389 return new ArrayWrapper(array_slice($window,
395 private static function realBySubscribed($subscribedId,
399 $sub = new Subscription();
401 $sub->subscribed = $subscribedId;
403 $sub->whereAdd('subscriber != ' . $subscribedId);
405 $sub->orderBy('created DESC');
406 $sub->limit($offset, $limit);
412 while ($sub->fetch()) {
413 $subs[] = clone($sub);
420 * Flush cached subscriptions when subscription is updated
422 * Because we cache subscriptions, it's useful to flush them
425 * @param mixed $orig Original version of object
427 * @return boolean success flag.
429 function update($orig=null)
431 $result = parent::update($orig);
433 self::blow('subscription:by-subscriber:'.$this->subscriber);
434 self::blow('subscription:by-subscribed:'.$this->subscribed);
441 if (!empty($this->uri)) {
444 return self::newURI($this->subscriber, $this->subscribed, $this->created);
448 static function newURI($subscriber_id, $subscribed_id, $created)
450 return TagURI::mint('follow:%d:%d:%s',
453 common_date_iso8601($created));