]> git.mxchange.org Git - quix0rs-gnu-social.git/blob - lib/nickname.php
UPDATE ActivityVerb
[quix0rs-gnu-social.git] / lib / nickname.php
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
20 class Nickname
21 {
22     /**
23      * Regex fragment for pulling a formated nickname *OR* ID number.
24      * Suitable for router def of 'id' parameters on API actions.
25      *
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.
29      *
30      * This, DISPLAY_FMT, and CANONICAL_FMT should not be enclosed in []s.
31      *
32      * @fixme would prefer to define in reference to the other constants
33      */
34     const INPUT_FMT = '(?:[0-9]+|[0-9a-zA-Z_]{1,64})';
35
36     /**
37      * Regex fragment for acceptable user-formatted variant of a nickname.
38      *
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.
42      *
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.
46      *
47      * This, INPUT_FMT and CANONICAL_FMT should not be enclosed in []s.
48      */
49     const DISPLAY_FMT = '[0-9a-zA-Z_]{1,64}';
50
51     /**
52      * Simplified regex fragment for acceptable full WebFinger ID of a user
53      *
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
56      */
57     const WEBFINGER_FMT = '[0-9a-zA-Z_]{1,64}\@[0-9a-zA-Z_-.]{3,255}';
58
59     /**
60      * Regex fragment for checking a canonical nickname.
61      *
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.
65      *
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.
69      *
70      * This, INPUT_FMT and DISPLAY_FMT should not be enclosed in []s.
71      */
72     const CANONICAL_FMT = '[0-9a-z]{1,64}';
73
74     /**
75      * Maximum number of characters in a canonical-form nickname.
76      */
77     const MAX_LEN = 64;
78
79     /**
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).'
83      *
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.
86      */
87     const BEFORE_MENTIONS = '(?:^|[\s\.\,\:\;\[\(]+)';
88
89     /**
90      * Nice simple check of whether the given string is a valid input nickname,
91      * which can be normalized into an internally canonical form.
92      *
93      * Note that valid nicknames may be in use or reserved.
94      *
95      * @param string    $str       The nickname string to test
96      * @param boolean   $checkuse  Check if it's in use (return false if it is)
97      *
98      * @return boolean  True if nickname is valid. False if invalid (or taken if checkuse==true).
99      */
100     public static function isValid($str, $checkuse=false)
101     {
102         try {
103             self::normalize($str, $checkuse);
104         } catch (NicknameException $e) {
105             return false;
106         }
107
108         return true;
109     }
110
111     /**
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.
114      *
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
118      *
119      * @throws NicknameException (base class)
120      * @throws   NicknameBlacklistedException
121      * @throws   NicknameEmptyException
122      * @throws   NicknameInvalidException
123      * @throws   NicknamePathCollisionException
124      * @throws   NicknameTakenException
125      * @throws   NicknameTooLongException
126      */
127     public static function normalize($str, $checkuse=false)
128     {
129         // We should also have UTF-8 normalization (å to a etc.)
130         $str = trim($str);
131         $str = str_replace('_', '', $str);
132         $str = mb_strtolower($str);
133
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);
149             }
150         }
151
152         return $str;
153     }
154
155     /**
156      * Is the given string a valid canonical nickname form?
157      *
158      * @param string $str
159      * @return boolean
160      */
161     public static function isCanonical($str)
162     {
163         return preg_match('/^(?:' . self::CANONICAL_FMT . ')$/', $str);
164     }
165
166     /**
167      * Is the given string in our nickname blacklist?
168      *
169      * @param string $str
170      * @return boolean
171      */
172      public static function isBlacklisted($str)
173      {
174          $blacklist = common_config('nickname', 'blacklist');
175          return in_array($str, $blacklist);
176      }
177
178     /**
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.
182      *
183      * @param string $str
184      * @return boolean
185      */
186      public static function isSystemPath($str)
187      {
188         $paths = array();
189
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;
194         }
195         $d->close();
196
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;
202             }
203         }
204
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;
208         }
209
210         return in_array($str, array_keys($paths));
211     }
212
213     /**
214      * Is the nickname already in use locally? Checks the User table.
215      *
216      * @param   string $str
217      * @return  Profile|null   Returns Profile if nickname found, otherwise null
218      */
219     public static function isTaken($str)
220     {
221         $found = User::getKV('nickname', $str);
222         if ($found instanceof User) {
223             return $found->getProfile();
224         }
225
226         $found = Local_group::getKV('nickname', $str);
227         if ($found instanceof Local_group) {
228             return $found->getProfile();
229         }
230
231         $found = Group_alias::getKV('alias', $str);
232         if ($found instanceof Group_alias) {
233             return $found->getProfile();
234         }
235
236         return null;
237     }
238 }
239
240 class NicknameException extends ClientException
241 {
242     function __construct($msg=null, $code=400)
243     {
244         if ($msg === null) {
245             $msg = $this->defaultMessage();
246         }
247         parent::__construct($msg, $code);
248     }
249
250     /**
251      * Default localized message for this type of exception.
252      * @return string
253      */
254     protected function defaultMessage()
255     {
256         return null;
257     }
258 }
259
260 class NicknameInvalidException extends NicknameException {
261     /**
262      * Default localized message for this type of exception.
263      * @return string
264      */
265     protected function defaultMessage()
266     {
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.');
269     }
270 }
271
272 class NicknameEmptyException extends NicknameInvalidException
273 {
274     /**
275      * Default localized message for this type of exception.
276      * @return string
277      */
278     protected function defaultMessage()
279     {
280         // TRANS: Validation error in form for registration, profile and group settings, etc.
281         return _('Nickname cannot be empty.');
282     }
283 }
284
285 class NicknameTooLongException extends NicknameInvalidException
286 {
287     /**
288      * Default localized message for this type of exception.
289      * @return string
290      */
291     protected function defaultMessage()
292     {
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.',
296                           Nickname::MAX_LEN),
297                        Nickname::MAX_LEN);
298     }
299 }
300
301 class NicknameBlacklistedException extends NicknameException
302 {
303     protected function defaultMessage()
304     {
305         // TRANS: Validation error in form for registration, profile and group settings, etc.
306         return _('Nickname is disallowed through blacklist.');
307     }
308 }
309
310 class NicknamePathCollisionException extends NicknameException
311 {
312     protected function defaultMessage()
313     {
314         // TRANS: Validation error in form for registration, profile and group settings, etc.
315         return _('Nickname is identical to system path names.');
316     }
317 }
318
319 class NicknameTakenException extends NicknameException
320 {
321     public $profile = null;    // the Profile which occupies the nickname
322
323     public function __construct(Profile $profile, $msg=null, $code=400)
324     {
325         $this->profile = $profile;
326
327         if ($msg === null) {
328             $msg = $this->defaultMessage();
329         }
330
331         parent::__construct($msg, $code);
332     }
333
334     protected function defaultMessage()
335     {
336         // TRANS: Validation error in form for registration, profile and group settings, etc.
337         return _('Nickname is already in use on this server.');
338     }
339 }