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 // @todo: move this block to EndSubscribe handler for
202 // OMB plugin when it exists.
204 if (!empty($sub->token)) {
206 $token = new Token();
208 $token->tok = $sub->token;
210 if ($token->find(true)) {
212 $result = $token->delete();
215 common_log_db_error($token, 'DELETE', __FILE__);
216 // TRANS: Exception thrown when the OMB token for a subscription could not deleted on the server.
217 throw new Exception(_('Could not delete subscription OMB token.'));
220 common_log(LOG_ERR, "Couldn't find credentials with token {$token->tok}");
224 $result = $sub->delete();
227 common_log_db_error($sub, 'DELETE', __FILE__);
228 // TRANS: Exception thrown when a subscription could not be deleted on the server.
229 throw new Exception(_('Could not delete subscription.'));
232 self::blow('user:notices_with_friends:%d', $subscriber->id);
234 self::blow('subscription:by-subscriber:'.$subscriber->id);
235 self::blow('subscription:by-subscribed:'.$other->id);
237 $subscriber->blowSubscriptionCount();
238 $other->blowSubscriberCount();
240 Event::handle('EndUnsubscribe', array($subscriber, $other));
246 function exists($subscriber, $other)
248 $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
249 'subscribed' => $other->id));
250 return (empty($sub)) ? false : true;
253 function asActivity()
255 $subscriber = Profile::staticGet('id', $this->subscriber);
256 $subscribed = Profile::staticGet('id', $this->subscribed);
258 $act = new Activity();
260 $act->verb = ActivityVerb::FOLLOW;
262 // XXX: rationalize this with the URL
264 $act->id = TagURI::mint('follow:%d:%d:%s',
267 common_date_iso8601($this->created));
269 $act->time = strtotime($this->created);
270 // TRANS: Activity title when subscribing to another person.
271 $act->title = _m('TITLE','Follow');
272 // TRANS: Notification given when one person starts following another.
273 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
274 $act->content = sprintf(_('%1$s is now following %2$s.'),
275 $subscriber->getBestName(),
276 $subscribed->getBestName());
278 $act->actor = ActivityObject::fromProfile($subscriber);
279 $act->objects[] = ActivityObject::fromProfile($subscribed);
281 $url = common_local_url('AtomPubShowSubscription',
282 array('subscriber' => $subscriber->id,
283 'subscribed' => $subscribed->id));
285 $act->selfLink = $url;
286 $act->editLink = $url;
292 * Stream of subscriptions with the same subscriber
294 * Useful for showing pages that list subscriptions in reverse
295 * chronological order. Has offset & limit to make paging
298 * @param integer $subscriberId Profile ID of the subscriber
299 * @param integer $offset Offset from latest
300 * @param integer $limit Maximum number to fetch
302 * @return Subscription stream of subscriptions; use fetch() to iterate
304 static function bySubscriber($subscriberId,
306 $limit = PROFILES_PER_PAGE)
308 if ($offset + $limit > self::CACHE_WINDOW) {
309 return new ArrayWrapper(self::realBySubscriber($subscriberId,
313 $key = 'subscription:by-subscriber:'.$subscriberId;
314 $window = self::cacheGet($key);
315 if ($window === false) {
316 $window = self::realBySubscriber($subscriberId,
319 self::cacheSet($key, $window);
321 return new ArrayWrapper(array_slice($window,
327 private static function realBySubscriber($subscriberId,
331 $sub = new Subscription();
333 $sub->subscriber = $subscriberId;
335 $sub->whereAdd('subscribed != ' . $subscriberId);
337 $sub->orderBy('created DESC');
338 $sub->limit($offset, $limit);
344 while ($sub->fetch()) {
345 $subs[] = clone($sub);
352 * Stream of subscriptions with the same subscribed profile
354 * Useful for showing pages that list subscribers in reverse
355 * chronological order. Has offset & limit to make paging
358 * @param integer $subscribedId Profile ID of the subscribed
359 * @param integer $offset Offset from latest
360 * @param integer $limit Maximum number to fetch
362 * @return Subscription stream of subscriptions; use fetch() to iterate
364 static function bySubscribed($subscribedId,
366 $limit = PROFILES_PER_PAGE)
368 if ($offset + $limit > self::CACHE_WINDOW) {
369 return new ArrayWrapper(self::realBySubscribed($subscribedId,
373 $key = 'subscription:by-subscribed:'.$subscribedId;
374 $window = self::cacheGet($key);
375 if ($window === false) {
376 $window = self::realBySubscribed($subscribedId,
379 self::cacheSet($key, $window);
381 return new ArrayWrapper(array_slice($window,
387 private static function realBySubscribed($subscribedId,
391 $sub = new Subscription();
393 $sub->subscribed = $subscribedId;
395 $sub->whereAdd('subscriber != ' . $subscribedId);
397 $sub->orderBy('created DESC');
398 $sub->limit($offset, $limit);
404 while ($sub->fetch()) {
405 $subs[] = clone($sub);
412 * Flush cached subscriptions when subscription is updated
414 * Because we cache subscriptions, it's useful to flush them
417 * @param mixed $orig Original version of object
419 * @return boolean success flag.
421 function update($orig=null)
423 $result = parent::update($orig);
425 self::blow('subscription:by-subscriber:'.$this->subscriber);
426 self::blow('subscription:by-subscribed:'.$this->subscribed);