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 = '[0-9a-zA-Z_]{1,64}\@[0-9a-zA-Z_-.]{3,255}';
60 * Regex fragment for checking a canonical nickname.
62 * Any non-matching string is not a valid canonical/normalized nickname.
63 * Matching strings are valid and canonical form, but may still be
64 * unavailable for registration due to blacklisting et.
66 * Only the canonical forms should be stored as keys in the database;
67 * there are multiple possible denormalized forms for each valid
68 * canonical-form name.
70 * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
72 const CANONICAL_FMT = '[0-9a-z]{1,64}';
75 * Maximum number of characters in a canonical-form nickname.
80 * Nice simple check of whether the given string is a valid input nickname,
81 * which can be normalized into an internally canonical form.
83 * Note that valid nicknames may be in use or reserved.
85 * @param string $str The nickname string to test
86 * @param boolean $checkuse Check if it's in use (return false if it is)
88 * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
90 public static function isValid($str, $checkuse=false)
93 self::normalize($str, $checkuse);
94 } catch (NicknameException $e) {
102 * Validate an input nickname string, and normalize it to its canonical form.
103 * The canonical form will be returned, or an exception thrown if invalid.
105 * @param string $str The nickname string to test
106 * @param boolean $checkuse Check if it's in use (return false if it is)
107 * @return string Normalized canonical form of $str
109 * @throws NicknameException (base class)
110 * @throws NicknameBlacklistedException
111 * @throws NicknameEmptyException
112 * @throws NicknameInvalidException
113 * @throws NicknamePathCollisionException
114 * @throws NicknameTakenException
115 * @throws NicknameTooLongException
117 public static function normalize($str, $checkuse=false)
119 // We should also have UTF-8 normalization (å to a etc.)
121 $str = str_replace('_', '', $str);
122 $str = mb_strtolower($str);
124 if (mb_strlen($str) > self::MAX_LEN) {
125 // Display forms must also fit!
126 throw new NicknameTooLongException();
127 } elseif (mb_strlen($str) < 1) {
128 throw new NicknameEmptyException();
129 } elseif (!self::isCanonical($str)) {
130 throw new NicknameInvalidException();
131 } elseif (self::isBlacklisted($str)) {
132 throw new NicknameBlacklistedException();
133 } elseif (self::isSystemPath($str)) {
134 throw new NicknamePathCollisionException();
135 } elseif ($checkuse) {
136 $profile = self::isTaken($str);
137 if ($profile instanceof Profile) {
138 throw new NicknameTakenException($profile);
146 * Is the given string a valid canonical nickname form?
151 public static function isCanonical($str)
153 return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
157 * Is the given string in our nickname blacklist?
162 public static function isBlacklisted($str)
164 $blacklist = common_config('nickname', 'blacklist');
165 return in_array($str, $blacklist);
169 * Is the given string identical to a system path or route?
170 * This could probably be put in some other class, but at
171 * at the moment, only Nickname requires this functionality.
176 public static function isSystemPath($str)
180 // All directory and file names in site root should be blacklisted
181 $d = dir(INSTALLDIR);
182 while (false !== ($entry = $d->read())) {
183 $paths[$entry] = true;
187 // All top level names in the router should be blacklisted
188 $router = Router::get();
189 foreach ($router->m->getPaths() as $path) {
190 if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
191 $paths[$matches[1]] = true;
195 // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
196 foreach (['avatar', 'attachments'] as $cat) {
197 $paths[basename(common_config($cat, 'path'))] = true;
200 return in_array($str, array_keys($paths));
204 * Is the nickname already in use locally? Checks the User table.
207 * @return Profile|null Returns Profile if nickname found, otherwise null
209 public static function isTaken($str)
211 $found = User::getKV('nickname', $str);
212 if ($found instanceof User) {
213 return $found->getProfile();
216 $found = Local_group::getKV('nickname', $str);
217 if ($found instanceof Local_group) {
218 return $found->getProfile();
221 $found = Group_alias::getKV('alias', $str);
222 if ($found instanceof Group_alias) {
223 return $found->getProfile();
230 class NicknameException extends ClientException
232 function __construct($msg=null, $code=400)
235 $msg = $this->defaultMessage();
237 parent::__construct($msg, $code);
241 * Default localized message for this type of exception.
244 protected function defaultMessage()
250 class NicknameInvalidException extends NicknameException {
252 * Default localized message for this type of exception.
255 protected function defaultMessage()
257 // TRANS: Validation error in form for registration, profile and group settings, etc.
258 return _('Nickname must have only lowercase letters and numbers and no spaces.');
262 class NicknameEmptyException extends NicknameInvalidException
265 * Default localized message for this type of exception.
268 protected function defaultMessage()
270 // TRANS: Validation error in form for registration, profile and group settings, etc.
271 return _('Nickname cannot be empty.');
275 class NicknameTooLongException extends NicknameInvalidException
278 * Default localized message for this type of exception.
281 protected function defaultMessage()
283 // TRANS: Validation error in form for registration, profile and group settings, etc.
284 return sprintf(_m('Nickname cannot be more than %d character long.',
285 'Nickname cannot be more than %d characters long.',
291 class NicknameBlacklistedException extends NicknameException
293 protected function defaultMessage()
295 // TRANS: Validation error in form for registration, profile and group settings, etc.
296 return _('Nickname is disallowed through blacklist.');
300 class NicknamePathCollisionException extends NicknameException
302 protected function defaultMessage()
304 // TRANS: Validation error in form for registration, profile and group settings, etc.
305 return _('Nickname is identical to system path names.');
309 class NicknameTakenException extends NicknameException
311 public $profile = null; // the Profile which occupies the nickname
313 public function __construct(Profile $profile, $msg=null, $code=400)
315 $this->profile = $profile;
318 $msg = $this->defaultMessage();
321 parent::__construct($msg, $code);
324 protected function defaultMessage()
326 // TRANS: Validation error in form for registration, profile and group settings, etc.
327 return _('Nickname is already in use on this server.');