]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - actions/avatarsettings.php
Make new menu the default menu
[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: Server error displayed in avatar upload page when no matching profile can be found for a user.
108             $this->serverError(_('User without matching profile.'));
109             return;
110         }
111
112         $original = $profile->getOriginalAvatar();
113
114         $this->elementStart('form', array('enctype' => 'multipart/form-data',
115                                           'method' => 'post',
116                                           'id' => 'form_settings_avatar',
117                                           'class' => 'form_settings',
118                                           'action' =>
119                                           common_local_url('avatarsettings')));
120         $this->elementStart('fieldset');
121         // TRANS: Avatar upload page form legend.
122         $this->element('legend', null, _('Avatar settings'));
123         $this->hidden('token', common_session_token());
124
125         if (Event::handle('StartAvatarFormData', array($this))) {
126             $this->elementStart('ul', 'form_data');
127             if ($original) {
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             }
140
141             $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
142
143             if ($avatar) {
144                 $this->elementStart('li', array('id' => 'avatar_preview',
145                                                 'class' => 'avatar_view'));
146                 // TRANS: Header on avatar upload page for thumbnail of to be used rendition of uploaded avatar (h2).
147                 $this->element('h2', null, _("Preview"));
148                 $this->elementStart('div', array('id'=>'avatar_preview_view'));
149                 $this->element('img', array('src' => $original->url,
150                                             'width' => AVATAR_PROFILE_SIZE,
151                                             'height' => AVATAR_PROFILE_SIZE,
152                                             'alt' => $user->nickname));
153                 $this->elementEnd('div');
154                 // TRANS: Button on avatar upload page to delete current avatar.
155                 $this->submit('delete', _m('BUTTON','Delete'));
156                 $this->elementEnd('li');
157             }
158
159             $this->elementStart('li', array ('id' => 'settings_attach'));
160             $this->element('input', array('name' => 'avatarfile',
161                                           'type' => 'file',
162                                           'id' => 'avatarfile'));
163             $this->element('input', array('name' => 'MAX_FILE_SIZE',
164                                           'type' => 'hidden',
165                                           'id' => 'MAX_FILE_SIZE',
166                                           'value' => ImageFile::maxFileSizeInt()));
167             $this->elementEnd('li');
168             $this->elementEnd('ul');
169
170             $this->elementStart('ul', 'form_actions');
171             $this->elementStart('li');
172                 // TRANS: Button on avatar upload page to upload an avatar.
173             $this->submit('upload', _m('BUTTON','Upload'));
174             $this->elementEnd('li');
175             $this->elementEnd('ul');
176         }
177         Event::handle('EndAvatarFormData', array($this));
178
179         $this->elementEnd('fieldset');
180         $this->elementEnd('form');
181     }
182
183     function showCropForm()
184     {
185         $user = common_current_user();
186
187         $profile = $user->getProfile();
188
189         if (!$profile) {
190             common_log_db_error($user, 'SELECT', __FILE__);
191             // TRANS: Server error displayed in avatar upload page when no matching profile can be found for a user.
192             $this->serverError(_('User without matching profile.'));
193             return;
194         }
195
196         $original = $profile->getOriginalAvatar();
197
198         $this->elementStart('form', array('method' => 'post',
199                                           'id' => 'form_settings_avatar',
200                                           'class' => 'form_settings',
201                                           'action' =>
202                                           common_local_url('avatarsettings')));
203         $this->elementStart('fieldset');
204         // TRANS: Avatar upload page crop form legend.
205         $this->element('legend', null, _('Avatar settings'));
206         $this->hidden('token', common_session_token());
207
208         $this->elementStart('ul', 'form_data');
209
210         $this->elementStart('li',
211                             array('id' => 'avatar_original',
212                                   'class' => 'avatar_view'));
213         // TRANS: Header on avatar upload crop form for thumbnail of originally uploaded avatar (h2).
214         $this->element('h2', null, _("Original"));
215         $this->elementStart('div', array('id'=>'avatar_original_view'));
216         $this->element('img', array('src' => Avatar::url($this->filedata['filename']),
217                                     'width' => $this->filedata['width'],
218                                     'height' => $this->filedata['height'],
219                                     'alt' => $user->nickname));
220         $this->elementEnd('div');
221         $this->elementEnd('li');
222
223         $this->elementStart('li',
224                             array('id' => 'avatar_preview',
225                                   'class' => 'avatar_view'));
226         // TRANS: Header on avatar upload crop form for thumbnail of to be used rendition of uploaded avatar (h2).
227         $this->element('h2', null, _("Preview"));
228         $this->elementStart('div', array('id'=>'avatar_preview_view'));
229         $this->element('img', array('src' => Avatar::url($this->filedata['filename']),
230                                     'width' => AVATAR_PROFILE_SIZE,
231                                     'height' => AVATAR_PROFILE_SIZE,
232                                     'alt' => $user->nickname));
233         $this->elementEnd('div');
234
235         foreach (array('avatar_crop_x', 'avatar_crop_y',
236                        'avatar_crop_w', 'avatar_crop_h') as $crop_info) {
237             $this->element('input', array('name' => $crop_info,
238                                           'type' => 'hidden',
239                                           'id' => $crop_info));
240         }
241
242         // TRANS: Button on avatar upload crop form to confirm a selected crop as avatar.
243         $this->submit('crop', _m('BUTTON','Crop'));
244
245         $this->elementEnd('li');
246         $this->elementEnd('ul');
247         $this->elementEnd('fieldset');
248         $this->elementEnd('form');
249     }
250
251     /**
252      * Handle a post
253      *
254      * We mux on the button name to figure out what the user actually wanted.
255      *
256      * @return void
257      */
258     function handlePost()
259     {
260         // Workaround for PHP returning empty $_POST and $_FILES when POST
261         // length > post_max_size in php.ini
262
263         if (empty($_FILES)
264             && empty($_POST)
265             && ($_SERVER['CONTENT_LENGTH'] > 0)
266         ) {
267             // TRANS: Client error displayed when the number of bytes in a POST request exceeds a limit.
268             // TRANS: %s is the number of bytes of the CONTENT_LENGTH.
269             $msg = _m('The server was unable to handle that much POST data (%s byte) due to its current configuration.',
270                       'The server was unable to handle that much POST data (%s bytes) due to its current configuration.',
271                       intval($_SERVER['CONTENT_LENGTH']));
272             $this->showForm(sprintf($msg, $_SERVER['CONTENT_LENGTH']));
273             return;
274         }
275
276         // CSRF protection
277
278         $token = $this->trimmed('token');
279         if (!$token || $token != common_session_token()) {
280             $this->showForm(_('There was a problem with your session token. '.
281                                'Try again, please.'));
282             return;
283         }
284
285         if (Event::handle('StartAvatarSaveForm', array($this))) {
286             if ($this->arg('upload')) {
287                 $this->uploadAvatar();
288                 } else if ($this->arg('crop')) {
289                     $this->cropAvatar();
290                 } else if ($this->arg('delete')) {
291                     $this->deleteAvatar();
292                 } else {
293                     // TRANS: Unexpected validation error on avatar upload form.
294                     $this->showForm(_('Unexpected form submission.'));
295                 }
296             Event::handle('EndAvatarSaveForm', array($this));
297         }
298     }
299
300     /**
301      * Handle an image upload
302      *
303      * Does all the magic for handling an image upload, and crops the
304      * image by default.
305      *
306      * @return void
307      */
308     function uploadAvatar()
309     {
310         try {
311             $imagefile = ImageFile::fromUpload('avatarfile');
312         } catch (Exception $e) {
313             $this->showForm($e->getMessage());
314             return;
315         }
316         if ($imagefile === null) {
317             // TRANS: Validation error on avatar upload form when no file was uploaded.
318             $this->showForm(_('No file uploaded.'));
319             return;
320         }
321
322         $cur = common_current_user();
323
324         $filename = Avatar::filename($cur->id,
325                                      image_type_to_extension($imagefile->type),
326                                      null,
327                                      'tmp'.common_timestamp());
328
329         $filepath = Avatar::path($filename);
330
331         move_uploaded_file($imagefile->filepath, $filepath);
332
333         $filedata = array('filename' => $filename,
334                           'filepath' => $filepath,
335                           'width' => $imagefile->width,
336                           'height' => $imagefile->height,
337                           'type' => $imagefile->type);
338
339         $_SESSION['FILEDATA'] = $filedata;
340
341         $this->filedata = $filedata;
342
343         $this->mode = 'crop';
344
345         // TRANS: Avatar upload form unstruction after uploading a file.
346         $this->showForm(_('Pick a square area of the image to be your avatar'),
347                         true);
348     }
349
350     /**
351      * Handle the results of jcrop.
352      *
353      * @return void
354      */
355     function cropAvatar()
356     {
357         $filedata = $_SESSION['FILEDATA'];
358
359         if (!$filedata) {
360             // TRANS: Server error displayed if an avatar upload went wrong somehow server side.
361             $this->serverError(_('Lost our file data.'));
362             return;
363         }
364
365         $file_d = ($filedata['width'] > $filedata['height'])
366                      ? $filedata['height'] : $filedata['width'];
367
368         $dest_x = $this->arg('avatar_crop_x') ? $this->arg('avatar_crop_x'):0;
369         $dest_y = $this->arg('avatar_crop_y') ? $this->arg('avatar_crop_y'):0;
370         $dest_w = $this->arg('avatar_crop_w') ? $this->arg('avatar_crop_w'):$file_d;
371         $dest_h = $this->arg('avatar_crop_h') ? $this->arg('avatar_crop_h'):$file_d;
372         $size = min($dest_w, $dest_h, MAX_ORIGINAL);
373
374         $user = common_current_user();
375         $profile = $user->getProfile();
376
377         $imagefile = new ImageFile($user->id, $filedata['filepath']);
378         $filename = $imagefile->resize($size, $dest_x, $dest_y, $dest_w, $dest_h);
379
380         if ($profile->setOriginal($filename)) {
381             @unlink($filedata['filepath']);
382             unset($_SESSION['FILEDATA']);
383             $this->mode = 'upload';
384             // TRANS: Success message for having updated a user avatar.
385             $this->showForm(_('Avatar updated.'), true);
386             common_broadcast_profile($profile);
387         } else {
388             // TRANS: Error displayed on the avatar upload page if the avatar could not be updated for an unknown reason.
389             $this->showForm(_('Failed updating avatar.'));
390         }
391     }
392
393     /**
394      * Get rid of the current avatar.
395      *
396      * @return void
397      */
398     function deleteAvatar()
399     {
400         $user = common_current_user();
401         $profile = $user->getProfile();
402
403         $avatar = $profile->getOriginalAvatar();
404         if($avatar) $avatar->delete();
405         $avatar = $profile->getAvatar(AVATAR_PROFILE_SIZE);
406         if($avatar) $avatar->delete();
407         $avatar = $profile->getAvatar(AVATAR_STREAM_SIZE);
408         if($avatar) $avatar->delete();
409         $avatar = $profile->getAvatar(AVATAR_MINI_SIZE);
410         if($avatar) $avatar->delete();
411
412         // TRANS: Success message for deleting a user avatar.
413         $this->showForm(_('Avatar deleted.'), true);
414     }
415
416     /**
417      * Add the jCrop stylesheet
418      *
419      * @return void
420      */
421
422     function showStylesheets()
423     {
424         parent::showStylesheets();
425         $this->cssLink('css/jquery.Jcrop.css','base','screen, projection, tv');
426     }
427
428     /**
429      * Add the jCrop scripts
430      *
431      * @return void
432      */
433     function showScripts()
434     {
435         parent::showScripts();
436
437         if ($this->mode == 'crop') {
438             $this->script('jcrop/jquery.Jcrop.min.js');
439             $this->script('jcrop/jquery.Jcrop.go.js');
440         }
441
442         $this->autofocus('avatarfile');
443     }
444 }