]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/apimediaupload.php
Handle selfLink in ActivityObject
[quix0rs-gnu-social.git] / actions / apimediaupload.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Upload an image via 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  * @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/
27  */
28
29 if (!defined('GNUSOCIAL')) { exit(1); }
30
31 /**
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.
34  *
35  * @category API
36  * @package  StatusNet
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/
40  */
41 class ApiMediaUploadAction extends ApiAuthAction
42 {
43     protected $needPost = true;
44
45     protected function prepare(array $args=array())
46     {
47         parent::prepare($args);
48
49         // fallback to xml for older clients etc
50         if (empty($this->format)) {
51             $this->format = 'xml';
52         }
53         if (!in_array($this->format, ['json', 'xml'])) {
54             throw new ClientException('This API call does not support the format '._ve($this->format));
55         }
56         return true;
57     }
58
59     protected function handle()
60     {
61         parent::handle();
62
63         // Workaround for PHP returning empty $_POST and $_FILES when POST
64         // length > post_max_size in php.ini
65
66         if (empty($_FILES)
67             && empty($_POST)
68             && ($_SERVER['CONTENT_LENGTH'] > 0)
69         ) {
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']));
76         }
77
78         try {
79             $upload = MediaFile::fromUpload('media', $this->scoped);
80         } catch (NoUploadedMediaException $e) {
81             common_debug('No media file was uploaded to the _FILES array');
82             $fh = tmpfile();
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')));
89             } else {
90                 common_debug('No media|media_data POST parameter was supplied');
91                 fclose($fh);
92                 throw $e;
93             }
94             common_debug('MediaFile importing the uploaded file with fromFilehandle');
95             $upload = MediaFile::fromFilehandle($fh, $this->scoped);
96         }
97         
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);
101     }
102
103     /**
104      * Show a Twitpic-like response with the ID of the media file
105      * and a (hopefully) shortened URL for it.
106      *
107      * @param MediaFile $upload  the uploaded file
108      *
109      * @return void
110      */
111     protected function showResponse(MediaFile $upload)
112     {
113         $this->initDocument($this->format);
114         switch ($this->format) {
115         case 'json':
116             return $this->showResponseJson($upload);
117         case 'xml':
118             return $this->showResponseXml($upload);
119         default:
120             throw new ClientException('This API call does not support the format '._ve($this->format));
121         }
122         $this->endDocument($this->format);
123     }
124
125     protected function showResponseJson(MediaFile $upload)
126     {
127         $enc = $upload->fileRecord->getEnclosure();
128
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!)
130         $output = [
131                 'media_id' => $upload->fileRecord->id,
132                 'media_id_string' => (string)$upload->fileRecord->id,
133                 'media_url' => $upload->shortUrl(),
134                 'size' => $upload->fileRecord->size,
135                 ];
136         if (common_get_mime_media($enc->mimetype) === 'image') {
137             $output['image'] = [
138                                 'w' => $enc->width,
139                                 'h' => $enc->height,
140                                 'image_type' => $enc->mimetype,
141                                 ];
142         }
143         print json_encode($output);
144     }
145
146     protected function showResponseXml(MediaFile $upload)
147     {
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);
153
154         $enclosure = $upload->fileRecord->getEnclosure();
155         $this->element('atom:link', array('rel'  => 'enclosure',
156                                           'href' => $enclosure->url,
157                                           'type' => $enclosure->mimetype));
158
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]);
164         }
165         $this->elementEnd('rsp');
166     }
167
168     /**
169      * Overrided clientError to show a more Twitpic-like error
170      *
171      * @param String $msg an error message
172      */
173     function clientError($msg, $code=400, $format=null)
174     {
175         $this->initDocument($this->format);
176         switch ($this->format) {
177         case 'json':
178             $error = ['errors' => array()];
179             $error['errors'][] = ['message'=>$msg, 'code'=>131];
180             print json_encode($error);
181             break;
182         case 'xml':
183             $this->elementStart('rsp', array('stat' => 'fail'));
184
185             // @todo add in error code
186             $errAttr = array('msg' => $msg);
187
188             $this->element('err', $errAttr, null);
189             $this->elementEnd('rsp');
190             break;
191         }
192         $this->endDocument($this->format);
193         exit;
194     }
195 }