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 * Regex with non-capturing group that matches whitespace and some
81 * characters which are allowed right before an @ or ! when mentioning
82 * other users. Like: 'This goes out to:@mmn (@chimo too) (!awwyiss).'
84 * FIXME: Make this so you can have multiple whitespace but not multiple
85 * parenthesis or something. '(((@n_n@)))' might as well be a smiley.
87 const BEFORE_MENTIONS = '(?:^|[\s\.\,\:\;\[\(]+)';
90 * Nice simple check of whether the given string is a valid input nickname,
91 * which can be normalized into an internally canonical form.
93 * Note that valid nicknames may be in use or reserved.
95 * @param string $str The nickname string to test
96 * @param boolean $checkuse Check if it's in use (return false if it is)
98 * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
100 public static function isValid($str, $checkuse=false)
103 self::normalize($str, $checkuse);
104 } catch (NicknameException $e) {
112 * Validate an input nickname string, and normalize it to its canonical form.
113 * The canonical form will be returned, or an exception thrown if invalid.
115 * @param string $str The nickname string to test
116 * @param boolean $checkuse Check if it's in use (return false if it is)
117 * @return string Normalized canonical form of $str
119 * @throws NicknameException (base class)
120 * @throws NicknameBlacklistedException
121 * @throws NicknameEmptyException
122 * @throws NicknameInvalidException
123 * @throws NicknamePathCollisionException
124 * @throws NicknameTakenException
125 * @throws NicknameTooLongException
127 public static function normalize($str, $checkuse=false)
129 // We should also have UTF-8 normalization (å to a etc.)
131 $str = str_replace('_', '', $str);
132 $str = mb_strtolower($str);
134 if (mb_strlen($str) > self::MAX_LEN) {
135 // Display forms must also fit!
136 throw new NicknameTooLongException();
137 } elseif (mb_strlen($str) < 1) {
138 throw new NicknameEmptyException();
139 } elseif (!self::isCanonical($str)) {
140 throw new NicknameInvalidException();
141 } elseif (self::isBlacklisted($str)) {
142 throw new NicknameBlacklistedException();
143 } elseif (self::isSystemPath($str)) {
144 throw new NicknamePathCollisionException();
145 } elseif ($checkuse) {
146 $profile = self::isTaken($str);
147 if ($profile instanceof Profile) {
148 throw new NicknameTakenException($profile);
156 * Is the given string a valid canonical nickname form?
161 public static function isCanonical($str)
163 return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
167 * Is the given string in our nickname blacklist?
172 public static function isBlacklisted($str)
174 $blacklist = common_config('nickname', 'blacklist');
175 return in_array($str, $blacklist);
179 * Is the given string identical to a system path or route?
180 * This could probably be put in some other class, but at
181 * at the moment, only Nickname requires this functionality.
186 public static function isSystemPath($str)
190 // All directory and file names in site root should be blacklisted
191 $d = dir(INSTALLDIR);
192 while (false !== ($entry = $d->read())) {
193 $paths[$entry] = true;
197 // All top level names in the router should be blacklisted
198 $router = Router::get();
199 foreach ($router->m->getPaths() as $path) {
200 if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
201 $paths[$matches[1]] = true;
205 // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
206 foreach (['avatar', 'attachments'] as $cat) {
207 $paths[basename(common_config($cat, 'path'))] = true;
210 return in_array($str, array_keys($paths));
214 * Is the nickname already in use locally? Checks the User table.
217 * @return Profile|null Returns Profile if nickname found, otherwise null
219 public static function isTaken($str)
221 $found = User::getKV('nickname', $str);
222 if ($found instanceof User) {
223 return $found->getProfile();
226 $found = Local_group::getKV('nickname', $str);
227 if ($found instanceof Local_group) {
228 return $found->getProfile();
231 $found = Group_alias::getKV('alias', $str);
232 if ($found instanceof Group_alias) {
233 return $found->getProfile();
240 class NicknameException extends ClientException
242 function __construct($msg=null, $code=400)
245 $msg = $this->defaultMessage();
247 parent::__construct($msg, $code);
251 * Default localized message for this type of exception.
254 protected function defaultMessage()
260 class NicknameInvalidException extends NicknameException {
262 * Default localized message for this type of exception.
265 protected function defaultMessage()
267 // TRANS: Validation error in form for registration, profile and group settings, etc.
268 return _('Nickname must have only lowercase letters and numbers and no spaces.');
272 class NicknameEmptyException extends NicknameInvalidException
275 * Default localized message for this type of exception.
278 protected function defaultMessage()
280 // TRANS: Validation error in form for registration, profile and group settings, etc.
281 return _('Nickname cannot be empty.');
285 class NicknameTooLongException extends NicknameInvalidException
288 * Default localized message for this type of exception.
291 protected function defaultMessage()
293 // TRANS: Validation error in form for registration, profile and group settings, etc.
294 return sprintf(_m('Nickname cannot be more than %d character long.',
295 'Nickname cannot be more than %d characters long.',
301 class NicknameBlacklistedException extends NicknameException
303 protected function defaultMessage()
305 // TRANS: Validation error in form for registration, profile and group settings, etc.
306 return _('Nickname is disallowed through blacklist.');
310 class NicknamePathCollisionException extends NicknameException
312 protected function defaultMessage()
314 // TRANS: Validation error in form for registration, profile and group settings, etc.
315 return _('Nickname is identical to system path names.');
319 class NicknameTakenException extends NicknameException
321 public $profile = null; // the Profile which occupies the nickname
323 public function __construct(Profile $profile, $msg=null, $code=400)
325 $this->profile = $profile;
328 $msg = $this->defaultMessage();
331 parent::__construct($msg, $code);
334 protected function defaultMessage()
336 // TRANS: Validation error in form for registration, profile and group settings, etc.
337 return _('Nickname is already in use on this server.');