apimediaupload.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196
  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. if (!defined('GNUSOCIAL')) { exit(1); }
  29. /**
  30. * Upload an image via the API. Returns a shortened URL for the image
  31. * to the user. Apparently modelled after a former Twitpic API.
  32. *
  33. * @category API
  34. * @package StatusNet
  35. * @author Zach Copley <zach@status.net>
  36. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  37. * @link http://status.net/
  38. */
  39. class ApiMediaUploadAction extends ApiAuthAction
  40. {
  41. protected $needPost = true;
  42. protected function prepare(array $args=array())
  43. {
  44. parent::prepare($args);
  45. // fallback to xml for older clients etc
  46. if (empty($this->format)) {
  47. $this->format = 'xml';
  48. }
  49. if (!in_array($this->format, ['json', 'xml'])) {
  50. throw new ClientException('This API call does not support the format '._ve($this->format));
  51. }
  52. return true;
  53. }
  54. protected function handle()
  55. {
  56. parent::handle();
  57. // Workaround for PHP returning empty $_POST and $_FILES when POST
  58. // length > post_max_size in php.ini
  59. if (empty($_FILES)
  60. && empty($_POST)
  61. && ($_SERVER['CONTENT_LENGTH'] > 0)
  62. ) {
  63. // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
  64. // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
  65. $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
  66. 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
  67. intval($_SERVER['CONTENT_LENGTH']));
  68. throw new ClientException(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
  69. }
  70. try {
  71. $upload = MediaFile::fromUpload('media', $this->scoped);
  72. } catch (NoUploadedMediaException $e) {
  73. common_debug('No media file was uploaded to the _FILES array');
  74. $fh = tmpfile();
  75. if ($this->arg('media')) {
  76. common_debug('Found media parameter which we hope contains a media file!');
  77. fwrite($fh, $this->arg('media'));
  78. } elseif ($this->arg('media_data')) {
  79. common_debug('Found media_data parameter which we hope contains a base64-encoded media file!');
  80. fwrite($fh, base64_decode($this->arg('media_data')));
  81. } else {
  82. common_debug('No media|media_data POST parameter was supplied');
  83. fclose($fh);
  84. throw $e;
  85. }
  86. common_debug('MediaFile importing the uploaded file with fromFilehandle');
  87. $upload = MediaFile::fromFilehandle($fh, $this->scoped);
  88. }
  89. common_debug('MediaFile completed and saved us fileRecord with id=='._ve($upload->fileRecord->id));
  90. // Thumbnails will be generated/cached on demand when accessed (such as with /attachment/:id/thumbnail)
  91. $this->showResponse($upload);
  92. }
  93. /**
  94. * Show a Twitpic-like response with the ID of the media file
  95. * and a (hopefully) shortened URL for it.
  96. *
  97. * @param MediaFile $upload the uploaded file
  98. *
  99. * @return void
  100. */
  101. protected function showResponse(MediaFile $upload)
  102. {
  103. $this->initDocument($this->format);
  104. switch ($this->format) {
  105. case 'json':
  106. return $this->showResponseJson($upload);
  107. case 'xml':
  108. return $this->showResponseXml($upload);
  109. default:
  110. throw new ClientException('This API call does not support the format '._ve($this->format));
  111. }
  112. $this->endDocument($this->format);
  113. }
  114. protected function showResponseJson(MediaFile $upload)
  115. {
  116. $enc = $upload->fileRecord->getEnclosure();
  117. // note that we use media_id instead of mediaid which XML users might've gotten used to (nowadays we service media_id in both!)
  118. $output = [
  119. 'media_id' => $upload->fileRecord->id,
  120. 'media_id_string' => (string)$upload->fileRecord->id,
  121. 'media_url' => $upload->shortUrl(),
  122. 'size' => $upload->fileRecord->size,
  123. ];
  124. if (common_get_mime_media($enc->mimetype) === 'image') {
  125. $output['image'] = [
  126. 'w' => $enc->width,
  127. 'h' => $enc->height,
  128. 'image_type' => $enc->mimetype,
  129. ];
  130. }
  131. print json_encode($output);
  132. }
  133. protected function showResponseXml(MediaFile $upload)
  134. {
  135. $this->elementStart('rsp', array('stat' => 'ok', 'xmlns:atom'=>Activity::ATOM));
  136. $this->element('mediaid', null, $upload->fileRecord->id);
  137. $this->element('mediaurl', null, $upload->shortUrl());
  138. $this->element('media_url', null, $upload->shortUrl());
  139. $this->element('size', null, $upload->fileRecord->size);
  140. $enclosure = $upload->fileRecord->getEnclosure();
  141. $this->element('atom:link', array('rel' => 'enclosure',
  142. 'href' => $enclosure->url,
  143. 'type' => $enclosure->mimetype));
  144. // Twitter specific metadata expected in response since Twitter's Media upload API v1.1 (even though Twitter doesn't use XML)
  145. $this->element('media_id', null, $upload->fileRecord->id);
  146. $this->element('media_id_string', null, (string)$upload->fileRecord->id);
  147. if (common_get_mime_media($enclosure->mimetype) === 'image') {
  148. $this->element('image', ['w'=>$enclosure->width, 'h'=>$enclosure->height, 'image_type'=>$enclosure->mimetype]);
  149. }
  150. $this->elementEnd('rsp');
  151. }
  152. /**
  153. * Overrided clientError to show a more Twitpic-like error
  154. *
  155. * @param String $msg an error message
  156. */
  157. function clientError($msg, $code=400, $format=null)
  158. {
  159. $this->initDocument($this->format);
  160. switch ($this->format) {
  161. case 'json':
  162. $error = ['errors' => array()];
  163. $error['errors'][] = ['message'=>$msg, 'code'=>131];
  164. print json_encode($error);
  165. break;
  166. case 'xml':
  167. $this->elementStart('rsp', array('stat' => 'fail'));
  168. // @todo add in error code
  169. $errAttr = array('msg' => $msg);
  170. $this->element('err', $errAttr, null);
  171. $this->elementEnd('rsp');
  172. break;
  173. }
  174. $this->endDocument($this->format);
  175. exit;
  176. }
  177. }