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