nickname.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008, 2009, StatusNet, Inc.
  5. *
  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.
  10. *
  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.
  15. *
  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/>.
  18. */
  19. class Nickname
  20. {
  21. /**
  22. * Regex fragment for pulling a formated nickname *OR* ID number.
  23. * Suitable for router def of 'id' parameters on API actions.
  24. *
  25. * Not guaranteed to be valid after normalization; run the string through
  26. * Nickname::normalize() to get the canonical form, or Nickname::isValid()
  27. * if you just need to check if it's properly formatted.
  28. *
  29. * This, DISPLAY_FMT, and CANONICAL_FMT should not be enclosed in []s.
  30. *
  31. * @fixme would prefer to define in reference to the other constants
  32. */
  33. const INPUT_FMT = '(?:[0-9]+|[0-9a-zA-Z_]{1,64})';
  34. /**
  35. * Regex fragment for acceptable user-formatted variant of a nickname.
  36. *
  37. * This includes some chars such as underscore which will be removed
  38. * from the normalized canonical form, but still must fit within
  39. * field length limits.
  40. *
  41. * Not guaranteed to be valid after normalization; run the string through
  42. * Nickname::normalize() to get the canonical form, or Nickname::isValid()
  43. * if you just need to check if it's properly formatted.
  44. *
  45. * This, INPUT_FMT and CANONICAL_FMT should not be enclosed in []s.
  46. */
  47. const DISPLAY_FMT = '[0-9a-zA-Z_]{1,64}';
  48. /**
  49. * Simplified regex fragment for acceptable full WebFinger ID of a user
  50. *
  51. * We could probably use an email regex here, but mainly we are interested
  52. * in matching it in our URLs, like https://social.example/user@example.com
  53. */
  54. const WEBFINGER_FMT = '(?:\w+[\w\-\_\.]*)?\w+\@'.URL_REGEX_DOMAIN_NAME;
  55. // old one without support for -_. in nickname part:
  56. // const WEBFINGER_FMT = '[0-9a-zA-Z_]{1,64}\@[0-9a-zA-Z_-.]{3,255}';
  57. /**
  58. * Regex fragment for checking a canonical nickname.
  59. *
  60. * Any non-matching string is not a valid canonical/normalized nickname.
  61. * Matching strings are valid and canonical form, but may still be
  62. * unavailable for registration due to blacklisting et.
  63. *
  64. * Only the canonical forms should be stored as keys in the database;
  65. * there are multiple possible denormalized forms for each valid
  66. * canonical-form name.
  67. *
  68. * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
  69. */
  70. const CANONICAL_FMT = '[0-9a-z_]{1,64}';
  71. /**
  72. * Maximum number of characters in a canonical-form nickname.
  73. */
  74. const MAX_LEN = 64;
  75. /**
  76. * Regex with non-capturing group that matches whitespace and some
  77. * characters which are allowed right before an @ or ! when mentioning
  78. * other users. Like: 'This goes out to:@mmn (@chimo too) (!awwyiss).'
  79. *
  80. * FIXME: Make this so you can have multiple whitespace but not multiple
  81. * parenthesis or something. '(((@n_n@)))' might as well be a smiley.
  82. */
  83. const BEFORE_MENTIONS = '(?:^|[\s\.\,\:\;\[\(]+)';
  84. /**
  85. * Nice simple check of whether the given string is a valid input nickname,
  86. * which can be normalized into an internally canonical form.
  87. *
  88. * Note that valid nicknames may be in use or reserved.
  89. *
  90. * @param string $str The nickname string to test
  91. * @param boolean $checkuse Check if it's in use (return false if it is)
  92. *
  93. * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
  94. */
  95. public static function isValid($str, $checkuse=false)
  96. {
  97. try {
  98. self::normalize($str, $checkuse);
  99. } catch (NicknameException $e) {
  100. return false;
  101. }
  102. return true;
  103. }
  104. /**
  105. * Validate an input nickname string, and normalize it to its canonical form.
  106. * The canonical form will be returned, or an exception thrown if invalid.
  107. *
  108. * @param string $str The nickname string to test
  109. * @param boolean $checkuse Check if it's in use (return false if it is)
  110. * @return string Normalized canonical form of $str
  111. *
  112. * @throws NicknameException (base class)
  113. * @throws NicknameBlacklistedException
  114. * @throws NicknameEmptyException
  115. * @throws NicknameInvalidException
  116. * @throws NicknamePathCollisionException
  117. * @throws NicknameTakenException
  118. * @throws NicknameTooLongException
  119. */
  120. public static function normalize($str, $checkuse=false)
  121. {
  122. if (mb_strlen($str) > self::MAX_LEN) {
  123. // Display forms must also fit!
  124. throw new NicknameTooLongException();
  125. }
  126. // We should also have UTF-8 normalization (å to a etc.)
  127. $str = trim($str);
  128. $str = mb_strtolower($str);
  129. if (mb_strlen($str) < 1) {
  130. throw new NicknameEmptyException();
  131. } elseif (!self::isCanonical($str) && !filter_var($str, FILTER_VALIDATE_EMAIL)) {
  132. throw new NicknameInvalidException();
  133. } elseif (self::isBlacklisted($str)) {
  134. throw new NicknameBlacklistedException();
  135. } elseif (self::isSystemPath($str)) {
  136. throw new NicknamePathCollisionException();
  137. } elseif ($checkuse) {
  138. $profile = self::isTaken($str);
  139. if ($profile instanceof Profile) {
  140. throw new NicknameTakenException($profile);
  141. }
  142. }
  143. return $str;
  144. }
  145. /**
  146. * Is the given string a valid canonical nickname form?
  147. *
  148. * @param string $str
  149. * @return boolean
  150. */
  151. public static function isCanonical($str)
  152. {
  153. return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
  154. }
  155. /**
  156. * Is the given string in our nickname blacklist?
  157. *
  158. * @param string $str
  159. * @return boolean
  160. */
  161. public static function isBlacklisted($str)
  162. {
  163. $blacklist = common_config('nickname', 'blacklist');
  164. if(!$blacklist)
  165. return false;
  166. return in_array($str, $blacklist);
  167. }
  168. /**
  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.
  172. *
  173. * @param string $str
  174. * @return boolean
  175. */
  176. public static function isSystemPath($str)
  177. {
  178. $paths = [];
  179. // All directory and file names in site root should be blacklisted
  180. $d = dir(PUBLICDIR);
  181. while (false !== ($entry = $d->read())) {
  182. $paths[$entry] = true;
  183. }
  184. $d->close();
  185. // All top level names in the router should be blacklisted
  186. $router = Router::get();
  187. foreach ($router->m->getPaths() as $path) {
  188. if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
  189. $paths[$matches[1]] = true;
  190. }
  191. }
  192. // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
  193. foreach (['avatar', 'attachments'] as $cat) {
  194. $paths[basename(common_config($cat, 'path'))] = true;
  195. }
  196. return in_array($str, array_keys($paths));
  197. }
  198. /**
  199. * Is the nickname already in use locally? Checks the User table.
  200. *
  201. * @param string $str
  202. * @return Profile|null Returns Profile if nickname found, otherwise null
  203. */
  204. public static function isTaken($str)
  205. {
  206. $found = User::getKV('nickname', $str);
  207. if ($found instanceof User) {
  208. return $found->getProfile();
  209. }
  210. $found = Local_group::getKV('nickname', $str);
  211. if ($found instanceof Local_group) {
  212. return $found->getProfile();
  213. }
  214. $found = Group_alias::getKV('alias', $str);
  215. if ($found instanceof Group_alias) {
  216. return $found->getProfile();
  217. }
  218. return null;
  219. }
  220. }
  221. class NicknameException extends ClientException
  222. {
  223. function __construct($msg=null, $code=400)
  224. {
  225. if ($msg === null) {
  226. $msg = $this->defaultMessage();
  227. }
  228. parent::__construct($msg, $code);
  229. }
  230. /**
  231. * Default localized message for this type of exception.
  232. * @return string
  233. */
  234. protected function defaultMessage()
  235. {
  236. return null;
  237. }
  238. }
  239. class NicknameInvalidException extends NicknameException {
  240. /**
  241. * Default localized message for this type of exception.
  242. * @return string
  243. */
  244. protected function defaultMessage()
  245. {
  246. // TRANS: Validation error in form for registration, profile and group settings, etc.
  247. return _('Nickname must have only lowercase letters and numbers and no spaces.');
  248. }
  249. }
  250. class NicknameEmptyException extends NicknameInvalidException
  251. {
  252. /**
  253. * Default localized message for this type of exception.
  254. * @return string
  255. */
  256. protected function defaultMessage()
  257. {
  258. // TRANS: Validation error in form for registration, profile and group settings, etc.
  259. return _('Nickname cannot be empty.');
  260. }
  261. }
  262. class NicknameTooLongException extends NicknameInvalidException
  263. {
  264. /**
  265. * Default localized message for this type of exception.
  266. * @return string
  267. */
  268. protected function defaultMessage()
  269. {
  270. // TRANS: Validation error in form for registration, profile and group settings, etc.
  271. return sprintf(_m('Nickname cannot be more than %d character long.',
  272. 'Nickname cannot be more than %d characters long.',
  273. Nickname::MAX_LEN),
  274. Nickname::MAX_LEN);
  275. }
  276. }
  277. class NicknameBlacklistedException extends NicknameException
  278. {
  279. protected function defaultMessage()
  280. {
  281. // TRANS: Validation error in form for registration, profile and group settings, etc.
  282. return _('Nickname is disallowed through blacklist.');
  283. }
  284. }
  285. class NicknamePathCollisionException extends NicknameException
  286. {
  287. protected function defaultMessage()
  288. {
  289. // TRANS: Validation error in form for registration, profile and group settings, etc.
  290. return _('Nickname is identical to system path names.');
  291. }
  292. }
  293. class NicknameTakenException extends NicknameException
  294. {
  295. public $profile = null; // the Profile which occupies the nickname
  296. public function __construct(Profile $profile, $msg=null, $code=400)
  297. {
  298. $this->profile = $profile;
  299. if ($msg === null) {
  300. $msg = $this->defaultMessage();
  301. }
  302. parent::__construct($msg, $code);
  303. }
  304. protected function defaultMessage()
  305. {
  306. // TRANS: Validation error in form for registration, profile and group settings, etc.
  307. return _('Nickname is already in use on this server.');
  308. }
  309. }