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