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