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