3 * StatusNet - the distributed open-source microblogging tool
4 * Copyright (C) 2008, 2009, StatusNet, Inc.
6 * This program is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU Affero General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU Affero General Public License for more details.
16 * You should have received a copy of the GNU Affero General Public License
17 * along with this program. If not, see <http://www.gnu.org/licenses/>.
23 * Regex fragment for pulling a formated nickname *OR* ID number.
24 * Suitable for router def of 'id' parameters on API actions.
26 * Not guaranteed to be valid after normalization; run the string through
27 * Nickname::normalize() to get the canonical form, or Nickname::isValid()
28 * if you just need to check if it's properly formatted.
30 * This, DISPLAY_FMT, and CANONICAL_FMT should not be enclosed in []s.
32 * @fixme would prefer to define in reference to the other constants
34 const INPUT_FMT = '(?:[0-9]+|[0-9a-zA-Z_]{1,64})';
37 * Regex fragment for acceptable user-formatted variant of a nickname.
39 * This includes some chars such as underscore which will be removed
40 * from the normalized canonical form, but still must fit within
41 * field length limits.
43 * Not guaranteed to be valid after normalization; run the string through
44 * Nickname::normalize() to get the canonical form, or Nickname::isValid()
45 * if you just need to check if it's properly formatted.
47 * This, INPUT_FMT and CANONICAL_FMT should not be enclosed in []s.
49 const DISPLAY_FMT = '[0-9a-zA-Z_]{1,64}';
52 * Simplified regex fragment for acceptable full WebFinger ID of a user
54 * We could probably use an email regex here, but mainly we are interested
55 * in matching it in our URLs, like https://social.example/user@example.com
57 const WEBFINGER_FMT = '(?:\w+[\w\-\_\.]*)?\w+\@'.URL_REGEX_DOMAIN_NAME;
59 // old one without support for -_. in nickname part:
60 // const WEBFINGER_FMT = '[0-9a-zA-Z_]{1,64}\@[0-9a-zA-Z_-.]{3,255}';
63 * Regex fragment for checking a canonical nickname.
65 * Any non-matching string is not a valid canonical/normalized nickname.
66 * Matching strings are valid and canonical form, but may still be
67 * unavailable for registration due to blacklisting et.
69 * Only the canonical forms should be stored as keys in the database;
70 * there are multiple possible denormalized forms for each valid
71 * canonical-form name.
73 * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
75 const CANONICAL_FMT = '[0-9a-z]{1,64}';
78 * Maximum number of characters in a canonical-form nickname.
83 * Regex with non-capturing group that matches whitespace and some
84 * characters which are allowed right before an @ or ! when mentioning
85 * other users. Like: 'This goes out to:@mmn (@chimo too) (!awwyiss).'
87 * FIXME: Make this so you can have multiple whitespace but not multiple
88 * parenthesis or something. '(((@n_n@)))' might as well be a smiley.
90 const BEFORE_MENTIONS = '(?:^|[\s\.\,\:\;\[\(]+)';
93 * Nice simple check of whether the given string is a valid input nickname,
94 * which can be normalized into an internally canonical form.
96 * Note that valid nicknames may be in use or reserved.
98 * @param string $str The nickname string to test
99 * @param boolean $checkuse Check if it's in use (return false if it is)
101 * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
103 public static function isValid($str, $checkuse=false)
106 self::normalize($str, $checkuse);
107 } catch (NicknameException $e) {
115 * Validate an input nickname string, and normalize it to its canonical form.
116 * The canonical form will be returned, or an exception thrown if invalid.
118 * @param string $str The nickname string to test
119 * @param boolean $checkuse Check if it's in use (return false if it is)
120 * @return string Normalized canonical form of $str
122 * @throws NicknameException (base class)
123 * @throws NicknameBlacklistedException
124 * @throws NicknameEmptyException
125 * @throws NicknameInvalidException
126 * @throws NicknamePathCollisionException
127 * @throws NicknameTakenException
128 * @throws NicknameTooLongException
130 public static function normalize($str, $checkuse=false)
132 if (mb_strlen($str) > self::MAX_LEN) {
133 // Display forms must also fit!
134 throw new NicknameTooLongException();
137 // We should also have UTF-8 normalization (å to a etc.)
139 $str = str_replace('_', '', $str);
140 $str = mb_strtolower($str);
142 if (mb_strlen($str) < 1) {
143 throw new NicknameEmptyException();
144 } elseif (!self::isCanonical($str)) {
145 throw new NicknameInvalidException();
146 } elseif (self::isBlacklisted($str)) {
147 throw new NicknameBlacklistedException();
148 } elseif (self::isSystemPath($str)) {
149 throw new NicknamePathCollisionException();
150 } elseif ($checkuse) {
151 $profile = self::isTaken($str);
152 if ($profile instanceof Profile) {
153 throw new NicknameTakenException($profile);
161 * Is the given string a valid canonical nickname form?
166 public static function isCanonical($str)
168 return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
172 * Is the given string in our nickname blacklist?
177 public static function isBlacklisted($str)
179 $blacklist = common_config('nickname', 'blacklist');
182 return in_array($str, $blacklist);
186 * Is the given string identical to a system path or route?
187 * This could probably be put in some other class, but at
188 * at the moment, only Nickname requires this functionality.
193 public static function isSystemPath($str)
197 // All directory and file names in site root should be blacklisted
198 $d = dir(INSTALLDIR);
199 while (false !== ($entry = $d->read())) {
200 $paths[$entry] = true;
204 // All top level names in the router should be blacklisted
205 $router = Router::get();
206 foreach ($router->m->getPaths() as $path) {
207 if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
208 $paths[$matches[1]] = true;
212 // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
213 foreach (['avatar', 'attachments'] as $cat) {
214 $paths[basename(common_config($cat, 'path'))] = true;
217 return in_array($str, array_keys($paths));
221 * Is the nickname already in use locally? Checks the User table.
224 * @return Profile|null Returns Profile if nickname found, otherwise null
226 public static function isTaken($str)
228 $found = User::getKV('nickname', $str);
229 if ($found instanceof User) {
230 return $found->getProfile();
233 $found = Local_group::getKV('nickname', $str);
234 if ($found instanceof Local_group) {
235 return $found->getProfile();
238 $found = Group_alias::getKV('alias', $str);
239 if ($found instanceof Group_alias) {
240 return $found->getProfile();
247 class NicknameException extends ClientException
249 function __construct($msg=null, $code=400)
252 $msg = $this->defaultMessage();
254 parent::__construct($msg, $code);
258 * Default localized message for this type of exception.
261 protected function defaultMessage()
267 class NicknameInvalidException extends NicknameException {
269 * Default localized message for this type of exception.
272 protected function defaultMessage()
274 // TRANS: Validation error in form for registration, profile and group settings, etc.
275 return _('Nickname must have only lowercase letters and numbers and no spaces.');
279 class NicknameEmptyException extends NicknameInvalidException
282 * Default localized message for this type of exception.
285 protected function defaultMessage()
287 // TRANS: Validation error in form for registration, profile and group settings, etc.
288 return _('Nickname cannot be empty.');
292 class NicknameTooLongException extends NicknameInvalidException
295 * Default localized message for this type of exception.
298 protected function defaultMessage()
300 // TRANS: Validation error in form for registration, profile and group settings, etc.
301 return sprintf(_m('Nickname cannot be more than %d character long.',
302 'Nickname cannot be more than %d characters long.',
308 class NicknameBlacklistedException extends NicknameException
310 protected function defaultMessage()
312 // TRANS: Validation error in form for registration, profile and group settings, etc.
313 return _('Nickname is disallowed through blacklist.');
317 class NicknamePathCollisionException extends NicknameException
319 protected function defaultMessage()
321 // TRANS: Validation error in form for registration, profile and group settings, etc.
322 return _('Nickname is identical to system path names.');
326 class NicknameTakenException extends NicknameException
328 public $profile = null; // the Profile which occupies the nickname
330 public function __construct(Profile $profile, $msg=null, $code=400)
332 $this->profile = $profile;
335 $msg = $this->defaultMessage();
338 parent::__construct($msg, $code);
341 protected function defaultMessage()
343 // TRANS: Validation error in form for registration, profile and group settings, etc.
344 return _('Nickname is already in use on this server.');