]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
Subscription::ensureStart skips AlreadyFulfilledException
[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('GNUSOCIAL')) { exit(1); }
21
22 /**
23  * Table Definition for subscription
24  */
25 class Subscription extends Managed_DataObject
26 {
27     const CACHE_WINDOW = 201;
28     const FORCE = true;
29
30     public $__table = 'subscription';                    // table name
31     public $subscriber;                      // int(4)  primary_key not_null
32     public $subscribed;                      // int(4)  primary_key not_null
33     public $jabber;                          // tinyint(1)   default_1
34     public $sms;                             // tinyint(1)   default_1
35     public $token;                           // varchar(191)   not 255 because utf8mb4 takes more space
36     public $secret;                          // varchar(191)   not 255 because utf8mb4 takes more space
37     public $uri;                             // varchar(191)   not 255 because utf8mb4 takes more space
38     public $created;                         // datetime()   not_null
39     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
40
41     public static function schemaDef()
42     {
43         return array(
44             'fields' => array(
45                 'subscriber' => array('type' => 'int', 'not null' => true, 'description' => 'profile listening'),
46                 'subscribed' => array('type' => 'int', 'not null' => true, 'description' => 'profile being listened to'),
47                 'jabber' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver jabber messages'),
48                 'sms' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver sms messages'),
49                 'token' => array('type' => 'varchar', 'length' => 191, 'description' => 'authorization token'),
50                 'secret' => array('type' => 'varchar', 'length' => 191, 'description' => 'token secret'),
51                 'uri' => array('type' => 'varchar', 'length' => 191, 'description' => 'universally unique identifier'),
52                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
53                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
54             ),
55             'primary key' => array('subscriber', 'subscribed'),
56             'unique keys' => array(
57                 'subscription_uri_key' => array('uri'),
58             ),
59             'indexes' => array(
60                 'subscription_subscriber_idx' => array('subscriber', 'created'),
61                 'subscription_subscribed_idx' => array('subscribed', 'created'),
62                 'subscription_token_idx' => array('token'),
63             ),
64         );
65     }
66
67     /**
68      * Make a new subscription
69      *
70      * @param Profile $subscriber party to receive new notices
71      * @param Profile $other      party sending notices; publisher
72      * @param bool    $force      pass Subscription::FORCE to override local subscription approval
73      *
74      * @return mixed Subscription or Subscription_queue: new subscription info
75      */
76
77     static function start(Profile $subscriber, Profile $other, $force=false)
78     {
79         if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
80             // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
81             throw new Exception(_('You have been banned from subscribing.'));
82         }
83
84         if (self::exists($subscriber, $other)) {
85             // TRANS: Exception thrown when trying to subscribe while already subscribed.
86             throw new AlreadyFulfilledException(_('Already subscribed!'));
87         }
88
89         if ($other->hasBlocked($subscriber)) {
90             // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
91             throw new Exception(_('User has blocked you.'));
92         }
93
94         if (Event::handle('StartSubscribe', array($subscriber, $other))) {
95             $otherUser = User::getKV('id', $other->id);
96             if ($otherUser instanceof User && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
97                 // Will throw an AlreadyFulfilledException if this queue item already exists.
98                 $sub = Subscription_queue::saveNew($subscriber, $other);
99                 $sub->notify();
100             } else {
101                 $sub = self::saveNew($subscriber->id, $other->id);
102                 $sub->notify();
103
104                 self::blow('user:notices_with_friends:%d', $subscriber->id);
105
106                 self::blow('subscription:by-subscriber:'.$subscriber->id);
107                 self::blow('subscription:by-subscribed:'.$other->id);
108
109                 $subscriber->blowSubscriptionCount();
110                 $other->blowSubscriberCount();
111
112                 if ($otherUser instanceof User &&
113                     $otherUser->autosubscribe &&
114                     !self::exists($other, $subscriber) &&
115                     !$subscriber->hasBlocked($other)) {
116
117                     try {
118                         self::start($other, $subscriber);
119                     } catch (AlreadyFulfilledException $e) {
120                         // This shouldn't happen due to !self::exists above
121                         common_debug('Tried to autosubscribe a user to its new subscriber.');
122                     } catch (Exception $e) {
123                         common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
124                     }
125                 }
126             }
127
128             if ($sub instanceof Subscription) { // i.e. not SubscriptionQueue
129                 Event::handle('EndSubscribe', array($subscriber, $other));
130             }
131         }
132
133         return $sub;
134     }
135
136     static function ensureStart(Profile $subscriber, Profile $other, $force=false)
137     {
138         try {
139             $sub = self::start($subscriber, $other, $force);
140         } catch (AlreadyFulfilledException $e) {
141             // Nothing to see here, move along...
142             return self::getSubscription($subscriber, $other);
143         }
144         return $sub;
145     }
146
147     /**
148      * Low-level subscription save.
149      * Outside callers should use Subscription::start()
150      */
151     protected function saveNew($subscriber_id, $other_id)
152     {
153         $sub = new Subscription();
154
155         $sub->subscriber = $subscriber_id;
156         $sub->subscribed = $other_id;
157         $sub->jabber     = 1;
158         $sub->sms        = 1;
159         $sub->created    = common_sql_now();
160         $sub->uri        = self::newURI($sub->subscriber,
161                                         $sub->subscribed,
162                                         $sub->created);
163
164         $result = $sub->insert();
165
166         if ($result===false) {
167             common_log_db_error($sub, 'INSERT', __FILE__);
168             // TRANS: Exception thrown when a subscription could not be stored on the server.
169             throw new Exception(_('Could not save subscription.'));
170         }
171
172         return $sub;
173     }
174
175     function notify()
176     {
177         // XXX: add other notifications (Jabber, SMS) here
178         // XXX: queue this and handle it offline
179         // XXX: Whatever happens, do it in Twitter-like API, too
180
181         $this->notifyEmail();
182     }
183
184     function notifyEmail()
185     {
186         $subscribedUser = User::getKV('id', $this->subscribed);
187
188         if ($subscribedUser instanceof User) {
189
190             $subscriber = Profile::getKV('id', $this->subscriber);
191
192             mail_subscribe_notify_profile($subscribedUser, $subscriber);
193         }
194     }
195
196     /**
197      * Cancel a subscription
198      *
199      */
200     static function cancel(Profile $subscriber, Profile $other)
201     {
202         if (!self::exists($subscriber, $other)) {
203             // TRANS: Exception thrown when trying to unsibscribe without a subscription.
204             throw new AlreadyFulfilledException(_('Not subscribed!'));
205         }
206
207         // Don't allow deleting self subs
208
209         if ($subscriber->id == $other->id) {
210             // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
211             throw new Exception(_('Could not delete self-subscription.'));
212         }
213
214         if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
215
216             $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
217                                                'subscribed' => $other->id));
218
219             // note we checked for existence above
220
221             assert(!empty($sub));
222
223             $result = $sub->delete();
224
225             if (!$result) {
226                 common_log_db_error($sub, 'DELETE', __FILE__);
227                 // TRANS: Exception thrown when a subscription could not be deleted on the server.
228                 throw new Exception(_('Could not delete subscription.'));
229             }
230
231             self::blow('user:notices_with_friends:%d', $subscriber->id);
232
233             self::blow('subscription:by-subscriber:'.$subscriber->id);
234             self::blow('subscription:by-subscribed:'.$other->id);
235
236             $subscriber->blowSubscriptionCount();
237             $other->blowSubscriberCount();
238
239             Event::handle('EndUnsubscribe', array($subscriber, $other));
240         }
241
242         return;
243     }
244
245     static function exists(Profile $subscriber, Profile $other)
246     {
247         try {
248             $sub = self::getSubscription($subscriber, $other);
249         } catch (NoResultException $e) {
250             return false;
251         }
252
253         return true;
254     }
255
256     static function getSubscription(Profile $subscriber, Profile $other)
257     {
258         // This is essentially a pkeyGet but we have an object to return in NoResultException
259         $sub = new Subscription();
260         $sub->subscriber = $subscriber->id;
261         $sub->subscribed = $other->id;
262         if (!$sub->find(true)) {
263             throw new NoResultException($sub);
264         }
265         return $sub;
266     }
267
268     function asActivity()
269     {
270         $subscriber = Profile::getKV('id', $this->subscriber);
271         $subscribed = Profile::getKV('id', $this->subscribed);
272
273         if (!$subscriber instanceof Profile) {
274             throw new NoProfileException($this->subscriber);
275         }
276
277         if (!$subscribed instanceof Profile) {
278             throw new NoProfileException($this->subscribed);
279         }
280
281         $act = new Activity();
282
283         $act->verb = ActivityVerb::FOLLOW;
284
285         // XXX: rationalize this with the URL
286
287         $act->id   = $this->getURI();
288
289         $act->time    = strtotime($this->created);
290         // TRANS: Activity title when subscribing to another person.
291         $act->title = _m('TITLE','Follow');
292         // TRANS: Notification given when one person starts following another.
293         // TRANS: %1$s is the subscriber, %2$s is the subscribed.
294         $act->content = sprintf(_('%1$s is now following %2$s.'),
295                                $subscriber->getBestName(),
296                                $subscribed->getBestName());
297
298         $act->actor     = $subscriber->asActivityObject();
299         $act->objects[] = $subscribed->asActivityObject();
300
301         $url = common_local_url('AtomPubShowSubscription',
302                                 array('subscriber' => $subscriber->id,
303                                       'subscribed' => $subscribed->id));
304
305         $act->selfLink = $url;
306         $act->editLink = $url;
307
308         return $act;
309     }
310
311     /**
312      * Stream of subscriptions with the same subscriber
313      *
314      * Useful for showing pages that list subscriptions in reverse
315      * chronological order. Has offset & limit to make paging
316      * easy.
317      *
318      * @param integer $profile_id   ID of the subscriber profile
319      * @param integer $offset       Offset from latest
320      * @param integer $limit        Maximum number to fetch
321      *
322      * @return Subscription stream of subscriptions; use fetch() to iterate
323      */
324     public static function bySubscriber($profile_id, $offset = 0, $limit = PROFILES_PER_PAGE)
325     {
326         // "by subscriber" means it is the list of subscribed users we want
327         $ids = self::getSubscribedIDs($profile_id, $offset, $limit);
328         return Subscription::listFind('subscribed', $ids);
329     }
330
331     /**
332      * Stream of subscriptions with the same subscriber
333      *
334      * Useful for showing pages that list subscriptions in reverse
335      * chronological order. Has offset & limit to make paging
336      * easy.
337      *
338      * @param integer $profile_id   ID of the subscribed profile
339      * @param integer $offset       Offset from latest
340      * @param integer $limit        Maximum number to fetch
341      *
342      * @return Subscription stream of subscriptions; use fetch() to iterate
343      */
344     public static function bySubscribed($profile_id, $offset = 0, $limit = PROFILES_PER_PAGE)
345     {
346         // "by subscribed" means it is the list of subscribers we want
347         $ids = self::getSubscriberIDs($profile_id, $offset, $limit);
348         return Subscription::listFind('subscriber', $ids);
349     }
350
351
352     // The following are helper functions to the subscription lists,
353     // notably the public ones get used in places such as Profile
354     public static function getSubscribedIDs($profile_id, $offset, $limit) {
355         return self::getSubscriptionIDs('subscribed', $profile_id, $offset, $limit);
356     }
357
358     public static function getSubscriberIDs($profile_id, $offset, $limit) {
359         return self::getSubscriptionIDs('subscriber', $profile_id, $offset, $limit);
360     }
361
362     private static function getSubscriptionIDs($get_type, $profile_id, $offset, $limit)
363     {
364         switch ($get_type) {
365         case 'subscribed':
366             $by_type  = 'subscriber';
367             break;
368         case 'subscriber':
369             $by_type  = 'subscribed';
370             break;
371         default:
372             throw new Exception('Bad type argument to getSubscriptionIDs');
373         }
374
375         $cacheKey = 'subscription:by-'.$by_type.':'.$profile_id;
376
377         $queryoffset = $offset;
378         $querylimit = $limit;
379
380         if ($offset + $limit <= self::CACHE_WINDOW) {
381             // Oh, it seems it should be cached
382             $ids = self::cacheGet($cacheKey);
383             if (is_array($ids)) {
384                 return array_slice($ids, $offset, $limit);
385             }
386             // Being here indicates we didn't find anything cached
387             // so we'll have to fill it up simultaneously
388             $queryoffset = 0;
389             $querylimit  = self::CACHE_WINDOW;
390         }
391
392         $sub = new Subscription();
393         $sub->$by_type = $profile_id;
394         $sub->selectAdd($get_type);
395         $sub->whereAdd("{$get_type} != {$profile_id}");
396         $sub->orderBy('created DESC');
397         $sub->limit($queryoffset, $querylimit);
398
399         if (!$sub->find()) {
400             return array();
401         }
402
403         $ids = $sub->fetchAll($get_type);
404
405         // If we're simultaneously filling up cache, remember to slice
406         if ($queryoffset === 0 && $querylimit === self::CACHE_WINDOW) {
407             self::cacheSet($cacheKey, $ids);
408             return array_slice($ids, $offset, $limit);
409         }
410
411         return $ids;
412     }
413
414     /**
415      * Flush cached subscriptions when subscription is updated
416      *
417      * Because we cache subscriptions, it's useful to flush them
418      * here.
419      *
420      * @param mixed $dataObject Original version of object
421      *
422      * @return boolean success flag.
423      */
424     function update($dataObject=false)
425     {
426         self::blow('subscription:by-subscriber:'.$this->subscriber);
427         self::blow('subscription:by-subscribed:'.$this->subscribed);
428
429         return parent::update($dataObject);
430     }
431
432     function getURI()
433     {
434         if (!empty($this->uri)) {
435             return $this->uri;
436         } else {
437             return self::newURI($this->subscriber, $this->subscribed, $this->created);
438         }
439     }
440
441     static function newURI($subscriber_id, $subscribed_id, $created)
442     {
443         return TagURI::mint('follow:%d:%d:%s',
444                             $subscriber_id,
445                             $subscribed_id,
446                             common_date_iso8601($created));
447     }
448 }