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