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