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 $created; // datetime() not_null
43 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
45 public static function schemaDef()
49 'subscriber' => array('type' => 'int', 'not null' => true, 'description' => 'profile listening'),
50 'subscribed' => array('type' => 'int', 'not null' => true, 'description' => 'profile being listened to'),
51 'jabber' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver jabber messages'),
52 'sms' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver sms messages'),
53 'token' => array('type' => 'varchar', 'length' => 255, 'description' => 'authorization token'),
54 'secret' => array('type' => 'varchar', 'length' => 255, 'description' => 'token secret'),
55 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
56 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
58 'primary key' => array('subscriber', 'subscribed'),
60 'subscription_subscriber_idx' => array('subscriber', 'created'),
61 'subscription_subscribed_idx' => array('subscribed', 'created'),
62 'subscription_token_idx' => array('token'),
68 function staticGet($k,$v=null)
69 { return Memcached_DataObject::staticGet('Subscription',$k,$v); }
71 /* the code above is auto generated do not remove the tag below */
76 return Memcached_DataObject::pkeyGet('Subscription', $kv);
80 * Make a new subscription
82 * @param Profile $subscriber party to receive new notices
83 * @param Profile $other party sending notices; publisher
84 * @param bool $force pass Subscription::FORCE to override local subscription approval
86 * @return mixed Subscription or Subscription_queue: new subscription info
89 static function start($subscriber, $other, $force=false)
91 // @fixme should we enforce this as profiles in callers instead?
92 if ($subscriber instanceof User) {
93 $subscriber = $subscriber->getProfile();
95 if ($other instanceof User) {
96 $other = $other->getProfile();
99 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
100 // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
101 throw new Exception(_('You have been banned from subscribing.'));
104 if (self::exists($subscriber, $other)) {
105 // TRANS: Exception thrown when trying to subscribe while already subscribed.
106 throw new Exception(_('Already subscribed!'));
109 if ($other->hasBlocked($subscriber)) {
110 // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
111 throw new Exception(_('User has blocked you.'));
114 if (Event::handle('StartSubscribe', array($subscriber, $other))) {
115 $otherUser = User::staticGet('id', $other->id);
116 if ($otherUser && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
117 $sub = Subscription_queue::saveNew($subscriber, $other);
120 $sub = self::saveNew($subscriber->id, $other->id);
123 self::blow('user:notices_with_friends:%d', $subscriber->id);
125 self::blow('subscription:by-subscriber:'.$subscriber->id);
126 self::blow('subscription:by-subscribed:'.$other->id);
128 $subscriber->blowSubscriptionCount();
129 $other->blowSubscriberCount();
131 if (!empty($otherUser) &&
132 $otherUser->autosubscribe &&
133 !self::exists($other, $subscriber) &&
134 !$subscriber->hasBlocked($other)) {
137 self::start($other, $subscriber);
138 } catch (Exception $e) {
139 common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
144 Event::handle('EndSubscribe', array($subscriber, $other));
151 * Low-level subscription save.
152 * Outside callers should use Subscription::start()
154 protected function saveNew($subscriber_id, $other_id)
156 $sub = new Subscription();
158 $sub->subscriber = $subscriber_id;
159 $sub->subscribed = $other_id;
162 $sub->created = common_sql_now();
164 $result = $sub->insert();
167 common_log_db_error($sub, 'INSERT', __FILE__);
168 // TRANS: Exception thrown when a subscription could not be stored on the server.
169 throw new Exception(_('Could not save subscription.'));
177 // XXX: add other notifications (Jabber, SMS) here
178 // XXX: queue this and handle it offline
179 // XXX: Whatever happens, do it in Twitter-like API, too
181 $this->notifyEmail();
184 function notifyEmail()
186 $subscribedUser = User::staticGet('id', $this->subscribed);
188 if (!empty($subscribedUser)) {
190 $subscriber = Profile::staticGet('id', $this->subscriber);
192 mail_subscribe_notify_profile($subscribedUser, $subscriber);
197 * Cancel a subscription
200 function cancel($subscriber, $other)
202 if (!self::exists($subscriber, $other)) {
203 // TRANS: Exception thrown when trying to unsibscribe without a subscription.
204 throw new Exception(_('Not subscribed!'));
207 // Don't allow deleting self subs
209 if ($subscriber->id == $other->id) {
210 // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
211 throw new Exception(_('Could not delete self-subscription.'));
214 if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
216 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
217 'subscribed' => $other->id));
219 // note we checked for existence above
221 assert(!empty($sub));
223 $result = $sub->delete();
226 common_log_db_error($sub, 'DELETE', __FILE__);
227 // TRANS: Exception thrown when a subscription could not be deleted on the server.
228 throw new Exception(_('Could not delete subscription.'));
231 self::blow('user:notices_with_friends:%d', $subscriber->id);
233 self::blow('subscription:by-subscriber:'.$subscriber->id);
234 self::blow('subscription:by-subscribed:'.$other->id);
236 $subscriber->blowSubscriptionCount();
237 $other->blowSubscriberCount();
239 Event::handle('EndUnsubscribe', array($subscriber, $other));
245 function exists($subscriber, $other)
247 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
248 'subscribed' => $other->id));
249 return (empty($sub)) ? false : true;
252 function asActivity()
254 $subscriber = Profile::staticGet('id', $this->subscriber);
255 $subscribed = Profile::staticGet('id', $this->subscribed);
257 $act = new Activity();
259 $act->verb = ActivityVerb::FOLLOW;
261 // XXX: rationalize this with the URL
263 $act->id = TagURI::mint('follow:%d:%d:%s',
266 common_date_iso8601($this->created));
268 $act->time = strtotime($this->created);
269 // TRANS: Activity title when subscribing to another person.
270 $act->title = _m('TITLE','Follow');
271 // TRANS: Notification given when one person starts following another.
272 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
273 $act->content = sprintf(_('%1$s is now following %2$s.'),
274 $subscriber->getBestName(),
275 $subscribed->getBestName());
277 $act->actor = ActivityObject::fromProfile($subscriber);
278 $act->objects[] = ActivityObject::fromProfile($subscribed);
280 $url = common_local_url('AtomPubShowSubscription',
281 array('subscriber' => $subscriber->id,
282 'subscribed' => $subscribed->id));
284 $act->selfLink = $url;
285 $act->editLink = $url;
291 * Stream of subscriptions with the same subscriber
293 * Useful for showing pages that list subscriptions in reverse
294 * chronological order. Has offset & limit to make paging
297 * @param integer $subscriberId Profile ID of the subscriber
298 * @param integer $offset Offset from latest
299 * @param integer $limit Maximum number to fetch
301 * @return Subscription stream of subscriptions; use fetch() to iterate
303 static function bySubscriber($subscriberId,
305 $limit = PROFILES_PER_PAGE)
307 if ($offset + $limit > self::CACHE_WINDOW) {
308 return new ArrayWrapper(self::realBySubscriber($subscriberId,
312 $key = 'subscription:by-subscriber:'.$subscriberId;
313 $window = self::cacheGet($key);
314 if ($window === false) {
315 $window = self::realBySubscriber($subscriberId,
318 self::cacheSet($key, $window);
320 return new ArrayWrapper(array_slice($window,
326 private static function realBySubscriber($subscriberId,
330 $sub = new Subscription();
332 $sub->subscriber = $subscriberId;
334 $sub->whereAdd('subscribed != ' . $subscriberId);
336 $sub->orderBy('created DESC');
337 $sub->limit($offset, $limit);
343 while ($sub->fetch()) {
344 $subs[] = clone($sub);
351 * Stream of subscriptions with the same subscribed profile
353 * Useful for showing pages that list subscribers in reverse
354 * chronological order. Has offset & limit to make paging
357 * @param integer $subscribedId Profile ID of the subscribed
358 * @param integer $offset Offset from latest
359 * @param integer $limit Maximum number to fetch
361 * @return Subscription stream of subscriptions; use fetch() to iterate
363 static function bySubscribed($subscribedId,
365 $limit = PROFILES_PER_PAGE)
367 if ($offset + $limit > self::CACHE_WINDOW) {
368 return new ArrayWrapper(self::realBySubscribed($subscribedId,
372 $key = 'subscription:by-subscribed:'.$subscribedId;
373 $window = self::cacheGet($key);
374 if ($window === false) {
375 $window = self::realBySubscribed($subscribedId,
378 self::cacheSet($key, $window);
380 return new ArrayWrapper(array_slice($window,
386 private static function realBySubscribed($subscribedId,
390 $sub = new Subscription();
392 $sub->subscribed = $subscribedId;
394 $sub->whereAdd('subscriber != ' . $subscribedId);
396 $sub->orderBy('created DESC');
397 $sub->limit($offset, $limit);
403 while ($sub->fetch()) {
404 $subs[] = clone($sub);
411 * Flush cached subscriptions when subscription is updated
413 * Because we cache subscriptions, it's useful to flush them
416 * @param mixed $orig Original version of object
418 * @return boolean success flag.
420 function update($orig=null)
422 $result = parent::update($orig);
424 self::blow('subscription:by-subscriber:'.$this->subscriber);
425 self::blow('subscription:by-subscribed:'.$this->subscribed);