function checkLogin($user_id = null, $token = null) { // XXX: login throttle //database use nickname we change it into username for more //easier to understand $nickname = $this->trimmed('username'); if (empty($nickname)) { $this->clientError(_('username empty')); return; } try { $nickname = Nickname::normalize($nickname); } catch (NicknameException $e) { $this->clientError(_('username error')); return; } $password = $this->arg('password'); $user = common_check_user($nickname, $password); if (!$user) { // TRANS: Form validation error displayed when trying to log in with incorrect credentials. $this->clientError(_('Incorrect username or password.')); return; } // success! if (!common_set_user($user)) { // TRANS: Server error displayed when during login a server error occurs. $this->serverError(_('Error setting user. You are probably not authorized.')); return; } common_real_login(true); $result = $this->twitterUserArray($user->getProfile(), false); $this->initDocument('json'); $this->showJsonObjects($result); $this->endDocument('json'); }
public function onStartCheckPassword($nickname, $password, &$authenticatedUser) { if (common_is_email($nickname)) { $this->unauthed_user = User::getKV('email', common_canonical_email($nickname)); } else { $this->unauthed_user = User::getKV('nickname', Nickname::normalize($nickname)); } if (!$this->unauthed_user instanceof User) { // Unknown username continue processing StartCheckPassword (maybe uninitialized LDAP user etc?) return true; } $this->failed_attempts = (int) $this->unauthed_user->getPref(self::FAILED_LOGIN_IP_SECTION, $this->client_ip); switch (true) { case $this->failed_attempts >= 5: common_log(LOG_WARNING, sprintf('Multiple failed login attempts for user %s from IP %s - brute force attack?', $this->unauthed_user->getNickname(), $this->client_ip)); // 5 seconds is a good max waiting time anyway... sleep($this->failed_attempts % 5 + 1); break; case $this->failed_attempts > 0: common_debug(sprintf('Previously failed login on user %s from IP %s - sleeping %u seconds.', $this->unauthed_user->getNickname(), $this->client_ip, $this->failed_attempts)); sleep($this->failed_attempts); break; default: // No sleeping if it's our first failed attempt. } return true; }
function prepare($args) { parent::prepare($args); $nickname_arg = $this->arg('nickname'); $nickname = Nickname::normalize($nickname_arg); // Permanent redirect on non-canonical nickname if ($nickname_arg != $nickname) { $args = array('nickname' => $nickname); if ($this->arg('page') && $this->arg('page') != 1) { $args['page'] = $this->arg['page']; } common_redirect(common_local_url($this->trimmed('action'), $args), 301); return false; } $this->user = User::staticGet('nickname', $nickname); if (!$this->user) { $this->clientError(_m('No such user.'), 404); return false; } $this->profile = $this->user->getProfile(); if (!$this->profile) { $this->serverError(_m('User has no profile.')); return false; } $page = $this->trimmed('page'); if (!empty($page) && Validate::number($page)) { $this->page = $page + 0; } else { $this->page = 1; } $this->notices = empty($this->tag) ? $this->user->getNotices(($this->page - 1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1) : $this->user->getTaggedNotices($this->tag, ($this->page - 1) * NOTICES_PER_PAGE, NOTICES_PER_PAGE + 1, 0, 0, null); return true; }
protected function doPost() { if (Event::handle('StartGroupSaveForm', array($this))) { $nickname = Nickname::normalize($this->trimmed('newnickname'), true); $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $description = $this->trimmed('description'); $location = $this->trimmed('location'); $private = $this->boolean('private'); $aliasstring = $this->trimmed('aliases'); if (!is_null($homepage) && strlen($homepage) > 0 && !common_valid_http_url($homepage)) { // TRANS: Group create form validation error. throw new ClientException(_('Homepage is not a valid URL.')); } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Group create form validation error. throw new ClientException(_('Full name is too long (maximum 255 characters).')); } else { if (User_group::descriptionTooLong($description)) { // TRANS: Group create form validation error. // TRANS: %d is the maximum number of allowed characters. throw new ClientException(sprintf(_m('Description is too long (maximum %d character).', 'Description is too long (maximum %d characters).', User_group::maxDescription()), User_group::maxDescription())); } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Group create form validation error. throw new ClientException(_('Location is too long (maximum 255 characters).')); } } } } if (!empty($aliasstring)) { $aliases = array_map(array('Nickname', 'normalize'), array_unique(preg_split('/[\\s,]+/', $aliasstring))); } else { $aliases = array(); } if (count($aliases) > common_config('group', 'maxaliases')) { // TRANS: Group create form validation error. // TRANS: %d is the maximum number of allowed aliases. throw new ClientException(sprintf(_m('Too many aliases! Maximum %d allowed.', 'Too many aliases! Maximum %d allowed.', common_config('group', 'maxaliases')), common_config('group', 'maxaliases'))); } if ($private) { $force_scope = 1; $join_policy = User_group::JOIN_POLICY_MODERATE; } else { $force_scope = 0; $join_policy = User_group::JOIN_POLICY_OPEN; } // This is set up in parent->prepare and checked in self->prepare assert(!is_null($this->scoped)); $group = User_group::register(array('nickname' => $nickname, 'fullname' => $fullname, 'homepage' => $homepage, 'description' => $description, 'location' => $location, 'aliases' => $aliases, 'userid' => $this->scoped->id, 'join_policy' => $join_policy, 'force_scope' => $force_scope, 'local' => true)); $this->group = $group; Event::handle('EndGroupSaveForm', array($this)); common_redirect($group->homeUrl(), 303); } }
/** * Test on the regex matching used in common_find_mentions * (testing on the full notice rendering is difficult as it needs * to be able to pull from global state) * * @dataProvider provider */ public function testAtReply($input, $expected, $expectedException = null) { if ($expected == false) { // nothing to do } else { $text = "@{$input} awesome! :)"; $matches = common_find_mentions_raw($text); $this->assertEquals(1, count($matches)); $this->assertEquals($expected, Nickname::normalize($matches[0][0])); } }
/** * Take arguments for running * * @param array $args $_REQUEST args * * @return boolean success flag */ protected function prepare(array $args = array()) { parent::prepare($args); $this->nickname = Nickname::normalize($this->arg('nickname'), true); $this->fullname = $this->arg('full_name'); $this->homepage = $this->arg('homepage'); $this->description = $this->arg('description'); $this->location = $this->arg('location'); $this->aliasstring = $this->arg('aliases'); return true; }
function changePassword($username, $oldpassword, $newpassword) { $username = Nickname::normalize($username); if (!$this->password_changeable) { return false; } $user = User::getKV('nickname', $username); if (empty($user)) { return false; } $original = clone $user; $user->password = $this->hashPassword($newpassword, $user->getProfile()); return true === $user->validate() && $user->update($original); }
protected function handle() { parent::handle(); $nickname = $this->trimmed('nickname'); try { Nickname::normalize($nickname, true); $nickname_ok = 1; } catch (NicknameException $e) { $nickname_ok = 0; } $this->initDocument('json'); $this->showJsonObjects($nickname_ok); $this->endDocument('json'); }
function bestNewNickname($display, $sreg) { // Try the passed-in nickname if (!empty($sreg['nickname'])) { $nickname = common_nicknamize($sreg['nickname']); if (Nickname::isValid($nickname, true)) { return $nickname; } } // Try the full name if (!empty($sreg['fullname'])) { $fullname = common_nicknamize($sreg['fullname']); if (Nickname::isValid($fullname, true)) { return $fullname; } } // Try the URL $from_url = $this->openidToNickname($display); if ($from_url && Nickname::isValid($from_url, true)) { return $from_url; } // XXX: others? return null; }
/** * Get a local user by name * @return User * @throws CommandException */ function getUser($arg) { $user = null; if (Event::handle('StartCommandGetUser', array($this, $arg, &$user))) { $user = User::getKV('nickname', Nickname::normalize($arg)); } Event::handle('EndCommandGetUser', array($this, $arg, &$user)); if (!$user) { // TRANS: Message given getting a non-existing user. // TRANS: %s is the nickname of the user that could not be found. throw new CommandException(sprintf(_('Could not find a local user with nickname %s.'), $arg)); } return $user; }
/** * Resolve an ambiguous profile nickname reference, checking in following order: * - profiles that $sender subscribes to * - profiles that subscribe to $sender * - local user profiles * * WARNING: does not validate or normalize $nickname -- MUST BE PRE-VALIDATED * OR THERE MAY BE A RISK OF SQL INJECTION ATTACKS. THIS FUNCTION DOES NOT * ESCAPE SQL. * * @fixme validate input * @fixme escape SQL * @fixme fix or remove mystery third parameter * @fixme is $sender a User or Profile? * * @param <type> $sender the user or profile in whose context we're looking * @param string $nickname validated nickname of * @param <type> $dt unused mystery parameter; in Notice reply-to handling a timestamp is passed. * * @return Profile or null */ function common_relative_profile($sender, $nickname, $dt = null) { // Will throw exception on invalid input. $nickname = Nickname::normalize($nickname); // Try to find profiles this profile is subscribed to that have this nickname $recipient = new Profile(); // XXX: use a join instead of a subquery $recipient->whereAdd('EXISTS (SELECT subscribed from subscription where subscriber = ' . intval($sender->id) . ' and subscribed = id)', 'AND'); $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND'); if ($recipient->find(true)) { // XXX: should probably differentiate between profiles with // the same name by date of most recent update return $recipient; } // Try to find profiles that listen to this profile and that have this nickname $recipient = new Profile(); // XXX: use a join instead of a subquery $recipient->whereAdd('EXISTS (SELECT subscriber from subscription where subscribed = ' . intval($sender->id) . ' and subscriber = id)', 'AND'); $recipient->whereAdd("nickname = '" . $recipient->escape($nickname) . "'", 'AND'); if ($recipient->find(true)) { // XXX: should probably differentiate between profiles with // the same name by date of most recent update return $recipient; } // If this is a local user, try to find a local user with that nickname. $sender = User::staticGet($sender->id); if ($sender) { $recipient_user = User::staticGet('nickname', $nickname); if ($recipient_user) { return $recipient_user->getProfile(); } } // Otherwise, no links. @messages from local users to remote users, // or from remote users to other remote users, are just // outside our ability to make intelligent guesses about return null; }
function nicknameFromName($name) { $parts = explode('@', $name); $nickname = $parts[0]; $nickname = preg_replace('/[^A-Za-z0-9]/', '', $nickname); $nickname = Nickname::normalize($nickname); $original = $nickname; $n = 0; while (User::staticGet('nickname', $nickname)) { $n++; $nickname = $original . $n; } return $nickname; }
/** * Handle a post * * Validate input and save changes. Reload the form with a success * or error message. * * @return void */ protected function doPost() { if (Event::handle('StartProfileSaveForm', array($this))) { // $nickname will only be set if this changenick value is true. if (common_config('profile', 'changenick') == true) { try { $nickname = Nickname::normalize($this->trimmed('nickname'), true); } catch (NicknameTakenException $e) { // Abort only if the nickname is occupied by _another_ local user profile if (!$this->scoped->sameAs($e->profile)) { throw $e; } // Since the variable wasn't set before the exception was thrown, let's run // the normalize sequence again, but without in-use check this time. $nickname = Nickname::normalize($this->trimmed('nickname')); } } $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $bio = $this->trimmed('bio'); $location = $this->trimmed('location'); $autosubscribe = $this->booleanintstring('autosubscribe'); $subscribe_policy = $this->trimmed('subscribe_policy'); $private_stream = $this->booleanintstring('private_stream'); $language = $this->trimmed('language'); $timezone = $this->trimmed('timezone'); $tagstring = $this->trimmed('tags'); // Some validation if (!is_null($homepage) && strlen($homepage) > 0 && !common_valid_http_url($homepage)) { // TRANS: Validation error in form for profile settings. throw new ClientException(_('Homepage is not a valid URL.')); } else { if (!is_null($fullname) && mb_strlen($fullname) > 191) { // TRANS: Validation error in form for profile settings. throw new ClientException(_('Full name is too long (maximum 191 characters).')); } else { if (Profile::bioTooLong($bio)) { // TRANS: Validation error in form for profile settings. // TRANS: Plural form is used based on the maximum number of allowed // TRANS: characters for the biography (%d). throw new ClientException(sprintf(_m('Bio is too long (maximum %d character).', 'Bio is too long (maximum %d characters).', Profile::maxBio()), Profile::maxBio())); } else { if (!is_null($location) && mb_strlen($location) > 191) { // TRANS: Validation error in form for profile settings. throw new ClientException(_('Location is too long (maximum 191 characters).')); } else { if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) { // TRANS: Validation error in form for profile settings. throw new ClientException(_('Timezone not selected.')); } else { if (!is_null($language) && strlen($language) > 50) { // TRANS: Validation error in form for profile settings. throw new ClientException(_('Language is too long (maximum 50 characters).')); } } } } } } $tags = array(); $tag_priv = array(); if (is_string($tagstring) && strlen($tagstring) > 0) { $tags = preg_split('/[\\s,]+/', $tagstring); foreach ($tags as &$tag) { $private = @$tag[0] === '.'; $tag = common_canonical_tag($tag); if (!common_valid_profile_tag($tag)) { // TRANS: Validation error in form for profile settings. // TRANS: %s is an invalid tag. throw new ClientException(sprintf(_('Invalid tag: "%s".'), $tag)); } $tag_priv[$tag] = $private; } } $user = $this->scoped->getUser(); $user->query('BEGIN'); // $user->nickname is updated through Profile->update(); // XXX: XOR if ($user->autosubscribe ^ $autosubscribe || $user->private_stream ^ $private_stream || $user->timezone != $timezone || $user->language != $language || $user->subscribe_policy != $subscribe_policy) { $original = clone $user; $user->autosubscribe = $autosubscribe; $user->language = $language; $user->private_stream = $private_stream; $user->subscribe_policy = $subscribe_policy; $user->timezone = $timezone; $result = $user->update($original); if ($result === false) { common_log_db_error($user, 'UPDATE', __FILE__); $user->query('ROLLBACK'); // TRANS: Server error thrown when user profile settings could not be updated to // TRANS: automatically subscribe to any subscriber. throw new ServerException(_('Could not update user for autosubscribe or subscribe_policy.')); } // Re-initialize language environment if it changed common_init_language(); } $original = clone $this->scoped; if (common_config('profile', 'changenick') == true && $this->scoped->getNickname() !== $nickname) { assert(Nickname::normalize($nickname) === $nickname); common_debug("Changing user nickname from '{$this->scoped->getNickname()}' to '{$nickname}'."); $this->scoped->nickname = $nickname; $this->scoped->profileurl = common_profile_url($this->scoped->getNickname()); } $this->scoped->fullname = $fullname; $this->scoped->homepage = $homepage; $this->scoped->bio = $bio; $this->scoped->location = $location; $loc = Location::fromName($location); if (empty($loc)) { $this->scoped->lat = null; $this->scoped->lon = null; $this->scoped->location_id = null; $this->scoped->location_ns = null; } else { $this->scoped->lat = $loc->lat; $this->scoped->lon = $loc->lon; $this->scoped->location_id = $loc->location_id; $this->scoped->location_ns = $loc->location_ns; } if (common_config('location', 'share') == 'user') { $exists = false; $prefs = User_location_prefs::getKV('user_id', $this->scoped->getID()); if (empty($prefs)) { $prefs = new User_location_prefs(); $prefs->user_id = $this->scoped->getID(); $prefs->created = common_sql_now(); } else { $exists = true; $orig = clone $prefs; } $prefs->share_location = $this->booleanintstring('sharelocation'); if ($exists) { $result = $prefs->update($orig); } else { $result = $prefs->insert(); } if ($result === false) { common_log_db_error($prefs, $exists ? 'UPDATE' : 'INSERT', __FILE__); $user->query('ROLLBACK'); // TRANS: Server error thrown when user profile location preference settings could not be updated. throw new ServerException(_('Could not save location prefs.')); } } common_debug('Old profile: ' . common_log_objstring($original), __FILE__); common_debug('New profile: ' . common_log_objstring($this->scoped), __FILE__); $result = $this->scoped->update($original); if ($result === false) { common_log_db_error($this->scoped, 'UPDATE', __FILE__); $user->query('ROLLBACK'); // TRANS: Server error thrown when user profile settings could not be saved. throw new ServerException(_('Could not save profile.')); } // Set the user tags $result = Profile_tag::setSelfTags($this->scoped, $tags, $tag_priv); $user->query('COMMIT'); Event::handle('EndProfileSaveForm', array($this)); // TRANS: Confirmation shown when user profile settings are saved. return _('Settings saved.'); } }
/** * Register a new user account and profile and set up default subscriptions. * If a new-user welcome message is configured, this will be sent. * * @param array $fields associative array of optional properties * string 'bio' * string 'email' * bool 'email_confirmed' pass true to mark email as pre-confirmed * string 'fullname' * string 'homepage' * string 'location' informal string description of geolocation * float 'lat' decimal latitude for geolocation * float 'lon' decimal longitude for geolocation * int 'location_id' geoname identifier * int 'location_ns' geoname namespace to interpret location_id * string 'nickname' REQUIRED * string 'password' (may be missing for eg OpenID registrations) * string 'code' invite code * ?string 'uri' permalink to notice; defaults to local notice URL * @return User object * @throws Exception on failure */ static function register(array $fields) { // MAGICALLY put fields into current scope extract($fields); $profile = new Profile(); if (!empty($email)) { $email = common_canonical_email($email); } // Normalize _and_ check whether it is in use. Throw NicknameException on failure. $profile->nickname = Nickname::normalize($nickname, true); $profile->profileurl = common_profile_url($profile->nickname); if (!empty($fullname)) { $profile->fullname = $fullname; } if (!empty($homepage)) { $profile->homepage = $homepage; } if (!empty($bio)) { $profile->bio = $bio; } if (!empty($location)) { $profile->location = $location; $loc = Location::fromName($location); if (!empty($loc)) { $profile->lat = $loc->lat; $profile->lon = $loc->lon; $profile->location_id = $loc->location_id; $profile->location_ns = $loc->location_ns; } } $profile->created = common_sql_now(); $user = new User(); $user->nickname = $profile->nickname; $invite = null; // Users who respond to invite email have proven their ownership of that address if (!empty($code)) { $invite = Invitation::getKV($code); if ($invite instanceof Invitation && $invite->address && $invite->address_type == 'email' && $invite->address == $email) { $user->email = $invite->address; } } if (isset($email_confirmed) && $email_confirmed) { $user->email = $email; } // Set default-on options here, otherwise they'll be disabled // initially for sites using caching, since the initial encache // doesn't know about the defaults in the database. $user->emailnotifysub = 1; $user->emailnotifynudge = 1; $user->emailnotifymsg = 1; $user->emailnotifyattn = 1; $user->emailmicroid = 1; $user->emailpost = 1; $user->jabbermicroid = 1; $user->created = common_sql_now(); if (Event::handle('StartUserRegister', array($profile))) { $profile->query('BEGIN'); $id = $profile->insert(); if ($id === false) { common_log_db_error($profile, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Profile data could not be inserted for some reason. throw new ServerException(_m('Could not insert profile data for new user.')); } $user->id = $id; if (!empty($uri)) { $user->uri = $uri; } else { $user->uri = common_user_uri($user); } if (!empty($password)) { // may not have a password for OpenID users $user->password = common_munge_password($password, $id); } $result = $user->insert(); if ($result === false) { common_log_db_error($user, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: User data could not be inserted for some reason. throw new ServerException(_m('Could not insert user data for new user.')); } // Everyone is subscribed to themself $subscription = new Subscription(); $subscription->subscriber = $user->id; $subscription->subscribed = $user->id; $subscription->created = $user->created; $result = $subscription->insert(); if (!$result) { common_log_db_error($subscription, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Subscription data could not be inserted for some reason. throw new ServerException(_m('Could not insert subscription data for new user.')); } // Mark that this invite was converted if (!empty($invite)) { $invite->convert($user); } if (!empty($email) && !$user->email) { $confirm = new Confirm_address(); $confirm->code = common_confirmation_code(128); $confirm->user_id = $user->id; $confirm->address = $email; $confirm->address_type = 'email'; $result = $confirm->insert(); if (!$result) { common_log_db_error($confirm, 'INSERT', __FILE__); $profile->query('ROLLBACK'); // TRANS: Email confirmation data could not be inserted for some reason. throw new ServerException(_m('Could not insert email confirmation data for new user.')); } } if (!empty($code) && $user->email) { $user->emailChanged(); } // Default system subscription $defnick = common_config('newuser', 'default'); if (!empty($defnick)) { $defuser = User::getKV('nickname', $defnick); if (empty($defuser)) { common_log(LOG_WARNING, sprintf("Default user %s does not exist.", $defnick), __FILE__); } else { Subscription::ensureStart($profile, $defuser->getProfile()); } } $profile->query('COMMIT'); if (!empty($email) && !$user->email) { mail_confirm_address($user, $confirm->code, $profile->nickname, $email); } // Welcome message $welcome = common_config('newuser', 'welcome'); if (!empty($welcome)) { $welcomeuser = User::getKV('nickname', $welcome); if (empty($welcomeuser)) { common_log(LOG_WARNING, sprintf("Welcome user %s does not exist.", $defnick), __FILE__); } else { $notice = Notice::saveNew($welcomeuser->id, sprintf(_('Welcome to %1$s, @%2$s!'), common_config('site', 'name'), $user->nickname), 'system'); } } Event::handle('EndUserRegister', array($profile)); } if (!$user instanceof User) { throw new ServerException('User could not be registered. Probably an event hook that failed.'); } return $user; }
} include APPDIR . 'Parser.php'; $data = parser(sanitize($data)); if (strpos($data, " ") !== FALSE) { list($verb, $words) = explode(" ", $data, 2); } else { list($verb, $words) = array($data, ""); } if (!defined('USERNAME') && $verb != 'nickname') { list($response->action, $response->data) = array('nickname', 'NONICK_SET'); print_r(json_encode($response)); return; } switch ($verb) { case 'nickname': $nickname = new Nickname(); list($response->action, $response->data) = $nickname->set($words); break; case __('EXIT_VERB'): $exits = new Exits(); list($response->action, $response->data) = $exits->show(); break; case __('NORTH_VERB'): case __('SOUTH_VERB'): case __('EAST_VERB'): case __('WEST_VERB'): case __('UP_VERB'): case __('DOWN_VERB'): case __('INSIDE_VERB'): case __('OUTSIDE_VERB'): $exits = new Exits();
/** * Handle the request * * @param array $args $_REQUEST data (unused) * * @return void */ protected function handle() { parent::handle(); $nickname = $this->trimmed('nickname'); $email = $this->trimmed('email'); $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $bio = $this->trimmed('bio'); $location = $this->trimmed('location'); // We don't trim these... whitespace is OK in a password! $password = $this->arg('password'); $confirm = $this->arg('confirm'); if (empty($this->code)) { common_ensure_session(); if (array_key_exists('invitecode', $_SESSION)) { $this->code = $_SESSION['invitecode']; } } if (common_config('site', 'inviteonly') && empty($this->code)) { // TRANS: Client error displayed when trying to register to an invite-only site without an invitation. $this->clientError(_('Sorry, only invited people can register.'), 401); } if (!empty($this->code)) { $this->invite = Invitation::getKV('code', $this->code); if (empty($this->invite)) { // TRANS: Client error displayed when trying to register to an invite-only site without a valid invitation. $this->clientError(_('Sorry, invalid invitation code.'), 401); } // Store this in case we need it common_ensure_session(); $_SESSION['invitecode'] = $this->code; } // Input scrubbing try { $nickname = Nickname::normalize($nickname, true); } catch (NicknameException $e) { // clientError handles Api exceptions with various formats and stuff $this->clientError($e->getMessage(), $e->getCode()); } $email = common_canonical_email($email); if ($email && !Validate::email($email, common_config('email', 'check_domain'))) { // TRANS: Form validation error displayed when trying to register without a valid e-mail address. $this->clientError(_('Not a valid email address.'), 400); } else { if ($this->emailExists($email)) { // TRANS: Form validation error displayed when trying to register with an already registered e-mail address. $this->clientError(_('Email address already exists.'), 400); } else { if (!is_null($homepage) && strlen($homepage) > 0 && !common_valid_http_url($homepage)) { // TRANS: Form validation error displayed when trying to register with an invalid homepage URL. $this->clientError(_('Homepage is not a valid URL.'), 400); } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Form validation error displayed when trying to register with a too long full name. $this->clientError(_('Full name is too long (maximum 255 characters).'), 400); } else { if (Profile::bioTooLong($bio)) { // TRANS: Form validation error on registration page when providing too long a bio text. // TRANS: %d is the maximum number of characters for bio; used for plural. $this->clientError(sprintf(_m('Bio is too long (maximum %d character).', 'Bio is too long (maximum %d characters).', Profile::maxBio()), Profile::maxBio()), 400); } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Form validation error displayed when trying to register with a too long location. $this->clientError(_('Location is too long (maximum 255 characters).'), 400); } else { if (strlen($password) < 6) { // TRANS: Form validation error displayed when trying to register with too short a password. $this->clientError(_('Password must be 6 or more characters.'), 400); } else { if ($password != $confirm) { // TRANS: Form validation error displayed when trying to register with non-matching passwords. $this->clientError(_('Passwords do not match.'), 400); } else { // annoy spammers sleep(7); try { $user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, 'location' => $location, 'code' => $this->code)); Event::handle('EndRegistrationTry', array($this)); $this->initDocument('json'); $this->showJsonObjects($this->twitterUserArray($user->getProfile())); $this->endDocument('json'); } catch (Exception $e) { $this->clientError($e->getMessage(), 400); } } } } } } } } } }
function bestNewNickname() { try { return Nickname::normalize($this->tw_fields['fullname'], true); } catch (NicknameException $e) { return null; } }
function bestNewNickname() { try { $nickname = Nickname::normalize($this->fbuser->username, true); return $nickname; } catch (NicknameException $e) { // Failed to normalize nickname, but let's try the full name } try { $nickname = Nickname::normalize($this->fbuser->name, true); return $nickname; } catch (NicknameException $e) { // Any more ideas? Nope. } return null; }
/** * Try to register a user * * Validates the input and tries to save a new user and profile * record. On success, shows an instructions page. * * @return void */ function tryRegister() { if (Event::handle('StartRegistrationTry', array($this))) { $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { // TRANS: Client error displayed when the session token does not match or is not given. $this->showForm(_('There was a problem with your session token. ' . 'Try again, please.')); return; } $nickname = $this->trimmed('nickname'); $email = $this->trimmed('email'); $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $bio = $this->trimmed('bio'); $location = $this->trimmed('location'); // We don't trim these... whitespace is OK in a password! $password = $this->arg('password'); $confirm = $this->arg('confirm'); // invitation code, if any $code = $this->trimmed('code'); if ($code) { $invite = Invitation::getKV($code); } if (common_config('site', 'inviteonly') && !($code && $invite)) { // TRANS: Client error displayed when trying to register to an invite-only site without an invitation. $this->clientError(_('Sorry, only invited people can register.')); } // Input scrubbing try { $nickname = Nickname::normalize($nickname, true); } catch (NicknameException $e) { $this->showForm($e->getMessage()); return; } $email = common_canonical_email($email); if (!$this->boolean('license')) { // TRANS: Form validation error displayed when trying to register without agreeing to the site license. $this->showForm(_('You cannot register if you do not ' . 'agree to the license.')); } else { if ($email && !Validate::email($email, common_config('email', 'check_domain'))) { // TRANS: Form validation error displayed when trying to register without a valid e-mail address. $this->showForm(_('Not a valid email address.')); } else { if ($this->emailExists($email)) { // TRANS: Form validation error displayed when trying to register with an already registered e-mail address. $this->showForm(_('Email address already exists.')); } else { if (!is_null($homepage) && strlen($homepage) > 0 && !common_valid_http_url($homepage)) { // TRANS: Form validation error displayed when trying to register with an invalid homepage URL. $this->showForm(_('Homepage is not a valid URL.')); } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Form validation error displayed when trying to register with a too long full name. $this->showForm(_('Full name is too long (maximum 255 characters).')); } else { if (Profile::bioTooLong($bio)) { // TRANS: Form validation error on registration page when providing too long a bio text. // TRANS: %d is the maximum number of characters for bio; used for plural. $this->showForm(sprintf(_m('Bio is too long (maximum %d character).', 'Bio is too long (maximum %d characters).', Profile::maxBio()), Profile::maxBio())); } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Form validation error displayed when trying to register with a too long location. $this->showForm(_('Location is too long (maximum 255 characters).')); } else { if (strlen($password) < 6) { // TRANS: Form validation error displayed when trying to register with too short a password. $this->showForm(_('Password must be 6 or more characters.')); } else { if ($password != $confirm) { // TRANS: Form validation error displayed when trying to register with non-matching passwords. $this->showForm(_('Passwords do not match.')); } else { try { $user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, 'location' => $location, 'code' => $code)); // success! if (!common_set_user($user)) { // TRANS: Server error displayed when saving fails during user registration. $this->serverError(_('Error setting user.')); } // this is a real login common_real_login(true); if ($this->boolean('rememberme')) { common_debug('Adding rememberme cookie for ' . $nickname); common_rememberme($user); } // Re-init language env in case it changed (not yet, but soon) common_init_language(); Event::handle('EndRegistrationTry', array($this)); $this->showSuccess(); } catch (Exception $e) { // TRANS: Form validation error displayed when trying to register with an invalid username or password. $this->showForm($e->getMessage()); } } } } } } } } } } } }
/** * Validate params for the new group * * @return void */ function validateParams() { if ($this->groupNicknameExists($this->nickname)) { $this->clientError(_('Nickname already in use. Try another one.'), 403, $this->format); return false; } else { if (!User_group::allowedNickname($this->nickname)) { $this->clientError(_('Not a valid nickname.'), 403, $this->format); return false; } elseif (!is_null($this->homepage) && strlen($this->homepage) > 0 && !Validate::uri($this->homepage, array('allowed_schemes' => array('http', 'https')))) { $this->clientError(_('Homepage is not a valid URL.'), 403, $this->format); return false; } elseif (!is_null($this->fullname) && mb_strlen($this->fullname) > 255) { $this->clientError(_('Full name is too long (maximum 255 characters).'), 403, $this->format); return false; } elseif (User_group::descriptionTooLong($this->description)) { $this->clientError(sprintf(_m('Description is too long (maximum %d character).', 'Description is too long (maximum %d characters).', User_group::maxDescription()), User_group::maxDescription()), 403, $this->format); return false; } elseif (!is_null($this->location) && mb_strlen($this->location) > 255) { $this->clientError(_('Location is too long (maximum 255 characters).'), 403, $this->format); return false; } } if (!empty($this->aliasstring)) { $this->aliases = array_map('common_canonical_nickname', array_unique(preg_split('/[\\s,]+/', $this->aliasstring))); } else { $this->aliases = array(); } if (count($this->aliases) > common_config('group', 'maxaliases')) { $this->clientError(sprintf(_m('Too many aliases! Maximum %d allowed.', 'Too many aliases! Maximum %d allowed.', common_config('group', 'maxaliases')), common_config('group', 'maxaliases')), 403, $this->format); return false; } foreach ($this->aliases as $alias) { if (!Nickname::isValid($alias)) { $this->clientError(sprintf(_('Invalid alias: "%s".'), $alias), 403, $this->format); return false; } if ($this->groupNicknameExists($alias)) { $this->clientError(sprintf(_('Alias "%s" already in use. Try another one.'), $alias), 403, $this->format); return false; } // XXX assumes alphanum nicknames if (strcmp($alias, $this->nickname) == 0) { $this->clientError(_('Alias can\'t be the same as nickname.'), 403, $this->format); return false; } } // Everything looks OK return true; }
/** * Try to register a user * * Validates the input and tries to save a new user and profile * record. On success, shows an instructions page. * * @return void */ function tryRegister() { if (Event::handle('StartRegistrationTry', array($this))) { $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { $this->showForm(_('There was a problem with your session token. ' . 'Try again, please.')); return; } $nickname = $this->trimmed('nickname'); $email = $this->trimmed('email'); $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $bio = $this->trimmed('bio'); $location = $this->trimmed('location'); // We don't trim these... whitespace is OK in a password! $password = $this->arg('password'); $confirm = $this->arg('confirm'); // invitation code, if any $code = $this->trimmed('code'); if ($code) { $invite = Invitation::staticGet($code); } if (common_config('site', 'inviteonly') && !($code && $invite)) { $this->clientError(_('Sorry, only invited people can register.')); return; } // Input scrubbing try { $nickname = Nickname::normalize($nickname); } catch (NicknameException $e) { $this->showForm($e->getMessage()); } $email = common_canonical_email($email); if (!$this->boolean('license')) { $this->showForm(_('You cannot register if you don\'t ' . 'agree to the license.')); } else { if ($email && !Validate::email($email, common_config('email', 'check_domain'))) { $this->showForm(_('Not a valid email address.')); } else { if ($this->nicknameExists($nickname)) { $this->showForm(_('Nickname already in use. Try another one.')); } else { if (!User::allowed_nickname($nickname)) { $this->showForm(_('Not a valid nickname.')); } else { if ($this->emailExists($email)) { $this->showForm(_('Email address already exists.')); } else { if (!is_null($homepage) && strlen($homepage) > 0 && !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { $this->showForm(_('Homepage is not a valid URL.')); return; } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (Profile::bioTooLong($bio)) { $this->showForm(sprintf(_m('Bio is too long (maximum %d character).', 'Bio is too long (maximum %d characters).', Profile::maxBio()), Profile::maxBio())); return; } else { if (!is_null($location) && mb_strlen($location) > 255) { $this->showForm(_('Location is too long (maximum 255 characters).')); return; } else { if (strlen($password) < 6) { $this->showForm(_('Password must be 6 or more characters.')); return; } else { if ($password != $confirm) { $this->showForm(_('Passwords don\'t match.')); } else { if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, 'location' => $location, 'code' => $code))) { if (!$user) { $this->showForm(_('Invalid username or password.')); return; } // success! if (!common_set_user($user)) { $this->serverError(_('Error setting user.')); return; } // this is a real login common_real_login(true); if ($this->boolean('rememberme')) { common_debug('Adding rememberme cookie for ' . $nickname); common_rememberme($user); } Event::handle('EndRegistrationTry', array($this)); // Re-init language env in case it changed (not yet, but soon) common_init_language(); $this->showSuccess(); } else { $this->showForm(_('Invalid username or password.')); } } } } } } } } } } } } } }
/** * Handle a post * * Validate input and save changes. Reload the form with a success * or error message. * * @return void */ function handlePost() { // CSRF protection $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { // TRANS: Form validation error. $this->showForm(_('There was a problem with your session token. ' . 'Try again, please.')); return; } if (Event::handle('StartProfileSaveForm', array($this))) { try { $nickname = Nickname::normalize($this->trimmed('nickname')); } catch (NicknameException $e) { $this->showForm($e->getMessage()); return; } $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $bio = $this->trimmed('bio'); $location = $this->trimmed('location'); $autosubscribe = $this->boolean('autosubscribe'); $subscribe_policy = $this->trimmed('subscribe_policy'); $private_stream = $this->boolean('private_stream'); $language = $this->trimmed('language'); $timezone = $this->trimmed('timezone'); $tagstring = $this->trimmed('tags'); // Some validation if (!User::allowed_nickname($nickname)) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Not a valid nickname.')); return; } else { if (!is_null($homepage) && strlen($homepage) > 0 && !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Homepage is not a valid URL.')); return; } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (Profile::bioTooLong($bio)) { // TRANS: Validation error in form for profile settings. // TRANS: Plural form is used based on the maximum number of allowed // TRANS: characters for the biography (%d). $this->showForm(sprintf(_m('Bio is too long (maximum %d character).', 'Bio is too long (maximum %d characters).', Profile::maxBio()), Profile::maxBio())); return; } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Location is too long (maximum 255 characters).')); return; } else { if (is_null($timezone) || !in_array($timezone, DateTimeZone::listIdentifiers())) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Timezone not selected.')); return; } else { if ($this->nicknameExists($nickname)) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Nickname already in use. Try another one.')); return; } else { if (!is_null($language) && strlen($language) > 50) { // TRANS: Validation error in form for profile settings. $this->showForm(_('Language is too long (maximum 50 characters).')); return; } } } } } } } } $tags = array(); $tag_priv = array(); if (is_string($tagstring) && strlen($tagstring) > 0) { $tags = preg_split('/[\\s,]+/', $tagstring); foreach ($tags as &$tag) { $private = @$tag[0] === '.'; $tag = common_canonical_tag($tag); if (!common_valid_profile_tag($tag)) { // TRANS: Validation error in form for profile settings. // TRANS: %s is an invalid tag. $this->showForm(sprintf(_('Invalid tag: "%s".'), $tag)); return; } $tag_priv[$tag] = $private; } } $user = common_current_user(); $user->query('BEGIN'); if ($user->nickname != $nickname || $user->language != $language || $user->timezone != $timezone) { common_debug('Updating user nickname from ' . $user->nickname . ' to ' . $nickname, __FILE__); common_debug('Updating user language from ' . $user->language . ' to ' . $language, __FILE__); common_debug('Updating user timezone from ' . $user->timezone . ' to ' . $timezone, __FILE__); $original = clone $user; $user->nickname = $nickname; $user->language = $language; $user->timezone = $timezone; $result = $user->updateKeys($original); if ($result === false) { common_log_db_error($user, 'UPDATE', __FILE__); // TRANS: Server error thrown when user profile settings could not be updated. $this->serverError(_('Could not update user.')); return; } else { // Re-initialize language environment if it changed common_init_language(); // Clear the site owner, in case nickname changed if ($user->hasRole(Profile_role::OWNER)) { User::blow('user:site_owner'); } } } // XXX: XOR if ($user->autosubscribe ^ $autosubscribe || $user->private_stream ^ $private_stream || $user->subscribe_policy != $subscribe_policy) { $original = clone $user; $user->autosubscribe = $autosubscribe; $user->private_stream = $private_stream; $user->subscribe_policy = $subscribe_policy; $result = $user->update($original); if ($result === false) { common_log_db_error($user, 'UPDATE', __FILE__); // TRANS: Server error thrown when user profile settings could not be updated to // TRANS: automatically subscribe to any subscriber. $this->serverError(_('Could not update user for autosubscribe or subscribe_policy.')); return; } } $profile = $user->getProfile(); $orig_profile = clone $profile; $profile->nickname = $user->nickname; $profile->fullname = $fullname; $profile->homepage = $homepage; $profile->bio = $bio; $profile->location = $location; $loc = Location::fromName($location); if (empty($loc)) { $profile->lat = null; $profile->lon = null; $profile->location_id = null; $profile->location_ns = null; } else { $profile->lat = $loc->lat; $profile->lon = $loc->lon; $profile->location_id = $loc->location_id; $profile->location_ns = $loc->location_ns; } $profile->profileurl = common_profile_url($nickname); if (common_config('location', 'share') == 'user') { $exists = false; $prefs = User_location_prefs::staticGet('user_id', $user->id); if (empty($prefs)) { $prefs = new User_location_prefs(); $prefs->user_id = $user->id; $prefs->created = common_sql_now(); } else { $exists = true; $orig = clone $prefs; } $prefs->share_location = $this->boolean('sharelocation'); if ($exists) { $result = $prefs->update($orig); } else { $result = $prefs->insert(); } if ($result === false) { common_log_db_error($prefs, $exists ? 'UPDATE' : 'INSERT', __FILE__); // TRANS: Server error thrown when user profile location preference settings could not be updated. $this->serverError(_('Could not save location prefs.')); return; } } common_debug('Old profile: ' . common_log_objstring($orig_profile), __FILE__); common_debug('New profile: ' . common_log_objstring($profile), __FILE__); $result = $profile->update($orig_profile); if ($result === false) { common_log_db_error($profile, 'UPDATE', __FILE__); // TRANS: Server error thrown when user profile settings could not be saved. $this->serverError(_('Could not save profile.')); return; } // Set the user tags $result = $user->setSelfTags($tags, $tag_priv); if (!$result) { // TRANS: Server error thrown when user profile settings tags could not be saved. $this->serverError(_('Could not save tags.')); return; } $user->query('COMMIT'); Event::handle('EndProfileSaveForm', array($this)); common_broadcast_profile($profile); // TRANS: Confirmation shown when user profile settings are saved. $this->showForm(_('Settings saved.'), true); } }
function prepare($argarray) { parent::prepare($argarray); if (common_config('site', 'closed')) { // TRANS: Client exception trown when registration by e-mail is not allowed. throw new ClientException(_m('Registration not allowed.'), 403); } if ($this->isPost()) { $this->checkSessionToken(); $this->email = $this->trimmed('email'); if (!empty($this->email)) { if (common_config('site', 'inviteonly')) { // TRANS: Client exception trown when trying to register without an invitation. throw new ClientException(_m('Sorry, only invited people can register.'), 403); } $this->email = common_canonical_email($this->email); $this->state = self::NEWEMAIL; } else { $this->state = self::SETPASSWORD; $this->code = $this->trimmed('code'); if (empty($this->code)) { // TRANS: Client exception thrown when no confirmation code was provided. throw new ClientException(_m('No confirmation code.')); } $this->invitation = Invitation::getKV('code', $this->code); if (!empty($this->invitation)) { if (!empty($this->invitation->registered_user_id)) { // TRANS: Client exception trown when using an invitation multiple times. throw new ClientException(_m('Invitation already used.'), 403); } } else { $this->confirmation = Confirm_address::getKV('code', $this->code); if (empty($this->confirmation)) { // TRANS: Client exception thrown when given confirmation code was not issued. throw new ClientException(_m('No such confirmation code.'), 403); } } $this->nickname = Nickname::normalize($this->trimmed('nickname')); $this->password1 = $this->trimmed('password1'); $this->password2 = $this->trimmed('password2'); $this->tos = $this->boolean('tos'); } } else { // GET $this->code = $this->trimmed('code'); if (empty($this->code)) { if (common_config('site', 'inviteonly')) { // TRANS: Client exception trown when trying to register without an invitation. throw new ClientException(_m('Sorry, only invited people can register.'), 403); } $this->state = self::NEWREGISTER; } else { $this->invitation = Invitation::getKV('code', $this->code); if (!empty($this->invitation)) { if (!empty($this->invitation->registered_user_id)) { // TRANS: Client exception trown when using an invitation multiple times. throw new ClientException(_m('Invitation already used.'), 403); } $this->state = self::CONFIRMINVITE; } else { $this->state = self::CONFIRMREGISTER; $this->confirmation = Confirm_address::getKV('code', $this->code); if (empty($this->confirmation)) { // TRANS: Client exception thrown when given confirmation code was not issued. throw new ClientException(_m('No such confirmation code.'), 405); } } } } return true; }
function common_nicknamize($str) { try { return Nickname::normalize($str); } catch (NicknameException $e) { return null; } }
/** * Handle the request * * See which request params have been set, and update the profile * * @return void */ protected function handle() { parent::handle(); if (!in_array($this->format, array('xml', 'json'))) { // TRANS: Client error displayed when coming across a non-supported API method. $this->clientError(_('API method not found.'), 404); } if (empty($this->user)) { // TRANS: Client error displayed when not providing a user or an invalid user. $this->clientError(_('No such user.'), 404); } if (empty($this->group)) { // TRANS: Client error displayed when not providing a group or an invalid group. $this->clientError(_('Group not found.'), 404); } if (!$this->user->isAdmin($this->group)) { // TRANS: Client error displayed when trying to edit a group without being an admin. $this->clientError(_('You must be an admin to edit the group.'), 403); } $this->group->query('BEGIN'); $orig = clone $this->group; try { if (common_config('profile', 'changenick') == true && $this->group->nickname !== $this->nickname) { try { $this->group->nickname = Nickname::normalize($this->nickname, true); } catch (NicknameException $e) { throw new ApiValidationException($e->getMessage()); } $this->group->mainpage = common_local_url('showgroup', array('nickname' => $this->group->nickname)); } if (!empty($this->fullname)) { $this->validateFullname(); $this->group->fullname = $this->fullname; } if (!empty($this->homepage)) { $this->validateHomepage(); $this->group->homepage = $this->homepage; } if (!empty($this->description)) { $this->validateDescription(); $this->group->description = $this->decription; } if (!empty($this->location)) { $this->validateLocation(); $this->group->location = $this->location; } } catch (ApiValidationException $ave) { $this->clientError($ave->getMessage(), 400); } $result = $this->group->update($orig); if (!$result) { common_log_db_error($this->group, 'UPDATE', __FILE__); // TRANS: Server error displayed when group update fails. $this->serverError(_('Could not update group.')); } $aliases = array(); try { if (!empty($this->aliasstring)) { $aliases = $this->validateAliases(); } } catch (ApiValidationException $ave) { $this->clientError($ave->getMessage(), 403); } $result = $this->group->setAliases($aliases); if (!$result) { // TRANS: Server error displayed when adding group aliases fails. $this->serverError(_('Could not create aliases.')); } $this->group->query('COMMIT'); switch ($this->format) { case 'xml': $this->showSingleXmlGroup($this->group); break; case 'json': $this->showSingleJsonGroup($this->group); break; default: // TRANS: Client error displayed when coming across a non-supported API method. $this->clientError(_('API method not found.'), 404); } }
function trySave() { if (Event::handle('StartGroupSaveForm', array($this))) { try { $nickname = Nickname::normalize($this->trimmed('nickname')); } catch (NicknameException $e) { $this->showForm($e->getMessage()); } $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $description = $this->trimmed('description'); $location = $this->trimmed('location'); $aliasstring = $this->trimmed('aliases'); if ($this->nicknameExists($nickname)) { // TRANS: Group create form validation error. $this->showForm(_('Nickname already in use. Try another one.')); return; } else { if (!User_group::allowedNickname($nickname)) { // TRANS: Group create form validation error. $this->showForm(_('Not a valid nickname.')); return; } else { if (!is_null($homepage) && strlen($homepage) > 0 && !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { // TRANS: Group create form validation error. $this->showForm(_('Homepage is not a valid URL.')); return; } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Group create form validation error. $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (User_group::descriptionTooLong($description)) { // TRANS: Group create form validation error. // TRANS: %d is the maximum number of allowed characters. $this->showForm(sprintf(_m('Description is too long (maximum %d character).', 'Description is too long (maximum %d characters).', User_group::maxDescription()), User_group::maxDescription())); return; } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Group create form validation error. $this->showForm(_('Location is too long (maximum 255 characters).')); return; } } } } } } if (!empty($aliasstring)) { $aliases = array_map('common_canonical_nickname', array_unique(preg_split('/[\\s,]+/', $aliasstring))); } else { $aliases = array(); } if (count($aliases) > common_config('group', 'maxaliases')) { // TRANS: Group create form validation error. // TRANS: %d is the maximum number of allowed aliases. $this->showForm(sprintf(_m('Too many aliases! Maximum %d allowed.', 'Too many aliases! Maximum %d allowed.', common_config('group', 'maxaliases')), common_config('group', 'maxaliases'))); return; } foreach ($aliases as $alias) { if (!Nickname::isValid($alias)) { // TRANS: Group create form validation error. // TRANS: %s is the invalid alias. $this->showForm(sprintf(_('Invalid alias: "%s"'), $alias)); return; } if ($this->nicknameExists($alias)) { // TRANS: Group create form validation error. %s is the already used alias. $this->showForm(sprintf(_('Alias "%s" already in use. Try another one.'), $alias)); return; } // XXX assumes alphanum nicknames if (strcmp($alias, $nickname) == 0) { // TRANS: Group create form validation error. $this->showForm(_('Alias cannot be the same as nickname.')); return; } } $cur = common_current_user(); // Checked in prepare() above assert(!is_null($cur)); $group = User_group::register(array('nickname' => $nickname, 'fullname' => $fullname, 'homepage' => $homepage, 'description' => $description, 'location' => $location, 'aliases' => $aliases, 'userid' => $cur->id, 'local' => true)); $this->group = $group; Event::handle('EndGroupSaveForm', array($this)); common_redirect($group->homeUrl(), 303); } }
function trySave() { $cur = common_current_user(); if (!$cur->isAdmin($this->group)) { // TRANS: Client error displayed trying to edit a group while not being a group admin. $this->clientError(_('You must be an admin to edit the group.'), 403); return; } if (Event::handle('StartGroupSaveForm', array($this))) { $nickname = Nickname::normalize($this->trimmed('newnickname')); $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $description = $this->trimmed('description'); $location = $this->trimmed('location'); $aliasstring = $this->trimmed('aliases'); $private = $this->boolean('private'); if ($private) { $force_scope = 1; $join_policy = User_group::JOIN_POLICY_MODERATE; } else { $force_scope = 0; $join_policy = User_group::JOIN_POLICY_OPEN; } if ($this->nicknameExists($nickname)) { // TRANS: Group edit form validation error. $this->showForm(_('Nickname already in use. Try another one.')); return; } else { if (!User_group::allowedNickname($nickname)) { // TRANS: Group edit form validation error. $this->showForm(_('Not a valid nickname.')); return; } else { if (!is_null($homepage) && strlen($homepage) > 0 && !Validate::uri($homepage, array('allowed_schemes' => array('http', 'https')))) { // TRANS: Group edit form validation error. $this->showForm(_('Homepage is not a valid URL.')); return; } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Group edit form validation error. $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (User_group::descriptionTooLong($description)) { $this->showForm(sprintf(_m('Description is too long (maximum %d character).', 'Description is too long (maximum %d characters).', User_group::maxDescription()), User_group::maxDescription())); return; } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Group edit form validation error. $this->showForm(_('Location is too long (maximum 255 characters).')); return; } } } } } } if (!empty($aliasstring)) { $aliases = array_map('common_canonical_nickname', array_unique(preg_split('/[\\s,]+/', $aliasstring))); } else { $aliases = array(); } if (count($aliases) > common_config('group', 'maxaliases')) { // TRANS: Group edit form validation error. // TRANS: %d is the maximum number of allowed aliases. $this->showForm(sprintf(_m('Too many aliases! Maximum %d allowed.', 'Too many aliases! Maximum %d allowed.', common_config('group', 'maxaliases')), common_config('group', 'maxaliases'))); return; } foreach ($aliases as $alias) { if (!Nickname::isValid($alias)) { // TRANS: Group edit form validation error. $this->showForm(sprintf(_('Invalid alias: "%s"'), $alias)); return; } if ($this->nicknameExists($alias)) { // TRANS: Group edit form validation error. $this->showForm(sprintf(_('Alias "%s" already in use. Try another one.'), $alias)); return; } // XXX assumes alphanum nicknames if (strcmp($alias, $nickname) == 0) { // TRANS: Group edit form validation error. $this->showForm(_('Alias can\'t be the same as nickname.')); return; } } // Comprobamos si hay algo que actualizar, o si no ha cambiado nada el usuario. $part1 = false; if ($this->group->nickname == $nickname && $this->group->fullname == $fullname && $this->group->homepage == $homepage && $this->group->description == $description && $this->group->location == $location && $this->group->mainpage == common_local_url('showgroup', array('nickname' => $nickname)) && $this->group->join_policy == $join_policy && $this->group->force_scope == $force_scope) { $part1 = true; } else { $this->group->query('BEGIN'); $orig = clone $this->group; $this->group->nickname = $nickname; $this->group->fullname = $fullname; $this->group->homepage = $homepage; $this->group->description = $description; $this->group->location = $location; $this->group->mainpage = common_local_url('showgroup', array('nickname' => $nickname)); $this->group->join_policy = $join_policy; $this->group->force_scope = $force_scope; $result = $this->group->update($orig); if (!$result) { common_log_db_error($this->group, 'UPDATE', __FILE__); // TRANS: Server error displayed when editing a group fails. $this->serverError(_('Could not update group.')); } } $newaliases = array_unique($aliases); $oldaliases = $this->group->getAliases(); $diffAlias1 = array_diff($oldaliases, $newaliases); $diffAlias2 = array_diff($newaliases, $oldaliases); if ($part1 && (empty($diffAlias1) && empty($diffAlias2))) { $this->showForm(_('Nada que actualizar')); return; } if (!empty($diffAlias1) || !empty($diffAlias2)) { if ($part1) { $this->group->query('BEGIN'); $orig = clone $this->group; } $result = $this->group->setAliases($aliases); if (!$result) { // TRANS: Server error displayed when group aliases could not be added. $this->serverError(_('Could not create aliases.')); } } if ($nickname != $orig->nickname) { common_log(LOG_INFO, "Saving local group info."); $local = Local_group::staticGet('group_id', $this->group->id); $local->setNickname($nickname); } $this->group->query('COMMIT'); Event::handle('EndGroupSaveForm', array($this)); } if ($this->group->nickname != $orig->nickname) { common_redirect(common_local_url('editgroup', array('nickname' => $nickname)), 303); } else { // TRANS: Group edit form success message. $this->showForm(_('Options saved.')); } }
/** * Try to register a user * * Validates the input and tries to save a new user and profile * record. On success, shows an instructions page. * * @return void */ function tryRegister() { if (Event::handle('StartRegistrationTry', array($this))) { $token = $this->trimmed('token'); if (!$token || $token != common_session_token()) { // TRANS: Client error displayed when the session token does not match or is not given. $this->showForm(_('There was a problem with your session token. ' . 'Try again, please.')); return; } $privatekey = "6LfbNe0SAAAAAMlC0ByC2IHKH8LKatPNX8HaMGGH"; $resp = recaptcha_check_answer($privatekey, $_SERVER["REMOTE_ADDR"], $_POST["recaptcha_challenge_field"], $_POST["recaptcha_response_field"]); if (!$resp->is_valid) { // What happens when the CAPTCHA was entered incorrectly $this->showForm(_("El reCAPTCHA no se ha introducido correctamente.")); } else { if ($this->trimmed('phoneLbl') != "") { return; } $nickname = $this->trimmed('nickname'); $email = $this->trimmed('email'); $fullname = $this->trimmed('fullname'); // We don't trim these... whitespace is OK in a password! $password = $this->arg('password'); $confirm = $this->arg('confirm'); // invitation code, if any $code = $this->trimmed('code'); if ($code) { $invite = Invitation::staticGet($code); } if (common_config('site', 'inviteonly') && !($code && $invite)) { // TRANS: Client error displayed when trying to register to an invite-only site without an invitation. $this->clientError(_('Sorry, only invited people can register.')); return; } // Input scrubbing try { $nickname = Nickname::normalize($nickname); } catch (NicknameException $e) { $this->showForm($e->getMessage()); return; } $email = common_canonical_email($email); if (!$this->boolean('license')) { // TRANS: Form validation error displayed when trying to register without agreeing to the site license. $this->showForm(_('You cannot register if you do not ' . 'agree to the license.')); } else { if (!$email) { $this->showForm(_("Email can't be empty")); } else { if ($email && !Validate::email($email, common_config('email', 'check_domain'))) { // TRANS: Form validation error displayed when trying to register without a valid e-mail address. $this->showForm(_('Not a valid email address.')); } else { if ($this->nicknameExists($nickname)) { // TRANS: Form validation error displayed when trying to register with an existing nickname. $this->showForm(_('Nickname already in use. Try another one.')); } else { if (!User::allowed_nickname($nickname)) { // TRANS: Form validation error displayed when trying to register with an invalid nickname. $this->showForm(_('Not a valid nickname.')); } else { if ($this->emailExists($email)) { // TRANS: Form validation error displayed when trying to register with an already registered e-mail address. $this->showForm(_('Email address already exists.')); } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Form validation error displayed when trying to register with a too long full name. $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (strlen($password) < 6) { // TRANS: Form validation error displayed when trying to register with too short a password. $this->showForm(_('Password must be 6 or more characters.')); return; } else { if ($password != $confirm) { // TRANS: Form validation error displayed when trying to register with non-matching passwords. $this->showForm(_('Passwords do not match.')); } else { if ($user = User::register(array('nickname' => $nickname, 'password' => $password, 'email' => $email, 'fullname' => $fullname, 'homepage' => $homepage, 'bio' => $bio, 'location' => $location, 'code' => $code))) { if (!$user) { // TRANS: Form validation error displayed when trying to register with an invalid username or password. $this->showForm(_('Invalid username or password.')); return; } // success! if (!common_set_user($user)) { // TRANS: Server error displayed when saving fails during user registration. $this->serverError(_('Error setting user.')); return; } // this is a real login common_real_login(true); // Re-init language env in case it changed (not yet, but soon) common_init_language(); Event::handle('EndRegistrationTry', array($this)); $this->showSuccess(); } else { // TRANS: Form validation error displayed when trying to register with an invalid username or password. $this->showForm(_('Invalid username or password.')); } } } } } } } } } } } } }
function isNewNickname($str) { if (!Nickname::isValid($str)) { return false; } if (!User::allowed_nickname($str)) { return false; } if (User::staticGet('nickname', $str)) { return false; } return true; }
function trySave() { $cur = common_current_user(); if (!$cur->isAdmin($this->group)) { // TRANS: Client error displayed trying to edit a group while not being a group admin. $this->clientError(_('You must be an admin to edit the group.'), 403); } if (Event::handle('StartGroupSaveForm', array($this))) { // $nickname will only be set if this changenick value is true. if (common_config('profile', 'changenick') == true) { try { $nickname = Nickname::normalize($this->trimmed('newnickname'), true); } catch (NicknameTakenException $e) { // Abort only if the nickname is occupied by _another_ group if ($e->profile->id != $this->group->profile_id) { $this->showForm($e->getMessage()); return; } $nickname = Nickname::normalize($this->trimmed('newnickname')); // without in-use check this time } catch (NicknameException $e) { $this->showForm($e->getMessage()); return; } } $fullname = $this->trimmed('fullname'); $homepage = $this->trimmed('homepage'); $description = $this->trimmed('description'); $location = $this->trimmed('location'); $aliasstring = $this->trimmed('aliases'); $private = $this->boolean('private'); if ($private) { $force_scope = 1; $join_policy = User_group::JOIN_POLICY_MODERATE; } else { $force_scope = 0; $join_policy = User_group::JOIN_POLICY_OPEN; } if (!is_null($homepage) && strlen($homepage) > 0 && !common_valid_http_url($homepage)) { // TRANS: Group edit form validation error. $this->showForm(_('Homepage is not a valid URL.')); return; } else { if (!is_null($fullname) && mb_strlen($fullname) > 255) { // TRANS: Group edit form validation error. $this->showForm(_('Full name is too long (maximum 255 characters).')); return; } else { if (User_group::descriptionTooLong($description)) { $this->showForm(sprintf(_m('Description is too long (maximum %d character).', 'Description is too long (maximum %d characters).', User_group::maxDescription()), User_group::maxDescription())); return; } else { if (!is_null($location) && mb_strlen($location) > 255) { // TRANS: Group edit form validation error. $this->showForm(_('Location is too long (maximum 255 characters).')); return; } } } } if (!empty($aliasstring)) { $aliases = array_map(array('Nickname', 'normalize'), array_unique(preg_split('/[\\s,]+/', $aliasstring))); } else { $aliases = array(); } if (count($aliases) > common_config('group', 'maxaliases')) { // TRANS: Group edit form validation error. // TRANS: %d is the maximum number of allowed aliases. $this->showForm(sprintf(_m('Too many aliases! Maximum %d allowed.', 'Too many aliases! Maximum %d allowed.', common_config('group', 'maxaliases')), common_config('group', 'maxaliases'))); return; } $this->group->query('BEGIN'); $orig = clone $this->group; if (common_config('profile', 'changenick') == true && $this->group->nickname !== $nickname) { assert(Nickname::normalize($nickname) === $nickname); common_debug("Changing group nickname from '{$profile->nickname}' to '{$nickname}'."); $this->group->nickname = $nickname; $this->group->mainpage = common_local_url('showgroup', array('nickname' => $this->group->nickname)); } $this->group->fullname = $fullname; $this->group->homepage = $homepage; $this->group->description = $description; $this->group->location = $location; $this->group->join_policy = $join_policy; $this->group->force_scope = $force_scope; $result = $this->group->update($orig); if ($result === false) { common_log_db_error($this->group, 'UPDATE', __FILE__); // TRANS: Server error displayed when editing a group fails. $this->serverError(_('Could not update group.')); } $result = $this->group->setAliases($aliases); if (!$result) { // TRANS: Server error displayed when group aliases could not be added. $this->serverError(_('Could not create aliases.')); } $this->group->query('COMMIT'); Event::handle('EndGroupSaveForm', array($this)); } if ($this->group->nickname != $orig->nickname) { common_redirect(common_local_url('editgroup', array('nickname' => $this->group->nickname)), 303); } else { // TRANS: Group edit form success message. $this->showForm(_('Options saved.')); } }