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;
32 /* the code below is auto generated do not remove the above tag */
34 public $__table = 'subscription'; // table name
35 public $subscriber; // int(4) primary_key not_null
36 public $subscribed; // int(4) primary_key not_null
37 public $jabber; // tinyint(1) default_1
38 public $sms; // tinyint(1) default_1
39 public $token; // varchar(255)
40 public $secret; // varchar(255)
41 public $created; // datetime() not_null
42 public $modified; // timestamp() not_null default_CURRENT_TIMESTAMP
45 function staticGet($k,$v=null)
46 { return Memcached_DataObject::staticGet('Subscription',$k,$v); }
48 /* the code above is auto generated do not remove the tag below */
53 return Memcached_DataObject::pkeyGet('Subscription', $kv);
57 * Make a new subscription
59 * @param Profile $subscriber party to receive new notices
60 * @param Profile $other party sending notices; publisher
62 * @return Subscription new subscription
65 static function start($subscriber, $other)
67 // @fixme should we enforce this as profiles in callers instead?
68 if ($subscriber instanceof User) {
69 $subscriber = $subscriber->getProfile();
71 if ($other instanceof User) {
72 $other = $other->getProfile();
75 if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
76 // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
77 throw new Exception(_('You have been banned from subscribing.'));
80 if (self::exists($subscriber, $other)) {
81 // TRANS: Exception thrown when trying to subscribe while already subscribed.
82 throw new Exception(_('Already subscribed!'));
85 if ($other->hasBlocked($subscriber)) {
86 // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
87 throw new Exception(_('User has blocked you.'));
90 if (Event::handle('StartSubscribe', array($subscriber, $other))) {
91 $sub = self::saveNew($subscriber->id, $other->id);
94 self::blow('user:notices_with_friends:%d', $subscriber->id);
96 self::blow('subscription:by-subscriber:'.$subscriber->id);
97 self::blow('subscription:by-subscribed:'.$other->id);
99 $subscriber->blowSubscriptionCount();
100 $other->blowSubscriberCount();
102 $otherUser = User::staticGet('id', $other->id);
104 if (!empty($otherUser) &&
105 $otherUser->autosubscribe &&
106 !self::exists($other, $subscriber) &&
107 !$subscriber->hasBlocked($other)) {
110 self::start($other, $subscriber);
111 } catch (Exception $e) {
112 common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
116 Event::handle('EndSubscribe', array($subscriber, $other));
123 * Low-level subscription save.
124 * Outside callers should use Subscription::start()
126 protected function saveNew($subscriber_id, $other_id)
128 $sub = new Subscription();
130 $sub->subscriber = $subscriber_id;
131 $sub->subscribed = $other_id;
134 $sub->created = common_sql_now();
136 $result = $sub->insert();
139 common_log_db_error($sub, 'INSERT', __FILE__);
140 // TRANS: Exception thrown when a subscription could not be stored on the server.
141 throw new Exception(_('Could not save subscription.'));
149 # XXX: add other notifications (Jabber, SMS) here
150 # XXX: queue this and handle it offline
151 # XXX: Whatever happens, do it in Twitter-like API, too
153 $this->notifyEmail();
156 function notifyEmail()
158 $subscribedUser = User::staticGet('id', $this->subscribed);
160 if (!empty($subscribedUser)) {
162 $subscriber = Profile::staticGet('id', $this->subscriber);
164 mail_subscribe_notify_profile($subscribedUser, $subscriber);
169 * Cancel a subscription
172 function cancel($subscriber, $other)
174 if (!self::exists($subscriber, $other)) {
175 // TRANS: Exception thrown when trying to unsibscribe without a subscription.
176 throw new Exception(_('Not subscribed!'));
179 // Don't allow deleting self subs
181 if ($subscriber->id == $other->id) {
182 // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
183 throw new Exception(_('Could not delete self-subscription.'));
186 if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
188 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
189 'subscribed' => $other->id));
191 // note we checked for existence above
193 assert(!empty($sub));
195 // @todo: move this block to EndSubscribe handler for
196 // OMB plugin when it exists.
198 if (!empty($sub->token)) {
200 $token = new Token();
202 $token->tok = $sub->token;
204 if ($token->find(true)) {
206 $result = $token->delete();
209 common_log_db_error($token, 'DELETE', __FILE__);
210 // TRANS: Exception thrown when the OMB token for a subscription could not deleted on the server.
211 throw new Exception(_('Could not delete subscription OMB token.'));
214 common_log(LOG_ERR, "Couldn't find credentials with token {$token->tok}");
218 $result = $sub->delete();
221 common_log_db_error($sub, 'DELETE', __FILE__);
222 // TRANS: Exception thrown when a subscription could not be deleted on the server.
223 throw new Exception(_('Could not delete subscription.'));
226 self::blow('user:notices_with_friends:%d', $subscriber->id);
228 self::blow('subscription:by-subscriber:'.$subscriber->id);
229 self::blow('subscription:by-subscribed:'.$other->id);
231 $subscriber->blowSubscriptionCount();
232 $other->blowSubscriberCount();
234 Event::handle('EndUnsubscribe', array($subscriber, $other));
240 function exists($subscriber, $other)
242 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
243 'subscribed' => $other->id));
244 return (empty($sub)) ? false : true;
247 function asActivity()
249 $subscriber = Profile::staticGet('id', $this->subscriber);
250 $subscribed = Profile::staticGet('id', $this->subscribed);
252 $act = new Activity();
254 $act->verb = ActivityVerb::FOLLOW;
256 // XXX: rationalize this with the URL
258 $act->id = TagURI::mint('follow:%d:%d:%s',
261 common_date_iso8601($this->created));
263 $act->time = strtotime($this->created);
264 // TRANS: Activity tile when subscribing to another person.
265 $act->title = _("Follow");
266 // TRANS: Notification given when one person starts following another.
267 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
268 $act->content = sprintf(_('%1$s is now following %2$s.'),
269 $subscriber->getBestName(),
270 $subscribed->getBestName());
272 $act->actor = ActivityObject::fromProfile($subscriber);
273 $act->objects[] = ActivityObject::fromProfile($subscribed);
275 $url = common_local_url('AtomPubShowSubscription',
276 array('subscriber' => $subscriber->id,
277 'subscribed' => $subscribed->id));
279 $act->selfLink = $url;
280 $act->editLink = $url;
286 * Stream of subscriptions with the same subscriber
288 * Useful for showing pages that list subscriptions in reverse
289 * chronological order. Has offset & limit to make paging
292 * @param integer $subscriberId Profile ID of the subscriber
293 * @param integer $offset Offset from latest
294 * @param integer $limit Maximum number to fetch
296 * @return Subscription stream of subscriptions; use fetch() to iterate
299 static function bySubscriber($subscriberId,
301 $limit = PROFILES_PER_PAGE)
303 if ($offset + $limit > self::CACHE_WINDOW) {
304 return new ArrayWrapper(self::realBySubscriber($subscriberId,
308 $key = 'subscription:by-subscriber:'.$subscriberId;
309 $window = self::cacheGet($key);
310 if ($window === false) {
311 $window = self::realBySubscriber($subscriberId,
314 self::cacheSet($key, $window);
316 return new ArrayWrapper(array_slice($window,
322 private static function realBySubscriber($subscriberId,
326 $sub = new Subscription();
328 $sub->subscriber = $subscriberId;
330 $sub->whereAdd('subscribed != ' . $subscriberId);
332 $sub->orderBy('created DESC');
333 $sub->limit($offset, $limit);
339 while ($sub->fetch()) {
340 $subs[] = clone($sub);
347 * Stream of subscriptions with the same subscribed profile
349 * Useful for showing pages that list subscribers in reverse
350 * chronological order. Has offset & limit to make paging
353 * @param integer $subscribedId Profile ID of the subscribed
354 * @param integer $offset Offset from latest
355 * @param integer $limit Maximum number to fetch
357 * @return Subscription stream of subscriptions; use fetch() to iterate
360 static function bySubscribed($subscribedId,
362 $limit = PROFILES_PER_PAGE)
364 if ($offset + $limit > self::CACHE_WINDOW) {
365 return new ArrayWrapper(self::realBySubscribed($subscribedId,
369 $key = 'subscription:by-subscribed:'.$subscribedId;
370 $window = self::cacheGet($key);
371 if ($window === false) {
372 $window = self::realBySubscribed($subscribedId,
375 self::cacheSet($key, $window);
377 return new ArrayWrapper(array_slice($window,
383 private static function realBySubscribed($subscribedId,
387 $sub = new Subscription();
389 $sub->subscribed = $subscribedId;
391 $sub->whereAdd('subscriber != ' . $subscribedId);
393 $sub->orderBy('created DESC');
394 $sub->limit($offset, $limit);
400 while ($sub->fetch()) {
401 $subs[] = clone($sub);
408 * Flush cached subscriptions when subscription is updated
410 * Because we cache subscriptions, it's useful to flush them
413 * @param mixed $orig Original version of object
415 * @return boolean success flag.
418 function update($orig=null)
420 $result = parent::update($orig);
422 self::blow('subscription:by-subscriber:'.$this->subscriber);
423 self::blow('subscription:by-subscribed:'.$this->subscribed);