Merge "API: Add ApiPageSet accessors for just good and missing titles"
[lhc/web/wiklou.git] / includes / context / RequestContext.php
1 <?php
2 /**
3 * Request-dependant objects containers.
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 * @since 1.18
21 *
22 * @author Alexandre Emsenhuber
23 * @author Daniel Friesen
24 * @file
25 */
26
27 /**
28 * Group all the pieces relevant to the context of a request into one instance
29 */
30 class RequestContext implements IContextSource {
31 /**
32 * @var WebRequest
33 */
34 private $request;
35
36 /**
37 * @var Title
38 */
39 private $title;
40
41 /**
42 * @var WikiPage
43 */
44 private $wikipage;
45
46 /**
47 * @var OutputPage
48 */
49 private $output;
50
51 /**
52 * @var User
53 */
54 private $user;
55
56 /**
57 * @var Language
58 */
59 private $lang;
60
61 /**
62 * @var Skin
63 */
64 private $skin;
65
66 /**
67 * @var Config
68 */
69 private $config;
70
71 /**
72 * @var RequestContext
73 */
74 private static $instance = null;
75
76 /**
77 * Set the Config object
78 *
79 * @param Config $c
80 */
81 public function setConfig( Config $c ) {
82 $this->config = $c;
83 }
84
85 /**
86 * Get the Config object
87 *
88 * @return Config
89 */
90 public function getConfig() {
91 if ( $this->config === null ) {
92 // @todo In the future, we could move this to WebStart.php so
93 // the Config object is ready for when initialization happens
94 $this->config = ConfigFactory::getDefaultInstance()->makeConfig( 'main' );
95 }
96
97 return $this->config;
98 }
99
100 /**
101 * Set the WebRequest object
102 *
103 * @param WebRequest $r
104 */
105 public function setRequest( WebRequest $r ) {
106 $this->request = $r;
107 }
108
109 /**
110 * Get the WebRequest object
111 *
112 * @return WebRequest
113 */
114 public function getRequest() {
115 if ( $this->request === null ) {
116 global $wgRequest; # fallback to $wg till we can improve this
117 $this->request = $wgRequest;
118 }
119
120 return $this->request;
121 }
122
123 /**
124 * Set the Title object
125 *
126 * @param Title $title
127 */
128 public function setTitle( Title $title ) {
129 $this->title = $title;
130 // Erase the WikiPage so a new one with the new title gets created.
131 $this->wikipage = null;
132 }
133
134 /**
135 * Get the Title object
136 *
137 * @return Title|null
138 */
139 public function getTitle() {
140 if ( $this->title === null ) {
141 global $wgTitle; # fallback to $wg till we can improve this
142 $this->title = $wgTitle;
143 wfDebugLog( 'GlobalTitleFail', __METHOD__ . ' called by ' . wfGetCaller() . ' with no title set.' );
144 }
145
146 return $this->title;
147 }
148
149 /**
150 * Check, if a Title object is set
151 *
152 * @since 1.25
153 * @return bool
154 */
155 public function hasTitle() {
156 return $this->title !== null;
157 }
158
159 /**
160 * Check whether a WikiPage object can be get with getWikiPage().
161 * Callers should expect that an exception is thrown from getWikiPage()
162 * if this method returns false.
163 *
164 * @since 1.19
165 * @return bool
166 */
167 public function canUseWikiPage() {
168 if ( $this->wikipage ) {
169 // If there's a WikiPage object set, we can for sure get it
170 return true;
171 }
172 // Only pages with legitimate titles can have WikiPages.
173 // That usually means pages in non-virtual namespaces.
174 $title = $this->getTitle();
175 return $title ? $title->canExist() : false;
176 }
177
178 /**
179 * Set the WikiPage object
180 *
181 * @since 1.19
182 * @param WikiPage $p
183 */
184 public function setWikiPage( WikiPage $p ) {
185 $contextTitle = $this->getTitle();
186 $pageTitle = $p->getTitle();
187 if ( !$contextTitle || !$pageTitle->equals( $contextTitle ) ) {
188 $this->setTitle( $pageTitle );
189 }
190 // Defer this to the end since setTitle sets it to null.
191 $this->wikipage = $p;
192 }
193
194 /**
195 * Get the WikiPage object.
196 * May throw an exception if there's no Title object set or the Title object
197 * belongs to a special namespace that doesn't have WikiPage, so use first
198 * canUseWikiPage() to check whether this method can be called safely.
199 *
200 * @since 1.19
201 * @throws MWException
202 * @return WikiPage
203 */
204 public function getWikiPage() {
205 if ( $this->wikipage === null ) {
206 $title = $this->getTitle();
207 if ( $title === null ) {
208 throw new MWException( __METHOD__ . ' called without Title object set' );
209 }
210 $this->wikipage = WikiPage::factory( $title );
211 }
212
213 return $this->wikipage;
214 }
215
216 /**
217 * @param OutputPage $o
218 */
219 public function setOutput( OutputPage $o ) {
220 $this->output = $o;
221 }
222
223 /**
224 * Get the OutputPage object
225 *
226 * @return OutputPage
227 */
228 public function getOutput() {
229 if ( $this->output === null ) {
230 $this->output = new OutputPage( $this );
231 }
232
233 return $this->output;
234 }
235
236 /**
237 * Set the User object
238 *
239 * @param User $u
240 */
241 public function setUser( User $u ) {
242 $this->user = $u;
243 }
244
245 /**
246 * Get the User object
247 *
248 * @return User
249 */
250 public function getUser() {
251 if ( $this->user === null ) {
252 $this->user = User::newFromSession( $this->getRequest() );
253 }
254
255 return $this->user;
256 }
257
258 /**
259 * Accepts a language code and ensures it's sane. Outputs a cleaned up language
260 * code and replaces with $wgLanguageCode if not sane.
261 * @param string $code Language code
262 * @return string
263 */
264 public static function sanitizeLangCode( $code ) {
265 global $wgLanguageCode;
266
267 // BCP 47 - letter case MUST NOT carry meaning
268 $code = strtolower( $code );
269
270 # Validate $code
271 if ( !$code || !Language::isValidCode( $code ) || $code === 'qqq' ) {
272 wfDebug( "Invalid user language code\n" );
273 $code = $wgLanguageCode;
274 }
275
276 return $code;
277 }
278
279 /**
280 * Set the Language object
281 *
282 * @param Language|string $l Language instance or language code
283 * @throws MWException
284 * @since 1.19
285 */
286 public function setLanguage( $l ) {
287 if ( $l instanceof Language ) {
288 $this->lang = $l;
289 } elseif ( is_string( $l ) ) {
290 $l = self::sanitizeLangCode( $l );
291 $obj = Language::factory( $l );
292 $this->lang = $obj;
293 } else {
294 throw new MWException( __METHOD__ . " was passed an invalid type of data." );
295 }
296 }
297
298 /**
299 * Get the Language object.
300 * Initialization of user or request objects can depend on this.
301 *
302 * @return Language
303 * @since 1.19
304 */
305 public function getLanguage() {
306 if ( isset( $this->recursion ) ) {
307 trigger_error( "Recursion detected in " . __METHOD__, E_USER_WARNING );
308 $e = new Exception;
309 wfDebugLog( 'recursion-guard', "Recursion detected:\n" . $e->getTraceAsString() );
310
311 $code = $this->getConfig()->get( 'LanguageCode' ) ?: 'en';
312 $this->lang = Language::factory( $code );
313 } elseif ( $this->lang === null ) {
314 $this->recursion = true;
315
316 global $wgContLang;
317
318 try {
319 $request = $this->getRequest();
320 $user = $this->getUser();
321
322 $code = $request->getVal( 'uselang', $user->getOption( 'language' ) );
323 $code = self::sanitizeLangCode( $code );
324
325 wfRunHooks( 'UserGetLanguageObject', array( $user, &$code, $this ) );
326
327 if ( $code === $this->getConfig()->get( 'LanguageCode' ) ) {
328 $this->lang = $wgContLang;
329 } else {
330 $obj = Language::factory( $code );
331 $this->lang = $obj;
332 }
333
334 unset( $this->recursion );
335 }
336 catch ( Exception $ex ) {
337 unset( $this->recursion );
338 throw $ex;
339 }
340 }
341
342 return $this->lang;
343 }
344
345 /**
346 * Set the Skin object
347 *
348 * @param Skin $s
349 */
350 public function setSkin( Skin $s ) {
351 $this->skin = clone $s;
352 $this->skin->setContext( $this );
353 }
354
355 /**
356 * Get the Skin object
357 *
358 * @return Skin
359 */
360 public function getSkin() {
361 if ( $this->skin === null ) {
362 wfProfileIn( __METHOD__ . '-createskin' );
363
364 $skin = null;
365 wfRunHooks( 'RequestContextCreateSkin', array( $this, &$skin ) );
366 $factory = SkinFactory::getDefaultInstance();
367
368 // If the hook worked try to set a skin from it
369 if ( $skin instanceof Skin ) {
370 $this->skin = $skin;
371 } elseif ( is_string( $skin ) ) {
372 // Normalize the key, just in case the hook did something weird.
373 $normalized = Skin::normalizeKey( $skin );
374 $this->skin = $factory->makeSkin( $normalized );
375 }
376
377 // If this is still null (the hook didn't run or didn't work)
378 // then go through the normal processing to load a skin
379 if ( $this->skin === null ) {
380 if ( !in_array( 'skin', $this->getConfig()->get( 'HiddenPrefs' ) ) ) {
381 # get the user skin
382 $userSkin = $this->getUser()->getOption( 'skin' );
383 $userSkin = $this->getRequest()->getVal( 'useskin', $userSkin );
384 } else {
385 # if we're not allowing users to override, then use the default
386 $userSkin = $this->getConfig()->get( 'DefaultSkin' );
387 }
388
389 // Normalize the key in case the user is passing gibberish
390 // or has old preferences (bug 69566).
391 $normalized = Skin::normalizeKey( $userSkin );
392
393 // Skin::normalizeKey will also validate it, so
394 // this won't throw an exception
395 $this->skin = $factory->makeSkin( $normalized );
396 }
397
398 // After all that set a context on whatever skin got created
399 $this->skin->setContext( $this );
400 wfProfileOut( __METHOD__ . '-createskin' );
401 }
402
403 return $this->skin;
404 }
405
406 /** Helpful methods **/
407
408 /**
409 * Get a Message object with context set
410 * Parameters are the same as wfMessage()
411 *
412 * @return Message
413 */
414 public function msg() {
415 $args = func_get_args();
416
417 return call_user_func_array( 'wfMessage', $args )->setContext( $this );
418 }
419
420 /** Static methods **/
421
422 /**
423 * Get the RequestContext object associated with the main request
424 *
425 * @return RequestContext
426 */
427 public static function getMain() {
428 if ( self::$instance === null ) {
429 self::$instance = new self;
430 }
431
432 return self::$instance;
433 }
434
435 /**
436 * Get the RequestContext object associated with the main request
437 * and gives a warning to the log, to find places, where a context maybe is missing.
438 *
439 * @param string $func
440 * @return RequestContext
441 * @since 1.24
442 */
443 public static function getMainAndWarn( $func = __METHOD__ ) {
444 wfDebug( $func . ' called without context. ' .
445 "Using RequestContext::getMain() for sanity\n" );
446
447 return self::getMain();
448 }
449
450 /**
451 * Resets singleton returned by getMain(). Should be called only from unit tests.
452 */
453 public static function resetMain() {
454 if ( !defined( 'MW_PHPUNIT_TEST' ) ) {
455 throw new MWException( __METHOD__ . '() should be called only from unit tests!' );
456 }
457 self::$instance = null;
458 }
459
460 /**
461 * Export the resolved user IP, HTTP headers, user ID, and session ID.
462 * The result will be reasonably sized to allow for serialization.
463 *
464 * @return array
465 * @since 1.21
466 */
467 public function exportSession() {
468 return array(
469 'ip' => $this->getRequest()->getIP(),
470 'headers' => $this->getRequest()->getAllHeaders(),
471 'sessionId' => session_id(),
472 'userId' => $this->getUser()->getId()
473 );
474 }
475
476 /**
477 * Import the resolved user IP, HTTP headers, user ID, and session ID.
478 * This sets the current session and sets $wgUser and $wgRequest.
479 * Once the return value falls out of scope, the old context is restored.
480 * This function can only be called within CLI mode scripts.
481 *
482 * This will setup the session from the given ID. This is useful when
483 * background scripts inherit context when acting on behalf of a user.
484 *
485 * @note suhosin.session.encrypt may interfere with this method.
486 *
487 * @param array $params Result of RequestContext::exportSession()
488 * @return ScopedCallback
489 * @throws MWException
490 * @since 1.21
491 */
492 public static function importScopedSession( array $params ) {
493 if ( PHP_SAPI !== 'cli' ) {
494 // Don't send random private cookies or turn $wgRequest into FauxRequest
495 throw new MWException( "Sessions can only be imported in cli mode." );
496 } elseif ( !strlen( $params['sessionId'] ) ) {
497 throw new MWException( "No session ID was specified." );
498 }
499
500 if ( $params['userId'] ) { // logged-in user
501 $user = User::newFromId( $params['userId'] );
502 $user->load();
503 if ( !$user->getId() ) {
504 throw new MWException( "No user with ID '{$params['userId']}'." );
505 }
506 } elseif ( !IP::isValid( $params['ip'] ) ) {
507 throw new MWException( "Could not load user '{$params['ip']}'." );
508 } else { // anon user
509 $user = User::newFromName( $params['ip'], false );
510 }
511
512 $importSessionFunction = function ( User $user, array $params ) {
513 global $wgRequest, $wgUser;
514
515 $context = RequestContext::getMain();
516 // Commit and close any current session
517 session_write_close(); // persist
518 session_id( '' ); // detach
519 $_SESSION = array(); // clear in-memory array
520 // Remove any user IP or agent information
521 $context->setRequest( new FauxRequest() );
522 $wgRequest = $context->getRequest(); // b/c
523 // Now that all private information is detached from the user, it should
524 // be safe to load the new user. If errors occur or an exception is thrown
525 // and caught (leaving the main context in a mixed state), there is no risk
526 // of the User object being attached to the wrong IP, headers, or session.
527 $context->setUser( $user );
528 $wgUser = $context->getUser(); // b/c
529 if ( strlen( $params['sessionId'] ) ) { // don't make a new random ID
530 wfSetupSession( $params['sessionId'] ); // sets $_SESSION
531 }
532 $request = new FauxRequest( array(), false, $_SESSION );
533 $request->setIP( $params['ip'] );
534 foreach ( $params['headers'] as $name => $value ) {
535 $request->setHeader( $name, $value );
536 }
537 // Set the current context to use the new WebRequest
538 $context->setRequest( $request );
539 $wgRequest = $context->getRequest(); // b/c
540 };
541
542 // Stash the old session and load in the new one
543 $oUser = self::getMain()->getUser();
544 $oParams = self::getMain()->exportSession();
545 $importSessionFunction( $user, $params );
546
547 // Set callback to save and close the new session and reload the old one
548 return new ScopedCallback( function () use ( $importSessionFunction, $oUser, $oParams ) {
549 $importSessionFunction( $oUser, $oParams );
550 } );
551 }
552
553 /**
554 * Create a new extraneous context. The context is filled with information
555 * external to the current session.
556 * - Title is specified by argument
557 * - Request is a FauxRequest, or a FauxRequest can be specified by argument
558 * - User is an anonymous user, for separation IPv4 localhost is used
559 * - Language will be based on the anonymous user and request, may be content
560 * language or a uselang param in the fauxrequest data may change the lang
561 * - Skin will be based on the anonymous user, should be the wiki's default skin
562 *
563 * @param Title $title Title to use for the extraneous request
564 * @param WebRequest|array $request A WebRequest or data to use for a FauxRequest
565 * @return RequestContext
566 */
567 public static function newExtraneousContext( Title $title, $request = array() ) {
568 $context = new self;
569 $context->setTitle( $title );
570 if ( $request instanceof WebRequest ) {
571 $context->setRequest( $request );
572 } else {
573 $context->setRequest( new FauxRequest( $request ) );
574 }
575 $context->user = User::newFromName( '127.0.0.1', false );
576
577 return $context;
578 }
579 }