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