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 $act->id = TagURI::mint('follow:%d:%d:%s',
259 common_date_iso8601($this->created));
261 $act->time = strtotime($this->created);
262 // TRANS: Activity tile when subscribing to another person.
263 $act->title = _("Follow");
264 // TRANS: Notification given when one person starts following another.
265 // TRANS: %1$s is the subscriber, %2$s is the subscribed.
266 $act->content = sprintf(_('%1$s is now following %2$s.'),
267 $subscriber->getBestName(),
268 $subscribed->getBestName());
270 $act->actor = ActivityObject::fromProfile($subscriber);
271 $act->objects[] = ActivityObject::fromProfile($subscribed);
277 * Stream of subscriptions with the same subscriber
279 * Useful for showing pages that list subscriptions in reverse
280 * chronological order. Has offset & limit to make paging
283 * @param integer $subscriberId Profile ID of the subscriber
284 * @param integer $offset Offset from latest
285 * @param integer $limit Maximum number to fetch
287 * @return Subscription stream of subscriptions; use fetch() to iterate
290 static function bySubscriber($subscriberId,
292 $limit = PROFILES_PER_PAGE)
294 if ($offset + $limit > self::CACHE_WINDOW) {
295 return new ArrayWrapper(self::realBySubscriber($subscriberId,
299 $key = 'subscription:by-subscriber:'.$subscriberId;
300 $window = self::cacheGet($key);
301 if ($window === false) {
302 $window = self::realBySubscriber($subscriberId,
305 self::cacheSet($key, $window);
307 return new ArrayWrapper(array_slice($window,
313 private static function realBySubscriber($subscriberId,
317 $sub = new Subscription();
319 $sub->subscriber = $subscriberId;
321 $sub->whereAdd('subscribed != ' . $subscriberId);
323 $sub->orderBy('created DESC');
324 $sub->limit($offset, $limit);
330 while ($sub->fetch()) {
331 $subs[] = clone($sub);
338 * Stream of subscriptions with the same subscribed profile
340 * Useful for showing pages that list subscribers in reverse
341 * chronological order. Has offset & limit to make paging
344 * @param integer $subscribedId Profile ID of the subscribed
345 * @param integer $offset Offset from latest
346 * @param integer $limit Maximum number to fetch
348 * @return Subscription stream of subscriptions; use fetch() to iterate
351 static function bySubscribed($subscribedId,
353 $limit = PROFILES_PER_PAGE)
355 if ($offset + $limit > self::CACHE_WINDOW) {
356 return new ArrayWrapper(self::realBySubscribed($subscribedId,
360 $key = 'subscription:by-subscribed:'.$subscribedId;
361 $window = self::cacheGet($key);
362 if ($window === false) {
363 $window = self::realBySubscribed($subscribedId,
366 self::cacheSet($key, $window);
368 return new ArrayWrapper(array_slice($window,
374 private static function realBySubscribed($subscribedId,
378 $sub = new Subscription();
380 $sub->subscribed = $subscribedId;
382 $sub->whereAdd('subscriber != ' . $subscribedId);
384 $sub->orderBy('created DESC');
385 $sub->limit($offset, $limit);
391 while ($sub->fetch()) {
392 $subs[] = clone($sub);
399 * Flush cached subscriptions when subscription is updated
401 * Because we cache subscriptions, it's useful to flush them
404 * @param mixed $orig Original version of object
406 * @return boolean success flag.
409 function update($orig=null)
411 $result = parent::update($orig);
413 self::blow('subscription:by-subscriber:'.$this->subscriber);
414 self::blow('subscription:by-subscribed:'.$this->subscribed);