Merge "Revert "Use display name in category page subheadings if provided""
[lhc/web/wiklou.git] / includes / auth / AuthenticationRequest.php
1 <?php
2 /**
3 * Authentication request value object
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup Auth
22 */
23
24 namespace MediaWiki\Auth;
25
26 use Message;
27
28 /**
29 * This is a value object for authentication requests.
30 *
31 * An AuthenticationRequest represents a set of form fields that are needed on
32 * and provided from a login, account creation, password change or similar form.
33 *
34 * @ingroup Auth
35 * @since 1.27
36 */
37 abstract class AuthenticationRequest {
38
39 /** Indicates that the request is not required for authentication to proceed. */
40 const OPTIONAL = 0;
41
42 /** Indicates that the request is required for authentication to proceed.
43 * This will only be used for UI purposes; it is the authentication providers'
44 * responsibility to verify that all required requests are present.
45 */
46 const REQUIRED = 1;
47
48 /** Indicates that the request is required by a primary authentication
49 * provider. Since the user can choose which primary to authenticate with,
50 * the request might or might not end up being actually required. */
51 const PRIMARY_REQUIRED = 2;
52
53 /** @var string|null The AuthManager::ACTION_* constant this request was
54 * created to be used for. The *_CONTINUE constants are not used here, the
55 * corresponding "begin" constant is used instead.
56 */
57 public $action = null;
58
59 /** @var int For login, continue, and link actions, one of self::OPTIONAL,
60 * self::REQUIRED, or self::PRIMARY_REQUIRED */
61 public $required = self::REQUIRED;
62
63 /** @var string|null Return-to URL, in case of redirect */
64 public $returnToUrl = null;
65
66 /** @var string|null Username. See AuthenticationProvider::getAuthenticationRequests()
67 * for details of what this means and how it behaves. */
68 public $username = null;
69
70 /**
71 * Supply a unique key for deduplication
72 *
73 * When the AuthenticationRequests instances returned by the providers are
74 * merged, the value returned here is used for keeping only one copy of
75 * duplicate requests.
76 *
77 * Subclasses should override this if multiple distinct instances would
78 * make sense, i.e. the request class has internal state of some sort.
79 *
80 * This value might be exposed to the user in web forms so it should not
81 * contain private information.
82 *
83 * @return string
84 */
85 public function getUniqueId() {
86 return get_called_class();
87 }
88
89 /**
90 * Fetch input field info
91 *
92 * The field info is an associative array mapping field names to info
93 * arrays. The info arrays have the following keys:
94 * - type: (string) Type of input. Types and equivalent HTML widgets are:
95 * - string: <input type="text">
96 * - password: <input type="password">
97 * - select: <select>
98 * - checkbox: <input type="checkbox">
99 * - multiselect: More a grid of checkboxes than <select multi>
100 * - button: <input type="submit"> (uses 'label' as button text)
101 * - hidden: Not visible to the user, but needs to be preserved for the next request
102 * - null: No widget, just display the 'label' message.
103 * - options: (array) Maps option values to Messages for the
104 * 'select' and 'multiselect' types.
105 * - value: (string) Value (for 'null' and 'hidden') or default value (for other types).
106 * - label: (Message) Text suitable for a label in an HTML form
107 * - help: (Message) Text suitable as a description of what the field is
108 * - optional: (bool) If set and truthy, the field may be left empty
109 * - sensitive: (bool) If set and truthy, the field is considered sensitive. Code using the
110 * request should avoid exposing the value of the field.
111 *
112 * All AuthenticationRequests are populated from the same data, so most of the time you'll
113 * want to prefix fields names with something unique to the extension/provider (although
114 * in some cases sharing the field with other requests is the right thing to do, e.g. for
115 * a 'password' field).
116 *
117 * @return array As above
118 */
119 abstract public function getFieldInfo();
120
121 /**
122 * Returns metadata about this request.
123 *
124 * This is mainly for the benefit of API clients which need more detailed render hints
125 * than what's available through getFieldInfo(). Semantics are unspecified and left to the
126 * individual subclasses, but the contents of the array should be primitive types so that they
127 * can be transformed into JSON or similar formats.
128 *
129 * @return array A (possibly nested) array with primitive types
130 */
131 public function getMetadata() {
132 return [];
133 }
134
135 /**
136 * Initialize form submitted form data.
137 *
138 * The default behavior is to to check for each key of self::getFieldInfo()
139 * in the submitted data, and copy the value - after type-appropriate transformations -
140 * to $this->$key. Most subclasses won't need to override this; if you do override it,
141 * make sure to always return false if self::getFieldInfo() returns an empty array.
142 *
143 * @param array $data Submitted data as an associative array (keys will correspond
144 * to getFieldInfo())
145 * @return bool Whether the request data was successfully loaded
146 */
147 public function loadFromSubmission( array $data ) {
148 $fields = array_filter( $this->getFieldInfo(), function ( $info ) {
149 return $info['type'] !== 'null';
150 } );
151 if ( !$fields ) {
152 return false;
153 }
154
155 foreach ( $fields as $field => $info ) {
156 // Checkboxes and buttons are special. Depending on the method used
157 // to populate $data, they might be unset meaning false or they
158 // might be boolean. Further, image buttons might submit the
159 // coordinates of the click rather than the expected value.
160 if ( $info['type'] === 'checkbox' || $info['type'] === 'button' ) {
161 $this->$field = isset( $data[$field] ) && $data[$field] !== false
162 || isset( $data["{$field}_x"] ) && $data["{$field}_x"] !== false;
163 if ( !$this->$field && empty( $info['optional'] ) ) {
164 return false;
165 }
166 continue;
167 }
168
169 // Multiselect are too, slightly
170 if ( !isset( $data[$field] ) && $info['type'] === 'multiselect' ) {
171 $data[$field] = [];
172 }
173
174 if ( !isset( $data[$field] ) ) {
175 return false;
176 }
177 if ( $data[$field] === '' || $data[$field] === [] ) {
178 if ( empty( $info['optional'] ) ) {
179 return false;
180 }
181 } else {
182 switch ( $info['type'] ) {
183 case 'select':
184 if ( !isset( $info['options'][$data[$field]] ) ) {
185 return false;
186 }
187 break;
188
189 case 'multiselect':
190 $data[$field] = (array)$data[$field];
191 $allowed = array_keys( $info['options'] );
192 if ( array_diff( $data[$field], $allowed ) !== [] ) {
193 return false;
194 }
195 break;
196 }
197 }
198
199 $this->$field = $data[$field];
200 }
201
202 return true;
203 }
204
205 /**
206 * Describe the credentials represented by this request
207 *
208 * This is used on requests returned by
209 * AuthenticationProvider::getAuthenticationRequests() for ACTION_LINK
210 * and ACTION_REMOVE and for requests returned in
211 * AuthenticationResponse::$linkRequest to create useful user interfaces.
212 *
213 * @return Message[] with the following keys:
214 * - provider: A Message identifying the service that provides
215 * the credentials, e.g. the name of the third party authentication
216 * service.
217 * - account: A Message identifying the credentials themselves,
218 * e.g. the email address used with the third party authentication
219 * service.
220 */
221 public function describeCredentials() {
222 return [
223 'provider' => new \RawMessage( '$1', [ get_called_class() ] ),
224 'account' => new \RawMessage( '$1', [ $this->getUniqueId() ] ),
225 ];
226 }
227
228 /**
229 * Update a set of requests with form submit data, discarding ones that fail
230 * @param AuthenticationRequest[] $reqs
231 * @param array $data
232 * @return AuthenticationRequest[]
233 */
234 public static function loadRequestsFromSubmission( array $reqs, array $data ) {
235 return array_values( array_filter( $reqs, function ( $req ) use ( $data ) {
236 return $req->loadFromSubmission( $data );
237 } ) );
238 }
239
240 /**
241 * Select a request by class name.
242 * @param AuthenticationRequest[] $reqs
243 * @param string $class Class name
244 * @param bool $allowSubclasses If true, also returns any request that's a subclass of the given
245 * class.
246 * @return AuthenticationRequest|null Returns null if there is not exactly
247 * one matching request.
248 */
249 public static function getRequestByClass( array $reqs, $class, $allowSubclasses = false ) {
250 $requests = array_filter( $reqs, function ( $req ) use ( $class, $allowSubclasses ) {
251 if ( $allowSubclasses ) {
252 return is_a( $req, $class, false );
253 } else {
254 return get_class( $req ) === $class;
255 }
256 } );
257 return count( $requests ) === 1 ? reset( $requests ) : null;
258 }
259
260 /**
261 * Get the username from the set of requests
262 *
263 * Only considers requests that have a "username" field.
264 *
265 * @param AuthenticationRequest[] $reqs
266 * @return string|null
267 * @throws \UnexpectedValueException If multiple different usernames are present.
268 */
269 public static function getUsernameFromRequests( array $reqs ) {
270 $username = null;
271 $otherClass = null;
272 foreach ( $reqs as $req ) {
273 $info = $req->getFieldInfo();
274 if ( $info && array_key_exists( 'username', $info ) && $req->username !== null ) {
275 if ( $username === null ) {
276 $username = $req->username;
277 $otherClass = get_class( $req );
278 } elseif ( $username !== $req->username ) {
279 $requestClass = get_class( $req );
280 throw new \UnexpectedValueException( "Conflicting username fields: \"{$req->username}\" from "
281 . "$requestClass::\$username vs. \"$username\" from $otherClass::\$username" );
282 }
283 }
284 }
285 return $username;
286 }
287
288 /**
289 * Merge the output of multiple AuthenticationRequest::getFieldInfo() calls.
290 * @param AuthenticationRequest[] $reqs
291 * @return array
292 * @throws \UnexpectedValueException If fields cannot be merged
293 */
294 public static function mergeFieldInfo( array $reqs ) {
295 $merged = [];
296
297 // fields that are required by some primary providers but not others are not actually required
298 $primaryRequests = array_filter( $reqs, function ( $req ) {
299 return $req->required === AuthenticationRequest::PRIMARY_REQUIRED;
300 } );
301 $sharedRequiredPrimaryFields = array_reduce( $primaryRequests, function ( $shared, $req ) {
302 $required = array_keys( array_filter( $req->getFieldInfo(), function ( $options ) {
303 return empty( $options['optional'] );
304 } ) );
305 if ( $shared === null ) {
306 return $required;
307 } else {
308 return array_intersect( $shared, $required );
309 }
310 }, null );
311
312 foreach ( $reqs as $req ) {
313 $info = $req->getFieldInfo();
314 if ( !$info ) {
315 continue;
316 }
317
318 foreach ( $info as $name => $options ) {
319 if (
320 // If the request isn't required, its fields aren't required either.
321 $req->required === self::OPTIONAL
322 // If there is a primary not requiring this field, no matter how many others do,
323 // authentication can proceed without it.
324 || $req->required === self::PRIMARY_REQUIRED
325 && !in_array( $name, $sharedRequiredPrimaryFields, true )
326 ) {
327 $options['optional'] = true;
328 } else {
329 $options['optional'] = !empty( $options['optional'] );
330 }
331
332 $options['sensitive'] = !empty( $options['sensitive'] );
333
334 if ( !array_key_exists( $name, $merged ) ) {
335 $merged[$name] = $options;
336 } elseif ( $merged[$name]['type'] !== $options['type'] ) {
337 throw new \UnexpectedValueException( "Field type conflict for \"$name\", " .
338 "\"{$merged[$name]['type']}\" vs \"{$options['type']}\""
339 );
340 } else {
341 if ( isset( $options['options'] ) ) {
342 if ( isset( $merged[$name]['options'] ) ) {
343 $merged[$name]['options'] += $options['options'];
344 } else {
345 // @codeCoverageIgnoreStart
346 $merged[$name]['options'] = $options['options'];
347 // @codeCoverageIgnoreEnd
348 }
349 }
350
351 $merged[$name]['optional'] = $merged[$name]['optional'] && $options['optional'];
352 $merged[$name]['sensitive'] = $merged[$name]['sensitive'] || $options['sensitive'];
353
354 // No way to merge 'value', 'image', 'help', or 'label', so just use
355 // the value from the first request.
356 }
357 }
358 }
359
360 return $merged;
361 }
362
363 /**
364 * Implementing this mainly for use from the unit tests.
365 * @param array $data
366 * @return AuthenticationRequest
367 */
368 public static function __set_state( $data ) {
369 $ret = new static();
370 foreach ( $data as $k => $v ) {
371 $ret->$k = $v;
372 }
373 return $ret;
374 }
375 }