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