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