avatarsettings.php 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445
  1. <?php
  2. /**
  3. * StatusNet, the distributed open-source microblogging tool
  4. *
  5. * Upload an avatar
  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 Settings
  23. * @package StatusNet
  24. * @author Evan Prodromou <evan@status.net>
  25. * @author Zach Copley <zach@status.net>
  26. * @copyright 2008-2009 StatusNet, Inc.
  27. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  28. * @link http://status.net/
  29. */
  30. if (!defined('GNUSOCIAL')) { exit(1); }
  31. /**
  32. * Upload an avatar
  33. *
  34. * We use jCrop plugin for jQuery to crop the image after upload.
  35. *
  36. * @category Settings
  37. * @package StatusNet
  38. * @author Evan Prodromou <evan@status.net>
  39. * @author Zach Copley <zach@status.net>
  40. * @author Sarven Capadisli <csarven@status.net>
  41. * @license http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
  42. * @link http://status.net/
  43. */
  44. class AvatarsettingsAction extends SettingsAction
  45. {
  46. var $mode = null;
  47. var $imagefile = null;
  48. var $filename = null;
  49. /**
  50. * Title of the page
  51. *
  52. * @return string Title of the page
  53. */
  54. function title()
  55. {
  56. // TRANS: Title for avatar upload page.
  57. return _('Avatar');
  58. }
  59. /**
  60. * Instructions for use
  61. *
  62. * @return instructions for use
  63. */
  64. function getInstructions()
  65. {
  66. // TRANS: Instruction for avatar upload page.
  67. // TRANS: %s is the maximum file size, for example "500b", "10kB" or "2MB".
  68. return sprintf(_('You can upload your personal avatar. The maximum file size is %s.'),
  69. ImageFile::maxFileSize());
  70. }
  71. /**
  72. * Content area of the page
  73. *
  74. * Shows a form for uploading an avatar.
  75. *
  76. * @return void
  77. */
  78. function showContent()
  79. {
  80. if ($this->mode == 'crop') {
  81. $this->showCropForm();
  82. } else {
  83. $this->showUploadForm();
  84. }
  85. }
  86. function showUploadForm()
  87. {
  88. $user = common_current_user();
  89. $profile = $user->getProfile();
  90. if (!$profile) {
  91. common_log_db_error($user, 'SELECT', __FILE__);
  92. // TRANS: Error message displayed when referring to a user without a profile.
  93. $this->serverError(_('User has no profile.'));
  94. }
  95. $this->elementStart('form', array('enctype' => 'multipart/form-data',
  96. 'method' => 'post',
  97. 'id' => 'form_settings_avatar',
  98. 'class' => 'form_settings',
  99. 'action' =>
  100. common_local_url('avatarsettings')));
  101. $this->elementStart('fieldset');
  102. // TRANS: Avatar upload page form legend.
  103. $this->element('legend', null, _('Avatar settings'));
  104. $this->hidden('token', common_session_token());
  105. if (Event::handle('StartAvatarFormData', array($this))) {
  106. $this->elementStart('ul', 'form_data');
  107. try {
  108. $original = Avatar::getUploaded($profile);
  109. $this->elementStart('li', array('id' => 'avatar_original',
  110. 'class' => 'avatar_view'));
  111. // TRANS: Header on avatar upload page for thumbnail of originally uploaded avatar (h2).
  112. $this->element('h2', null, _("Original"));
  113. $this->elementStart('div', array('id'=>'avatar_original_view'));
  114. $this->element('img', array('src' => $original->displayUrl(),
  115. 'width' => $original->width,
  116. 'height' => $original->height,
  117. 'alt' => $user->nickname));
  118. $this->elementEnd('div');
  119. $this->elementEnd('li');
  120. } catch (NoAvatarException $e) {
  121. // No original avatar found!
  122. }
  123. try {
  124. $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
  125. $this->elementStart('li', array('id' => 'avatar_preview',
  126. 'class' => 'avatar_view'));
  127. // TRANS: Header on avatar upload page for thumbnail of to be used rendition of uploaded avatar (h2).
  128. $this->element('h2', null, _("Preview"));
  129. $this->elementStart('div', array('id'=>'avatar_preview_view'));
  130. $this->element('img', array('src' => $avatar->displayUrl(),
  131. 'width' => AVATAR_PROFILE_SIZE,
  132. 'height' => AVATAR_PROFILE_SIZE,
  133. 'alt' => $user->nickname));
  134. $this->elementEnd('div');
  135. if (!empty($avatar->filename)) {
  136. // TRANS: Button on avatar upload page to delete current avatar.
  137. $this->submit('delete', _m('BUTTON','Delete'));
  138. }
  139. $this->elementEnd('li');
  140. } catch (NoAvatarException $e) {
  141. // No previously uploaded avatar to preview.
  142. }
  143. $this->elementStart('li', array ('id' => 'settings_attach'));
  144. $this->element('input', array('name' => 'MAX_FILE_SIZE',
  145. 'type' => 'hidden',
  146. 'id' => 'MAX_FILE_SIZE',
  147. 'value' => ImageFile::maxFileSizeInt()));
  148. $this->element('input', array('name' => 'avatarfile',
  149. 'type' => 'file',
  150. 'id' => 'avatarfile'));
  151. $this->elementEnd('li');
  152. $this->elementEnd('ul');
  153. $this->elementStart('ul', 'form_actions');
  154. $this->elementStart('li');
  155. // TRANS: Button on avatar upload page to upload an avatar.
  156. $this->submit('upload', _m('BUTTON','Upload'));
  157. $this->elementEnd('li');
  158. $this->elementEnd('ul');
  159. }
  160. Event::handle('EndAvatarFormData', array($this));
  161. $this->elementEnd('fieldset');
  162. $this->elementEnd('form');
  163. }
  164. function showCropForm()
  165. {
  166. $user = common_current_user();
  167. $profile = $user->getProfile();
  168. if (!$profile) {
  169. common_log_db_error($user, 'SELECT', __FILE__);
  170. // TRANS: Error message displayed when referring to a user without a profile.
  171. $this->serverError(_('User has no profile.'));
  172. }
  173. $this->elementStart('form', array('method' => 'post',
  174. 'id' => 'form_settings_avatar',
  175. 'class' => 'form_settings',
  176. 'action' =>
  177. common_local_url('avatarsettings')));
  178. $this->elementStart('fieldset');
  179. // TRANS: Avatar upload page crop form legend.
  180. $this->element('legend', null, _('Avatar settings'));
  181. $this->hidden('token', common_session_token());
  182. $this->elementStart('ul', 'form_data');
  183. $this->elementStart('li',
  184. array('id' => 'avatar_original',
  185. 'class' => 'avatar_view'));
  186. // TRANS: Header on avatar upload crop form for thumbnail of originally uploaded avatar (h2).
  187. $this->element('h2', null, _('Original'));
  188. $this->elementStart('div', array('id'=>'avatar_original_view'));
  189. $this->element('img', array('src' => Avatar::url($this->filedata['filename']),
  190. 'width' => $this->filedata['width'],
  191. 'height' => $this->filedata['height'],
  192. 'alt' => $user->nickname));
  193. $this->elementEnd('div');
  194. $this->elementEnd('li');
  195. $this->elementStart('li',
  196. array('id' => 'avatar_preview',
  197. 'class' => 'avatar_view'));
  198. // TRANS: Header on avatar upload crop form for thumbnail of to be used rendition of uploaded avatar (h2).
  199. $this->element('h2', null, _('Preview'));
  200. $this->elementStart('div', array('id'=>'avatar_preview_view'));
  201. $this->element('img', array('src' => Avatar::url($this->filedata['filename']),
  202. 'width' => AVATAR_PROFILE_SIZE,
  203. 'height' => AVATAR_PROFILE_SIZE,
  204. 'alt' => $user->nickname));
  205. $this->elementEnd('div');
  206. foreach (array('avatar_crop_x', 'avatar_crop_y',
  207. 'avatar_crop_w', 'avatar_crop_h') as $crop_info) {
  208. $this->element('input', array('name' => $crop_info,
  209. 'type' => 'hidden',
  210. 'id' => $crop_info));
  211. }
  212. // TRANS: Button on avatar upload crop form to confirm a selected crop as avatar.
  213. $this->submit('crop', _m('BUTTON','Crop'));
  214. $this->elementEnd('li');
  215. $this->elementEnd('ul');
  216. $this->elementEnd('fieldset');
  217. $this->elementEnd('form');
  218. }
  219. /**
  220. * Handle a post
  221. *
  222. * We mux on the button name to figure out what the user actually wanted.
  223. *
  224. * @return void
  225. */
  226. function handlePost()
  227. {
  228. // Workaround for PHP returning empty $_POST and $_FILES when POST
  229. // length > post_max_size in php.ini
  230. if (empty($_FILES)
  231. && empty($_POST)
  232. && ($_SERVER['CONTENT_LENGTH'] > 0)
  233. ) {
  234. // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
  235. // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
  236. $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
  237. 'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
  238. intval($_SERVER['CONTENT_LENGTH']));
  239. $this->showForm(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
  240. return;
  241. }
  242. // CSRF protection
  243. $token = $this->trimmed('token');
  244. if (!$token || $token != common_session_token()) {
  245. // TRANS: Client error displayed when the session token does not match or is not given.
  246. $this->showForm(_('There was a problem with your session token. '.
  247. 'Try again, please.'));
  248. return;
  249. }
  250. if (Event::handle('StartAvatarSaveForm', array($this))) {
  251. if ($this->arg('upload')) {
  252. $this->uploadAvatar();
  253. } else if ($this->arg('crop')) {
  254. $this->cropAvatar();
  255. } else if ($this->arg('delete')) {
  256. $this->deleteAvatar();
  257. } else {
  258. // TRANS: Unexpected validation error on avatar upload form.
  259. $this->showForm(_('Unexpected form submission.'));
  260. }
  261. Event::handle('EndAvatarSaveForm', array($this));
  262. }
  263. }
  264. /**
  265. * Handle an image upload
  266. *
  267. * Does all the magic for handling an image upload, and crops the
  268. * image by default.
  269. *
  270. * @return void
  271. */
  272. function uploadAvatar()
  273. {
  274. try {
  275. $imagefile = ImageFile::fromUpload('avatarfile');
  276. } catch (Exception $e) {
  277. $this->showForm($e->getMessage());
  278. return;
  279. }
  280. if ($imagefile === null) {
  281. // TRANS: Validation error on avatar upload form when no file was uploaded.
  282. $this->showForm(_('No file uploaded.'));
  283. return;
  284. }
  285. $cur = common_current_user();
  286. $type = $imagefile->preferredType();
  287. $filename = Avatar::filename($cur->id,
  288. image_type_to_extension($type),
  289. null,
  290. 'tmp'.common_timestamp());
  291. $filepath = Avatar::path($filename);
  292. $imagefile = $imagefile->copyTo($filepath);
  293. $filedata = array('filename' => $filename,
  294. 'filepath' => $filepath,
  295. 'width' => $imagefile->width,
  296. 'height' => $imagefile->height,
  297. 'type' => $type);
  298. $_SESSION['FILEDATA'] = $filedata;
  299. $this->filedata = $filedata;
  300. $this->mode = 'crop';
  301. // TRANS: Avatar upload form instruction after uploading a file.
  302. $this->showForm(_('Pick a square area of the image to be your avatar.'),
  303. true);
  304. }
  305. /**
  306. * Handle the results of jcrop.
  307. *
  308. * @return void
  309. */
  310. public function cropAvatar()
  311. {
  312. $filedata = $_SESSION['FILEDATA'];
  313. if (!$filedata) {
  314. // TRANS: Server error displayed if an avatar upload went wrong somehow server side.
  315. $this->serverError(_('Lost our file data.'));
  316. }
  317. $file_d = ($filedata['width'] > $filedata['height'])
  318. ? $filedata['height'] : $filedata['width'];
  319. $dest_x = $this->arg('avatar_crop_x') ? $this->arg('avatar_crop_x'):0;
  320. $dest_y = $this->arg('avatar_crop_y') ? $this->arg('avatar_crop_y'):0;
  321. $dest_w = $this->arg('avatar_crop_w') ? $this->arg('avatar_crop_w'):$file_d;
  322. $dest_h = $this->arg('avatar_crop_h') ? $this->arg('avatar_crop_h'):$file_d;
  323. $size = intval(min($dest_w, $dest_h, common_config('avatar', 'maxsize')));
  324. $box = array('width' => $size, 'height' => $size,
  325. 'x' => $dest_x, 'y' => $dest_y,
  326. 'w' => $dest_w, 'h' => $dest_h);
  327. $user = common_current_user();
  328. $profile = $user->getProfile();
  329. $imagefile = new ImageFile(null, $filedata['filepath']);
  330. $filename = Avatar::filename($profile->getID(), image_type_to_extension($imagefile->preferredType()),
  331. $size, common_timestamp());
  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 ($profile->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. $this->showForm(_('Avatar updated.'), true);
  347. } else {
  348. // TRANS: Error displayed on the avatar upload page if the avatar could not be updated for an unknown reason.
  349. $this->showForm(_('Failed updating avatar.'));
  350. }
  351. }
  352. /**
  353. * Get rid of the current avatar.
  354. *
  355. * @return void
  356. */
  357. function deleteAvatar()
  358. {
  359. $user = common_current_user();
  360. $profile = $user->getProfile();
  361. Avatar::deleteFromProfile($profile);
  362. // TRANS: Success message for deleting a user avatar.
  363. $this->showForm(_('Avatar deleted.'), true);
  364. }
  365. /**
  366. * Add the jCrop stylesheet
  367. *
  368. * @return void
  369. */
  370. function showStylesheets()
  371. {
  372. parent::showStylesheets();
  373. $this->cssLink('js/extlib/jquery-jcrop/css/jcrop.css','base','screen, projection, tv');
  374. }
  375. /**
  376. * Add the jCrop scripts
  377. *
  378. * @return void
  379. */
  380. function showScripts()
  381. {
  382. parent::showScripts();
  383. if ($this->mode == 'crop') {
  384. $this->script('extlib/jquery-jcrop/jcrop.js');
  385. $this->script('jcrop.go.js');
  386. }
  387. $this->autofocus('avatarfile');
  388. }
  389. }