nickname.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347
  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 = str_replace('_', '', $str);
  129. $str = mb_strtolower($str);
  130. if (mb_strlen($str) < 1) {
  131. throw new NicknameEmptyException();
  132. } elseif (!self::isCanonical($str) && !filter_var($str, FILTER_VALIDATE_EMAIL)) {
  133. throw new NicknameInvalidException();
  134. } elseif (self::isBlacklisted($str)) {
  135. throw new NicknameBlacklistedException();
  136. } elseif (self::isSystemPath($str)) {
  137. throw new NicknamePathCollisionException();
  138. } elseif ($checkuse) {
  139. $profile = self::isTaken($str);
  140. if ($profile instanceof Profile) {
  141. throw new NicknameTakenException($profile);
  142. }
  143. }
  144. return $str;
  145. }
  146. /**
  147. * Is the given string a valid canonical nickname form?
  148. *
  149. * @param string $str
  150. * @return boolean
  151. */
  152. public static function isCanonical($str)
  153. {
  154. return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
  155. }
  156. /**
  157. * Is the given string in our nickname blacklist?
  158. *
  159. * @param string $str
  160. * @return boolean
  161. */
  162. public static function isBlacklisted($str)
  163. {
  164. $blacklist = common_config('nickname', 'blacklist');
  165. if(!$blacklist)
  166. return false;
  167. return in_array($str, $blacklist);
  168. }
  169. /**
  170. * Is the given string identical to a system path or route?
  171. * This could probably be put in some other class, but at
  172. * at the moment, only Nickname requires this functionality.
  173. *
  174. * @param string $str
  175. * @return boolean
  176. */
  177. public static function isSystemPath($str)
  178. {
  179. $paths = array();
  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;
  184. }
  185. $d->close();
  186. // All top level names in the router should be blacklisted
  187. $router = Router::get();
  188. foreach ($router->m->getPaths() as $path) {
  189. if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
  190. $paths[$matches[1]] = true;
  191. }
  192. }
  193. // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
  194. foreach (['avatar', 'attachments'] as $cat) {
  195. $paths[basename(common_config($cat, 'path'))] = true;
  196. }
  197. return in_array($str, array_keys($paths));
  198. }
  199. /**
  200. * Is the nickname already in use locally? Checks the User table.
  201. *
  202. * @param string $str
  203. * @return Profile|null Returns Profile if nickname found, otherwise null
  204. */
  205. public static function isTaken($str)
  206. {
  207. $found = User::getKV('nickname', $str);
  208. if ($found instanceof User) {
  209. return $found->getProfile();
  210. }
  211. $found = Local_group::getKV('nickname', $str);
  212. if ($found instanceof Local_group) {
  213. return $found->getProfile();
  214. }
  215. $found = Group_alias::getKV('alias', $str);
  216. if ($found instanceof Group_alias) {
  217. return $found->getProfile();
  218. }
  219. return null;
  220. }
  221. }
  222. class NicknameException extends ClientException
  223. {
  224. function __construct($msg=null, $code=400)
  225. {
  226. if ($msg === null) {
  227. $msg = $this->defaultMessage();
  228. }
  229. parent::__construct($msg, $code);
  230. }
  231. /**
  232. * Default localized message for this type of exception.
  233. * @return string
  234. */
  235. protected function defaultMessage()
  236. {
  237. return null;
  238. }
  239. }
  240. class NicknameInvalidException extends NicknameException {
  241. /**
  242. * Default localized message for this type of exception.
  243. * @return string
  244. */
  245. protected function defaultMessage()
  246. {
  247. // TRANS: Validation error in form for registration, profile and group settings, etc.
  248. return _('Nickname must have only lowercase letters and numbers and no spaces.');
  249. }
  250. }
  251. class NicknameEmptyException extends NicknameInvalidException
  252. {
  253. /**
  254. * Default localized message for this type of exception.
  255. * @return string
  256. */
  257. protected function defaultMessage()
  258. {
  259. // TRANS: Validation error in form for registration, profile and group settings, etc.
  260. return _('Nickname cannot be empty.');
  261. }
  262. }
  263. class NicknameTooLongException extends NicknameInvalidException
  264. {
  265. /**
  266. * Default localized message for this type of exception.
  267. * @return string
  268. */
  269. protected function defaultMessage()
  270. {
  271. // TRANS: Validation error in form for registration, profile and group settings, etc.
  272. return sprintf(_m('Nickname cannot be more than %d character long.',
  273. 'Nickname cannot be more than %d characters long.',
  274. Nickname::MAX_LEN),
  275. Nickname::MAX_LEN);
  276. }
  277. }
  278. class NicknameBlacklistedException extends NicknameException
  279. {
  280. protected function defaultMessage()
  281. {
  282. // TRANS: Validation error in form for registration, profile and group settings, etc.
  283. return _('Nickname is disallowed through blacklist.');
  284. }
  285. }
  286. class NicknamePathCollisionException extends NicknameException
  287. {
  288. protected function defaultMessage()
  289. {
  290. // TRANS: Validation error in form for registration, profile and group settings, etc.
  291. return _('Nickname is identical to system path names.');
  292. }
  293. }
  294. class NicknameTakenException extends NicknameException
  295. {
  296. public $profile = null; // the Profile which occupies the nickname
  297. public function __construct(Profile $profile, $msg=null, $code=400)
  298. {
  299. $this->profile = $profile;
  300. if ($msg === null) {
  301. $msg = $this->defaultMessage();
  302. }
  303. parent::__construct($msg, $code);
  304. }
  305. protected function defaultMessage()
  306. {
  307. // TRANS: Validation error in form for registration, profile and group settings, etc.
  308. return _('Nickname is already in use on this server.');
  309. }
  310. }