]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - classes/Subscription.php
7ab0136fa718a420988c22bcd6bde90b1036f65b
[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     /* the code above is auto generated do not remove the tag below */
73     ###END_AUTOCODE
74
75     function pkeyGet($kv)
76     {
77         return Memcached_DataObject::pkeyGet('Subscription', $kv);
78     }
79
80     /**
81      * Make a new subscription
82      *
83      * @param Profile $subscriber party to receive new notices
84      * @param Profile $other      party sending notices; publisher
85      * @param bool    $force      pass Subscription::FORCE to override local subscription approval
86      *
87      * @return mixed Subscription or Subscription_queue: new subscription info
88      */
89
90     static function start($subscriber, $other, $force=false)
91     {
92         // @fixme should we enforce this as profiles in callers instead?
93         if ($subscriber instanceof User) {
94             $subscriber = $subscriber->getProfile();
95         }
96         if ($other instanceof User) {
97             $other = $other->getProfile();
98         }
99
100         if (!$subscriber->hasRight(Right::SUBSCRIBE)) {
101             // TRANS: Exception thrown when trying to subscribe while being banned from subscribing.
102             throw new Exception(_('You have been banned from subscribing.'));
103         }
104
105         if (self::exists($subscriber, $other)) {
106             // TRANS: Exception thrown when trying to subscribe while already subscribed.
107             throw new Exception(_('Already subscribed!'));
108         }
109
110         if ($other->hasBlocked($subscriber)) {
111             // TRANS: Exception thrown when trying to subscribe to a user who has blocked the subscribing user.
112             throw new Exception(_('User has blocked you.'));
113         }
114
115         if (Event::handle('StartSubscribe', array($subscriber, $other))) {
116             $otherUser = User::staticGet('id', $other->id);
117             if ($otherUser && $otherUser->subscribe_policy == User::SUBSCRIBE_POLICY_MODERATE && !$force) {
118                 $sub = Subscription_queue::saveNew($subscriber, $other);
119                 $sub->notify();
120             } else {
121                 $sub = self::saveNew($subscriber->id, $other->id);
122                 $sub->notify();
123
124                 self::blow('user:notices_with_friends:%d', $subscriber->id);
125
126                 self::blow('subscription:by-subscriber:'.$subscriber->id);
127                 self::blow('subscription:by-subscribed:'.$other->id);
128
129                 $subscriber->blowSubscriptionCount();
130                 $other->blowSubscriberCount();
131
132                 if (!empty($otherUser) &&
133                     $otherUser->autosubscribe &&
134                     !self::exists($other, $subscriber) &&
135                     !$subscriber->hasBlocked($other)) {
136
137                     try {
138                         self::start($other, $subscriber);
139                     } catch (Exception $e) {
140                         common_log(LOG_ERR, "Exception during autosubscribe of {$other->nickname} to profile {$subscriber->id}: {$e->getMessage()}");
141                     }
142                 }
143             }
144
145             Event::handle('EndSubscribe', array($subscriber, $other));
146         }
147
148         return $sub;
149     }
150
151     /**
152      * Low-level subscription save.
153      * Outside callers should use Subscription::start()
154      */
155     protected function saveNew($subscriber_id, $other_id)
156     {
157         $sub = new Subscription();
158
159         $sub->subscriber = $subscriber_id;
160         $sub->subscribed = $other_id;
161         $sub->jabber     = 1;
162         $sub->sms        = 1;
163         $sub->created    = common_sql_now();
164         $sub->uri        = self::newURI($sub->subscriber,
165                                         $sub->subscribed,
166                                         $sub->created);
167
168         $result = $sub->insert();
169
170         if (!$result) {
171             common_log_db_error($sub, 'INSERT', __FILE__);
172             // TRANS: Exception thrown when a subscription could not be stored on the server.
173             throw new Exception(_('Could not save subscription.'));
174         }
175
176         return $sub;
177     }
178
179     function notify()
180     {
181         // XXX: add other notifications (Jabber, SMS) here
182         // XXX: queue this and handle it offline
183         // XXX: Whatever happens, do it in Twitter-like API, too
184
185         $this->notifyEmail();
186     }
187
188     function notifyEmail()
189     {
190         $subscribedUser = User::staticGet('id', $this->subscribed);
191
192         if (!empty($subscribedUser)) {
193
194             $subscriber = Profile::staticGet('id', $this->subscriber);
195
196             mail_subscribe_notify_profile($subscribedUser, $subscriber);
197         }
198     }
199
200     /**
201      * Cancel a subscription
202      *
203      */
204     function cancel($subscriber, $other)
205     {
206         if (!self::exists($subscriber, $other)) {
207             // TRANS: Exception thrown when trying to unsibscribe without a subscription.
208             throw new Exception(_('Not subscribed!'));
209         }
210
211         // Don't allow deleting self subs
212
213         if ($subscriber->id == $other->id) {
214             // TRANS: Exception thrown when trying to unsubscribe a user from themselves.
215             throw new Exception(_('Could not delete self-subscription.'));
216         }
217
218         if (Event::handle('StartUnsubscribe', array($subscriber, $other))) {
219
220             $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
221                                                'subscribed' => $other->id));
222
223             // note we checked for existence above
224
225             assert(!empty($sub));
226
227             $result = $sub->delete();
228
229             if (!$result) {
230                 common_log_db_error($sub, 'DELETE', __FILE__);
231                 // TRANS: Exception thrown when a subscription could not be deleted on the server.
232                 throw new Exception(_('Could not delete subscription.'));
233             }
234
235             self::blow('user:notices_with_friends:%d', $subscriber->id);
236
237             self::blow('subscription:by-subscriber:'.$subscriber->id);
238             self::blow('subscription:by-subscribed:'.$other->id);
239
240             $subscriber->blowSubscriptionCount();
241             $other->blowSubscriberCount();
242
243             Event::handle('EndUnsubscribe', array($subscriber, $other));
244         }
245
246         return;
247     }
248
249     function exists($subscriber, $other)
250     {
251         $sub = Subscription::pkeyGet(array('subscriber' => $subscriber->id,
252                                            'subscribed' => $other->id));
253         return (empty($sub)) ? false : true;
254     }
255
256     function asActivity()
257     {
258         $subscriber = Profile::staticGet('id', $this->subscriber);
259         $subscribed = Profile::staticGet('id', $this->subscribed);
260
261         if (empty($subscriber)) {
262             throw new Exception(sprintf(_('No profile for the subscriber: %d'), $this->subscriber));
263         }
264
265         if (empty($subscribed)) {
266             throw new Exception(sprintf(_('No profile for the subscribed: %d'), $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     = ActivityObject::fromProfile($subscriber);
287         $act->objects[] = ActivityObject::fromProfile($subscribed);
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 $subscriberId Profile ID of the subscriber
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     static function bySubscriber($subscriberId,
313                                  $offset = 0,
314                                  $limit = PROFILES_PER_PAGE)
315     {
316         if ($offset + $limit > self::CACHE_WINDOW) {
317             return new ArrayWrapper(self::realBySubscriber($subscriberId,
318                                                            $offset,
319                                                            $limit));
320         } else {
321             $key = 'subscription:by-subscriber:'.$subscriberId;
322             $window = self::cacheGet($key);
323             if ($window === false) {
324                 $window = self::realBySubscriber($subscriberId,
325                                                  0,
326                                                  self::CACHE_WINDOW);
327                 self::cacheSet($key, $window);
328             }
329             return new ArrayWrapper(array_slice($window,
330                                                 $offset,
331                                                 $limit));
332         }
333     }
334
335     private static function realBySubscriber($subscriberId,
336                                              $offset,
337                                              $limit)
338     {
339         $sub = new Subscription();
340
341         $sub->subscriber = $subscriberId;
342
343         $sub->whereAdd('subscribed != ' . $subscriberId);
344
345         $sub->orderBy('created DESC');
346         $sub->limit($offset, $limit);
347
348         $sub->find();
349
350         $subs = array();
351
352         while ($sub->fetch()) {
353             $subs[] = clone($sub);
354         }
355
356         return $subs;
357     }
358
359     /**
360      * Stream of subscriptions with the same subscribed profile
361      *
362      * Useful for showing pages that list subscribers in reverse
363      * chronological order. Has offset & limit to make paging
364      * easy.
365      *
366      * @param integer $subscribedId Profile ID of the subscribed
367      * @param integer $offset       Offset from latest
368      * @param integer $limit        Maximum number to fetch
369      *
370      * @return Subscription stream of subscriptions; use fetch() to iterate
371      */
372     static function bySubscribed($subscribedId,
373                                  $offset = 0,
374                                  $limit = PROFILES_PER_PAGE)
375     {
376         if ($offset + $limit > self::CACHE_WINDOW) {
377             return new ArrayWrapper(self::realBySubscribed($subscribedId,
378                                                            $offset,
379                                                            $limit));
380         } else {
381             $key = 'subscription:by-subscribed:'.$subscribedId;
382             $window = self::cacheGet($key);
383             if ($window === false) {
384                 $window = self::realBySubscribed($subscribedId,
385                                                  0,
386                                                  self::CACHE_WINDOW);
387                 self::cacheSet($key, $window);
388             }
389             return new ArrayWrapper(array_slice($window,
390                                                 $offset,
391                                                 $limit));
392         }
393     }
394
395     private static function realBySubscribed($subscribedId,
396                                              $offset,
397                                              $limit)
398     {
399         $sub = new Subscription();
400
401         $sub->subscribed = $subscribedId;
402
403         $sub->whereAdd('subscriber != ' . $subscribedId);
404
405         $sub->orderBy('created DESC');
406         $sub->limit($offset, $limit);
407
408         $sub->find();
409
410         $subs = array();
411
412         while ($sub->fetch()) {
413             $subs[] = clone($sub);
414         }
415
416         return $subs;
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 $orig Original version of object
426      *
427      * @return boolean success flag.
428      */
429     function update($orig=null)
430     {
431         $result = parent::update($orig);
432
433         self::blow('subscription:by-subscriber:'.$this->subscriber);
434         self::blow('subscription:by-subscribed:'.$this->subscribed);
435
436         return $result;
437     }
438
439     function getURI()
440     {
441         if (!empty($this->uri)) {
442             return $this->uri;
443         } else {
444             return self::newURI($this->subscriber, $this->subscribed, $this->created);
445         }
446     }
447
448     static function newURI($subscriber_id, $subscribed_id, $created)
449     {
450         return TagURI::mint('follow:%d:%d:%s',
451                             $subscriber_id,
452                             $subscribed_id,
453                             common_date_iso8601($created));
454     }
455 }