]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
Our URLs are permanent redirects, mind you!
[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             // unless subscription is forced, the user policy for subscription approvals is tested
96             if (!$force && $other->requiresSubscriptionApproval($subscriber)) {
97                 try {
98                     $sub = Subscription_queue::saveNew($subscriber, $other);
99                     $sub->notify();
100                 } catch (AlreadyFulfilledException $e) {
101                     $sub = Subscription_queue::getSubQueue($subscriber, $other);
102                 }
103             } else {
104                 $otherUser = User::getKV('id', $other->id);
105                 $sub = self::saveNew($subscriber, $other);
106                 $sub->notify();
107
108                 self::blow('user:notices_with_friends:%d', $subscriber->id);
109
110                 self::blow('subscription:by-subscriber:'.$subscriber->id);
111                 self::blow('subscription:by-subscribed:'.$other->id);
112
113                 $subscriber->blowSubscriptionCount();
114                 $other->blowSubscriberCount();
115
116                 if ($otherUser instanceof User &&
117                     $otherUser->autosubscribe &&
118                     !self::exists($other, $subscriber) &&
119                     !$subscriber->hasBlocked($other)) {
120
121                     try {
122                         self::start($other, $subscriber);
123                     } catch (AlreadyFulfilledException $e) {
124                         // This shouldn't happen due to !self::exists above
125                         common_debug('Tried to autosubscribe a user to its new subscriber.');
126                     } catch (Exception $e) {
127                         common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
128                     }
129                 }
130             }
131
132             if ($sub instanceof Subscription) { // i.e. not Subscription_queue
133                 Event::handle('EndSubscribe', array($subscriber, $other));
134             }
135         }
136
137         return $sub;
138     }
139
140     static function ensureStart(Profile $subscriber, Profile $other, $force=false)
141     {
142         try {
143             $sub = self::start($subscriber, $other, $force);
144         } catch (AlreadyFulfilledException $e) {
145             return self::getSubscription($subscriber, $other);
146         }
147         return $sub;
148     }
149
150     /**
151      * Low-level subscription save.
152      * Outside callers should use Subscription::start()
153      */
154     protected static function saveNew(Profile $subscriber, Profile $other)
155     {
156         $sub = new Subscription();
157
158         $sub->subscriber = $subscriber->getID();
159         $sub->subscribed = $other->getID();
160         $sub->jabber     = 1;
161         $sub->sms        = 1;
162         $sub->created    = common_sql_now();
163         $sub->uri        = self::newUri($subscriber,
164                                         $other,
165                                         $sub->created);
166
167         $result = $sub->insert();
168
169         if ($result===false) {
170             common_log_db_error($sub, 'INSERT', __FILE__);
171             // TRANS: Exception thrown when a subscription could not be stored on the server.
172             throw new Exception(_('Could not save subscription.'));
173         }
174
175         return $sub;
176     }
177
178     function notify()
179     {
180         // XXX: add other notifications (Jabber, SMS) here
181         // XXX: queue this and handle it offline
182         // XXX: Whatever happens, do it in Twitter-like API, too
183
184         $this->notifyEmail();
185     }
186
187     function notifyEmail()
188     {
189         $subscribedUser = User::getKV('id', $this->subscribed);
190
191         if ($subscribedUser instanceof User) {
192
193             $subscriber = Profile::getKV('id', $this->subscriber);
194
195             mail_subscribe_notify_profile($subscribedUser, $subscriber);
196         }
197     }
198
199     /**
200      * Cancel a subscription
201      *
202      */
203     static function cancel(Profile $subscriber, Profile $other)
204     {
205         if (!self::exists($subscriber, $other)) {
206             // TRANS: Exception thrown when trying to unsibscribe without a subscription.
207             throw new AlreadyFulfilledException(_('Not subscribed!'));
208         }
209
210         // Don't allow deleting self subs
211
212         if ($subscriber->id == $other->id) {
213             // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
214             throw new Exception(_('Could not delete self-subscription.'));
215         }
216
217         if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
218
219             $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
220                                                'subscribed' => $other->id));
221
222             // note we checked for existence above
223
224             assert(!empty($sub));
225
226             $result = $sub->delete();
227
228             if (!$result) {
229                 common_log_db_error($sub, 'DELETE', __FILE__);
230                 // TRANS: Exception thrown when a subscription could not be deleted on the server.
231                 throw new Exception(_('Could not delete subscription.'));
232             }
233
234             self::blow('user:notices_with_friends:%d', $subscriber->id);
235
236             self::blow('subscription:by-subscriber:'.$subscriber->id);
237             self::blow('subscription:by-subscribed:'.$other->id);
238
239             $subscriber->blowSubscriptionCount();
240             $other->blowSubscriberCount();
241
242             Event::handle('EndUnsubscribe', array($subscriber, $other));
243         }
244
245         return;
246     }
247
248     static function exists(Profile $subscriber, Profile $other)
249     {
250         try {
251             $sub = self::getSubscription($subscriber, $other);
252         } catch (NoResultException $e) {
253             return false;
254         }
255
256         return true;
257     }
258
259     static function getSubscription(Profile $subscriber, Profile $other)
260     {
261         // This is essentially a pkeyGet but we have an object to return in NoResultException
262         $sub = new Subscription();
263         $sub->subscriber = $subscriber->id;
264         $sub->subscribed = $other->id;
265         if (!$sub->find(true)) {
266             throw new NoResultException($sub);
267         }
268         return $sub;
269     }
270
271     public function getSubscriber()
272     {
273         return Profile::getByID($this->subscriber);
274     }
275
276     public function getSubscribed()
277     {
278         return Profile::getByID($this->subscribed);
279     }
280
281     function asActivity()
282     {
283         $subscriber = $this->getSubscriber();
284         $subscribed = $this->getSubscribed();
285
286         $act = new Activity();
287
288         $act->verb = ActivityVerb::FOLLOW;
289
290         // XXX: rationalize this with the URL
291
292         $act->id   = $this->getUri();
293
294         $act->time    = strtotime($this->created);
295         // TRANS: Activity title when subscribing to another person.
296         $act->title = _m('TITLE','Follow');
297         // TRANS: Notification given when one person starts following another.
298         // TRANS: %1$s is the subscriber, %2$s is the subscribed.
299         $act->content = sprintf(_('%1$s is now following %2$s.'),
300                                $subscriber->getBestName(),
301                                $subscribed->getBestName());
302
303         $act->actor     = $subscriber->asActivityObject();
304         $act->objects[] = $subscribed->asActivityObject();
305
306         $url = common_local_url('AtomPubShowSubscription',
307                                 array('subscriber' => $subscriber->id,
308                                       'subscribed' => $subscribed->id));
309
310         $act->selfLink = $url;
311         $act->editLink = $url;
312
313         return $act;
314     }
315
316     /**
317      * Stream of subscriptions with the same subscriber
318      *
319      * Useful for showing pages that list subscriptions in reverse
320      * chronological order. Has offset & limit to make paging
321      * easy.
322      *
323      * @param integer $profile_id   ID of the subscriber profile
324      * @param integer $offset       Offset from latest
325      * @param integer $limit        Maximum number to fetch
326      *
327      * @return Subscription stream of subscriptions; use fetch() to iterate
328      */
329     public static function bySubscriber($profile_id, $offset = 0, $limit = PROFILES_PER_PAGE)
330     {
331         // "by subscriber" means it is the list of subscribed users we want
332         $ids = self::getSubscribedIDs($profile_id, $offset, $limit);
333         return Subscription::listFind('subscribed', $ids);
334     }
335
336     /**
337      * Stream of subscriptions with the same subscriber
338      *
339      * Useful for showing pages that list subscriptions in reverse
340      * chronological order. Has offset & limit to make paging
341      * easy.
342      *
343      * @param integer $profile_id   ID of the subscribed profile
344      * @param integer $offset       Offset from latest
345      * @param integer $limit        Maximum number to fetch
346      *
347      * @return Subscription stream of subscriptions; use fetch() to iterate
348      */
349     public static function bySubscribed($profile_id, $offset = 0, $limit = PROFILES_PER_PAGE)
350     {
351         // "by subscribed" means it is the list of subscribers we want
352         $ids = self::getSubscriberIDs($profile_id, $offset, $limit);
353         return Subscription::listFind('subscriber', $ids);
354     }
355
356
357     // The following are helper functions to the subscription lists,
358     // notably the public ones get used in places such as Profile
359     public static function getSubscribedIDs($profile_id, $offset, $limit) {
360         return self::getSubscriptionIDs('subscribed', $profile_id, $offset, $limit);
361     }
362
363     public static function getSubscriberIDs($profile_id, $offset, $limit) {
364         return self::getSubscriptionIDs('subscriber', $profile_id, $offset, $limit);
365     }
366
367     private static function getSubscriptionIDs($get_type, $profile_id, $offset, $limit)
368     {
369         switch ($get_type) {
370         case 'subscribed':
371             $by_type  = 'subscriber';
372             break;
373         case 'subscriber':
374             $by_type  = 'subscribed';
375             break;
376         default:
377             throw new Exception('Bad type argument to getSubscriptionIDs');
378         }
379
380         $cacheKey = 'subscription:by-'.$by_type.':'.$profile_id;
381
382         $queryoffset = $offset;
383         $querylimit = $limit;
384
385         if ($offset + $limit <= self::CACHE_WINDOW) {
386             // Oh, it seems it should be cached
387             $ids = self::cacheGet($cacheKey);
388             if (is_array($ids)) {
389                 return array_slice($ids, $offset, $limit);
390             }
391             // Being here indicates we didn't find anything cached
392             // so we'll have to fill it up simultaneously
393             $queryoffset = 0;
394             $querylimit  = self::CACHE_WINDOW;
395         }
396
397         $sub = new Subscription();
398         $sub->$by_type = $profile_id;
399         $sub->selectAdd($get_type);
400         $sub->whereAdd("{$get_type} != {$profile_id}");
401         $sub->orderBy('created DESC');
402         $sub->limit($queryoffset, $querylimit);
403
404         if (!$sub->find()) {
405             return array();
406         }
407
408         $ids = $sub->fetchAll($get_type);
409
410         // If we're simultaneously filling up cache, remember to slice
411         if ($queryoffset === 0 && $querylimit === self::CACHE_WINDOW) {
412             self::cacheSet($cacheKey, $ids);
413             return array_slice($ids, $offset, $limit);
414         }
415
416         return $ids;
417     }
418
419     /**
420      * Flush cached subscriptions when subscription is updated
421      *
422      * Because we cache subscriptions, it's useful to flush them
423      * here.
424      *
425      * @param mixed $dataObject Original version of object
426      *
427      * @return boolean success flag.
428      */
429     function update($dataObject=false)
430     {
431         self::blow('subscription:by-subscriber:'.$this->subscriber);
432         self::blow('subscription:by-subscribed:'.$this->subscribed);
433
434         return parent::update($dataObject);
435     }
436
437     public function getUri()
438     {
439         return $this->uri ?: self::newUri($this->getSubscriber(), $this->getSubscribed(), $this->created);
440     }
441 }