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