avatarsettings.php 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434
  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 avatar
  18. *
  19. * @category Settings
  20. * @package GNUsocial
  21. *
  22. * @author Evan Prodromou <evan@status.net>
  23. * @author Zach Copley <zach@status.net>
  24. * @author Diogo Cordeiro <diogo@fc.up.pt>
  25. * @copyright 2008-2009, 2020 Free Software Foundation http://fsf.org
  26. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  27. */
  28. defined('GNUSOCIAL') || die;
  29. /**
  30. * Upload an avatar
  31. *
  32. * We use jCrop plugin for jQuery to crop the image after upload.
  33. *
  34. * @category Settings
  35. * @package StatusNet
  36. *
  37. * @author Evan Prodromou <evan@status.net>
  38. * @author Zach Copley <zach@status.net>
  39. * @author Sarven Capadisli <csarven@status.net>
  40. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  41. *
  42. * @see http://status.net/
  43. */
  44. class AvatarsettingsAction extends SettingsAction
  45. {
  46. public $mode;
  47. public $imagefile;
  48. public $filename;
  49. public function prepare(array $args = [])
  50. {
  51. $avatarpath = Avatar::path('');
  52. if (!is_writable($avatarpath)) {
  53. throw new Exception(_m("The administrator of your site needs to
  54. add write permissions on the avatar upload folder before
  55. you're able to set one."));
  56. }
  57. parent::prepare($args);
  58. return true;
  59. }
  60. /**
  61. * Title of the page
  62. *
  63. * @return string Title of the page
  64. * @throws Exception
  65. *
  66. */
  67. public function title()
  68. {
  69. // TRANS: Title for avatar upload page.
  70. return _m('Avatar');
  71. }
  72. /**
  73. * Instructions for use
  74. *
  75. * @return string instructions for use
  76. * @throws Exception
  77. *
  78. */
  79. public function getInstructions()
  80. {
  81. // TRANS: Instruction for avatar upload page.
  82. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  83. return sprintf(
  84. _m('You can upload your personal avatar. The maximum file size is %s.'),
  85. ImageFile::maxFileSize()
  86. );
  87. }
  88. /**
  89. * Content area of the page
  90. *
  91. * Shows a form for uploading an avatar. Currently overrides FormAction's showContent
  92. * since we haven't made classes out of AvatarCropForm and AvatarUploadForm.
  93. *
  94. * @return void
  95. */
  96. public function showContent()
  97. {
  98. if ($this->mode == 'crop') {
  99. $this->showCropForm();
  100. } else {
  101. $this->showUploadForm();
  102. }
  103. }
  104. public function showUploadForm()
  105. {
  106. // If we detect that the user didn't finish setting a new avatar, remove the temporary file.
  107. if (isset($_SESSION['FILEDATA'])) {
  108. @unlink($_SESSION['FILEDATA']['filepath']);
  109. unset($_SESSION['FILEDATA']);
  110. }
  111. $this->elementStart('form', ['enctype' => 'multipart/form-data',
  112. 'method' => 'post',
  113. 'id' => 'form_settings_avatar',
  114. 'class' => 'form_settings',
  115. 'action' => common_local_url('avatarsettings'),]);
  116. $this->elementStart('fieldset');
  117. // TRANS: Avatar upload page form legend.
  118. $this->element('legend', null, _m('Avatar settings'));
  119. $this->hidden('token', common_session_token());
  120. if (Event::handle('StartAvatarFormData', [$this])) {
  121. $this->elementStart('ul', 'form_data');
  122. try {
  123. $original = Avatar::getUploaded($this->scoped);
  124. $this->elementStart('li', ['id' => 'avatar_original',
  125. 'class' => 'avatar_view',]);
  126. // TRANS: Header on avatar upload page for thumbnail of originally uploaded avatar (h2).
  127. $this->element('h2', null, _m('Original'));
  128. $this->elementStart('div', ['id' => 'avatar_original_view']);
  129. $this->element('img', ['src' => $original->displayUrl(),
  130. 'width' => $original->width,
  131. 'height' => $original->height,
  132. 'alt' => $this->scoped->getNickname(),]);
  133. $this->elementEnd('div');
  134. $this->elementEnd('li');
  135. } catch (NoAvatarException $e) {
  136. // No original avatar found!
  137. }
  138. try {
  139. $avatar = $this->scoped->getAvatar(AVATAR_PROFILE_SIZE);
  140. $this->elementStart('li', ['id' => 'avatar_preview',
  141. 'class' => 'avatar_view',]);
  142. // TRANS: Header on avatar upload page for thumbnail of to be used rendition of uploaded avatar (h2).
  143. $this->element('h2', null, _m('Preview'));
  144. $this->elementStart('div', ['id' => 'avatar_preview_view']);
  145. $this->element('img', ['src' => $avatar->displayUrl(),
  146. 'width' => AVATAR_PROFILE_SIZE,
  147. 'height' => AVATAR_PROFILE_SIZE,
  148. 'alt' => $this->scoped->getNickname(),]);
  149. $this->elementEnd('div');
  150. if (!empty($avatar->filename)) {
  151. // TRANS: Button on avatar upload page to delete current avatar.
  152. $this->submit('delete', _m('BUTTON', 'Delete'));
  153. }
  154. $this->elementEnd('li');
  155. } catch (NoAvatarException $e) {
  156. // No previously uploaded avatar to preview.
  157. }
  158. $this->elementStart('li', ['id' => 'settings_attach']);
  159. $this->element('input', ['name' => 'MAX_FILE_SIZE',
  160. 'type' => 'hidden',
  161. 'id' => 'MAX_FILE_SIZE',
  162. 'value' => ImageFile::maxFileSizeInt(),]);
  163. $this->element('input', ['name' => 'avatarfile',
  164. 'type' => 'file',
  165. 'id' => 'avatarfile',]);
  166. $this->elementEnd('li');
  167. $this->elementEnd('ul');
  168. $this->elementStart('ul', 'form_actions');
  169. $this->elementStart('li');
  170. // TRANS: Button on avatar upload page to upload an avatar.
  171. $this->submit('upload', _m('BUTTON', 'Upload'));
  172. $this->elementEnd('li');
  173. $this->elementEnd('ul');
  174. }
  175. Event::handle('EndAvatarFormData', [$this]);
  176. $this->elementEnd('fieldset');
  177. $this->elementEnd('form');
  178. }
  179. public function showCropForm()
  180. {
  181. $this->elementStart('form', ['method' => 'post',
  182. 'id' => 'form_settings_avatar',
  183. 'class' => 'form_settings',
  184. 'action' => common_local_url('avatarsettings'),]);
  185. $this->elementStart('fieldset');
  186. // TRANS: Avatar upload page crop form legend.
  187. $this->element('legend', null, _m('Avatar settings'));
  188. $this->hidden('token', common_session_token());
  189. $this->elementStart('ul', 'form_data');
  190. $this->elementStart(
  191. 'li',
  192. ['id' => 'avatar_original',
  193. 'class' => 'avatar_view',]
  194. );
  195. // TRANS: Header on avatar upload crop form for thumbnail of originally uploaded avatar (h2).
  196. $this->element('h2', null, _m('Original'));
  197. $this->elementStart('div', ['id' => 'avatar_original_view']);
  198. $this->element('img', ['src' => Avatar::url($this->filedata['filename']),
  199. 'width' => $this->filedata['width'],
  200. 'height' => $this->filedata['height'],
  201. 'alt' => $this->scoped->getNickname(),]);
  202. $this->elementEnd('div');
  203. $this->elementEnd('li');
  204. $this->elementStart(
  205. 'li',
  206. ['id' => 'avatar_preview',
  207. 'class' => 'avatar_view',]
  208. );
  209. // TRANS: Header on avatar upload crop form for thumbnail of to be used rendition of uploaded avatar (h2).
  210. $this->element('h2', null, _m('Preview'));
  211. $this->elementStart('div', ['id' => 'avatar_preview_view']);
  212. $this->element('img', ['src' => Avatar::url($this->filedata['filename']),
  213. 'width' => AVATAR_PROFILE_SIZE,
  214. 'height' => AVATAR_PROFILE_SIZE,
  215. 'alt' => $this->scoped->getNickname(),]);
  216. $this->elementEnd('div');
  217. foreach (['avatar_crop_x', 'avatar_crop_y',
  218. 'avatar_crop_w', 'avatar_crop_h',] as $crop_info) {
  219. $this->element('input', ['name' => $crop_info,
  220. 'type' => 'hidden',
  221. 'id' => $crop_info,]);
  222. }
  223. // TRANS: Button on avatar upload crop form to confirm a selected crop as avatar.
  224. $this->submit('crop', _m('BUTTON', 'Crop'));
  225. $this->elementEnd('li');
  226. $this->elementEnd('ul');
  227. $this->elementEnd('fieldset');
  228. $this->elementEnd('form');
  229. }
  230. /**
  231. * @return string
  232. * @throws NoResultException
  233. * @throws NoUploadedMediaException
  234. * @throws ServerException
  235. * @throws UnsupportedMediaException
  236. * @throws UseFileAsThumbnailException
  237. * @throws Exception
  238. *
  239. * @throws ClientException
  240. */
  241. protected function doPost()
  242. {
  243. if (Event::handle('StartAvatarSaveForm', [$this])) {
  244. if ($this->trimmed('upload')) {
  245. return $this->uploadAvatar();
  246. } elseif ($this->trimmed('crop')) {
  247. return $this->cropAvatar();
  248. } elseif ($this->trimmed('delete')) {
  249. return $this->deleteAvatar();
  250. } else {
  251. // TRANS: Unexpected validation error on avatar upload form.
  252. throw new ClientException(_m('Unexpected form submission.'));
  253. }
  254. Event::handle('EndAvatarSaveForm', [$this]);
  255. }
  256. }
  257. /**
  258. * Handle an image upload
  259. *
  260. * Does all the magic for handling an image upload, and crops the
  261. * image by default.
  262. *
  263. * @return string
  264. * @throws NoResultException
  265. * @throws NoUploadedMediaException
  266. * @throws ServerException
  267. * @throws UnsupportedMediaException
  268. * @throws UseFileAsThumbnailException
  269. *
  270. * @throws ClientException
  271. */
  272. public function uploadAvatar(): string
  273. {
  274. // ImageFile throws exception if something goes wrong, which we'll
  275. // pick up and show as an error message above the form.
  276. $imagefile = ImageFile::fromUpload('avatarfile');
  277. $type = $imagefile->preferredType();
  278. $filename = Avatar::filename(
  279. $this->scoped->getID(),
  280. image_type_to_extension($type),
  281. null,
  282. 'tmp' . common_timestamp()
  283. );
  284. $filepath = Avatar::path($filename);
  285. $imagefile = $imagefile->copyTo($filepath);
  286. $filedata = [
  287. 'filename' => $filename,
  288. 'filepath' => $filepath,
  289. 'width' => $imagefile->width,
  290. 'height' => $imagefile->height,
  291. 'type' => $type,
  292. ];
  293. $_SESSION['FILEDATA'] = $filedata;
  294. $this->filedata = $filedata;
  295. $this->mode = 'crop';
  296. // TRANS: Avatar upload form instruction after uploading a file.
  297. return _m('Pick a square area of the image to be your avatar.');
  298. }
  299. /**
  300. * Handle the results of jcrop.
  301. *
  302. * @return string
  303. * @throws NoResultException
  304. * @throws ServerException
  305. * @throws UnsupportedMediaException
  306. *
  307. * @throws ClientException
  308. */
  309. public function cropAvatar()
  310. {
  311. $filedata = $_SESSION['FILEDATA'];
  312. if (empty($filedata)) {
  313. // TRANS: Server error displayed if an avatar upload went wrong somehow server side.
  314. throw new ServerException(_m('Lost our file data.'));
  315. }
  316. $file_d = min($filedata['width'], $filedata['height']);
  317. $dest_x = $this->arg('avatar_crop_x') ? $this->arg('avatar_crop_x') : 0;
  318. $dest_y = $this->arg('avatar_crop_y') ? $this->arg('avatar_crop_y') : 0;
  319. $dest_w = $this->arg('avatar_crop_w') ? $this->arg('avatar_crop_w') : $file_d;
  320. $dest_h = $this->arg('avatar_crop_h') ? $this->arg('avatar_crop_h') : $file_d;
  321. $size = (int)(min($dest_w, $dest_h, common_config('avatar', 'maxsize')));
  322. $box = ['width' => $size, 'height' => $size,
  323. 'x' => $dest_x, 'y' => $dest_y,
  324. 'w' => $dest_w, 'h' => $dest_h,];
  325. $imagefile = new ImageFile(-1, $filedata['filepath']);
  326. $filename = Avatar::filename(
  327. $this->scoped->getID(),
  328. image_type_to_extension($imagefile->preferredType()),
  329. $size,
  330. common_timestamp()
  331. );
  332. try {
  333. $imagefile->resizeTo(Avatar::path($filename), $box);
  334. } catch (UseFileAsThumbnailException $e) {
  335. common_debug('Using uploaded avatar directly without resizing, copying it to: ' . $filename);
  336. if (!copy($filedata['filepath'], Avatar::path($filename))) {
  337. common_debug('Tried to copy image file ' . $filedata['filepath'] . ' to destination ' . Avatar::path($filename));
  338. throw new ServerException('Could not copy file to destination.');
  339. }
  340. }
  341. if ($this->scoped->setOriginal($filename)) {
  342. @unlink($filedata['filepath']);
  343. unset($_SESSION['FILEDATA']);
  344. $this->mode = 'upload';
  345. // TRANS: Success message for having updated a user avatar.
  346. return _m('Avatar updated.');
  347. }
  348. // TRANS: Error displayed on the avatar upload page if the avatar could not be updated for an unknown reason.
  349. throw new ServerException(_m('Failed updating avatar.'));
  350. }
  351. /**
  352. * Get rid of the current avatar.
  353. *
  354. * @return string
  355. * @throws Exception
  356. *
  357. */
  358. public function deleteAvatar()
  359. {
  360. Avatar::deleteFromProfile($this->scoped);
  361. // TRANS: Success message for deleting a user avatar.
  362. return _m('Avatar deleted.');
  363. }
  364. /**
  365. * Add the jCrop stylesheet
  366. *
  367. * @return void
  368. */
  369. public function showStylesheets()
  370. {
  371. parent::showStylesheets();
  372. $this->cssLink('js/extlib/jquery-jcrop/css/jcrop.css', 'base', 'screen, projection, tv');
  373. }
  374. /**
  375. * Add the jCrop scripts
  376. *
  377. * @return void
  378. */
  379. public function showScripts()
  380. {
  381. parent::showScripts();
  382. if ($this->mode == 'crop') {
  383. $this->script('extlib/jquery-jcrop/jcrop.js');
  384. $this->script('jcrop.go.js');
  385. }
  386. $this->autofocus('avatarfile');
  387. }
  388. }