apimediaupload.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. <?php
  2. // This file is part of GNU social - https://www.gnu.org/software/social
  3. //
  4. // GNU social is free software: you can redistribute it and/or modify
  5. // it under the terms of the GNU Affero General Public License as published by
  6. // the Free Software Foundation, either version 3 of the License, or
  7. // (at your option) any later version.
  8. //
  9. // GNU social is distributed in the hope that it will be useful,
  10. // but WITHOUT ANY WARRANTY; without even the implied warranty of
  11. // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  12. // GNU Affero General Public License for more details.
  13. //
  14. // You should have received a copy of the GNU Affero General Public License
  15. // along with GNU social. If not, see <http://www.gnu.org/licenses/>.
  16. /**
  17. * Upload an image via the API
  18. *
  19. * @category API
  20. * @author Zach Copley <zach@status.net>
  21. * @copyright 2010 StatusNet, Inc.
  22. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  23. */
  24. defined('GNUSOCIAL') || die();
  25. /**
  26. * Upload an image via the API. Returns a shortened URL for the image
  27. * to the user. Apparently modelled after a former Twitpic API.
  28. *
  29. * @category API
  30. * @package GNUsocial
  31. * @author Zach Copley <zach@status.net>
  32. * @license https://www.gnu.org/licenses/agpl.html GNU AGPL v3 or later
  33. */
  34. class ApiMediaUploadAction extends ApiAuthAction
  35. {
  36. protected $needPost = true;
  37. protected function prepare(array $args = [])
  38. {
  39. parent::prepare($args);
  40. // fallback to xml for older clients etc
  41. if (empty($this->format)) {
  42. $this->format = 'xml';
  43. }
  44. if (!in_array($this->format, ['json', 'xml'])) {
  45. throw new ClientException('This API call does not support the format '._ve($this->format));
  46. }
  47. return true;
  48. }
  49. protected function handle()
  50. {
  51. parent::handle();
  52. // Workaround for PHP returning empty $_POST and $_FILES when POST
  53. // length > post_max_size in php.ini
  54. if (empty($_FILES)
  55. && empty($_POST)
  56. && ($_SERVER['CONTENT_LENGTH'] > 0)
  57. ) {
  58. // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
  59. // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
  60. $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
  61. 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
  62. intval($_SERVER['CONTENT_LENGTH']));
  63. throw new ClientException(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
  64. }
  65. try {
  66. $upload = MediaFile::fromUpload('media', $this->scoped);
  67. } catch (NoUploadedMediaException $e) {
  68. common_debug('No media file was uploaded to the _FILES array');
  69. $tempfile = new TemporaryFile('gs-mediaupload');
  70. if ($this->arg('media')) {
  71. common_debug('Found media parameter which we hope contains a media file!');
  72. fwrite($tempfile->getResource(), $this->arg('media'));
  73. } elseif ($this->arg('media_data')) {
  74. common_debug('Found media_data parameter which we hope contains a base64-encoded media file!');
  75. fwrite($tempfile->getResource(), base64_decode($this->arg('media_data')));
  76. } else {
  77. common_debug('No media|media_data POST parameter was supplied');
  78. unset($tempfile);
  79. throw $e;
  80. }
  81. common_debug('MediaFile importing the uploaded file with fromFileInfo');
  82. fflush($tempfile->getResource());
  83. $upload = MediaFile::fromFileInfo($tempfile, $this->scoped);
  84. }
  85. common_debug('MediaFile completed and saved us fileRecord with id=='._ve($upload->fileRecord->id));
  86. // Thumbnails will be generated/cached on demand when accessed (such as with /attachment/:id/thumbnail)
  87. $this->showResponse($upload);
  88. }
  89. /**
  90. * Show a Twitpic-like response with the ID of the media file
  91. * and a (hopefully) shortened URL for it.
  92. *
  93. * @param MediaFile $upload the uploaded file
  94. *
  95. * @return void
  96. */
  97. protected function showResponse(MediaFile $upload)
  98. {
  99. $this->initDocument($this->format);
  100. switch ($this->format) {
  101. case 'json':
  102. return $this->showResponseJson($upload);
  103. case 'xml':
  104. return $this->showResponseXml($upload);
  105. default:
  106. throw new ClientException('This API call does not support the format '._ve($this->format));
  107. }
  108. $this->endDocument($this->format);
  109. }
  110. protected function showResponseJson(MediaFile $upload)
  111. {
  112. $enc = $upload->fileRecord->getEnclosure();
  113. // note that we use media_id instead of mediaid which XML users might've gotten used to (nowadays we service media_id in both!)
  114. $output = [
  115. 'media_id' => $upload->fileRecord->id,
  116. 'media_id_string' => (string)$upload->fileRecord->id,
  117. 'media_url' => $upload->shortUrl(),
  118. 'size' => $upload->fileRecord->size,
  119. ];
  120. if (common_get_mime_media($enc->mimetype) === 'image') {
  121. $output['image'] = [
  122. 'w' => $enc->width,
  123. 'h' => $enc->height,
  124. 'image_type' => $enc->mimetype,
  125. ];
  126. }
  127. print json_encode($output);
  128. }
  129. protected function showResponseXml(MediaFile $upload)
  130. {
  131. $this->elementStart('rsp', array('stat' => 'ok', 'xmlns:atom'=>Activity::ATOM));
  132. $this->element('mediaid', null, $upload->fileRecord->id);
  133. $this->element('mediaurl', null, $upload->shortUrl());
  134. $this->element('media_url', null, $upload->shortUrl());
  135. $this->element('size', null, $upload->fileRecord->size);
  136. $enclosure = $upload->fileRecord->getEnclosure();
  137. $this->element('atom:link', array('rel' => 'enclosure',
  138. 'href' => $enclosure->url,
  139. 'type' => $enclosure->mimetype));
  140. // Twitter specific metadata expected in response since Twitter's Media upload API v1.1 (even though Twitter doesn't use XML)
  141. $this->element('media_id', null, $upload->fileRecord->id);
  142. $this->element('media_id_string', null, (string)$upload->fileRecord->id);
  143. if (common_get_mime_media($enclosure->mimetype) === 'image') {
  144. $this->element('image', ['w'=>$enclosure->width, 'h'=>$enclosure->height, 'image_type'=>$enclosure->mimetype]);
  145. }
  146. $this->elementEnd('rsp');
  147. }
  148. /**
  149. * Overrided clientError to show a more Twitpic-like error
  150. *
  151. * @param string $msg an error message
  152. */
  153. public function clientError($msg, $code = 400, $format = null)
  154. {
  155. $this->initDocument($this->format);
  156. switch ($this->format) {
  157. case 'json':
  158. $error = ['errors' => array()];
  159. $error['errors'][] = ['message'=>$msg, 'code'=>131];
  160. print json_encode($error);
  161. break;
  162. case 'xml':
  163. $this->elementStart('rsp', array('stat' => 'fail'));
  164. // @todo add in error code
  165. $errAttr = array('msg' => $msg);
  166. $this->element('err', $errAttr, null);
  167. $this->elementEnd('rsp');
  168. break;
  169. }
  170. $this->endDocument($this->format);
  171. exit;
  172. }
  173. }