]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apistatusesupdate.php
Fix OpenID discovery in pages using uppercase <HEAD> tag
[quix0rs-gnu-social.git] / actions / apistatusesupdate.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Post a notice (update your status) through the API
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    Tom Blankenship <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-2010 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 /* External API usage documentation. Please update when you change how this method works. */
38
39 /*! @page statusesupdate statuses/update
40
41     @section Description
42     Updates the authenticating user's status. Requires the status parameter specified below.
43     Request must be a POST.
44
45     @par URL pattern
46     /api/statuses/update.:format
47
48     @par Formats (:format)
49     xml, json
50
51     @par HTTP Method(s)
52     POST
53
54     @par Requires Authentication
55     Yes
56
57     @param status (Required) The URL-encoded text of the status update.
58     @param source (Optional) The source application name, if using HTTP authentication or an anonymous OAuth consumer.
59     @param in_reply_to_status_id (Optional) The ID of an existing status that the update is in reply to.
60     @param lat (Optional) The latitude the status refers to.
61     @param long (Optional) The longitude the status refers to.
62     @param media (Optional) a media upload, such as an image or movie file.
63
64     @sa @ref authentication
65     @sa @ref apiroot
66
67     @subsection usagenotes Usage notes
68
69     @li The URL pattern is relative to the @ref apiroot.
70     @li If the @e source parameter is not supplied the source of the status will default to 'api'. When authenticated via a registered OAuth application, the application's registered name and URL will always override the source parameter.
71     @li The XML response uses <a href="http://georss.org/Main_Page">GeoRSS</a>
72     to encode the latitude and longitude (see example response below <georss:point>).
73     @li Data uploaded via the @e media parameter should be multipart/form-data encoded.
74
75     @subsection exampleusage Example usage
76
77     @verbatim
78     curl -u username:password http://example.com/api/statuses/update.xml -d status='Howdy!' -d lat='30.468' -d long='-94.743'
79     @endverbatim
80
81     @subsection exampleresponse Example response
82
83     @verbatim
84     <?xml version="1.0" encoding="UTF-8"?>
85     <status>
86       <text>Howdy!</text>
87       <truncated>false</truncated>
88       <created_at>Tue Mar 30 23:28:05 +0000 2010</created_at>
89       <in_reply_to_status_id/>
90       <source>api</source>
91       <id>26668724</id>
92       <in_reply_to_user_id/>
93       <in_reply_to_screen_name/>
94       <geo xmlns:georss="http://www.georss.org/georss">
95         <georss:point>30.468 -94.743</georss:point>
96       </geo>
97       <favorited>false</favorited>
98       <user>
99         <id>25803</id>
100         <name>Jed Sanders</name>
101         <screen_name>jedsanders</screen_name>
102         <location>Hoop and Holler, Texas</location>
103         <description>I like to think of myself as America's Favorite.</description>
104         <profile_image_url>http://avatar.example.com/25803-48-20080924200604.png</profile_image_url>
105         <url>http://jedsanders.net</url>
106         <protected>false</protected>
107         <followers_count>5</followers_count>
108         <profile_background_color/>
109         <profile_text_color/>
110         <profile_link_color/>
111         <profile_sidebar_fill_color/>
112         <profile_sidebar_border_color/>
113         <friends_count>2</friends_count>
114         <created_at>Wed Sep 24 20:04:00 +0000 2008</created_at>
115         <favourites_count>0</favourites_count>
116         <utc_offset>0</utc_offset>
117         <time_zone>UTC</time_zone>
118         <profile_background_image_url/>
119         <profile_background_tile>false</profile_background_tile>
120         <statuses_count>70</statuses_count>
121         <following>true</following>
122         <notifications>true</notifications>
123       </user>
124     </status>
125     @endverbatim
126 */
127
128 if (!defined('STATUSNET')) {
129     exit(1);
130 }
131
132 /**
133  * Updates the authenticating user's status (posts a notice).
134  *
135  * @category API
136  * @package  StatusNet
137  * @author   Craig Andrews <candrews@integralblue.com>
138  * @author   Evan Prodromou <evan@status.net>
139  * @author   Jeffery To <jeffery.to@gmail.com>
140  * @author   Tom Blankenship <mac65@mac65.com>
141  * @author   Mike Cochrane <mikec@mikenz.geek.nz>
142  * @author   Robin Millette <robin@millette.info>
143  * @author   Zach Copley <zach@status.net>
144  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
145  * @link     http://status.net/
146  */
147 class ApiStatusesUpdateAction extends ApiAuthAction
148 {
149     protected $needPost = true;
150
151     var $status                = null;
152     var $in_reply_to_status_id = null;
153     var $lat                   = null;
154     var $lon                   = null;
155     var $media_ids             = array();   // file_id in the keys
156
157     /**
158      * Take arguments for running
159      *
160      * @param array $args $_REQUEST args
161      *
162      * @return boolean success flag
163      */
164     protected function prepare(array $args=array())
165     {
166         parent::prepare($args);
167
168         $this->status = $this->trimmed('status');
169         $this->lat    = $this->trimmed('lat');
170         $this->lon    = $this->trimmed('long');
171         $matches = array();
172         common_debug(get_called_class().': media_ids=='._ve($this->trimmed('media_ids')));
173         if (preg_match_all('/\d+/', $this->trimmed('media_ids'), $matches) !== false) {
174             foreach (array_unique($matches[0]) as $match) {
175                 try {
176                     $this->media_ids[$match] = File::getByID($match);
177                 } catch (EmptyIdException $e) {
178                     // got a zero from the client, at least Twidere does this on occasion
179                 } catch (NoResultException $e) {
180                     // File ID was not found. Do we abort and report to the client?
181                 }
182             }
183         }
184
185         $this->in_reply_to_status_id
186             = intval($this->trimmed('in_reply_to_status_id'));
187
188         return true;
189     }
190
191     /**
192      * Handle the request
193      *
194      * Make a new notice for the update, save it, and show it
195      *
196      * @return void
197      */
198     protected function handle()
199     {
200         parent::handle();
201
202         // Workaround for PHP returning empty $_POST and $_FILES when POST
203         // length > post_max_size in php.ini
204
205         if (empty($_FILES)
206             && empty($_POST)
207             && ($_SERVER['CONTENT_LENGTH'] > 0)
208         ) {
209              // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
210              // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
211              $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
212                       'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
213                       intval($_SERVER['CONTENT_LENGTH']));
214
215             $this->clientError(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
216         }
217
218         if (empty($this->status)) {
219             // TRANS: Client error displayed when the parameter "status" is missing.
220             $this->clientError(_('Client must provide a \'status\' parameter with a value.'));
221         }
222
223         if (is_null($this->scoped)) {
224             // TRANS: Client error displayed when updating a status for a non-existing user.
225             $this->clientError(_('No such user.'), 404);
226         }
227
228         /* Do not call shortenLinks until the whole notice has been build */
229
230         // Check for commands
231
232         $inter = new CommandInterpreter();
233         $cmd = $inter->handle_command($this->auth_user, $this->status);
234
235         if ($cmd) {
236             if ($this->supported($cmd)) {
237                 $cmd->execute(new Channel());
238             }
239
240             // Cmd not supported?  Twitter just returns your latest status.
241             // And, it returns your last status whether the cmd was successful
242             // or not!
243
244             $this->notice = $this->auth_user->getCurrentNotice();
245         } else {
246             $reply_to = null;
247
248             if (!empty($this->in_reply_to_status_id)) {
249                 // Check whether notice actually exists
250
251                 $reply = Notice::getKV($this->in_reply_to_status_id);
252
253                 if ($reply) {
254                     $reply_to = $this->in_reply_to_status_id;
255                 } else {
256                     // TRANS: Client error displayed when replying to a non-existing notice.
257                     $this->clientError(_('Parent notice not found.'), 404);
258                 }
259             }
260
261             foreach(array_keys($this->media_ids) as $media_id) {
262                 // FIXME: Validation on this... Worst case is that if someone sends bad media_ids then
263                 // we'll fill the notice with non-working links, so no real harm, done, but let's fix.
264                 // The File objects are in the array, so we could get URLs from them directly.
265                 $this->status .= ' ' . common_local_url('attachment', array('attachment' => $media_id));
266             }
267
268             $upload = null;
269             try {
270                 $upload = MediaFile::fromUpload('media', $this->scoped);
271                 $this->status .= ' ' . $upload->shortUrl();
272                 /* Do not call shortenLinks until the whole notice has been build */
273             } catch (NoUploadedMediaException $e) {
274                 // There was no uploaded media for us today.
275             }
276
277             /* Do call shortenlinks here & check notice length since notice is about to be saved & sent */
278             $status_shortened = $this->auth_user->shortenLinks($this->status);
279
280             if (Notice::contentTooLong($status_shortened)) {
281                 if ($upload instanceof MediaFile) {
282                     $upload->delete();
283                 }
284                 // TRANS: Client error displayed exceeding the maximum notice length.
285                 // TRANS: %d is the maximum lenth for a notice.
286                 $msg = _m('Maximum notice size is %d character, including attachment URL.',
287                           'Maximum notice size is %d characters, including attachment URL.',
288                           Notice::maxContent());
289                 /* Use HTTP 413 error code (Request Entity Too Large)
290                  * instead of basic 400 for better understanding
291                  */
292                 $this->clientError(sprintf($msg, Notice::maxContent()), 413);
293             }
294
295
296             $content = html_entity_decode($status_shortened, ENT_NOQUOTES, 'UTF-8');
297
298             $options = array('reply_to' => $reply_to);
299
300             if ($this->scoped->shareLocation()) {
301
302                 $locOptions = Notice::locationOptions($this->lat,
303                                                       $this->lon,
304                                                       null,
305                                                       null,
306                                                       $this->scoped);
307
308                 $options = array_merge($options, $locOptions);
309             }
310
311             try {
312                 $this->notice = Notice::saveNew(
313                     $this->scoped->id,
314                     $content,
315                     $this->source,
316                     $options
317                 );
318             } catch (Exception $e) {
319                 $this->clientError($e->getMessage(), $e->getCode());
320             }
321
322             if (isset($upload)) {
323                 $upload->attachToNotice($this->notice);
324             }
325         }
326
327         $this->showNotice();
328     }
329
330     /**
331      * Show the resulting notice
332      *
333      * @return void
334      */
335     function showNotice()
336     {
337         if (!empty($this->notice)) {
338             if ($this->format == 'xml') {
339                 $this->showSingleXmlStatus($this->notice);
340             } elseif ($this->format == 'json') {
341                 $this->show_single_json_status($this->notice);
342             }
343         }
344     }
345
346     /**
347      * Is this command supported when doing an update from the API?
348      *
349      * @param string $cmd the command to check for
350      *
351      * @return boolean true or false
352      */
353     function supported($cmd)
354     {
355         static $cmdlist = array('SubCommand', 'UnsubCommand',
356             'OnCommand', 'OffCommand', 'JoinCommand', 'LeaveCommand');
357
358         $supported = null;
359
360         if (Event::handle('CommandSupportedAPI', array($cmd, &$supported))) {
361             $supported = $supported || in_array(get_class($cmd), $cmdlist);
362         }
363
364         return $supported;
365     }
366 }