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