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