3 * StatusNet, the distributed open-source microblogging tool
5 * Upload an image via the API
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.
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.
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/>.
23 * @author Zach Copley <zach@status.net>
24 * @copyright 2010 StatusNet, Inc.
25 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
26 * @link http://status.net/
29 if (!defined('GNUSOCIAL')) { exit(1); }
32 * Upload an image via the API. Returns a shortened URL for the image
33 * to the user. Apparently modelled after a former Twitpic API.
37 * @author Zach Copley <zach@status.net>
38 * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
39 * @link http://status.net/
41 class ApiMediaUploadAction extends ApiAuthAction
43 protected $needPost = true;
45 protected function prepare(array $args=array())
47 parent::prepare($args);
49 // fallback to xml for older clients etc
50 if (empty($this->format)) {
51 $this->format = 'xml';
53 if (!in_array($this->format, ['json', 'xml'])) {
54 throw new ClientException('This API call does not support the format '._ve($this->format));
59 protected function handle()
63 // Workaround for PHP returning empty $_POST and $_FILES when POST
64 // length > post_max_size in php.ini
68 && ($_SERVER['CONTENT_LENGTH'] > 0)
70 // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
71 // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
72 $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
73 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
74 intval($_SERVER['CONTENT_LENGTH']));
75 throw new ClientException(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
79 $upload = MediaFile::fromUpload('media', $this->scoped);
80 } catch (NoUploadedMediaException $e) {
81 common_debug('No media file was uploaded to the _FILES array');
83 if ($this->arg('media')) {
84 common_debug('Found media parameter which we hope contains a media file!');
85 fwrite($fh, $this->arg('media'));
86 } elseif ($this->arg('media_data')) {
87 common_debug('Found media_data parameter which we hope contains a base64-encoded media file!');
88 fwrite($fh, base64_decode($this->arg('media_data')));
90 common_debug('No media|media_data POST parameter was supplied');
94 common_debug('MediaFile importing the uploaded file with fromFilehandle');
95 $upload = MediaFile::fromFilehandle($fh, $this->scoped);
98 common_debug('MediaFile completed and saved us fileRecord with id=='._ve($upload->fileRecord->id));
99 // Thumbnails will be generated/cached on demand when accessed (such as with /attachment/:id/thumbnail)
100 $this->showResponse($upload);
104 * Show a Twitpic-like response with the ID of the media file
105 * and a (hopefully) shortened URL for it.
107 * @param MediaFile $upload the uploaded file
111 protected function showResponse(MediaFile $upload)
113 $this->initDocument($this->format);
114 switch ($this->format) {
116 return $this->showResponseJson($upload);
118 return $this->showResponseXml($upload);
120 throw new ClientException('This API call does not support the format '._ve($this->format));
122 $this->endDocument($this->format);
125 protected function showResponseJson(MediaFile $upload)
127 $enc = $upload->fileRecord->getEnclosure();
129 // note that we use media_id instead of mediaid which XML users might've gotten used to (nowadays we service media_id in both!)
131 'media_id' => $upload->fileRecord->id,
132 'media_id_string' => (string)$upload->fileRecord->id,
133 'media_url' => $upload->shortUrl(),
134 'size' => $upload->fileRecord->size,
136 if (common_get_mime_media($enc->mimetype) === 'image') {
140 'image_type' => $enc->mimetype,
143 print json_encode($output);
146 protected function showResponseXml(MediaFile $upload)
148 $this->elementStart('rsp', array('stat' => 'ok', 'xmlns:atom'=>Activity::ATOM));
149 $this->element('mediaid', null, $upload->fileRecord->id);
150 $this->element('mediaurl', null, $upload->shortUrl());
151 $this->element('media_url', null, $upload->shortUrl());
152 $this->element('size', null, $upload->fileRecord->size);
154 $enclosure = $upload->fileRecord->getEnclosure();
155 $this->element('atom:link', array('rel' => 'enclosure',
156 'href' => $enclosure->url,
157 'type' => $enclosure->mimetype));
159 // Twitter specific metadata expected in response since Twitter's Media upload API v1.1 (even though Twitter doesn't use XML)
160 $this->element('media_id', null, $upload->fileRecord->id);
161 $this->element('media_id_string', null, (string)$upload->fileRecord->id);
162 if (common_get_mime_media($enclosure->mimetype) === 'image') {
163 $this->element('image', ['w'=>$enclosure->width, 'h'=>$enclosure->height, 'image_type'=>$enclosure->mimetype]);
165 $this->elementEnd('rsp');
169 * Overrided clientError to show a more Twitpic-like error
171 * @param String $msg an error message
173 function clientError($msg, $code=400, $format=null)
175 $this->initDocument($this->format);
176 switch ($this->format) {
178 $error = ['errors' => array()];
179 $error['errors'][] = ['message'=>$msg, 'code'=>131];
180 print json_encode($error);
183 $this->elementStart('rsp', array('stat' => 'fail'));
185 // @todo add in error code
186 $errAttr = array('msg' => $msg);
188 $this->element('err', $errAttr, null);
189 $this->elementEnd('rsp');
192 $this->endDocument($this->format);