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 Memcached_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
46 function staticGet($k,$v=null)
47 { return Memcached_DataObject::staticGet('Subscription',$k,$v); }
49 /* the code above is auto generated do not remove the tag below */
54 return Memcached_DataObject::pkeyGet('Subscription', $kv);
58 * Make a new subscription
60 * @param Profile $subscriber party to receive new notices
61 * @param Profile $other party sending notices; publisher
62 * @param bool $force pass Subscription::FORCE to override local subscription approval
64 * @return mixed Subscription or Subscription_queue: new subscription info
67 static function start($subscriber, $other, $force=false)
69 // @fixme should we enforce this as profiles in callers instead?
70 if ($subscriber instanceof User) {
71 $subscriber = $subscriber->getProfile();
73 if ($other instanceof User) {
74 $other = $other->getProfile();
77 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
78 // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
79 throw new Exception(_('You have been banned from subscribing.'));
82 if (self::exists($subscriber, $other)) {
83 // TRANS: Exception thrown when trying to subscribe while already subscribed.
84 throw new Exception(_('Already subscribed!'));
87 if ($other->hasBlocked($subscriber)) {
88 // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
89 throw new Exception(_('User has blocked you.'));
92 if (Event::handle('StartSubscribe', array($subscriber, $other))) {
93 $otherUser = User::staticGet('id', $other->id);
94 if ($otherUser && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
95 $sub = Subscription_queue::saveNew($subscriber, $other);
98 $sub = self::saveNew($subscriber->id, $other->id);
101 self::blow('user:notices_with_friends:%d', $subscriber->id);
103 self::blow('subscription:by-subscriber:'.$subscriber->id);
104 self::blow('subscription:by-subscribed:'.$other->id);
106 $subscriber->blowSubscriptionCount();
107 $other->blowSubscriberCount();
109 if (!empty($otherUser) &&
110 $otherUser->autosubscribe &&
111 !self::exists($other, $subscriber) &&
112 !$subscriber->hasBlocked($other)) {
115 self::start($other, $subscriber);
116 } catch (Exception $e) {
117 common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
122 Event::handle('EndSubscribe', array($subscriber, $other));
129 * Low-level subscription save.
130 * Outside callers should use Subscription::start()
132 protected function saveNew($subscriber_id, $other_id)
134 $sub = new Subscription();
136 $sub->subscriber = $subscriber_id;
137 $sub->subscribed = $other_id;
140 $sub->created = common_sql_now();
142 $result = $sub->insert();
145 common_log_db_error($sub, 'INSERT', __FILE__);
146 // TRANS: Exception thrown when a subscription could not be stored on the server.
147 throw new Exception(_('Could not save subscription.'));
155 // XXX: add other notifications (Jabber, SMS) here
156 // XXX: queue this and handle it offline
157 // XXX: Whatever happens, do it in Twitter-like API, too
159 $this->notifyEmail();
162 function notifyEmail()
164 $subscribedUser = User::staticGet('id', $this->subscribed);
166 if (!empty($subscribedUser)) {
168 $subscriber = Profile::staticGet('id', $this->subscriber);
170 mail_subscribe_notify_profile($subscribedUser, $subscriber);
175 * Cancel a subscription
178 function cancel($subscriber, $other)
180 if (!self::exists($subscriber, $other)) {
181 // TRANS: Exception thrown when trying to unsibscribe without a subscription.
182 throw new Exception(_('Not subscribed!'));
185 // Don't allow deleting self subs
187 if ($subscriber->id == $other->id) {
188 // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
189 throw new Exception(_('Could not delete self-subscription.'));
192 if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
194 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
195 'subscribed' => $other->id));
197 // note we checked for existence above
199 assert(!empty($sub));
201 $result = $sub->delete();
204 common_log_db_error($sub, 'DELETE', __FILE__);
205 // TRANS: Exception thrown when a subscription could not be deleted on the server.
206 throw new Exception(_('Could not delete subscription.'));
209 self::blow('user:notices_with_friends:%d', $subscriber->id);
211 self::blow('subscription:by-subscriber:'.$subscriber->id);
212 self::blow('subscription:by-subscribed:'.$other->id);
214 $subscriber->blowSubscriptionCount();
215 $other->blowSubscriberCount();
217 Event::handle('EndUnsubscribe', array($subscriber, $other));
223 function exists($subscriber, $other)
225 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
226 'subscribed' => $other->id));
227 return (empty($sub)) ? false : true;
230 function asActivity()
232 $subscriber = Profile::staticGet('id', $this->subscriber);
233 $subscribed = Profile::staticGet('id', $this->subscribed);
235 $act = new Activity();
237 $act->verb = ActivityVerb::FOLLOW;
239 // XXX: rationalize this with the URL
241 $act->id = TagURI::mint('follow:%d:%d:%s',
244 common_date_iso8601($this->created));
246 $act->time = strtotime($this->created);
247 // TRANS: Activity title when subscribing to another person.
248 $act->title = _m('TITLE','Follow');
249 // TRANS: Notification given when one person starts following another.
250 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
251 $act->content = sprintf(_('%1$s is now following %2$s.'),
252 $subscriber->getBestName(),
253 $subscribed->getBestName());
255 $act->actor = ActivityObject::fromProfile($subscriber);
256 $act->objects[] = ActivityObject::fromProfile($subscribed);
258 $url = common_local_url('AtomPubShowSubscription',
259 array('subscriber' => $subscriber->id,
260 'subscribed' => $subscribed->id));
262 $act->selfLink = $url;
263 $act->editLink = $url;
269 * Stream of subscriptions with the same subscriber
271 * Useful for showing pages that list subscriptions in reverse
272 * chronological order. Has offset & limit to make paging
275 * @param integer $subscriberId Profile ID of the subscriber
276 * @param integer $offset Offset from latest
277 * @param integer $limit Maximum number to fetch
279 * @return Subscription stream of subscriptions; use fetch() to iterate
281 static function bySubscriber($subscriberId,
283 $limit = PROFILES_PER_PAGE)
285 if ($offset + $limit > self::CACHE_WINDOW) {
286 return new ArrayWrapper(self::realBySubscriber($subscriberId,
290 $key = 'subscription:by-subscriber:'.$subscriberId;
291 $window = self::cacheGet($key);
292 if ($window === false) {
293 $window = self::realBySubscriber($subscriberId,
296 self::cacheSet($key, $window);
298 return new ArrayWrapper(array_slice($window,
304 private static function realBySubscriber($subscriberId,
308 $sub = new Subscription();
310 $sub->subscriber = $subscriberId;
312 $sub->whereAdd('subscribed != ' . $subscriberId);
314 $sub->orderBy('created DESC');
315 $sub->limit($offset, $limit);
321 while ($sub->fetch()) {
322 $subs[] = clone($sub);
329 * Stream of subscriptions with the same subscribed profile
331 * Useful for showing pages that list subscribers in reverse
332 * chronological order. Has offset & limit to make paging
335 * @param integer $subscribedId Profile ID of the subscribed
336 * @param integer $offset Offset from latest
337 * @param integer $limit Maximum number to fetch
339 * @return Subscription stream of subscriptions; use fetch() to iterate
341 static function bySubscribed($subscribedId,
343 $limit = PROFILES_PER_PAGE)
345 if ($offset + $limit > self::CACHE_WINDOW) {
346 return new ArrayWrapper(self::realBySubscribed($subscribedId,
350 $key = 'subscription:by-subscribed:'.$subscribedId;
351 $window = self::cacheGet($key);
352 if ($window === false) {
353 $window = self::realBySubscribed($subscribedId,
356 self::cacheSet($key, $window);
358 return new ArrayWrapper(array_slice($window,
364 private static function realBySubscribed($subscribedId,
368 $sub = new Subscription();
370 $sub->subscribed = $subscribedId;
372 $sub->whereAdd('subscriber != ' . $subscribedId);
374 $sub->orderBy('created DESC');
375 $sub->limit($offset, $limit);
381 while ($sub->fetch()) {
382 $subs[] = clone($sub);
389 * Flush cached subscriptions when subscription is updated
391 * Because we cache subscriptions, it's useful to flush them
394 * @param mixed $orig Original version of object
396 * @return boolean success flag.
398 function update($orig=null)
400 $result = parent::update($orig);
402 self::blow('subscription:by-subscriber:'.$this->subscriber);
403 self::blow('subscription:by-subscribed:'.$this->subscribed);