]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apitimelineuser.php
allow posting to user timeline using AtomPub
[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             $atom->addEntryFromNotices($this->notices);
161             $this->raw($atom->getString());
162
163             break;
164         case 'json':
165             $this->showJsonTimeline($this->notices);
166             break;
167         default:
168             $this->clientError(_('API method not found.'), $code = 404);
169             break;
170         }
171
172     }
173
174     /**
175      * Get notices
176      *
177      * @return array notices
178      */
179
180     function getNotices()
181     {
182         $notices = array();
183
184         $notice = $this->user->getNotices(
185                                           ($this->page-1) * $this->count, $this->count,
186                                           $this->since_id, $this->max_id
187                                           );
188
189         while ($notice->fetch()) {
190             $notices[] = clone($notice);
191         }
192
193         return $notices;
194     }
195
196     /**
197      * Is this action read only?
198      *
199      * @param array $args other arguments
200      *
201      * @return boolean true
202      */
203
204     function isReadOnly($args)
205     {
206         return true;
207     }
208
209     /**
210      * When was this feed last modified?
211      *
212      * @return string datestamp of the latest notice in the stream
213      */
214
215     function lastModified()
216     {
217         if (!empty($this->notices) && (count($this->notices) > 0)) {
218             return strtotime($this->notices[0]->created);
219         }
220
221         return null;
222     }
223
224     /**
225      * An entity tag for this stream
226      *
227      * Returns an Etag based on the action name, language, user ID, and
228      * timestamps of the first and last notice in the timeline
229      *
230      * @return string etag
231      */
232
233     function etag()
234     {
235         if (!empty($this->notices) && (count($this->notices) > 0)) {
236
237             $last = count($this->notices) - 1;
238
239             return '"' . implode(
240                                  ':',
241                                  array($this->arg('action'),
242                                        common_user_cache_hash($this->auth_user),
243                                        common_language(),
244                                        $this->user->id,
245                                        strtotime($this->notices[0]->created),
246                                        strtotime($this->notices[$last]->created))
247                                  )
248               . '"';
249         }
250
251         return null;
252     }
253
254     function handlePost()
255     {
256         if (empty($this->auth_user) ||
257             $this->auth_user->id != $this->user->id) {
258             $this->clientError(_("Only the user can add to their own timeline."));
259             return;
260         }
261
262         if ($this->format != 'atom') {
263             // Only handle posts for Atom
264             $this->clientError(_("Only accept AtomPub for atom feeds."));
265             return;
266         }
267
268         $xml = file_get_contents('php://input');
269
270         $dom = DOMDocument::loadXML($xml);
271
272         if ($dom->documentElement->namespaceURI != Activity::ATOM ||
273             $dom->documentElement->localName != 'entry') {
274             $this->clientError(_('Atom post must be an Atom entry.'));
275             return;
276         }
277
278         $activity = new Activity($dom->documentElement);
279
280         if ($activity->verb != ActivityVerb::POST) {
281             $this->clientError(_('Can only handle post activities.'));
282             return;
283         }
284
285         $note = $activity->objects[0];
286
287         if (!in_array($note->type, array(ActivityObject::NOTE,
288                                          ActivityObject::BLOGENTRY,
289                                          ActivityObject::STATUS))) {
290             $this->clientError(sprintf(_('Cannot handle activity object type "%s"',
291                                          $note->type)));
292             return;
293         }
294
295         // Use summary as fallback for content
296
297         if (!empty($note->content)) {
298             $sourceContent = $note->content;
299         } else if (!empty($note->summary)) {
300             $sourceContent = $note->summary;
301         } else if (!empty($note->title)) {
302             $sourceContent = $note->title;
303         } else {
304             // @fixme fetch from $sourceUrl?
305             // @todo i18n FIXME: use sprintf and add i18n.
306             $this->clientError("No content for notice {$note->id}.");
307             return;
308         }
309
310         // Get (safe!) HTML and text versions of the content
311
312         $rendered = $this->purify($sourceContent);
313         $content = html_entity_decode(strip_tags($rendered), ENT_QUOTES, 'UTF-8');
314
315         $shortened = common_shorten_links($content);
316
317         $options = array('is_local' => Notice::LOCAL_PUBLIC,
318                          'rendered' => $rendered,
319                          'replies' => array(),
320                          'groups' => array(),
321                          'tags' => array(),
322                          'urls' => array());
323
324         // accept remote URI (not necessarily a good idea)
325
326         common_debug("Note ID is {$note->id}");
327
328         if (!empty($note->id)) {
329             $notice = Notice::staticGet('uri', trim($note->id));
330
331             if (!empty($notice)) {
332                 $this->clientError(sprintf(_('Notice with URI "%s" already exists.'),
333                                            $note->id));
334                 return;
335             }
336             common_log(LOG_NOTICE, "Saving client-supplied notice URI '$note->id'");
337             $options['uri'] = $note->id;
338         }
339
340         // accept remote create time (also maybe not such a good idea)
341
342         if (!empty($activity->time)) {
343             common_log(LOG_NOTICE, "Saving client-supplied create time {$activity->time}");
344             $options['created'] = common_sql_date($activity->time);
345         }
346
347         // Check for optional attributes...
348
349         if (!empty($activity->context)) {
350
351             foreach ($activity->context->attention as $uri) {
352
353                 $profile = Profile::fromURI($uri);
354
355                 if (!empty($profile)) {
356                     $options['replies'] = $uri;
357                 } else {
358                     $group = User_group::staticGet('uri', $uri);
359                     if (!empty($group)) {
360                         $options['groups'] = $uri;
361                     } else {
362                         // @fixme: hook for discovery here
363                         common_log(LOG_WARNING, sprintf(_('AtomPub post with unknown attention URI %s'), $uri));
364                     }
365                 }
366             }
367
368             // Maintain direct reply associations
369             // @fixme what about conversation ID?
370
371             if (!empty($activity->context->replyToID)) {
372                 $orig = Notice::staticGet('uri',
373                                           $activity->context->replyToID);
374                 if (!empty($orig)) {
375                     $options['reply_to'] = $orig->id;
376                 }
377             }
378
379             $location = $activity->context->location;
380
381             if ($location) {
382                 $options['lat'] = $location->lat;
383                 $options['lon'] = $location->lon;
384                 if ($location->location_id) {
385                     $options['location_ns'] = $location->location_ns;
386                     $options['location_id'] = $location->location_id;
387                 }
388             }
389         }
390
391         // Atom categories <-> hashtags
392
393         foreach ($activity->categories as $cat) {
394             if ($cat->term) {
395                 $term = common_canonical_tag($cat->term);
396                 if ($term) {
397                     $options['tags'][] = $term;
398                 }
399             }
400         }
401
402         // Atom enclosures -> attachment URLs
403         foreach ($activity->enclosures as $href) {
404             // @fixme save these locally or....?
405             $options['urls'][] = $href;
406         }
407
408         $saved = Notice::saveNew($this->user->id,
409                                  $content,
410                                  'atompub', // TODO: deal with this
411                                  $options);
412
413         if (!empty($saved)) {
414             header("Location: " . common_local_url('ApiStatusesShow', array('notice_id' => $saved->id,
415                                                                             'format' => 'atom')));
416             $this->showSingleAtomStatus($saved);
417         }
418     }
419
420     function purify($content)
421     {
422         require_once INSTALLDIR.'/extlib/htmLawed/htmLawed.php';
423
424         $config = array('safe' => 1,
425                         'deny_attribute' => 'id,style,on*');
426         return htmLawed($content, $config);
427     }
428 }