]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apitimelineuser.php
1ec6b74de6ea74bf495f1369820134beefb2c43c
[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 /**
42  * Returns the most recent notices (default 20) posted by the authenticating
43  * user. Another user's timeline can be requested via the id parameter. This
44  * is the API equivalent of the user profile web page.
45  *
46  * @category API
47  * @package  StatusNet
48  * @author   Craig Andrews <candrews@integralblue.com>
49  * @author   Evan Prodromou <evan@status.net>
50  * @author   Jeffery To <jeffery.to@gmail.com>
51  * @author   mac65 <mac65@mac65.com>
52  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
53  * @author   Robin Millette <robin@millette.info>
54  * @author   Zach Copley <zach@status.net>
55  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
56  * @link     http://status.net/
57  */
58 class ApiTimelineUserAction extends ApiBareAuthAction
59 {
60     var $notices = null;
61
62     var $next_id = null;
63
64     /**
65      * Take arguments for running
66      *
67      * @param array $args $_REQUEST args
68      *
69      * @return boolean success flag
70      */
71     protected function prepare(array $args=array())
72     {
73         parent::prepare($args);
74
75         $this->target = $this->getTargetProfile($this->arg('id'));
76
77         if (!($this->target instanceof Profile)) {
78             // TRANS: Client error displayed requesting most recent notices for a non-existing user.
79             $this->clientError(_('No such user.'), 404);
80         }
81
82         if (!$this->target->isLocal()) {
83             $this->serverError(_('Remote user timelines are not available here yet.'), 501);
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      * @return void
97      */
98     protected function handle()
99     {
100         parent::handle();
101
102         if ($this->isPost()) {
103             $this->handlePost();
104         } else {
105             $this->showTimeline();
106         }
107     }
108
109     /**
110      * Show the timeline of notices
111      *
112      * @return void
113      */
114     function showTimeline()
115     {
116         // We'll use the shared params from the Atom stub
117         // for other feed types.
118         $atom = new AtomUserNoticeFeed($this->target->getUser(), $this->auth_user);
119
120         $link = common_local_url(
121                                  'showstream',
122                                  array('nickname' => $this->target->nickname)
123                                  );
124
125         $self = $this->getSelfUri();
126
127         // FriendFeed's SUP protocol
128         // Also added RSS and Atom feeds
129
130         $suplink = common_local_url('sup', null, null, $this->target->id);
131         header('X-SUP-ID: ' . $suplink);
132
133
134         // paging links
135         $nextUrl = !empty($this->next_id)
136                     ? common_local_url('ApiTimelineUser',
137                                     array('format' => $this->format,
138                                           'id' => $this->target->id),
139                                     array('max_id' => $this->next_id))
140                     : null;
141
142         $prevExtra = array();
143         if (!empty($this->notices)) {
144             assert($this->notices[0] instanceof Notice);
145             $prevExtra['since_id'] = $this->notices[0]->id;
146         }
147
148         $prevUrl = common_local_url('ApiTimelineUser',
149                                     array('format' => $this->format,
150                                           'id' => $this->target->id),
151                                     $prevExtra);
152         $firstUrl = common_local_url('ApiTimelineUser',
153                                     array('format' => $this->format,
154                                           'id' => $this->target->id));
155
156         switch($this->format) {
157         case 'xml':
158             $this->showXmlTimeline($this->notices);
159             break;
160         case 'rss':
161             $this->showRssTimeline(
162                                    $this->notices,
163                                    $atom->title,
164                                    $link,
165                                    $atom->subtitle,
166                                    $suplink,
167                                    $atom->logo,
168                                    $self
169                                    );
170             break;
171         case 'atom':
172             header('Content-Type: application/atom+xml; charset=utf-8');
173
174             $atom->setId($self);
175             $atom->setSelfLink($self);
176
177             // Add navigation links: next, prev, first
178             // Note: we use IDs rather than pages for navigation; page boundaries
179             // change too quickly!
180
181             if (!empty($this->next_id)) {
182                 $atom->addLink($nextUrl,
183                                array('rel' => 'next',
184                                      'type' => 'application/atom+xml'));
185             }
186
187             if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
188                 $atom->addLink($prevUrl,
189                                array('rel' => 'prev',
190                                      'type' => 'application/atom+xml'));
191             }
192
193             if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
194                 $atom->addLink($firstUrl,
195                                array('rel' => 'first',
196                                      'type' => 'application/atom+xml'));
197
198             }
199
200             $atom->addEntryFromNotices($this->notices);
201             $this->raw($atom->getString());
202
203             break;
204         case 'json':
205             $this->showJsonTimeline($this->notices);
206             break;
207         case 'as':
208             header('Content-Type: ' . ActivityStreamJSONDocument::CONTENT_TYPE);
209             $doc = new ActivityStreamJSONDocument($this->auth_user);
210             $doc->setTitle($atom->title);
211             $doc->addLink($link, 'alternate', 'text/html');
212             $doc->addItemsFromNotices($this->notices);
213
214             if (!empty($this->next_id)) {
215                 $doc->addLink($nextUrl,
216                                array('rel' => 'next',
217                                      'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
218             }
219
220             if (($this->page > 1 || !empty($this->max_id)) && !empty($this->notices)) {
221                 $doc->addLink($prevUrl,
222                                array('rel' => 'prev',
223                                      'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
224             }
225
226             if ($this->page > 1 || !empty($this->since_id) || !empty($this->max_id)) {
227                 $doc->addLink($firstUrl,
228                                array('rel' => 'first',
229                                      'type' => ActivityStreamJSONDocument::CONTENT_TYPE));
230             }
231
232             $this->raw($doc->asString());
233             break;
234         default:
235             // TRANS: Client error displayed when coming across a non-supported API method.
236             $this->clientError(_('API method not found.'), 404);
237         }
238     }
239
240     /**
241      * Get notices
242      *
243      * @return array notices
244      */
245     function getNotices()
246     {
247         $notices = array();
248
249         $notice = $this->target->getNotices(($this->page-1) * $this->count,
250                                           $this->count + 1,
251                                           $this->since_id,
252                                           $this->max_id,
253                                           $this->scoped);
254
255         while ($notice->fetch()) {
256             if (count($notices) < $this->count) {
257                 $notices[] = clone($notice);
258             } else {
259                 $this->next_id = $notice->id;
260                 break;
261             }
262         }
263
264         return $notices;
265     }
266
267     /**
268      * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
269      *
270      * @param array $args other arguments
271      *
272      * @return boolean true
273      */
274
275     function isReadOnly(array $args=array())
276     {
277         return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
278     }
279
280     /**
281      * When was this feed last modified?
282      *
283      * @return string datestamp of the latest notice in the stream
284      */
285     function lastModified()
286     {
287         if (!empty($this->notices) && (count($this->notices) > 0)) {
288             return strtotime($this->notices[0]->created);
289         }
290
291         return null;
292     }
293
294     /**
295      * An entity tag for this stream
296      *
297      * Returns an Etag based on the action name, language, user ID, and
298      * timestamps of the first and last notice in the timeline
299      *
300      * @return string etag
301      */
302     function etag()
303     {
304         if (!empty($this->notices) && (count($this->notices) > 0)) {
305             $last = count($this->notices) - 1;
306
307             return '"' . implode(
308                                  ':',
309                                  array($this->arg('action'),
310                                        common_user_cache_hash($this->auth_user),
311                                        common_language(),
312                                        $this->target->id,
313                                        strtotime($this->notices[0]->created),
314                                        strtotime($this->notices[$last]->created))
315                                  )
316               . '"';
317         }
318
319         return null;
320     }
321
322     function handlePost()
323     {
324         if (empty($this->auth_user) ||
325             $this->auth_user->id != $this->target->id) {
326             // TRANS: Client error displayed trying to add a notice to another user's timeline.
327             $this->clientError(_('Only the user can add to their own timeline.'));
328         }
329
330         // Only handle posts for Atom
331         if ($this->format != 'atom') {
332             // TRANS: Client error displayed when using another format than AtomPub.
333             $this->clientError(_('Only accept AtomPub for Atom feeds.'));
334         }
335
336         $xml = trim(file_get_contents('php://input'));
337         if (empty($xml)) {
338             // TRANS: Client error displayed attempting to post an empty API notice.
339             $this->clientError(_('Atom post must not be empty.'));
340         }
341
342         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
343         $dom = new DOMDocument();
344         $ok = $dom->loadXML($xml);
345         error_reporting($old);
346         if (!$ok) {
347             // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
348             $this->clientError(_('Atom post must be well-formed XML.'));
349         }
350
351         if ($dom->documentElement->namespaceURI != Activity::ATOM ||
352             $dom->documentElement->localName != 'entry') {
353             // TRANS: Client error displayed when not using an Atom entry.
354             $this->clientError(_('Atom post must be an Atom entry.'));
355         }
356
357         $activity = new Activity($dom->documentElement);
358
359         $saved = null;
360
361         if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->target->getUser(), &$saved))) {
362             if ($activity->verb != ActivityVerb::POST) {
363                 // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
364                 $this->clientError(_('Can only handle POST activities.'));
365             }
366
367             $note = $activity->objects[0];
368
369             if (!in_array($note->type, array(ActivityObject::NOTE,
370                                              ActivityObject::BLOGENTRY,
371                                              ActivityObject::STATUS))) {
372                 // TRANS: Client error displayed when using an unsupported activity object type.
373                 // TRANS: %s is the unsupported activity object type.
374                 $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
375                                              $note->type));
376             }
377
378             $saved = $this->postNote($activity);
379
380             Event::handle('EndAtomPubNewActivity', array($activity, $this->target->getUser(), $saved));
381         }
382
383         if (!empty($saved)) {
384             header('HTTP/1.1 201 Created');
385             header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
386                                                                             'format' => 'atom')));
387             $this->showSingleAtomStatus($saved);
388         }
389     }
390
391     function postNote($activity)
392     {
393         $note = $activity->objects[0];
394
395         // Use summary as fallback for content
396
397         if (!empty($note->content)) {
398             $sourceContent = $note->content;
399         } else if (!empty($note->summary)) {
400             $sourceContent = $note->summary;
401         } else if (!empty($note->title)) {
402             $sourceContent = $note->title;
403         } else {
404             // @fixme fetch from $sourceUrl?
405             // TRANS: Client error displayed when posting a notice without content through the API.
406             // TRANS: %d is the notice ID (number).
407             $this->clientError(sprintf(_('No content for notice %d.'), $note->id));
408         }
409
410         // Get (safe!) HTML and text versions of the content
411
412         $rendered = common_purify($sourceContent);
413         $content = common_strip_html($rendered);
414
415         $shortened = $this->auth_user->shortenLinks($content);
416
417         $options = array('is_local' => Notice::LOCAL_PUBLIC,
418                          'rendered' => $rendered,
419                          'replies' => array(),
420                          'groups' => array(),
421                          'tags' => array(),
422                          'urls' => array());
423
424         // accept remote URI (not necessarily a good idea)
425
426         common_debug("Note ID is {$note->id}");
427
428         if (!empty($note->id)) {
429             $notice = Notice::getKV('uri', trim($note->id));
430
431             if (!empty($notice)) {
432                 // TRANS: Client error displayed when using another format than AtomPub.
433                 // TRANS: %s is the notice URI.
434                 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'), $note->id));
435             }
436             common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
437             $options['uri'] = $note->id;
438         }
439
440         // accept remote create time (also maybe not such a good idea)
441
442         if (!empty($activity->time)) {
443             common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
444             $options['created'] = common_sql_date($activity->time);
445         }
446
447         // Check for optional attributes...
448
449         if ($activity->context instanceof ActivityContext) {
450
451             foreach ($activity->context->attention as $uri=>$type) {
452                 try {
453                     $profile = Profile::fromUri($uri);
454                     if ($profile->isGroup()) {
455                         $options['groups'][] = $profile->id;
456                     } else {
457                         $options['replies'][] = $uri;
458                     }
459                 } catch (UnknownUriException $e) {
460                     common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
461                 }
462             }
463
464             // Maintain direct reply associations
465             // @fixme what about conversation ID?
466
467             if (!empty($activity->context->replyToID)) {
468                 $orig = Notice::getKV('uri',
469                                           $activity->context->replyToID);
470                 if (!empty($orig)) {
471                     $options['reply_to'] = $orig->id;
472                 }
473             }
474
475             $location = $activity->context->location;
476
477             if ($location) {
478                 $options['lat'] = $location->lat;
479                 $options['lon'] = $location->lon;
480                 if ($location->location_id) {
481                     $options['location_ns'] = $location->location_ns;
482                     $options['location_id'] = $location->location_id;
483                 }
484             }
485         }
486
487         // Atom categories <-> hashtags
488
489         foreach ($activity->categories as $cat) {
490             if ($cat->term) {
491                 $term = common_canonical_tag($cat->term);
492                 if ($term) {
493                     $options['tags'][] = $term;
494                 }
495             }
496         }
497
498         // Atom enclosures -> attachment URLs
499         foreach ($activity->enclosures as $href) {
500             // @fixme save these locally or....?
501             $options['urls'][] = $href;
502         }
503
504         $saved = Notice::saveNew($this->target->id,
505                                  $content,
506                                  'atompub', // TODO: deal with this
507                                  $options);
508
509         return $saved;
510     }
511 }