Nickname::exists adaptation and registration stuff
[statusnet:freesocial.git] / actions / profilesettings.php
1 <?php
2 /**
3  * StatusNet, the distributed open-source microblogging tool
4  *
5  * Change profile settings
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  * @author    Sarven Capadisli <csarven@status.net>
27  * @copyright 2008-2009 StatusNet, Inc.
28  * @license   http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
29  * @link      http://status.net/
30  */
31
32 if (!defined('STATUSNET') && !defined('LACONICA')) {
33     exit(1);
34 }
35
36 /**
37  * Change profile settings
38  *
39  * @category Settings
40  * @package  StatusNet
41  * @author   Evan Prodromou <evan@status.net>
42  * @author   Zach Copley <zach@status.net>
43  * @author   Sarven Capadisli <csarven@status.net>
44  * @license  http://www.fsf.org/licensing/licenses/agpl-3.0.html GNU Affero General Public License version 3.0
45  * @link     http://status.net/
46  */
47 class ProfilesettingsAction extends SettingsAction
48 {
49     /**
50      * Title of the page
51      *
52      * @return string Title of the page
53      */
54     function title()
55     {
56         // TRANS: Page title for profile settings.
57         return _('Profile settings');
58     }
59
60     /**
61      * Instructions for use
62      *
63      * @return instructions for use
64      */
65     function getInstructions()
66     {
67         // TRANS: Usage instructions for profile settings.
68         return _('You can update your personal profile info here '.
69                  'so people know more about you.');
70     }
71
72     function showScripts()
73     {
74         parent::showScripts();
75         $this->autofocus('nickname');
76     }
77
78     /**
79      * Content area of the page
80      *
81      * Shows a form for uploading an avatar.
82      *
83      * @return void
84      */
85     function showContent()
86     {
87         $user = common_current_user();
88         $profile = $user->getProfile();
89
90         $this->elementStart('form', array('method' => 'post',
91                                           'id' => 'form_settings_profile',
92                                           'class' => 'form_settings',
93                                           'action' => common_local_url('profilesettings')));
94         $this->elementStart('fieldset');
95         // TRANS: Profile settings form legend.
96         $this->element('legend', null, _('Profile information'));
97         $this->hidden('token', common_session_token());
98
99         // too much common patterns here... abstractable?
100         $this->elementStart('ul', 'form_data');
101         if (Event::handle('StartProfileFormData', array($this))) {
102             $this->elementStart('li');
103             // TRANS: Field label in form for profile settings.
104             if (common_config('profile', 'changenick') == true) {
105                 $this->input('nickname', _('Nickname'),
106                          ($this->arg('nickname')) ? $this->arg('nickname') : $profile->nickname,
107                          // TRANS: Tooltip for field label in form for profile settings.
108                          _('1-64 lowercase letters or numbers, no punctuation or spaces.'));
109             } else {
110                 $this->elementStart('div');
111                 $this->text(sprintf(_m('Editing profile %s'), ($this->arg('nickname') ? $this->arg('nickname') : $profile->nickname)));
112                 $this->elementEnd('div');
113             }
114             $this->elementEnd('li');
115             $this->elementStart('li');
116             // TRANS: Field label in form for profile settings.
117             $this->input('fullname', _('Full name'),
118                          ($this->arg('fullname')) ? $this->arg('fullname') : $profile->fullname);
119             $this->elementEnd('li');
120             $this->elementStart('li');
121             // TRANS: Field label in form for profile settings.
122             $this->input('homepage', _('Homepage'),
123                          ($this->arg('homepage')) ? $this->arg('homepage') : $profile->homepage,
124                          // TRANS: Tooltip for field label in form for profile settings.
125                          _('URL of your homepage, blog, or profile on another site.'));
126             $this->elementEnd('li');
127             $this->elementStart('li');
128             $maxBio = Profile::maxBio();
129             if ($maxBio > 0) {
130                 // TRANS: Tooltip for field label in form for profile settings. Plural
131                 // TRANS: is decided by the number of characters available for the
132                 // TRANS: biography (%d).
133                 $bioInstr = sprintf(_m('Describe yourself and your interests in %d character.',
134                                        'Describe yourself and your interests in %d characters.',
135                                        $maxBio),
136                                     $maxBio);
137             } else {
138                 // TRANS: Tooltip for field label in form for profile settings.
139                 $bioInstr = _('Describe yourself and your interests.');
140             }
141             // TRANS: Text area label in form for profile settings where users can provide
142             // TRANS: their biography.
143             $this->textarea('bio', _('Bio'),
144                             ($this->arg('bio')) ? $this->arg('bio') : $profile->bio,
145                             $bioInstr);
146             $this->elementEnd('li');
147             $this->elementStart('li');
148             // TRANS: Field label in form for profile settings.
149             $this->input('location', _('Location'),
150                          ($this->arg('location')) ? $this->arg('location') : $profile->location,
151                          // TRANS: Tooltip for field label in form for profile settings.
152                          _('Where you are, like "City, State (or Region), Country".'));
153             $this->elementEnd('li');
154             if (common_config('location', 'share') == 'user') {
155                 $this->elementStart('li');
156                 // TRANS: Checkbox label in form for profile settings.
157                 $this->checkbox('sharelocation', _('Share my current location when posting notices'),
158                                 ($this->arg('sharelocation')) ?
159                                 $this->arg('sharelocation') : $user->shareLocation());
160                 $this->elementEnd('li');
161             }
162             Event::handle('EndProfileFormData', array($this));
163             $this->elementStart('li');
164             // TRANS: Field label in form for profile settings.
165             $this->input('tags', _('Tags'),
166                          ($this->arg('tags')) ? $this->arg('tags') : implode(' ', $user->getSelfTags()),
167                          // TRANS: Tooltip for field label in form for profile settings.
168                          _('Tags for yourself (letters, numbers, -, ., and _), comma- or space- separated.'));
169             $this->elementEnd('li');
170             $this->elementStart('li');
171             $language = common_language();
172             // TRANS: Dropdownlist label in form for profile settings.
173             $this->dropdown('language', _('Language'),
174                          // TRANS: Tooltip for dropdown list label in form for profile settings.
175                             get_nice_language_list(), _('Preferred language.'),
176                             false, $language);
177             $this->elementEnd('li');
178             $timezone = common_timezone();
179             $timezones = array();
180             foreach(DateTimeZone::listIdentifiers() as $k => $v) {
181                 $timezones[$v] = $v;
182             }
183             $this->elementStart('li');
184             // TRANS: Dropdownlist label in form for profile settings.
185             $this->dropdown('timezone', _('Timezone'),
186                          // TRANS: Tooltip for dropdown list label in form for profile settings.
187                             $timezones, _('What timezone are you normally in?'),
188                             true, $timezone);
189             $this->elementEnd('li');
190             $this->elementStart('li');
191             $this->checkbox('autosubscribe',
192                             // TRANS: Checkbox label in form for profile settings.
193                             _('Automatically subscribe to whoever '.
194                               'subscribes to me (best for non-humans)'),
195                             ($this->arg('autosubscribe')) ?
196                             $this->boolean('autosubscribe') : $user->autosubscribe);
197             $this->elementEnd('li');
198             $this->elementStart('li');
199             $this->dropdown('subscribe_policy',
200                             // TRANS: Dropdown field label on profile settings, for what policies to apply when someone else tries to subscribe to your updates.
201                             _('Subscription policy'),
202                             // TRANS: Dropdown field option for following policy.
203                             array(User::SUBSCRIBE_POLICY_OPEN     => _('Let anyone follow me'),
204                                   // TRANS: Dropdown field option for following policy.
205                                   User::SUBSCRIBE_POLICY_MODERATE => _('Ask me first')),
206                             // TRANS: Dropdown field title on group edit form.
207                             _('Whether other users need your permission to follow your updates.'),
208                             false,
209                             (empty($user->subscribe_policy)) ? User::SUBSCRIBE_POLICY_OPEN : $user->subscribe_policy);
210             $this->elementEnd('li');
211         }
212         $this->elementStart('li');
213         $this->checkbox('private_stream',
214                         // TRANS: Checkbox label in profile settings.
215                         _('Make updates visible only to my followers'),
216                         ($this->arg('private_stream')) ?
217                         $this->boolean('private_stream') : $user->private_stream);
218         $this->elementEnd('li');
219         $this->elementEnd('ul');
220         // TRANS: Button to save input in profile settings.
221         $this->submit('save', _m('BUTTON','Save'));
222
223         $this->elementEnd('fieldset');
224         $this->elementEnd('form');
225     }
226
227     /**
228      * Handle a post
229      *
230      * Validate input and save changes. Reload the form with a success
231      * or error message.
232      *
233      * @return void
234      */
235     function handlePost()
236     {
237         // CSRF protection
238         $token = $this->trimmed('token');
239         if (!$token || $token != common_session_token()) {
240             // TRANS: Form validation error.
241             $this->showForm(_('There was a problem with your session token. '.
242                               'Try again, please.'));
243             return;
244         }
245                 $cur = common_current_user();
246
247         if (Event::handle('StartProfileSaveForm', array($this))) {
248
249             if (common_config('profile', 'changenick') == true) {
250                 try {
251                     $nickname = Nickname::normalize($this->trimmed('nickname'));
252                 } catch (NicknameException $e) {
253                     $this->showForm($e->getMessage());
254                     return;
255                 }
256             } else {
257                                 $nickname = $cur->nickname;
258                         }
259
260             $fullname = $this->trimmed('fullname');
261             $homepage = $this->trimmed('homepage');
262             $bio = $this->trimmed('bio');
263             $location = $this->trimmed('location');
264             $autosubscribe = $this->boolean('autosubscribe');
265             $subscribe_policy = $this->trimmed('subscribe_policy');
266             $private_stream = $this->boolean('private_stream');
267             $language = $this->trimmed('language');
268             $timezone = $this->trimmed('timezone');
269             $tagstring = $this->trimmed('tags');
270
271             // Some validation
272             if (!User::allowed_nickname($nickname)) {
273                 // TRANS: Validation error in form for profile settings.
274                 $this->showForm(_('Not a valid nickname.'));
275                 return;
276             } else if (!is_null($homepage) && (strlen($homepage) > 0) &&
277                        !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) {
278                 // TRANS: Validation error in form for profile settings.
279                 $this->showForm(_('Homepage is not a valid URL.'));
280                 return;
281             } else if (!is_null($fullname) && mb_strlen($fullname) > 255) {
282                 // TRANS: Validation error in form for profile settings.
283                 $this->showForm(_('Full name is too long (maximum 255 characters).'));
284                 return;
285             } else if (Profile::bioTooLong($bio)) {
286                 // TRANS: Validation error in form for profile settings.
287                 // TRANS: Plural form is used based on the maximum number of allowed
288                 // TRANS: characters for the biography (%d).
289                 $this->showForm(sprintf(_m('Bio is too long (maximum %d character).',
290                                            'Bio is too long (maximum %d characters).',
291                                            Profile::maxBio()),
292                                         Profile::maxBio()));
293                 return;
294             } else if (!is_null($location) && mb_strlen($location) > 255) {
295                 // TRANS: Validation error in form for profile settings.
296                 $this->showForm(_('Location is too long (maximum 255 characters).'));
297                 return;
298             }  else if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) {
299                 // TRANS: Validation error in form for profile settings.
300                 $this->showForm(_('Timezone not selected.'));
301                 return;
302             } else if (Nickname::exists($nickname, $cur->id)) {
303                 // TRANS: Validation error in form for profile settings.
304                 $this->showForm(_('Nickname already in use. Try another one.'));
305                 return;
306             } else if (!is_null($language) && strlen($language) > 50) {
307                 // TRANS: Validation error in form for profile settings.
308                 $this->showForm(_('Language is too long (maximum 50 characters).'));
309                 return;
310             }
311
312             $tags = array();
313             $tag_priv = array();
314             if (is_string($tagstring) && strlen($tagstring) > 0) {
315
316                 $tags = preg_split('/[\s,]+/', $tagstring);
317
318                 foreach ($tags as &$tag) {
319                     $private = @$tag[0] === '.';
320
321                     $tag = common_canonical_tag($tag);
322                     if (!common_valid_profile_tag($tag)) {
323                         // TRANS: Validation error in form for profile settings.
324                         // TRANS: %s is an invalid tag.
325                         $this->showForm(sprintf(_('Invalid tag: "%s".'), $tag));
326                         return;
327                     }
328
329                     $tag_priv[$tag] = $private;
330                 }
331             }
332
333             $user = common_current_user();
334
335             $user->query('BEGIN');
336
337             if ($user->nickname != $nickname ||
338                 $user->language != $language ||
339                 $user->timezone != $timezone) {
340
341                 common_debug('Updating user language from ' . $user->language . ' to ' . $language,
342                              __FILE__);
343                 common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone,
344                              __FILE__);
345
346                 $original = clone($user);
347
348                 if (common_config('profile', 'changenick') == true) {
349                     common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname,
350                                  __FILE__);
351                     $user->nickname = $nickname;
352                 }
353                 $user->language = $language;
354                 $user->timezone = $timezone;
355
356                 $result = $user->updateKeys($original);
357
358                 if ($result === false) {
359                     common_log_db_error($user, 'UPDATE', __FILE__);
360                     // TRANS: Server error thrown when user profile settings could not be updated.
361                     $this->serverError(_('Could not update user.'));
362                     return;
363                 } else {
364                     // Re-initialize language environment if it changed
365                     common_init_language();
366                     // Clear the site owner, in case nickname changed
367                     if ($user->hasRole(Profile_role::OWNER)) {
368                         User::blow('user:site_owner');
369                     }
370                 }
371             }
372
373             // XXX: XOR
374             if (($user->autosubscribe ^ $autosubscribe) ||
375                 ($user->private_stream ^ $private_stream) ||
376                 ($user->subscribe_policy != $subscribe_policy)) {
377
378                 $original = clone($user);
379
380                 $user->autosubscribe    = $autosubscribe;
381                 $user->private_stream   = $private_stream;
382                 $user->subscribe_policy = $subscribe_policy;
383
384                 $result = $user->update($original);
385
386                 if ($result === false) {
387                     common_log_db_error($user, 'UPDATE', __FILE__);
388                     // TRANS: Server error thrown when user profile settings could not be updated to
389                     // TRANS: automatically subscribe to any subscriber.
390                     $this->serverError(_('Could not update user for autosubscribe or subscribe_policy.'));
391                     return;
392                 }
393             }
394
395             $profile = $user->getProfile();
396
397             $orig_profile = clone($profile);
398
399             $profile->nickname = $user->nickname;
400             $profile->fullname = $fullname;
401             $profile->homepage = $homepage;
402             $profile->bio = $bio;
403             $profile->location = $location;
404
405             $loc = Location::fromName($location);
406
407             if (empty($loc)) {
408                 $profile->lat         = null;
409                 $profile->lon         = null;
410                 $profile->location_id = null;
411                 $profile->location_ns = null;
412             } else {
413                 $profile->lat         = $loc->lat;
414                 $profile->lon         = $loc->lon;
415                 $profile->location_id = $loc->location_id;
416                 $profile->location_ns = $loc->location_ns;
417             }
418
419             $profile->profileurl = common_profile_url($profile->nickname);
420
421             if (common_config('location', 'share') == 'user') {
422
423                 $exists = false;
424
425                 $prefs = User_location_prefs::staticGet('user_id', $user->id);
426
427                 if (empty($prefs)) {
428                     $prefs = new User_location_prefs();
429
430                     $prefs->user_id = $user->id;
431                     $prefs->created = common_sql_now();
432                 } else {
433                     $exists = true;
434                     $orig = clone($prefs);
435                 }
436
437                 $prefs->share_location = $this->boolean('sharelocation');
438
439                 if ($exists) {
440                     $result = $prefs->update($orig);
441                 } else {
442                     $result = $prefs->insert();
443                 }
444
445                 if ($result === false) {
446                     common_log_db_error($prefs, ($exists) ? 'UPDATE' : 'INSERT', __FILE__);
447                     // TRANS: Server error thrown when user profile location preference settings could not be updated.
448                     $this->serverError(_('Could not save location prefs.'));
449                     return;
450                 }
451             }
452
453             common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__);
454             common_debug('New profile: ' . common_log_objstring($profile), __FILE__);
455
456             $result = $profile->update($orig_profile);
457
458             if ($result === false) {
459                 common_log_db_error($profile, 'UPDATE', __FILE__);
460                 // TRANS: Server error thrown when user profile settings could not be saved.
461                 $this->serverError(_('Could not save profile.'));
462                 return;
463             }
464
465             // Set the user tags
466             $result = $user->setSelfTags($tags, $tag_priv);
467
468             if (!$result) {
469                 // TRANS: Server error thrown when user profile settings tags could not be saved.
470                 $this->serverError(_('Could not save tags.'));
471                 return;
472             }
473
474             $user->query('COMMIT');
475             Event::handle('EndProfileSaveForm', array($this));
476             common_broadcast_profile($profile);
477
478             // TRANS: Confirmation shown when user profile settings are saved.
479             $this->showForm(_('Settings saved.'), true);
480
481         }
482     }
483
484     function showAside() {
485         $user = common_current_user();
486
487         $this->elementStart('div', array('id' => 'aside_primary',
488                                          'class' => 'aside'));
489
490         $this->elementStart('div', array('id' => 'account_actions',
491                                          'class' => 'section'));
492         $this->elementStart('ul');
493         if (Event::handle('StartProfileSettingsActions', array($this))) {
494             if ($user->hasRight(Right::BACKUPACCOUNT)) {
495                 $this->elementStart('li');
496                 $this->element('a',
497                                array('href' => common_local_url('backupaccount')),
498                                // TRANS: Option in profile settings to create a backup of the account of the currently logged in user.
499                                _('Backup account'));
500                 $this->elementEnd('li');
501             }
502             if ($user->hasRight(Right::DELETEACCOUNT)) {
503                 $this->elementStart('li');
504                 $this->element('a',
505                                array('href' => common_local_url('deleteaccount')),
506                                // TRANS: Option in profile settings to delete the account of the currently logged in user.
507                                _('Delete account'));
508                 $this->elementEnd('li');
509             }
510             if ($user->hasRight(Right::RESTOREACCOUNT)) {
511                 $this->elementStart('li');
512                 $this->element('a',
513                                array('href' => common_local_url('restoreaccount')),
514                                // TRANS: Option in profile settings to restore the account of the currently logged in user from a backup.
515                                _('Restore account'));
516                 $this->elementEnd('li');
517             }
518             Event::handle('EndProfileSettingsActions', array($this));
519         }
520         $this->elementEnd('ul');
521         $this->elementEnd('div');
522         $this->elementEnd('div');
523     }
524 }