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