]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apitimelineuser.php
Merge branch '0.9.x' into atompub
[quix0rs-gnu-social.git] / actions / apitimelineuser.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Show a user's timeline
6  *
7  * PHP version 5
8  *
9  * LICENCE: This program is free software: you can redistribute it and/or modify
10  * it under the terms of the GNU Affero General Public License as published by
11  * the Free Software Foundation, either version 3 of the License, or
12  * (at your option) any later version.
13  *
14  * This program is distributed in the hope that it will be useful,
15  * but WITHOUT ANY WARRANTY; without even the implied warranty of
16  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
17  * GNU Affero General Public License for more details.
18  *
19  * You should have received a copy of the GNU Affero General Public License
20  * along with this program.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  * @category  API
23  * @package   StatusNet
24  * @author    Craig Andrews <candrews@integralblue.com>
25  * @author    Evan Prodromou <evan@status.net>
26  * @author    Jeffery To <jeffery.to@gmail.com>
27  * @author    mac65 <mac65@mac65.com>
28  * @author    Mike Cochrane <mikec@mikenz.geek.nz>
29  * @author    Robin Millette <robin@millette.info>
30  * @author    Zach Copley <zach@status.net>
31  * @copyright 2009 StatusNet, Inc.
32  * @copyright 2009 Free Software Foundation, Inc http://www.fsf.org
33  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
34  * @link      http://status.net/
35  */
36
37 if (!defined('STATUSNET')) {
38     exit(1);
39 }
40
41 require_once INSTALLDIR . '/lib/apibareauth.php';
42
43 /**
44  * Returns the most recent notices (default 20) posted by the authenticating
45  * user. Another user's timeline can be requested via the id parameter. This
46  * is the API equivalent of the user profile web page.
47  *
48  * @category API
49  * @package  StatusNet
50  * @author   Craig Andrews <candrews@integralblue.com>
51  * @author   Evan Prodromou <evan@status.net>
52  * @author   Jeffery To <jeffery.to@gmail.com>
53  * @author   mac65 <mac65@mac65.com>
54  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
55  * @author   Robin Millette <robin@millette.info>
56  * @author   Zach Copley <zach@status.net>
57  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
58  * @link     http://status.net/
59  */
60
61 class ApiTimelineUserAction extends ApiBareAuthAction
62 {
63
64     var $notices = null;
65
66     /**
67      * Take arguments for running
68      *
69      * @param array $args $_REQUEST args
70      *
71      * @return boolean success flag
72      *
73      */
74
75     function prepare($args)
76     {
77         parent::prepare($args);
78
79         $this->user = $this->getTargetUser($this->arg('id'));
80
81         if (empty($this->user)) {
82             $this->clientError(_('No such user.'), 404, $this->format);
83             return;
84         }
85
86         $this->notices = $this->getNotices();
87
88         return true;
89     }
90
91     /**
92      * Handle the request
93      *
94      * Just show the notices
95      *
96      * @param array $args $_REQUEST data (unused)
97      *
98      * @return void
99      */
100
101     function handle($args)
102     {
103         parent::handle($args);
104
105         if ($this->isPost()) {
106             $this->handlePost();
107         } else {
108             $this->showTimeline();
109         }
110     }
111
112     /**
113      * Show the timeline of notices
114      *
115      * @return void
116      */
117
118     function showTimeline()
119     {
120         $profile = $this->user->getProfile();
121
122         // We'll use the shared params from the Atom stub
123         // for other feed types.
124         $atom = new AtomUserNoticeFeed($this->user, $this->auth_user);
125
126         $link = common_local_url(
127                                  'showstream',
128                                  array('nickname' => $this->user->nickname)
129                                  );
130
131         $self = $this->getSelfUri();
132
133         // FriendFeed's SUP protocol
134         // Also added RSS and Atom feeds
135
136         $suplink = common_local_url('sup', null, null, $this->user->id);
137         header('X-SUP-ID: ' . $suplink);
138
139         switch($this->format) {
140         case 'xml':
141             $this->showXmlTimeline($this->notices);
142             break;
143         case 'rss':
144             $this->showRssTimeline(
145                                    $this->notices,
146                                    $atom->title,
147                                    $link,
148                                    $atom->subtitle,
149                                    $suplink,
150                                    $atom->logo,
151                                    $self
152                                    );
153             break;
154         case 'atom':
155
156             header('Content-Type: application/atom+xml; charset=utf-8');
157
158             $atom->setId($self);
159             $atom->setSelfLink($self);
160
161             // Add navigation links: next, prev, first
162             // Note: we use IDs rather than pages for navigation; page boundaries
163             // change too quickly!
164
165             if (!empty($this->next_id)) {
166                 $nextUrl = common_local_url('ApiTimelineUser',
167                                             array('format' => 'atom',
168                                                   'id' => $this->user->id),
169                                             array('max_id' => $this->next_id));
170
171                 $atom->addLink($nextUrl,
172                                array('rel' => 'next',
173                                      'type' => 'application/atom+xml'));
174             }
175
176             if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
177
178                 $lastNotice = $this->notices[0];
179                 $lastId     = $lastNotice->id;
180
181                 $prevUrl = common_local_url('ApiTimelineUser',
182                                             array('format' => 'atom',
183                                                   'id' => $this->user->id),
184                                             array('since_id' => $lastId));
185
186                 $atom->addLink($prevUrl,
187                                array('rel' => 'prev',
188                                      'type' => 'application/atom+xml'));
189             }
190
191             if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
192
193                 $firstUrl = common_local_url('ApiTimelineUser',
194                                             array('format' => 'atom',
195                                                   'id' => $this->user->id));
196
197                 $atom->addLink($firstUrl,
198                                array('rel' => 'first',
199                                      'type' => 'application/atom+xml'));
200
201             }
202
203             $atom->addEntryFromNotices($this->notices);
204             $this->raw($atom->getString());
205
206             break;
207         case 'json':
208             $this->showJsonTimeline($this->notices);
209             break;
210         default:
211             $this->clientError(_('API method not found.'), $code = 404);
212             break;
213         }
214
215     }
216
217     /**
218      * Get notices
219      *
220      * @return array notices
221      */
222
223     function getNotices()
224     {
225         $notices = array();
226
227         $notice = $this->user->getNotices(($this->page-1) * $this->count,
228                                           $this->count + 1,
229                                           $this->since_id,
230                                           $this->max_id);
231
232         while ($notice->fetch()) {
233             if (count($notices) < $this->count) {
234                 $notices[] = clone($notice);
235             } else {
236                 $this->next_id = $notice->id;
237                 break;
238             }
239         }
240
241         return $notices;
242     }
243
244     /**
245      * Is this action read only?
246      *
247      * @param array $args other arguments
248      *
249      * @return boolean true
250      */
251
252     function isReadOnly($args)
253     {
254         return true;
255     }
256
257     /**
258      * When was this feed last modified?
259      *
260      * @return string datestamp of the latest notice in the stream
261      */
262
263     function lastModified()
264     {
265         if (!empty($this->notices) && (count($this->notices) > 0)) {
266             return strtotime($this->notices[0]->created);
267         }
268
269         return null;
270     }
271
272     /**
273      * An entity tag for this stream
274      *
275      * Returns an Etag based on the action name, language, user ID, and
276      * timestamps of the first and last notice in the timeline
277      *
278      * @return string etag
279      */
280
281     function etag()
282     {
283         if (!empty($this->notices) && (count($this->notices) > 0)) {
284
285             $last = count($this->notices) - 1;
286
287             return '"' . implode(
288                                  ':',
289                                  array($this->arg('action'),
290                                        common_user_cache_hash($this->auth_user),
291                                        common_language(),
292                                        $this->user->id,
293                                        strtotime($this->notices[0]->created),
294                                        strtotime($this->notices[$last]->created))
295                                  )
296               . '"';
297         }
298
299         return null;
300     }
301
302     function handlePost()
303     {
304         if (empty($this->auth_user) ||
305             $this->auth_user->id != $this->user->id) {
306             $this->clientError(_("Only the user can add to their own timeline."));
307             return;
308         }
309
310         if ($this->format != 'atom') {
311             // Only handle posts for Atom
312             $this->clientError(_("Only accept AtomPub for atom feeds."));
313             return;
314         }
315
316         $xml = file_get_contents('php://input');
317
318         $dom = DOMDocument::loadXML($xml);
319
320         if ($dom->documentElement->namespaceURI != Activity::ATOM ||
321             $dom->documentElement->localName != 'entry') {
322             $this->clientError(_('Atom post must be an Atom entry.'));
323             return;
324         }
325
326         $activity = new Activity($dom->documentElement);
327
328         if ($activity->verb != ActivityVerb::POST) {
329             $this->clientError(_('Can only handle post activities.'));
330             return;
331         }
332
333         $note = $activity->objects[0];
334
335         if (!in_array($note->type, array(ActivityObject::NOTE,
336                                          ActivityObject::BLOGENTRY,
337                                          ActivityObject::STATUS))) {
338             $this->clientError(sprintf(_('Cannot handle activity object type "%s"',
339                                          $note->type)));
340             return;
341         }
342
343         // Use summary as fallback for content
344
345         if (!empty($note->content)) {
346             $sourceContent = $note->content;
347         } else if (!empty($note->summary)) {
348             $sourceContent = $note->summary;
349         } else if (!empty($note->title)) {
350             $sourceContent = $note->title;
351         } else {
352             // @fixme fetch from $sourceUrl?
353             // @todo i18n FIXME: use sprintf and add i18n.
354             $this->clientError("No content for notice {$note->id}.");
355             return;
356         }
357
358         // Get (safe!) HTML and text versions of the content
359
360         $rendered = $this->purify($sourceContent);
361         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
362
363         $shortened = common_shorten_links($content);
364
365         $options = array('is_local' => Notice::LOCAL_PUBLIC,
366                          'rendered' => $rendered,
367                          'replies' => array(),
368                          'groups' => array(),
369                          'tags' => array(),
370                          'urls' => array());
371
372         // accept remote URI (not necessarily a good idea)
373
374         common_debug("Note ID is {$note->id}");
375
376         if (!empty($note->id)) {
377             $notice = Notice::staticGet('uri', trim($note->id));
378
379             if (!empty($notice)) {
380                 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'),
381                                            $note->id));
382                 return;
383             }
384             common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
385             $options['uri'] = $note->id;
386         }
387
388         // accept remote create time (also maybe not such a good idea)
389
390         if (!empty($activity->time)) {
391             common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
392             $options['created'] = common_sql_date($activity->time);
393         }
394
395         // Check for optional attributes...
396
397         if (!empty($activity->context)) {
398
399             foreach ($activity->context->attention as $uri) {
400
401                 $profile = Profile::fromURI($uri);
402
403                 if (!empty($profile)) {
404                     $options['replies'] = $uri;
405                 } else {
406                     $group = User_group::staticGet('uri', $uri);
407                     if (!empty($group)) {
408                         $options['groups'] = $uri;
409                     } else {
410                         // @fixme: hook for discovery here
411                         common_log(LOG_WARNING, sprintf(_('AtomPub post with unknown attention URI %s'), $uri));
412                     }
413                 }
414             }
415
416             // Maintain direct reply associations
417             // @fixme what about conversation ID?
418
419             if (!empty($activity->context->replyToID)) {
420                 $orig = Notice::staticGet('uri',
421                                           $activity->context->replyToID);
422                 if (!empty($orig)) {
423                     $options['reply_to'] = $orig->id;
424                 }
425             }
426
427             $location = $activity->context->location;
428
429             if ($location) {
430                 $options['lat'] = $location->lat;
431                 $options['lon'] = $location->lon;
432                 if ($location->location_id) {
433                     $options['location_ns'] = $location->location_ns;
434                     $options['location_id'] = $location->location_id;
435                 }
436             }
437         }
438
439         // Atom categories <-> hashtags
440
441         foreach ($activity->categories as $cat) {
442             if ($cat->term) {
443                 $term = common_canonical_tag($cat->term);
444                 if ($term) {
445                     $options['tags'][] = $term;
446                 }
447             }
448         }
449
450         // Atom enclosures -> attachment URLs
451         foreach ($activity->enclosures as $href) {
452             // @fixme save these locally or....?
453             $options['urls'][] = $href;
454         }
455
456         $saved = Notice::saveNew($this->user->id,
457                                  $content,
458                                  'atompub', // TODO: deal with this
459                                  $options);
460
461         if (!empty($saved)) {
462             header("Location: " . common_local_url('ApiStatusesShow', array('notice_id' => $saved->id,
463                                                                             'format' => 'atom')));
464             $this->showSingleAtomStatus($saved);
465         }
466     }
467
468     function purify($content)
469     {
470         require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
471
472         $config = array('safe' => 1,
473                         'deny_attribute' => 'id,style,on*');
474         return htmLawed($content, $config);
475     }
476 }