nickname.php 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. * Nice simple check of whether the given string is a valid input nickname,
  75. * which can be normalized into an internally canonical form.
  76. *
  77. * Note that valid nicknames may be in use or reserved.
  78. *
  79. * @param string $str The nickname string to test
  80. * @param boolean $checkuse Check if it's in use (return false if it is)
  81. *
  82. * @return boolean True if nickname is valid. False if invalid (or taken if checkuse==true).
  83. */
  84. public static function isValid($str, $checkuse=false)
  85. {
  86. try {
  87. self::normalize($str, $checkuse);
  88. } catch (NicknameException $e) {
  89. return false;
  90. }
  91. return true;
  92. }
  93. /**
  94. * Validate an input nickname string, and normalize it to its canonical form.
  95. * The canonical form will be returned, or an exception thrown if invalid.
  96. *
  97. * @param string $str The nickname string to test
  98. * @param boolean $checkuse Check if it's in use (return false if it is)
  99. * @return string Normalized canonical form of $str
  100. *
  101. * @throws NicknameException (base class)
  102. * @throws NicknameBlacklistedException
  103. * @throws NicknameEmptyException
  104. * @throws NicknameInvalidException
  105. * @throws NicknamePathCollisionException
  106. * @throws NicknameTakenException
  107. * @throws NicknameTooLongException
  108. */
  109. public static function normalize($str, $checkuse=false)
  110. {
  111. // We should also have UTF-8 normalization (å to a etc.)
  112. $str = trim($str);
  113. $str = str_replace('_', '', $str);
  114. $str = mb_strtolower($str);
  115. if (mb_strlen($str) > self::MAX_LEN) {
  116. // Display forms must also fit!
  117. throw new NicknameTooLongException();
  118. } elseif (mb_strlen($str) < 1) {
  119. throw new NicknameEmptyException();
  120. } elseif (!self::isCanonical($str)) {
  121. throw new NicknameInvalidException();
  122. } elseif (self::isBlacklisted($str)) {
  123. throw new NicknameBlacklistedException();
  124. } elseif (self::isSystemPath($str)) {
  125. throw new NicknamePathCollisionException();
  126. } elseif ($checkuse) {
  127. $profile = self::isTaken($str);
  128. if ($profile instanceof Profile) {
  129. throw new NicknameTakenException($profile);
  130. }
  131. }
  132. return $str;
  133. }
  134. /**
  135. * Is the given string a valid canonical nickname form?
  136. *
  137. * @param string $str
  138. * @return boolean
  139. */
  140. public static function isCanonical($str)
  141. {
  142. return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
  143. }
  144. /**
  145. * Is the given string in our nickname blacklist?
  146. *
  147. * @param string $str
  148. * @return boolean
  149. */
  150. public static function isBlacklisted($str)
  151. {
  152. $blacklist = common_config('nickname', 'blacklist');
  153. return in_array($str, $blacklist);
  154. }
  155. /**
  156. * Is the given string identical to a system path or route?
  157. * This could probably be put in some other class, but at
  158. * at the moment, only Nickname requires this functionality.
  159. *
  160. * @param string $str
  161. * @return boolean
  162. */
  163. public static function isSystemPath($str)
  164. {
  165. $paths = array();
  166. // All directory and file names in site root should be blacklisted
  167. $d = dir(INSTALLDIR);
  168. while (false !== ($entry = $d->read())) {
  169. $paths[$entry] = true;
  170. }
  171. $d->close();
  172. // All top level names in the router should be blacklisted
  173. $router = Router::get();
  174. foreach ($router->m->getPaths() as $path) {
  175. if (preg_match('/^([^\/\?]+)[\/\?]/',$path,$matches) && isset($matches[1])) {
  176. $paths[$matches[1]] = true;
  177. }
  178. }
  179. // FIXME: this assumes the 'path' is in the first-level directory, though common it's not certain
  180. foreach (['avatar', 'attachments'] as $cat) {
  181. $paths[basename(common_config($cat, 'path'))] = true;
  182. }
  183. return in_array($str, array_keys($paths));
  184. }
  185. /**
  186. * Is the nickname already in use locally? Checks the User table.
  187. *
  188. * @param string $str
  189. * @return Profile|null Returns Profile if nickname found, otherwise null
  190. */
  191. public static function isTaken($str)
  192. {
  193. $found = User::getKV('nickname', $str);
  194. if ($found instanceof User) {
  195. return $found->getProfile();
  196. }
  197. $found = Local_group::getKV('nickname', $str);
  198. if ($found instanceof Local_group) {
  199. return $found->getProfile();
  200. }
  201. $found = Group_alias::getKV('alias', $str);
  202. if ($found instanceof Group_alias) {
  203. return $found->getProfile();
  204. }
  205. return null;
  206. }
  207. }
  208. class NicknameException extends ClientException
  209. {
  210. function __construct($msg=null, $code=400)
  211. {
  212. if ($msg === null) {
  213. $msg = $this->defaultMessage();
  214. }
  215. parent::__construct($msg, $code);
  216. }
  217. /**
  218. * Default localized message for this type of exception.
  219. * @return string
  220. */
  221. protected function defaultMessage()
  222. {
  223. return null;
  224. }
  225. }
  226. class NicknameInvalidException extends NicknameException {
  227. /**
  228. * Default localized message for this type of exception.
  229. * @return string
  230. */
  231. protected function defaultMessage()
  232. {
  233. // TRANS: Validation error in form for registration, profile and group settings, etc.
  234. return _('Nickname must have only lowercase letters and numbers and no spaces.');
  235. }
  236. }
  237. class NicknameEmptyException extends NicknameInvalidException
  238. {
  239. /**
  240. * Default localized message for this type of exception.
  241. * @return string
  242. */
  243. protected function defaultMessage()
  244. {
  245. // TRANS: Validation error in form for registration, profile and group settings, etc.
  246. return _('Nickname cannot be empty.');
  247. }
  248. }
  249. class NicknameTooLongException extends NicknameInvalidException
  250. {
  251. /**
  252. * Default localized message for this type of exception.
  253. * @return string
  254. */
  255. protected function defaultMessage()
  256. {
  257. // TRANS: Validation error in form for registration, profile and group settings, etc.
  258. return sprintf(_m('Nickname cannot be more than %d character long.',
  259. 'Nickname cannot be more than %d characters long.',
  260. Nickname::MAX_LEN),
  261. Nickname::MAX_LEN);
  262. }
  263. }
  264. class NicknameBlacklistedException extends NicknameException
  265. {
  266. protected function defaultMessage()
  267. {
  268. // TRANS: Validation error in form for registration, profile and group settings, etc.
  269. return _('Nickname is disallowed through blacklist.');
  270. }
  271. }
  272. class NicknamePathCollisionException extends NicknameException
  273. {
  274. protected function defaultMessage()
  275. {
  276. // TRANS: Validation error in form for registration, profile and group settings, etc.
  277. return _('Nickname is identical to system path names.');
  278. }
  279. }
  280. class NicknameTakenException extends NicknameException
  281. {
  282. public $profile = null; // the Profile which occupies the nickname
  283. public function __construct(Profile $profile, $msg=null, $code=400)
  284. {
  285. $this->profile = $profile;
  286. if ($msg === null) {
  287. $msg = $this->defaultMessage();
  288. }
  289. parent::__construct($msg, $code);
  290. }
  291. protected function defaultMessage()
  292. {
  293. // TRANS: Validation error in form for registration, profile and group settings, etc.
  294. return _('Nickname is already in use on this server.');
  295. }
  296. }