]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
Merge branch '0.9.x' of gitorious.org:statusnet/mainline 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         $act->id   = TagURI::mint('follow:%d:%d:%s',
257                                   $subscriber->id,
258                                   $subscribed->id,
259                                   common_date_iso8601($this->created));
260
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());
269
270         $act->actor     = ActivityObject::fromProfile($subscriber);
271         $act->objects[] = ActivityObject::fromProfile($subscribed);
272
273         return $act;
274     }
275
276     /**
277      * Stream of subscriptions with the same subscriber
278      *
279      * Useful for showing pages that list subscriptions in reverse
280      * chronological order. Has offset & limit to make paging
281      * easy.
282      *
283      * @param integer $subscriberId Profile ID of the subscriber
284      * @param integer $offset       Offset from latest
285      * @param integer $limit        Maximum number to fetch
286      *
287      * @return Subscription stream of subscriptions; use fetch() to iterate
288      */
289
290     static function bySubscriber($subscriberId,
291                                  $offset = 0,
292                                  $limit = PROFILES_PER_PAGE)
293     {
294         if ($offset + $limit > self::CACHE_WINDOW) {
295             return new ArrayWrapper(self::realBySubscriber($subscriberId,
296                                                            $offset,
297                                                            $limit));
298         } else {
299             $key = 'subscription:by-subscriber:'.$subscriberId;
300             $window = self::cacheGet($key);
301             if ($window === false) {
302                 $window = self::realBySubscriber($subscriberId,
303                                                  0,
304                                                  self::CACHE_WINDOW);
305                 self::cacheSet($key, $window);
306             }
307             return new ArrayWrapper(array_slice($window,
308                                                 $offset,
309                                                 $limit));
310         }
311     }
312
313     private static function realBySubscriber($subscriberId,
314                                              $offset,
315                                              $limit)
316     {
317         $sub = new Subscription();
318
319         $sub->subscriber = $subscriberId;
320
321         $sub->whereAdd('subscribed != ' . $subscriberId);
322
323         $sub->orderBy('created DESC');
324         $sub->limit($offset, $limit);
325
326         $sub->find();
327
328         $subs = array();
329
330         while ($sub->fetch()) {
331             $subs[] = clone($sub);
332         }
333
334         return $subs;
335     }
336
337     /**
338      * Stream of subscriptions with the same subscribed profile
339      *
340      * Useful for showing pages that list subscribers in reverse
341      * chronological order. Has offset & limit to make paging
342      * easy.
343      *
344      * @param integer $subscribedId Profile ID of the subscribed
345      * @param integer $offset       Offset from latest
346      * @param integer $limit        Maximum number to fetch
347      *
348      * @return Subscription stream of subscriptions; use fetch() to iterate
349      */
350
351     static function bySubscribed($subscribedId,
352                                  $offset = 0,
353                                  $limit = PROFILES_PER_PAGE)
354     {
355         if ($offset + $limit > self::CACHE_WINDOW) {
356             return new ArrayWrapper(self::realBySubscribed($subscribedId,
357                                                            $offset,
358                                                            $limit));
359         } else {
360             $key = 'subscription:by-subscribed:'.$subscribedId;
361             $window = self::cacheGet($key);
362             if ($window === false) {
363                 $window = self::realBySubscribed($subscribedId,
364                                                  0,
365                                                  self::CACHE_WINDOW);
366                 self::cacheSet($key, $window);
367             }
368             return new ArrayWrapper(array_slice($window,
369                                                 $offset,
370                                                 $limit));
371         }
372     }
373
374     private static function realBySubscribed($subscribedId,
375                                              $offset,
376                                              $limit)
377     {
378         $sub = new Subscription();
379
380         $sub->subscribed = $subscribedId;
381
382         $sub->whereAdd('subscriber != ' . $subscribedId);
383
384         $sub->orderBy('created DESC');
385         $sub->limit($offset, $limit);
386
387         $sub->find();
388
389         $subs = array();
390
391         while ($sub->fetch()) {
392             $subs[] = clone($sub);
393         }
394
395         return $subs;
396     }
397
398     /**
399      * Flush cached subscriptions when subscription is updated
400      *
401      * Because we cache subscriptions, it's useful to flush them
402      * here.
403      *
404      * @param mixed $orig Original version of object
405      *
406      * @return boolean success flag.
407      */
408
409     function update($orig=null)
410     {
411         $result = parent::update($orig);
412
413         self::blow('subscription:by-subscriber:'.$this->subscriber);
414         self::blow('subscription:by-subscribed:'.$this->subscribed);
415
416         return $result;
417     }
418 }