]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/useractivitystream.php
Merge branch 'issue-326' into 'master'
[quix0rs-gnu-social.git] / lib / useractivitystream.php
1 <?php
2 /*
3  * StatusNet - the distributed open-source microblogging tool
4  * Copyright (C) 2010 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 /**
21  * Class for activity streams
22  *
23  * Includes objects like notices, subscriptions and from plugins.
24  *
25  * We extend atomusernoticefeed since it does some nice setup for us.
26  *
27  */
28 class UserActivityStream extends AtomUserNoticeFeed
29 {
30     public $activities = array();
31     public $after = null;
32
33     const OUTPUT_STRING = 1;
34     const OUTPUT_RAW = 2;
35     public $outputMode = self::OUTPUT_STRING;
36
37     /**
38      *
39      * @param User $user
40      * @param boolean $indent
41      * @param boolean $outputMode: UserActivityStream::OUTPUT_STRING to return a string,
42      *                           or UserActivityStream::OUTPUT_RAW to go to raw output.
43      *                           Raw output mode will attempt to stream, keeping less
44      *                           data in memory but will leave $this->activities incomplete.
45      */
46     function __construct($user, $indent = true, $outputMode = UserActivityStream::OUTPUT_STRING, $after = null)
47     {
48         parent::__construct($user, null, $indent);
49
50         $this->outputMode = $outputMode;
51
52         if ($this->outputMode == self::OUTPUT_STRING) {
53             // String buffering? Grab all the notices now.
54             $notices = $this->getNotices();
55         } elseif ($this->outputMode == self::OUTPUT_RAW) {
56             // Raw output... need to restructure from the stringer init.
57             $this->xw = new XMLWriter();
58             $this->xw->openURI('php://output');
59             if(is_null($indent)) {
60                 $indent = common_config('site', 'indent');
61             }
62             $this->xw->setIndent($indent);
63
64             // We'll fetch notices later.
65             $notices = array();
66         } else {
67             throw new Exception('Invalid outputMode provided to ' . __METHOD__);
68         }
69
70         $this->after = $after;
71
72         // Assume that everything but notices is feasible
73         // to pull at once and work with in memory...
74
75         $subscriptions = $this->getSubscriptions();
76         $subscribers   = $this->getSubscribers();
77         $groups        = $this->getGroups();
78
79         $objs = array_merge($subscriptions, $subscribers, $groups, $notices);
80
81         Event::handle('AppendUserActivityStreamObjects', array($this, &$objs));
82
83         $subscriptions = null;
84         $subscribers   = null;
85         $groups        = null;
86
87         unset($subscriptions);
88         unset($subscribers);
89         unset($groups);
90
91         // Sort by create date
92
93         usort($objs, 'UserActivityStream::compareObject');
94
95         // We'll keep these around for later, and interleave them into
96         // the output stream with the user's notices.
97
98         $this->objs = $objs;
99     }
100
101     /**
102      * Interleave the pre-sorted objects with the user's
103      * notices, all in reverse chron order.
104      */
105     function renderEntries($format=Feed::ATOM, $handle=null)
106     {
107         $haveOne = false;
108
109         $end = time() + 1;
110         foreach ($this->objs as $obj) {
111             set_time_limit(10);
112
113             try {
114                 $act = $obj->asActivity();
115             } catch (Exception $e) {
116                 common_log(LOG_ERR, $e->getMessage());
117                 continue;
118             }
119
120             $start = $act->time;
121
122             if ($this->outputMode == self::OUTPUT_RAW && $start != $end) {
123                 // In raw mode, we haven't pre-fetched notices.
124                 // Grab the chunks of notices between other activities.
125                 try {
126                     $notices = $this->getNoticesBetween($start, $end);
127                     foreach ($notices as $noticeAct) {
128                         try {
129                             $nact = $noticeAct->asActivity($this->user->getProfile());
130                             if ($format == Feed::ATOM) {
131                                 $nact->outputTo($this, false, false);
132                             } else {
133                                 if ($haveOne) {
134                                     fwrite($handle, ",");
135                                 }
136                                 fwrite($handle, json_encode($nact->asArray()));
137                                 $haveOne = true;
138                             }
139                         } catch (Exception $e) {
140                             common_log(LOG_ERR, $e->getMessage());
141                             continue;
142                         }
143                         $nact = null;
144                         unset($nact);
145                     }
146                 } catch (Exception $e) {
147                     common_log(LOG_ERR, $e->getMessage());
148                 }
149             }
150
151             $notices = null;
152             unset($notices);
153
154             try {
155                 if ($format == Feed::ATOM) {
156                     // Only show the author sub-element if it's different from default user
157                     $act->outputTo($this, false, ($act->actor->id != $this->user->getUri()));
158                 } else {
159                     if ($haveOne) {
160                         fwrite($handle, ",");
161                     }
162                     fwrite($handle, json_encode($act->asArray()));
163                     $haveOne = true;
164                 }
165             } catch (Exception $e) {
166                 common_log(LOG_ERR, $e->getMessage());
167             }
168
169             $act = null;
170             unset($act);
171
172             $end = $start;
173         }
174
175         if ($this->outputMode == self::OUTPUT_RAW) {
176             // Grab anything after the last pre-sorted activity.
177             try {
178                 if (!empty($this->after)) {
179                     $notices = $this->getNoticesBetween($this->after, $end);
180                 } else {
181                     $notices = $this->getNoticesBetween(0, $end);
182                 }
183                 foreach ($notices as $noticeAct) {
184                     try {
185                         $nact = $noticeAct->asActivity($this->user->getProfile());
186                         if ($format == Feed::ATOM) {
187                             $nact->outputTo($this, false, false);
188                         } else {
189                             if ($haveOne) {
190                                 fwrite($handle, ",");
191                             }
192                             fwrite($handle, json_encode($nact->asArray()));
193                             $haveOne = true;
194                         }
195                     } catch (Exception $e) {
196                         common_log(LOG_ERR, $e->getMessage());
197                         continue;
198                     }
199                 }
200             } catch (Exception $e) {
201                 common_log(LOG_ERR, $e->getMessage());
202             }
203         }
204
205         if (empty($this->after) || strtotime($this->user->created) > $this->after) {
206             // We always add the registration activity at the end, even if
207             // they have older activities (from restored backups) in their stream.
208
209             try {
210                 $ract = $this->user->registrationActivity();
211                 if ($format == Feed::ATOM) {
212                     $ract->outputTo($this, false, false);
213                 } else {
214                     if ($haveOne) {
215                         fwrite($handle, ",");
216                     }
217                     fwrite($handle, json_encode($ract->asArray()));
218                     $haveOne = true;
219                 }
220             } catch (Exception $e) {
221                 common_log(LOG_ERR, $e->getMessage());
222             }
223         }
224     }
225
226     function compareObject($a, $b)
227     {
228         $ac = strtotime((empty($a->created)) ? $a->modified : $a->created);
229         $bc = strtotime((empty($b->created)) ? $b->modified : $b->created);
230
231         return (($ac == $bc) ? 0 : (($ac < $bc) ? 1 : -1));
232     }
233
234     function getSubscriptions()
235     {
236         $subs = array();
237
238         $sub = new Subscription();
239
240         $sub->subscriber = $this->user->id;
241
242         if (!empty($this->after)) {
243             $sub->whereAdd("created > '" . common_sql_date($this->after) . "'");
244         }
245
246         if ($sub->find()) {
247             while ($sub->fetch()) {
248                 if ($sub->subscribed != $this->user->id) {
249                     $subs[] = clone($sub);
250                 }
251             }
252         }
253
254         return $subs;
255     }
256
257     function getSubscribers()
258     {
259         $subs = array();
260
261         $sub = new Subscription();
262
263         $sub->subscribed = $this->user->id;
264
265         if (!empty($this->after)) {
266             $sub->whereAdd("created > '" . common_sql_date($this->after) . "'");
267         }
268
269         if ($sub->find()) {
270             while ($sub->fetch()) {
271                 if ($sub->subscriber != $this->user->id) {
272                     $subs[] = clone($sub);
273                 }
274             }
275         }
276
277         return $subs;
278     }
279
280     /**
281      *
282      * @param int $start unix timestamp for earliest
283      * @param int $end unix timestamp for latest
284      * @return array of Notice objects
285      */
286     function getNoticesBetween($start=0, $end=0)
287     {
288         $notices = array();
289
290         $notice = new Notice();
291
292         $notice->profile_id = $this->user->id;
293
294         // Only stuff after $this->after
295
296         if (!empty($this->after)) {
297             if ($start) {
298                 $start = max($start, $this->after);
299             }
300             if ($end) {
301                 $end = max($end, $this->after);
302             }
303         }
304
305         if ($start) {
306             $tsstart = common_sql_date($start);
307             $notice->whereAdd("created >= '$tsstart'");
308         }
309         if ($end) {
310             $tsend = common_sql_date($end);
311             $notice->whereAdd("created < '$tsend'");
312         }
313
314         $notice->orderBy('created DESC');
315
316         if ($notice->find()) {
317             while ($notice->fetch()) {
318                 $notices[] = clone($notice);
319             }
320         }
321
322         return $notices;
323     }
324
325     function getNotices()
326     {
327         if (!empty($this->after)) {
328             return $this->getNoticesBetween($this->after);
329         } else {
330             return $this->getNoticesBetween();
331         }
332     }
333
334     function getGroups()
335     {
336         $groups = array();
337
338         $gm = new Group_member();
339
340         $gm->profile_id = $this->user->id;
341
342         if (!empty($this->after)) {
343             $gm->whereAdd("created > '" . common_sql_date($this->after) . "'");
344         }
345
346         if ($gm->find()) {
347             while ($gm->fetch()) {
348                 $groups[] = clone($gm);
349             }
350         }
351
352         return $groups;
353     }
354
355     function createdAfter($item) {
356         $created = strtotime((empty($item->created)) ? $item->modified : $item->created);
357         return ($created >= $this->after);
358     }
359
360     function writeJSON($handle)
361     {
362         require_once INSTALLDIR.'/lib/activitystreamjsondocument.php';
363         fwrite($handle, '{"items": [');
364         $this->renderEntries(Feed::JSON, $handle);
365         fwrite($handle, ']}');
366     }
367 }