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