]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
Merge remote branch 'evan/1.0.x' into 1.0.x
[quix0rs-gnu-social.git] / classes / Subscription.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2008, 2009, StatusNet, Inc.
5  *
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.
10  *
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.
15  *
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/>.
18  */
19
20 if (!defined('STATUSNET') && !defined('LACONICA')) { exit(1); }
21
22 /**
23  * Table Definition for subscription
24  */
25 require_once INSTALLDIR.'/classes/Memcached_DataObject.php';
26
27 class Subscription extends Memcached_DataObject
28 {
29     const CACHE_WINDOW = 201;
30     const FORCE = true;
31
32     ###START_AUTOCODE
33     /* the code below is auto generated do not remove the above tag */
34
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
44
45     /* Static get */
46     function staticGet($k,$v=null)
47     { return Memcached_DataObject::staticGet('Subscription',$k,$v); }
48
49     /* the code above is auto generated do not remove the tag below */
50     ###END_AUTOCODE
51
52     function pkeyGet($kv)
53     {
54         return Memcached_DataObject::pkeyGet('Subscription', $kv);
55     }
56
57     /**
58      * Make a new subscription
59      *
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
63      *
64      * @return mixed Subscription or Subscription_queue: new subscription info
65      */
66
67     static function start($subscriber, $other, $force=false)
68     {
69         // @fixme should we enforce this as profiles in callers instead?
70         if ($subscriber instanceof User) {
71             $subscriber = $subscriber->getProfile();
72         }
73         if ($other instanceof User) {
74             $other = $other->getProfile();
75         }
76
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.'));
80         }
81
82         if (self::exists($subscriber, $other)) {
83             // TRANS: Exception thrown when trying to subscribe while already subscribed.
84             throw new Exception(_('Already subscribed!'));
85         }
86
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.'));
90         }
91
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);
96                 $sub->notify();
97             } else {
98                 $sub = self::saveNew($subscriber->id, $other->id);
99                 $sub->notify();
100
101                 self::blow('user:notices_with_friends:%d', $subscriber->id);
102
103                 self::blow('subscription:by-subscriber:'.$subscriber->id);
104                 self::blow('subscription:by-subscribed:'.$other->id);
105
106                 $subscriber->blowSubscriptionCount();
107                 $other->blowSubscriberCount();
108
109                 if (!empty($otherUser) &&
110                     $otherUser->autosubscribe &&
111                     !self::exists($other, $subscriber) &&
112                     !$subscriber->hasBlocked($other)) {
113
114                     try {
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()}");
118                     }
119                 }
120             }
121
122             Event::handle('EndSubscribe', array($subscriber, $other));
123         }
124
125         return $sub;
126     }
127
128     /**
129      * Low-level subscription save.
130      * Outside callers should use Subscription::start()
131      */
132     protected function saveNew($subscriber_id, $other_id)
133     {
134         $sub = new Subscription();
135
136         $sub->subscriber = $subscriber_id;
137         $sub->subscribed = $other_id;
138         $sub->jabber     = 1;
139         $sub->sms        = 1;
140         $sub->created    = common_sql_now();
141
142         $result = $sub->insert();
143
144         if (!$result) {
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.'));
148         }
149
150         return $sub;
151     }
152
153     function notify()
154     {
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
158
159         $this->notifyEmail();
160     }
161
162     function notifyEmail()
163     {
164         $subscribedUser = User::staticGet('id', $this->subscribed);
165
166         if (!empty($subscribedUser)) {
167
168             $subscriber = Profile::staticGet('id', $this->subscriber);
169
170             mail_subscribe_notify_profile($subscribedUser, $subscriber);
171         }
172     }
173
174     /**
175      * Cancel a subscription
176      *
177      */
178     function cancel($subscriber, $other)
179     {
180         if (!self::exists($subscriber, $other)) {
181             // TRANS: Exception thrown when trying to unsibscribe without a subscription.
182             throw new Exception(_('Not subscribed!'));
183         }
184
185         // Don't allow deleting self subs
186
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.'));
190         }
191
192         if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
193
194             $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
195                                                'subscribed' => $other->id));
196
197             // note we checked for existence above
198
199             assert(!empty($sub));
200
201             // @todo: move this block to EndSubscribe handler for
202             // OMB plugin when it exists.
203
204             if (!empty($sub->token)) {
205
206                 $token = new Token();
207
208                 $token->tok    = $sub->token;
209
210                 if ($token->find(true)) {
211
212                     $result = $token->delete();
213
214                     if (!$result) {
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.'));
218                     }
219                 } else {
220                     common_log(LOG_ERR, "Couldn't find credentials with token {$token->tok}");
221                 }
222             }
223
224             $result = $sub->delete();
225
226             if (!$result) {
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.'));
230             }
231
232             self::blow('user:notices_with_friends:%d', $subscriber->id);
233
234             self::blow('subscription:by-subscriber:'.$subscriber->id);
235             self::blow('subscription:by-subscribed:'.$other->id);
236
237             $subscriber->blowSubscriptionCount();
238             $other->blowSubscriberCount();
239
240             Event::handle('EndUnsubscribe', array($subscriber, $other));
241         }
242
243         return;
244     }
245
246     function exists($subscriber, $other)
247     {
248         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
249                                            'subscribed' => $other->id));
250         return (empty($sub)) ? false : true;
251     }
252
253     function asActivity()
254     {
255         $subscriber = Profile::staticGet('id', $this->subscriber);
256         $subscribed = Profile::staticGet('id', $this->subscribed);
257
258         $act = new Activity();
259
260         $act->verb = ActivityVerb::FOLLOW;
261
262         // XXX: rationalize this with the URL
263
264         $act->id   = TagURI::mint('follow:%d:%d:%s',
265                                   $subscriber->id,
266                                   $subscribed->id,
267                                   common_date_iso8601($this->created));
268
269         $act->time    = strtotime($this->created);
270         // TRANS: Activity tile when subscribing to another person.
271         $act->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());
277
278         $act->actor     = ActivityObject::fromProfile($subscriber);
279         $act->objects[] = ActivityObject::fromProfile($subscribed);
280
281         $url = common_local_url('AtomPubShowSubscription',
282                                 array('subscriber' => $subscriber->id,
283                                       'subscribed' => $subscribed->id));
284
285         $act->selfLink = $url;
286         $act->editLink = $url;
287
288         return $act;
289     }
290
291     /**
292      * Stream of subscriptions with the same subscriber
293      *
294      * Useful for showing pages that list subscriptions in reverse
295      * chronological order. Has offset & limit to make paging
296      * easy.
297      *
298      * @param integer $subscriberId Profile ID of the subscriber
299      * @param integer $offset       Offset from latest
300      * @param integer $limit        Maximum number to fetch
301      *
302      * @return Subscription stream of subscriptions; use fetch() to iterate
303      */
304
305     static function bySubscriber($subscriberId,
306                                  $offset = 0,
307                                  $limit = PROFILES_PER_PAGE)
308     {
309         if ($offset + $limit > self::CACHE_WINDOW) {
310             return new ArrayWrapper(self::realBySubscriber($subscriberId,
311                                                            $offset,
312                                                            $limit));
313         } else {
314             $key = 'subscription:by-subscriber:'.$subscriberId;
315             $window = self::cacheGet($key);
316             if ($window === false) {
317                 $window = self::realBySubscriber($subscriberId,
318                                                  0,
319                                                  self::CACHE_WINDOW);
320                 self::cacheSet($key, $window);
321             }
322             return new ArrayWrapper(array_slice($window,
323                                                 $offset,
324                                                 $limit));
325         }
326     }
327
328     private static function realBySubscriber($subscriberId,
329                                              $offset,
330                                              $limit)
331     {
332         $sub = new Subscription();
333
334         $sub->subscriber = $subscriberId;
335
336         $sub->whereAdd('subscribed != ' . $subscriberId);
337
338         $sub->orderBy('created DESC');
339         $sub->limit($offset, $limit);
340
341         $sub->find();
342
343         $subs = array();
344
345         while ($sub->fetch()) {
346             $subs[] = clone($sub);
347         }
348
349         return $subs;
350     }
351
352     /**
353      * Stream of subscriptions with the same subscribed profile
354      *
355      * Useful for showing pages that list subscribers in reverse
356      * chronological order. Has offset & limit to make paging
357      * easy.
358      *
359      * @param integer $subscribedId Profile ID of the subscribed
360      * @param integer $offset       Offset from latest
361      * @param integer $limit        Maximum number to fetch
362      *
363      * @return Subscription stream of subscriptions; use fetch() to iterate
364      */
365
366     static function bySubscribed($subscribedId,
367                                  $offset = 0,
368                                  $limit = PROFILES_PER_PAGE)
369     {
370         if ($offset + $limit > self::CACHE_WINDOW) {
371             return new ArrayWrapper(self::realBySubscribed($subscribedId,
372                                                            $offset,
373                                                            $limit));
374         } else {
375             $key = 'subscription:by-subscribed:'.$subscribedId;
376             $window = self::cacheGet($key);
377             if ($window === false) {
378                 $window = self::realBySubscribed($subscribedId,
379                                                  0,
380                                                  self::CACHE_WINDOW);
381                 self::cacheSet($key, $window);
382             }
383             return new ArrayWrapper(array_slice($window,
384                                                 $offset,
385                                                 $limit));
386         }
387     }
388
389     private static function realBySubscribed($subscribedId,
390                                              $offset,
391                                              $limit)
392     {
393         $sub = new Subscription();
394
395         $sub->subscribed = $subscribedId;
396
397         $sub->whereAdd('subscriber != ' . $subscribedId);
398
399         $sub->orderBy('created DESC');
400         $sub->limit($offset, $limit);
401
402         $sub->find();
403
404         $subs = array();
405
406         while ($sub->fetch()) {
407             $subs[] = clone($sub);
408         }
409
410         return $subs;
411     }
412
413     /**
414      * Flush cached subscriptions when subscription is updated
415      *
416      * Because we cache subscriptions, it's useful to flush them
417      * here.
418      *
419      * @param mixed $orig Original version of object
420      *
421      * @return boolean success flag.
422      */
423
424     function update($orig=null)
425     {
426         $result = parent::update($orig);
427
428         self::blow('subscription:by-subscriber:'.$this->subscriber);
429         self::blow('subscription:by-subscribed:'.$this->subscribed);
430
431         return $result;
432     }
433 }