]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/useractivitystream.php
Merge branch 'master' of git://gitorious.org/statusnet/darksider3s-gnu-social into...
[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         $messagesFrom  = $this->getMessagesFrom();
79         $messagesTo    = $this->getMessagesTo();
80
81         $objs = array_merge($subscriptions, $subscribers, $groups, $notices, $messagesFrom, $messagesTo);
82
83         Event::handle('AppendUserActivityStreamObjects', array($this, &$objs));
84
85         $subscriptions = null;
86         $subscribers   = null;
87         $groups        = null;
88
89         unset($subscriptions);
90         unset($subscribers);
91         unset($groups);
92
93         // Sort by create date
94
95         usort($objs, 'UserActivityStream::compareObject');
96
97         // We'll keep these around for later, and interleave them into
98         // the output stream with the user's notices.
99
100         $this->objs = $objs;
101     }
102
103     /**
104      * Interleave the pre-sorted objects with the user's
105      * notices, all in reverse chron order.
106      */
107     function renderEntries($format=Feed::ATOM, $handle=null)
108     {
109         $haveOne = false;
110
111         $end = time() + 1;
112         foreach ($this->objs as $obj) {
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);
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);
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                 continue;
223             }
224         }
225     }
226
227     function compareObject($a, $b)
228     {
229         $ac = strtotime((empty($a->created)) ? $a->modified : $a->created);
230         $bc = strtotime((empty($b->created)) ? $b->modified : $b->created);
231
232         return (($ac == $bc) ? 0 : (($ac < $bc) ? 1 : -1));
233     }
234
235     function getSubscriptions()
236     {
237         $subs = array();
238
239         $sub = new Subscription();
240
241         $sub->subscriber = $this->user->id;
242
243         if (!empty($this->after)) {
244             $sub->whereAdd("created > '" . common_sql_date($this->after) . "'");
245         }
246
247         if ($sub->find()) {
248             while ($sub->fetch()) {
249                 if ($sub->subscribed != $this->user->id) {
250                     $subs[] = clone($sub);
251                 }
252             }
253         }
254
255         return $subs;
256     }
257
258     function getSubscribers()
259     {
260         $subs = array();
261
262         $sub = new Subscription();
263
264         $sub->subscribed = $this->user->id;
265
266         if (!empty($this->after)) {
267             $sub->whereAdd("created > '" . common_sql_date($this->after) . "'");
268         }
269
270         if ($sub->find()) {
271             while ($sub->fetch()) {
272                 if ($sub->subscriber != $this->user->id) {
273                     $subs[] = clone($sub);
274                 }
275             }
276         }
277
278         return $subs;
279     }
280
281     /**
282      *
283      * @param int $start unix timestamp for earliest
284      * @param int $end unix timestamp for latest
285      * @return array of Notice objects
286      */
287     function getNoticesBetween($start=0, $end=0)
288     {
289         $notices = array();
290
291         $notice = new Notice();
292
293         $notice->profile_id = $this->user->id;
294
295         // Only stuff after $this->after
296
297         if (!empty($this->after)) {
298             if ($start) {
299                 $start = max($start, $this->after);
300             }
301             if ($end) {
302                 $end = max($end, $this->after);
303             }
304         }
305
306         if ($start) {
307             $tsstart = common_sql_date($start);
308             $notice->whereAdd("created >= '$tsstart'");
309         }
310         if ($end) {
311             $tsend = common_sql_date($end);
312             $notice->whereAdd("created < '$tsend'");
313         }
314
315         $notice->orderBy('created DESC');
316
317         if ($notice->find()) {
318             while ($notice->fetch()) {
319                 $notices[] = clone($notice);
320             }
321         }
322
323         return $notices;
324     }
325
326     function getNotices()
327     {
328         if (!empty($this->after)) {
329             return $this->getNoticesBetween($this->after);
330         } else {
331             return $this->getNoticesBetween();
332         }
333     }
334
335     function getGroups()
336     {
337         $groups = array();
338
339         $gm = new Group_member();
340
341         $gm->profile_id = $this->user->id;
342
343         if (!empty($this->after)) {
344             $gm->whereAdd("created > '" . common_sql_date($this->after) . "'");
345         }
346
347         if ($gm->find()) {
348             while ($gm->fetch()) {
349                 $groups[] = clone($gm);
350             }
351         }
352
353         return $groups;
354     }
355
356     function getMessagesTo()
357     {
358         $msgMap = Message::listGet('to_profile', array($this->user->id));
359
360         $messages = $msgMap[$this->user->id];
361
362         if (!empty($this->after)) {
363             $messages = array_filter($messages, array($this, 'createdAfter'));
364         }
365
366         return $messages;
367     }
368
369     function getMessagesFrom()
370     {
371         $msgMap = Message::listGet('from_profile', array($this->user->id));
372
373         $messages = $msgMap[$this->user->id];
374
375         if (!empty($this->after)) {
376             $messages = array_filter($messages, array($this, 'createdAfter'));
377         }
378
379         return $messages;
380     }
381
382     function createdAfter($item) {
383         $created = strtotime((empty($item->created)) ? $item->modified : $item->created);
384         return ($created >= $this->after);
385     }
386
387     function writeJSON($handle)
388     {
389         require_once INSTALLDIR.'/lib/activitystreamjsondocument.php';
390         fwrite($handle, '{"items": [');
391         $this->renderEntries(Feed::JSON, $handle);
392         fwrite($handle, ']}');
393     }
394 }