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