]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
Tidying up getUser calls to profiles and some events
[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 Managed_DataObject
28 {
29     const CACHE_WINDOW = 201;
30     const FORCE = true;
31
32     ###START_AUTOCODE
33     /* the code below is auto generated do not remove the above tag */
34
35     public $__table = 'subscription';                    // table name
36     public $subscriber;                      // int(4)  primary_key not_null
37     public $subscribed;                      // int(4)  primary_key not_null
38     public $jabber;                          // tinyint(1)   default_1
39     public $sms;                             // tinyint(1)   default_1
40     public $token;                           // varchar(255)
41     public $secret;                          // varchar(255)
42     public $uri;                             // varchar(255)
43     public $created;                         // datetime()   not_null
44     public $modified;                        // timestamp()   not_null default_CURRENT_TIMESTAMP
45
46     public static function schemaDef()
47     {
48         return array(
49             'fields' => array(
50                 'subscriber' => array('type' => 'int', 'not null' => true, 'description' => 'profile listening'),
51                 'subscribed' => array('type' => 'int', 'not null' => true, 'description' => 'profile being listened to'),
52                 'jabber' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver jabber messages'),
53                 'sms' => array('type' => 'int', 'size' => 'tiny', 'default' => 1, 'description' => 'deliver sms messages'),
54                 'token' => array('type' => 'varchar', 'length' => 255, 'description' => 'authorization token'),
55                 'secret' => array('type' => 'varchar', 'length' => 255, 'description' => 'token secret'),
56                 'uri' => array('type' => 'varchar', 'length' => 255, 'description' => 'universally unique identifier'),
57                 'created' => array('type' => 'datetime', 'not null' => true, 'description' => 'date this record was created'),
58                 'modified' => array('type' => 'timestamp', 'not null' => true, 'description' => 'date this record was modified'),
59             ),
60             'primary key' => array('subscriber', 'subscribed'),
61             'unique keys' => array(
62                 'subscription_uri_key' => array('uri'),
63             ),
64             'indexes' => array(
65                 'subscription_subscriber_idx' => array('subscriber', 'created'),
66                 'subscription_subscribed_idx' => array('subscribed', 'created'),
67                 'subscription_token_idx' => array('token'),
68             ),
69         );
70     }
71
72     /**
73      * Make a new subscription
74      *
75      * @param Profile $subscriber party to receive new notices
76      * @param Profile $other      party sending notices; publisher
77      * @param bool    $force      pass Subscription::FORCE to override local subscription approval
78      *
79      * @return mixed Subscription or Subscription_queue: new subscription info
80      */
81
82     static function start(Profile $subscriber, Profile $other, $force=false)
83     {
84         if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
85             // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
86             throw new Exception(_('You have been banned from subscribing.'));
87         }
88
89         if (self::exists($subscriber, $other)) {
90             // TRANS: Exception thrown when trying to subscribe while already subscribed.
91             throw new Exception(_('Already subscribed!'));
92         }
93
94         if ($other->hasBlocked($subscriber)) {
95             // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
96             throw new Exception(_('User has blocked you.'));
97         }
98
99         if (Event::handle('StartSubscribe', array($subscriber, $other))) {
100             $otherUser = User::getKV('id', $other->id);
101             if ($otherUser && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
102                 $sub = Subscription_queue::saveNew($subscriber, $other);
103                 $sub->notify();
104             } else {
105                 $sub = self::saveNew($subscriber->id, $other->id);
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 (!empty($otherUser) &&
117                     $otherUser->autosubscribe &&
118                     !self::exists($other, $subscriber) &&
119                     !$subscriber->hasBlocked($other)) {
120
121                     try {
122                         self::start($other, $subscriber);
123                     } catch (Exception $e) {
124                         common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
125                     }
126                 }
127             }
128
129             Event::handle('EndSubscribe', array($subscriber, $other));
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) {
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 (!empty($subscribedUser)) {
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     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 Exception(_('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     function exists($subscriber, $other)
234     {
235         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
236                                            'subscribed' => $other->id));
237         return (empty($sub)) ? false : true;
238     }
239
240     function asActivity()
241     {
242         $subscriber = Profile::getKV('id', $this->subscriber);
243         $subscribed = Profile::getKV('id', $this->subscribed);
244
245         if (empty($subscriber)) {
246             throw new Exception(sprintf(_('No profile for the subscriber: %d'), $this->subscriber));
247         }
248
249         if (empty($subscribed)) {
250             throw new Exception(sprintf(_('No profile for the subscribed: %d'), $this->subscribed));
251         }
252
253         $act = new Activity();
254
255         $act->verb = ActivityVerb::FOLLOW;
256
257         // XXX: rationalize this with the URL
258
259         $act->id   = $this->getURI();
260
261         $act->time    = strtotime($this->created);
262         // TRANS: Activity title when subscribing to another person.
263         $act->title = _m('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         $url = common_local_url('AtomPubShowSubscription',
274                                 array('subscriber' => $subscriber->id,
275                                       'subscribed' => $subscribed->id));
276
277         $act->selfLink = $url;
278         $act->editLink = $url;
279
280         return $act;
281     }
282
283     /**
284      * Stream of subscriptions with the same subscriber
285      *
286      * Useful for showing pages that list subscriptions in reverse
287      * chronological order. Has offset & limit to make paging
288      * easy.
289      *
290      * @param integer $subscriberId Profile ID of the subscriber
291      * @param integer $offset       Offset from latest
292      * @param integer $limit        Maximum number to fetch
293      *
294      * @return Subscription stream of subscriptions; use fetch() to iterate
295      */
296     static function bySubscriber($subscriberId,
297                                  $offset = 0,
298                                  $limit = PROFILES_PER_PAGE)
299     {
300         if ($offset + $limit > self::CACHE_WINDOW) {
301             return new ArrayWrapper(self::realBySubscriber($subscriberId,
302                                                            $offset,
303                                                            $limit));
304         } else {
305             $key = 'subscription:by-subscriber:'.$subscriberId;
306             $window = self::cacheGet($key);
307             if ($window === false) {
308                 $window = self::realBySubscriber($subscriberId,
309                                                  0,
310                                                  self::CACHE_WINDOW);
311                 self::cacheSet($key, $window);
312             }
313             return new ArrayWrapper(array_slice($window,
314                                                 $offset,
315                                                 $limit));
316         }
317     }
318
319     private static function realBySubscriber($subscriberId,
320                                              $offset,
321                                              $limit)
322     {
323         $sub = new Subscription();
324
325         $sub->subscriber = $subscriberId;
326
327         $sub->whereAdd('subscribed != ' . $subscriberId);
328
329         $sub->orderBy('created DESC');
330         $sub->limit($offset, $limit);
331
332         $sub->find();
333
334         $subs = array();
335
336         while ($sub->fetch()) {
337             $subs[] = clone($sub);
338         }
339
340         return $subs;
341     }
342
343     /**
344      * Stream of subscriptions with the same subscribed profile
345      *
346      * Useful for showing pages that list subscribers in reverse
347      * chronological order. Has offset & limit to make paging
348      * easy.
349      *
350      * @param integer $subscribedId Profile ID of the subscribed
351      * @param integer $offset       Offset from latest
352      * @param integer $limit        Maximum number to fetch
353      *
354      * @return Subscription stream of subscriptions; use fetch() to iterate
355      */
356     static function bySubscribed($subscribedId,
357                                  $offset = 0,
358                                  $limit = PROFILES_PER_PAGE)
359     {
360         if ($offset + $limit > self::CACHE_WINDOW) {
361             return new ArrayWrapper(self::realBySubscribed($subscribedId,
362                                                            $offset,
363                                                            $limit));
364         } else {
365             $key = 'subscription:by-subscribed:'.$subscribedId;
366             $window = self::cacheGet($key);
367             if ($window === false) {
368                 $window = self::realBySubscribed($subscribedId,
369                                                  0,
370                                                  self::CACHE_WINDOW);
371                 self::cacheSet($key, $window);
372             }
373             return new ArrayWrapper(array_slice($window,
374                                                 $offset,
375                                                 $limit));
376         }
377     }
378
379     private static function realBySubscribed($subscribedId,
380                                              $offset,
381                                              $limit)
382     {
383         $sub = new Subscription();
384
385         $sub->subscribed = $subscribedId;
386
387         $sub->whereAdd('subscriber != ' . $subscribedId);
388
389         $sub->orderBy('created DESC');
390         $sub->limit($offset, $limit);
391
392         $sub->find();
393
394         $subs = array();
395
396         while ($sub->fetch()) {
397             $subs[] = clone($sub);
398         }
399
400         return $subs;
401     }
402
403     /**
404      * Flush cached subscriptions when subscription is updated
405      *
406      * Because we cache subscriptions, it's useful to flush them
407      * here.
408      *
409      * @param mixed $orig Original version of object
410      *
411      * @return boolean success flag.
412      */
413     function update($orig=null)
414     {
415         $result = parent::update($orig);
416
417         self::blow('subscription:by-subscriber:'.$this->subscriber);
418         self::blow('subscription:by-subscribed:'.$this->subscribed);
419
420         return $result;
421     }
422
423     function getURI()
424     {
425         if (!empty($this->uri)) {
426             return $this->uri;
427         } else {
428             return self::newURI($this->subscriber, $this->subscribed, $this->created);
429         }
430     }
431
432     static function newURI($subscriber_id, $subscribed_id, $created)
433     {
434         return TagURI::mint('follow:%d:%d:%s',
435                             $subscriber_id,
436                             $subscribed_id,
437                             common_date_iso8601($created));
438     }
439 }