]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apitimelineuser.php
OAuth related syntax fixes, nothing big
[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
234         while ($notice->fetch()) {
235             if (count($notices) < $this->count) {
236                 $notices[] = clone($notice);
237             } else {
238                 $this->next_id = $notice->id;
239                 break;
240             }
241         }
242
243         return $notices;
244     }
245
246     /**
247      * We expose AtomPub here, so non-GET/HEAD reqs must be read/write.
248      *
249      * @param array $args other arguments
250      *
251      * @return boolean true
252      */
253
254     function isReadOnly($args)
255     {
256         return ($_SERVER['REQUEST_METHOD'] == 'GET' || $_SERVER['REQUEST_METHOD'] == 'HEAD');
257     }
258
259     /**
260      * When was this feed last modified?
261      *
262      * @return string datestamp of the latest notice in the stream
263      */
264     function lastModified()
265     {
266         if (!empty($this->notices) && (count($this->notices) > 0)) {
267             return strtotime($this->notices[0]->created);
268         }
269
270         return null;
271     }
272
273     /**
274      * An entity tag for this stream
275      *
276      * Returns an Etag based on the action name, language, user ID, and
277      * timestamps of the first and last notice in the timeline
278      *
279      * @return string etag
280      */
281     function etag()
282     {
283         if (!empty($this->notices) && (count($this->notices) > 0)) {
284             $last = count($this->notices) - 1;
285
286             return '"' . implode(
287                                  ':',
288                                  array($this->arg('action'),
289                                        common_user_cache_hash($this->auth_user),
290                                        common_language(),
291                                        $this->user->id,
292                                        strtotime($this->notices[0]->created),
293                                        strtotime($this->notices[$last]->created))
294                                  )
295               . '"';
296         }
297
298         return null;
299     }
300
301     function handlePost()
302     {
303         if (empty($this->auth_user) ||
304             $this->auth_user->id != $this->user->id) {
305             // TRANS: Client error displayed trying to add a notice to another user's timeline.
306             $this->clientError(_('Only the user can add to their own timeline.'));
307             return;
308         }
309
310         // Only handle posts for Atom
311         if ($this->format != 'atom') {
312             // TRANS: Client error displayed when using another format than AtomPub.
313             $this->clientError(_('Only accept AtomPub for Atom feeds.'));
314             return;
315         }
316
317         $xml = trim(file_get_contents('php://input'));
318         if (empty($xml)) {
319             // TRANS: Client error displayed attempting to post an empty API notice.
320             $this->clientError(_('Atom post must not be empty.'));
321         }
322
323         $old = error_reporting(error_reporting() & ~(E_WARNING | E_NOTICE));
324         $dom = new DOMDocument();
325         $ok = $dom->loadXML($xml);
326         error_reporting($old);
327         if (!$ok) {
328             // TRANS: Client error displayed attempting to post an API that is not well-formed XML.
329             $this->clientError(_('Atom post must be well-formed XML.'));
330         }
331
332         if ($dom->documentElement->namespaceURI != Activity::ATOM ||
333             $dom->documentElement->localName != 'entry') {
334             // TRANS: Client error displayed when not using an Atom entry.
335             $this->clientError(_('Atom post must be an Atom entry.'));
336             return;
337         }
338
339         $activity = new Activity($dom->documentElement);
340
341         $saved = null;
342
343         if (Event::handle('StartAtomPubNewActivity', array(&$activity, $this->user, &$saved))) {
344             if ($activity->verb != ActivityVerb::POST) {
345                 // TRANS: Client error displayed when not using the POST verb. Do not translate POST.
346                 $this->clientError(_('Can only handle POST activities.'));
347                 return;
348             }
349
350             $note = $activity->objects[0];
351
352             if (!in_array($note->type, array(ActivityObject::NOTE,
353                                              ActivityObject::BLOGENTRY,
354                                              ActivityObject::STATUS))) {
355                 // TRANS: Client error displayed when using an unsupported activity object type.
356                 // TRANS: %s is the unsupported activity object type.
357                 $this->clientError(sprintf(_('Cannot handle activity object type "%s".'),
358                                              $note->type));
359                 return;
360             }
361
362             $saved = $this->postNote($activity);
363
364             Event::handle('EndAtomPubNewActivity', array($activity, $this->user, $saved));
365         }
366
367         if (!empty($saved)) {
368             header('HTTP/1.1 201 Created');
369             header("Location: " . common_local_url('ApiStatusesShow', array('id' => $saved->id,
370                                                                             'format' => 'atom')));
371             $this->showSingleAtomStatus($saved);
372         }
373     }
374
375     function postNote($activity)
376     {
377         $note = $activity->objects[0];
378
379         // Use summary as fallback for content
380
381         if (!empty($note->content)) {
382             $sourceContent = $note->content;
383         } else if (!empty($note->summary)) {
384             $sourceContent = $note->summary;
385         } else if (!empty($note->title)) {
386             $sourceContent = $note->title;
387         } else {
388             // @fixme fetch from $sourceUrl?
389             // TRANS: Client error displayed when posting a notice without content through the API.
390             // TRANS: %d is the notice ID (number).
391             $this->clientError(sprintf(_('No content for notice %d.'),
392                                        $note->id));
393             return;
394         }
395
396         // Get (safe!) HTML and text versions of the content
397
398         $rendered = $this->purify($sourceContent);
399         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
400
401         $shortened = $this->auth_user->shortenLinks($content);
402
403         $options = array('is_local' => Notice::LOCAL_PUBLIC,
404                          'rendered' => $rendered,
405                          'replies' => array(),
406                          'groups' => array(),
407                          'tags' => array(),
408                          'urls' => array());
409
410         // accept remote URI (not necessarily a good idea)
411
412         common_debug("Note ID is {$note->id}");
413
414         if (!empty($note->id)) {
415             $notice = Notice::getKV('uri', trim($note->id));
416
417             if (!empty($notice)) {
418                 // TRANS: Client error displayed when using another format than AtomPub.
419                 // TRANS: %s is the notice URI.
420                 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'),
421                                            $note->id));
422                 return;
423             }
424             common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
425             $options['uri'] = $note->id;
426         }
427
428         // accept remote create time (also maybe not such a good idea)
429
430         if (!empty($activity->time)) {
431             common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
432             $options['created'] = common_sql_date($activity->time);
433         }
434
435         // Check for optional attributes...
436
437         if (!empty($activity->context)) {
438
439             foreach ($activity->context->attention as $uri) {
440
441                 $profile = Profile::fromURI($uri);
442
443                 if (!empty($profile)) {
444                     $options['replies'][] = $uri;
445                 } else {
446                     $group = User_group::getKV('uri', $uri);
447                     if (!empty($group)) {
448                         $options['groups'][] = $group->id;
449                     } else {
450                         // @fixme: hook for discovery here
451                         common_log(LOG_WARNING, sprintf('AtomPub post with unknown attention URI %s', $uri));
452                     }
453                 }
454             }
455
456             // Maintain direct reply associations
457             // @fixme what about conversation ID?
458
459             if (!empty($activity->context->replyToID)) {
460                 $orig = Notice::getKV('uri',
461                                           $activity->context->replyToID);
462                 if (!empty($orig)) {
463                     $options['reply_to'] = $orig->id;
464                 }
465             }
466
467             $location = $activity->context->location;
468
469             if ($location) {
470                 $options['lat'] = $location->lat;
471                 $options['lon'] = $location->lon;
472                 if ($location->location_id) {
473                     $options['location_ns'] = $location->location_ns;
474                     $options['location_id'] = $location->location_id;
475                 }
476             }
477         }
478
479         // Atom categories <-> hashtags
480
481         foreach ($activity->categories as $cat) {
482             if ($cat->term) {
483                 $term = common_canonical_tag($cat->term);
484                 if ($term) {
485                     $options['tags'][] = $term;
486                 }
487             }
488         }
489
490         // Atom enclosures -> attachment URLs
491         foreach ($activity->enclosures as $href) {
492             // @fixme save these locally or....?
493             $options['urls'][] = $href;
494         }
495
496         $saved = Notice::saveNew($this->user->id,
497                                  $content,
498                                  'atompub', // TODO: deal with this
499                                  $options);
500
501         return $saved;
502     }
503
504     function purify($content)
505     {
506         require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
507
508         $config = array('safe' => 1,
509                         'deny_attribute' => 'id,style,on*');
510         return htmLawed($content, $config);
511     }
512 }