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