nickname.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340
  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 = '[0-9a-zA-Z_]{1,64}\@[0-9a-zA-Z_-.]{3,255}';
  55. /**
  56. * Regex fragment for checking a canonical nickname.
  57. *
  58. * Any non-matching string is not a valid canonical/normalized nickname.
  59. * Matching strings are valid and canonical form, but may still be
  60. * unavailable for registration due to blacklisting et.
  61. *
  62. * Only the canonical forms should be stored as keys in the database;
  63. * there are multiple possible denormalized forms for each valid
  64. * canonical-form name.
  65. *
  66. * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
  67. */
  68. const CANONICAL_FMT = '[0-9a-z]{1,64}';
  69. /**
  70. * Maximum number of characters in a canonical-form nickname.
  71. */
  72. const MAX_LEN = 64;
  73. /**
  74. * Regex with non-capturing group that matches whitespace and some
  75. * characters which are allowed right before an @ or ! when mentioning
  76. * other users. Like: 'This goes out to:@mmn (@chimo too) (!awwyiss).'
  77. *
  78. * FIXME: Make this so you can have multiple whitespace but not multiple
  79. * parenthesis or something. '(((@n_n@)))' might as well be a smiley.
  80. */
  81. const BEFORE_MENTIONS = '(?:^|[\s\.\,\:\;\[\(]+)';
  82. /**
  83. * Nice simple check of whether the given string is a valid input nickname,
  84. * which can be normalized into an internally canonical form.
  85. *
  86. * Note that valid nicknames may be in use or reserved.
  87. *
  88. * @param string $str The nickname string to test
  89. * @param boolean $checkuse Check if it's in use (return false if it is)
  90. *
  91. * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
  92. */
  93. public static function isValid($str, $checkuse=false)
  94. {
  95. try {
  96. self::normalize($str, $checkuse);
  97. } catch (NicknameException $e) {
  98. return false;
  99. }
  100. return true;
  101. }
  102. /**
  103. * Validate an input nickname string, and normalize it to its canonical form.
  104. * The canonical form will be returned, or an exception thrown if invalid.
  105. *
  106. * @param string $str The nickname string to test
  107. * @param boolean $checkuse Check if it's in use (return false if it is)
  108. * @return string Normalized canonical form of $str
  109. *
  110. * @throws NicknameException (base class)
  111. * @throws NicknameBlacklistedException
  112. * @throws NicknameEmptyException
  113. * @throws NicknameInvalidException
  114. * @throws NicknamePathCollisionException
  115. * @throws NicknameTakenException
  116. * @throws NicknameTooLongException
  117. */
  118. public static function normalize($str, $checkuse=false)
  119. {
  120. // We should also have UTF-8 normalization (å to a etc.)
  121. $str = trim($str);
  122. $str = str_replace('_', '', $str);
  123. $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);
  139. }
  140. }
  141. return $str;
  142. }
  143. /**
  144. * Is the given string a valid canonical nickname form?
  145. *
  146. * @param string $str
  147. * @return boolean
  148. */
  149. public static function isCanonical($str)
  150. {
  151. return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
  152. }
  153. /**
  154. * Is the given string in our nickname blacklist?
  155. *
  156. * @param string $str
  157. * @return boolean
  158. */
  159. public static function isBlacklisted($str)
  160. {
  161. $blacklist = common_config('nickname', 'blacklist');
  162. return in_array($str, $blacklist);
  163. }
  164. /**
  165. * Is the given string identical to a system path or route?
  166. * This could probably be put in some other class, but at
  167. * at the moment, only Nickname requires this functionality.
  168. *
  169. * @param string $str
  170. * @return boolean
  171. */
  172. public static function isSystemPath($str)
  173. {
  174. $paths = array();
  175. // All directory and file names in site root should be blacklisted
  176. $d = dir(INSTALLDIR);
  177. while (false !== ($entry = $d->read())) {
  178. $paths[$entry] = true;
  179. }
  180. $d->close();
  181. // All top level names in the router should be blacklisted
  182. $router = Router::get();
  183. foreach ($router->m->getPaths() as $path) {
  184. if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
  185. $paths[$matches[1]] = true;
  186. }
  187. }
  188. // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
  189. foreach (['avatar', 'attachments'] as $cat) {
  190. $paths[basename(common_config($cat, 'path'))] = true;
  191. }
  192. return in_array($str, array_keys($paths));
  193. }
  194. /**
  195. * Is the nickname already in use locally? Checks the User table.
  196. *
  197. * @param string $str
  198. * @return Profile|null Returns Profile if nickname found, otherwise null
  199. */
  200. public static function isTaken($str)
  201. {
  202. $found = User::getKV('nickname', $str);
  203. if ($found instanceof User) {
  204. return $found->getProfile();
  205. }
  206. $found = Local_group::getKV('nickname', $str);
  207. if ($found instanceof Local_group) {
  208. return $found->getProfile();
  209. }
  210. $found = Group_alias::getKV('alias', $str);
  211. if ($found instanceof Group_alias) {
  212. return $found->getProfile();
  213. }
  214. return null;
  215. }
  216. }
  217. class NicknameException extends ClientException
  218. {
  219. function __construct($msg=null, $code=400)
  220. {
  221. if ($msg === null) {
  222. $msg = $this->defaultMessage();
  223. }
  224. parent::__construct($msg, $code);
  225. }
  226. /**
  227. * Default localized message for this type of exception.
  228. * @return string
  229. */
  230. protected function defaultMessage()
  231. {
  232. return null;
  233. }
  234. }
  235. class NicknameInvalidException extends NicknameException {
  236. /**
  237. * Default localized message for this type of exception.
  238. * @return string
  239. */
  240. protected function defaultMessage()
  241. {
  242. // TRANS: Validation error in form for registration, profile and group settings, etc.
  243. return _('Nickname must have only lowercase letters and numbers and no spaces.');
  244. }
  245. }
  246. class NicknameEmptyException extends NicknameInvalidException
  247. {
  248. /**
  249. * Default localized message for this type of exception.
  250. * @return string
  251. */
  252. protected function defaultMessage()
  253. {
  254. // TRANS: Validation error in form for registration, profile and group settings, etc.
  255. return _('Nickname cannot be empty.');
  256. }
  257. }
  258. class NicknameTooLongException extends NicknameInvalidException
  259. {
  260. /**
  261. * Default localized message for this type of exception.
  262. * @return string
  263. */
  264. protected function defaultMessage()
  265. {
  266. // TRANS: Validation error in form for registration, profile and group settings, etc.
  267. return sprintf(_m('Nickname cannot be more than %d character long.',
  268. 'Nickname cannot be more than %d characters long.',
  269. Nickname::MAX_LEN),
  270. Nickname::MAX_LEN);
  271. }
  272. }
  273. class NicknameBlacklistedException extends NicknameException
  274. {
  275. protected function defaultMessage()
  276. {
  277. // TRANS: Validation error in form for registration, profile and group settings, etc.
  278. return _('Nickname is disallowed through blacklist.');
  279. }
  280. }
  281. class NicknamePathCollisionException extends NicknameException
  282. {
  283. protected function defaultMessage()
  284. {
  285. // TRANS: Validation error in form for registration, profile and group settings, etc.
  286. return _('Nickname is identical to system path names.');
  287. }
  288. }
  289. class NicknameTakenException extends NicknameException
  290. {
  291. public $profile = null; // the Profile which occupies the nickname
  292. public function __construct(Profile $profile, $msg=null, $code=400)
  293. {
  294. $this->profile = $profile;
  295. if ($msg === null) {
  296. $msg = $this->defaultMessage();
  297. }
  298. parent::__construct($msg, $code);
  299. }
  300. protected function defaultMessage()
  301. {
  302. // TRANS: Validation error in form for registration, profile and group settings, etc.
  303. return _('Nickname is already in use on this server.');
  304. }
  305. }