Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
91.35% covered (success)
91.35%
190 / 208
72.97% covered (warning)
72.97%
27 / 37
CRAP
0.00% covered (danger)
0.00%
0 / 1
MobileContext
91.35% covered (success)
91.35%
190 / 208
72.97% covered (warning)
72.97%
27 / 37
89.68
0.00% covered (danger)
0.00%
0 / 1
 singleton
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 resetInstanceForTesting
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 __construct
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isMobileDevice
88.89% covered (warning)
88.89%
8 / 9
0.00% covered (danger)
0.00%
0 / 1
5.03
 setForceMobileView
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isAmcUser
0.00% covered (danger)
0.00%
0 / 3
0.00% covered (danger)
0.00%
0 / 1
2
 shouldDisplayMobileView
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 shouldDisplayMobileViewInternal
95.00% covered (success)
95.00%
19 / 20
0.00% covered (danger)
0.00%
0 / 1
9
 getMobileAction
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 getUseFormat
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
2
 setStopMobileRedirectCookie
100.00% covered (success)
100.00%
10 / 10
100.00% covered (success)
100.00%
1 / 1
1
 unsetStopMobileRedirectCookie
50.00% covered (danger)
50.00%
2 / 4
0.00% covered (danger)
0.00%
0 / 1
2.50
 getStopMobileRedirectCookie
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 getUseFormatCookie
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getCookieDomain
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getStopMobileRedirectCookieDomain
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 setUseFormatCookie
100.00% covered (success)
100.00%
9 / 9
100.00% covered (success)
100.00%
1 / 1
1
 unsetUseFormatCookie
0.00% covered (danger)
0.00%
0 / 4
0.00% covered (danger)
0.00%
0 / 1
6
 getUseFormatCookieExpiry
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 getUseFormatCookieDuration
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
2
 getMobileUrlCallback
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 hasMobileDomain
90.91% covered (success)
90.91%
10 / 11
0.00% covered (danger)
0.00%
0 / 1
3.01
 getMobileUrl
92.31% covered (success)
92.31%
12 / 13
0.00% covered (danger)
0.00%
0 / 1
6.02
 usingMobileDomain
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
2
 getDesktopUrl
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 updateDesktopUrlHost
100.00% covered (success)
100.00%
3 / 3
100.00% covered (success)
100.00%
1 / 1
3
 updateDesktopUrlQuery
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
3
 toggleView
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 doToggling
90.91% covered (success)
90.91%
20 / 22
0.00% covered (danger)
0.00%
0 / 1
6.03
 checkToggleView
100.00% covered (success)
100.00%
7 / 7
100.00% covered (success)
100.00%
1 / 1
4
 isLocalUrl
100.00% covered (success)
100.00%
4 / 4
100.00% covered (success)
100.00%
1 / 1
1
 addAnalyticsLogItem
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
 getAnalyticsLogItems
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
1
 getXAnalyticsHeader
91.67% covered (success)
91.67%
11 / 12
0.00% covered (danger)
0.00%
0 / 1
4.01
 addAnalyticsLogItemFromXAnalytics
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 logMobileMode
0.00% covered (danger)
0.00%
0 / 2
0.00% covered (danger)
0.00%
0 / 1
6
 shouldShowWikibaseDescriptions
100.00% covered (success)
100.00%
6 / 6
100.00% covered (success)
100.00%
1 / 1
2
1<?php
2
3use MediaWiki\Config\Config;
4use MediaWiki\Context\ContextSource;
5use MediaWiki\Context\IContextSource;
6use MediaWiki\Context\RequestContext;
7use MediaWiki\MainConfigNames;
8use MediaWiki\MediaWikiServices;
9use MediaWiki\Utils\UrlUtils;
10use MobileFrontend\Amc\UserMode;
11use MobileFrontend\Devices\DeviceDetectorService;
12use MobileFrontend\WMFBaseDomainExtractor;
13
14/**
15 * Provide various request-dependant methods to use in mobile context
16 */
17class MobileContext extends ContextSource {
18    public const STOP_MOBILE_REDIRECT_COOKIE_NAME = 'stopMobileRedirect';
19    public const USEFORMAT_COOKIE_NAME = 'mf_useformat';
20    // Keep in sync with https://wikitech.wikimedia.org/wiki/X-Analytics.
21    private const ANALYTICS_HEADER_KEY = 'mf-m';
22    private const ANALYTICS_HEADER_DELIMITER = ',';
23    private const ANALYTICS_HEADER_VALUE_AMC = 'amc';
24
25    /**
26     * Save explicitly requested format
27     */
28    protected ?string $useFormat = null;
29
30    /**
31     * Key/value pairs of things to add to X-Analytics response header for analytics
32     * @var array[]
33     */
34    protected array $analyticsLogItems = [];
35
36    /**
37     * The memoized result of `MobileContext#isMobileDevice`.
38     *
39     * This defaults to `null`, meaning that `MobileContext#isMobileDevice` has
40     * yet to be called.
41     *
42     * @see MobileContext#isMobileDevice
43     */
44    private ?bool $isMobileDevice = null;
45
46    /**
47     * Saves requested Mobile action
48     */
49    protected ?string $mobileAction = null;
50
51    /**
52     * Save whether the mobile view is explicitly requested
53     */
54    private bool $forceMobileView = false;
55
56    /**
57     * Save whether we should display the mobile view
58     */
59    private ?bool $mobileView = null;
60
61    /**
62     * Have we already checked for desktop/mobile view toggling?
63     */
64    private bool $toggleViewChecked = false;
65
66    private static ?self $instance = null;
67
68    /**
69     * @var string|null What to switch the view to
70     */
71    private ?string $viewChange = null;
72
73    /**
74     * @var string|null Domain to use for the stopMobileRedirect cookie
75     */
76    public static ?string $mfStopRedirectCookieHost = null;
77
78    /**
79     * In-process cache for checking whether the current wiki has a mobile URL that's
80     * different from the desktop one.
81     */
82    private ?bool $hasMobileUrl = null;
83
84    /**
85     * Returns the actual MobileContext Instance or create a new if no exists
86     * @deprecated use MediaWikiServices::getInstance()->getService( 'MobileFrontend.Context' );
87     * @return self
88     */
89    public static function singleton() {
90        if ( !self::$instance ) {
91            self::$instance = new self(
92                RequestContext::getMain(),
93                MediaWikiServices::getInstance()->getService( 'MobileFrontend.Config' )
94            );
95        }
96        return self::$instance;
97    }
98
99    /**
100     * Resets the singleton instance.
101     */
102    public static function resetInstanceForTesting() {
103        self::$instance = null;
104    }
105
106    protected function __construct(
107        IContextSource $context,
108        private readonly Config $config,
109    ) {
110        $this->setContext( $context );
111    }
112
113    /**
114     * Detects whether the UA is sending the request from a device and, if so,
115     * whether to display the mobile view to that device.
116     *
117     * The mobile view will always be displayed to mobile devices. However, it
118     * will only be displayed to tablet devices if `$wgMFShowMobileViewToTablets`
119     * is truthy.
120     *
121     * @fixme This should be renamed to something more appropriate, e.g.
122     * `shouldDisplayMobileViewToDevice`.
123     *
124     * @see MobileContext::shouldDisplayMobileView
125     *
126     * @return bool
127     */
128    public function isMobileDevice() {
129        if ( $this->isMobileDevice !== null ) {
130            return $this->isMobileDevice;
131        }
132
133        $this->isMobileDevice = false;
134
135        $properties = DeviceDetectorService::factory( $this->config )
136            ->detectDeviceProperties( $this->getRequest(), $_SERVER );
137
138        if ( $properties ) {
139            $this->isMobileDevice = $properties->isMobileDevice ||
140                ( $properties->isTabletDevice && $this->config->get( 'MFShowMobileViewToTablets' ) );
141        }
142
143        return $this->isMobileDevice;
144    }
145
146    /**
147     * Save whether mobile view should always be enforced
148     * @param bool $value should mobile view be enforced?
149     */
150    public function setForceMobileView( $value ) {
151        $this->forceMobileView = $value;
152    }
153
154    /**
155     * Whether the current user has advanced mobile contributions enabled.
156     * @return bool
157     */
158    private static function isAmcUser() {
159        $services = MediaWikiServices::getInstance();
160        /** @var UserMode $userMode */
161        $userMode = $services->getService( 'MobileFrontend.AMC.UserMode' );
162        return $userMode->isEnabled();
163    }
164
165    /**
166     * Determine whether we should display the mobile view
167     *
168     * Step through the hierarchy of what should or should not trigger
169     * the mobile view.
170     *
171     * Primacy is given to the page action - we will never show the mobile view
172     * for page edits or page history. 'useformat' request param is then
173     * honored, followed by cookie settings, then actual device detection,
174     * finally falling back on false.
175     * @return bool
176     */
177    public function shouldDisplayMobileView() {
178        if ( $this->mobileView === null ) {
179            // Compute viewChange, to toggle between mobile/desktop view
180            $this->checkToggleView();
181            $this->mobileView = $this->shouldDisplayMobileViewInternal();
182        }
183        return $this->mobileView;
184    }
185
186    /**
187     * Value for shouldDisplayMobileView()
188     * @return bool
189     */
190    private function shouldDisplayMobileViewInternal() {
191        // May be overridden programmatically
192        if ( $this->forceMobileView ) {
193            return true;
194        }
195
196        // always display the desktop or mobile view if it's explicitly requested
197        $useFormat = $this->getUseFormat();
198        if ( $useFormat === 'desktop' ) {
199            return false;
200        } elseif ( $useFormat === 'mobile' ) {
201            return true;
202        }
203
204        if ( $this->getRequest()->getRawVal( 'mobileformat' ) !== null ) {
205            return true;
206        }
207
208        /**
209         * If a user is accessing the site from a mobile domain, then we should
210         * always display the mobile version of the site (otherwise, the cache
211         * may get polluted). See
212         * https://phabricator.wikimedia.org/T48473
213         */
214        if ( $this->usingMobileDomain() ) {
215            return true;
216        }
217
218        // check cookies for what to display
219        $useMobileFormat = $this->getUseFormatCookie();
220        if ( $useMobileFormat === 'true' ) {
221            return true;
222        }
223        $stopMobileRedirect = $this->getStopMobileRedirectCookie();
224        if ( $stopMobileRedirect === 'true' ) {
225            return false;
226        }
227
228        // do device detection
229        if ( $this->isMobileDevice() ) {
230            return true;
231        }
232
233        return false;
234    }
235
236    /**
237     * Get requested mobile action
238     * @return string
239     */
240    public function getMobileAction() {
241        if ( $this->mobileAction === null ) {
242            $this->mobileAction = $this->getRequest()->getRawVal( 'mobileaction' );
243        }
244
245        return $this->mobileAction;
246    }
247
248    /**
249     * Gets the value of the `useformat` query string parameter.
250     *
251     * @return string Typically "desktop" or "mobile"
252     */
253    private function getUseFormat() {
254        if ( $this->useFormat === null ) {
255            $this->useFormat = $this->getRequest()->getRawVal( 'useformat' );
256        }
257        return $this->useFormat;
258    }
259
260    /**
261     * Set Cookie to stop automatically redirect to mobile page
262     * @param int|null $expiry Expire time of cookie
263     */
264    public function setStopMobileRedirectCookie( $expiry = null ) {
265        $this->getRequest()->response()->setCookie(
266            self::STOP_MOBILE_REDIRECT_COOKIE_NAME,
267            'true',
268            $expiry ?? $this->getUseFormatCookieExpiry(),
269            [
270                'domain' => $this->getStopMobileRedirectCookieDomain(),
271                'prefix' => '',
272                'secure' => (bool)$this->config->get( 'MFStopMobileRedirectCookieSecureValue' ),
273            ]
274        );
275    }
276
277    /**
278     * Remove cookie and continue automatic redirect to mobile page
279     */
280    public function unsetStopMobileRedirectCookie() {
281        if ( $this->getStopMobileRedirectCookie() === null ) {
282            return;
283        }
284        $expire = $this->getUseFormatCookieExpiry( time(), -3600 );
285        $this->setStopMobileRedirectCookie( $expire );
286    }
287
288    /**
289     * Read cookie for stop automatic mobile redirect
290     * @return string
291     */
292    public function getStopMobileRedirectCookie() {
293        return $this->getRequest()
294            ->getCookie( self::STOP_MOBILE_REDIRECT_COOKIE_NAME, '' );
295    }
296
297    /**
298     * This cookie can determine whether a user should see the mobile
299     * version of a page.
300     *
301     * @return string|null
302     */
303    public function getUseFormatCookie() {
304        return $this->getRequest()->getCookie( self::USEFORMAT_COOKIE_NAME, '' );
305    }
306
307    /**
308     * Return the base level domain or IP address
309     *
310     * @return string|null
311     */
312    public function getCookieDomain() {
313        return ( new WMFBaseDomainExtractor() )->getCookieDomain( $this->config->get( MainConfigNames::Server ) );
314    }
315
316    /**
317     * Determine the correct domain to use for the stopMobileRedirect cookie
318     *
319     * Will use $wgMFStopRedirectCookieHost if it's set, otherwise will use
320     * the result of getCookieDomain()
321     * @return string|null
322     */
323    public function getStopMobileRedirectCookieDomain() {
324        $mfStopRedirectCookieHost = $this->config->get( 'MFStopRedirectCookieHost' );
325
326        if ( !$mfStopRedirectCookieHost ) {
327            self::$mfStopRedirectCookieHost = $this->getCookieDomain();
328        } else {
329            self::$mfStopRedirectCookieHost = $mfStopRedirectCookieHost;
330        }
331
332        return self::$mfStopRedirectCookieHost;
333    }
334
335    /**
336     * Set the mf_useformat cookie
337     *
338     * This cookie can determine whether a user should see the mobile
339     * version of pages.
340     *
341     * @param string $cookieFormat should user see the mobile version of pages?
342     * @param int|null $expiry Expiration of cookie
343     */
344    public function setUseFormatCookie( $cookieFormat = 'true', $expiry = null ) {
345        $this->getRequest()->response()->setCookie(
346            self::USEFORMAT_COOKIE_NAME,
347            $cookieFormat,
348            $expiry ?? $this->getUseFormatCookieExpiry(),
349            [
350                'prefix' => '',
351                'httpOnly' => true,
352            ]
353        );
354    }
355
356    /**
357     * Remove cookie based saved useformat value
358     */
359    public function unsetUseFormatCookie() {
360        if ( $this->getUseFormatCookie() === null ) {
361            return;
362        }
363
364        // set expiration date in the past
365        $expire = $this->getUseFormatCookieExpiry( time(), -3600 );
366        $this->setUseFormatCookie( '', $expire );
367    }
368
369    /**
370     * Get the expiration time for the mf_useformat cookie
371     *
372     * @param int|null $startTime The base time (in seconds since Epoch) from which to calculate
373     *  cookie expiration. If null, time() is used.
374     * @param int|null $cookieDuration The time (in seconds) the cookie should last
375     * @return int The time (in seconds since Epoch) that the cookie should expire
376     */
377    protected function getUseFormatCookieExpiry( $startTime = null, $cookieDuration = null ) {
378        // use $cookieDuration if it's valid
379        if ( intval( $cookieDuration ) === 0 ) {
380            $cookieDuration = $this->getUseFormatCookieDuration();
381        }
382
383        // use $startTime if it's valid
384        if ( intval( $startTime ) === 0 ) {
385            $startTime = time();
386        }
387
388        return $startTime + $cookieDuration;
389    }
390
391    /**
392     * Determine the duration the cookie should last.
393     *
394     * If $wgMobileFrontendFormatcookieExpiry has a non-0 value, use that
395     * for the duration. Otherwise, fall back to $wgCookieExpiration.
396     *
397     * @return int The number of seconds for which the cookie should last.
398     */
399    public function getUseFormatCookieDuration() {
400        $mobileFrontendFormatCookieExpiry =
401            $this->config->get( 'MobileFrontendFormatCookieExpiry' );
402
403        return ( abs( (int)$mobileFrontendFormatCookieExpiry ) > 0 )
404            ? $mobileFrontendFormatCookieExpiry
405            : $this->getConfig()->get( MainConfigNames::CookieExpiration );
406    }
407
408    /**
409     * Returns the callback from $wgMobileUrlCallback, which changes
410     *   a desktop domain into a mobile domain.
411     * @return callable|null
412     * @phan-return callable(string):string|null
413     */
414    private function getMobileUrlCallback(): ?callable {
415        return $this->config->get( 'MobileUrlCallback' );
416    }
417
418    /**
419     * True if the current wiki has separate mobile and desktop domains (regardless
420     * of which domain is used by the current request).
421     */
422    public function hasMobileDomain(): bool {
423        if ( $this->hasMobileUrl !== null ) {
424            return $this->hasMobileUrl;
425        }
426
427        $mobileUrlCallback = $this->getMobileUrlCallback();
428        if ( $mobileUrlCallback ) {
429            $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
430            $server = $urlUtils->expand( $this->getConfig()->get( MainConfigNames::Server ), PROTO_CANONICAL ) ?? '';
431            $host = $urlUtils->parse( $server )['host'] ?? '';
432            $mobileDomain = $mobileUrlCallback( $host );
433            $this->hasMobileUrl = $mobileDomain !== $host;
434        } else {
435            $this->hasMobileUrl = false;
436        }
437
438        return $this->hasMobileUrl;
439    }
440
441    /**
442     * Take a URL and return the equivalent mobile URL (ie. replace the domain with the
443     * mobile domain).
444     *
445     * Typically, this is a URL for the current wiki, but it can be anything as long as
446     * $wgMobileUrlCallback can convert its domain (so e.g. interwiki links can be
447     * converted). If the domain is already a mobile domain, or not recognized by
448     * $wgMobileUrlCallback, or the wiki does not use mobile domains, and so
449     * $wgMobileUrlCallback is not set, the URL will be returned unchanged.
450     *
451     * @param string $url URL to convert
452     * @return string|bool
453     */
454    public function getMobileUrl( $url ) {
455        $mobileUrlCallback = $this->getMobileUrlCallback();
456
457        if ( !$mobileUrlCallback ) {
458            // Optimization: Return original URL instead of parsing and reassembling it if we don't have a
459            // reason to modify it
460            return $url;
461        }
462
463        $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
464        $parsedUrl = $urlUtils->parse( $url );
465        // if parsing failed, maybe it's a local Url, try to expand and reparse it - task T107505
466        if ( !$parsedUrl ) {
467            $expandedUrl = $urlUtils->expand( $url, PROTO_CURRENT );
468            if ( $expandedUrl ) {
469                $parsedUrl = $urlUtils->parse( $expandedUrl );
470            }
471            if ( !$expandedUrl || !$parsedUrl ) {
472                return false;
473            }
474        }
475
476        $parsedUrl['host'] = $mobileUrlCallback( $parsedUrl['host'] );
477
478        return UrlUtils::assemble( $parsedUrl );
479    }
480
481    /**
482     * Checks whether the current request is using the mobile domain.
483     *
484     * This assumes that some infrastructure outside MediaWiki will set a
485     * header (specified by $wgMFMobileHeader) on requests which should use the
486     * mobile format. This means that the traffic routing layer can rewrite
487     * any m-dot hostnames to be canonical, allowing non-MobileFrontend-aware
488     * code in MediaWiki to work as-is.
489     *
490     * @return bool
491     */
492    public function usingMobileDomain() {
493        $mobileHeader = $this->config->get( 'MFMobileHeader' );
494        return ( $mobileHeader
495            && $this->getRequest()->getHeader( $mobileHeader ) !== false
496        );
497    }
498
499    /**
500     * Take a URL and return a copy that removes any mobile tokens.
501     *
502     * This only works with URLs of the current wiki.
503     *
504     * @param string $url representing a page on the mobile domain e.g. `https://en.m.wikipedia.org/`
505     * @return string (absolute url)
506     */
507    public function getDesktopUrl( $url ) {
508        $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
509        $parsedUrl = $urlUtils->parse( $url ) ?? [];
510        $parsedUrl = $this->updateDesktopUrlHost( $parsedUrl );
511        $parsedUrl = $this->updateDesktopUrlQuery( $parsedUrl );
512
513        return UrlUtils::assemble( $parsedUrl );
514    }
515
516    /**
517     * Change the host field of a URL to wgServer
518     * @param array $parsedUrl Result of UrlUtils::parse()
519     * @return array
520     */
521    protected function updateDesktopUrlHost( array $parsedUrl ): array {
522        if ( $this->hasMobileDomain() ) {
523            $parsedUrl['host'] = parse_url( $this->getConfig()->get( MainConfigNames::Server ), PHP_URL_HOST, ) ?: '';
524        }
525
526        return $parsedUrl;
527    }
528
529    /**
530     * Change the query parameters of a URL to remove any 'useformat' param
531     * @param array $parsedUrl Result of UrlUtils::parse()
532     * @return array
533     */
534    protected function updateDesktopUrlQuery( array $parsedUrl ): array {
535        if ( isset( $parsedUrl['query'] ) && strpos( $parsedUrl['query'], 'useformat' ) !== false ) {
536            $query = wfCgiToArray( $parsedUrl['query'] );
537            unset( $query['useformat'] );
538            $parsedUrl['query'] = wfArrayToCgi( $query );
539        }
540        return $parsedUrl;
541    }
542
543    /**
544     * Toggles view to one specified by the user
545     *
546     * When a user requests a particular view (e.g. click 'Desktop view' on a mobile page),
547     * - apply the requested view to this particular request
548     * - set a cookie to keep them on that view for subsequent requests
549     * - redirect to strip off the 'mobileaction' parameter,
550     *   to avoid issues with CDN caching or URL sharing (T401595)
551     *
552     * @param string $view User requested particular view
553     */
554    private function toggleView( $view ) {
555        $this->viewChange = $view;
556        $this->useFormat = $view;
557    }
558
559    /**
560     * Set the toggling cookie and redirect, as requested by toggleView()
561     */
562    public function doToggling() {
563        // Compute viewChange now, if not already
564        $this->shouldDisplayMobileView();
565
566        if ( !$this->viewChange ) {
567            return;
568        }
569
570        $title = $this->getTitle();
571        if ( !$title ) {
572            return;
573        }
574
575        $query = $this->getRequest()->getQueryValues();
576        unset( $query['mobileaction'] );
577        unset( $query['useformat'] );
578        unset( $query['title'] );
579        $url = $title->getFullURL( $query, false, PROTO_CURRENT );
580
581        if ( $this->viewChange === 'mobile' ) {
582            // remove old desktop opt-in choice (if any)
583            $this->unsetStopMobileRedirectCookie();
584
585            // preserve mobile opt-in choice for future pageviews via same-domain cookie
586            $this->setUseFormatCookie();
587
588            // redirect to strip 'mobileaction' param (T401595)
589            $mobileUrl = $this->getMobileUrl( $url );
590            $this->getOutput()->redirect( $mobileUrl, 301 );
591        } elseif ( $this->viewChange === 'desktop' ) {
592            // remove old mobile opt-in choice (if any)
593            if ( $this->getUseFormatCookie() === 'true' ) {
594                $this->unsetUseFormatCookie();
595            }
596
597            // preserve desktop opt-in choice for future pageviews via same-domain cookie
598            $this->setStopMobileRedirectCookie();
599
600            // redirect to strip 'mobileaction' param (T401595)
601            $desktopUrl = $this->getDesktopUrl( $url );
602            $this->getOutput()->redirect( $desktopUrl, 301 );
603        }
604    }
605
606    /**
607     * Determine whether we need to toggle the view, and toggle it
608     */
609    public function checkToggleView() {
610        if ( !$this->toggleViewChecked ) {
611            $this->toggleViewChecked = true;
612            $mobileAction = $this->getMobileAction();
613            if ( $mobileAction === 'toggle_view_desktop' ) {
614                $this->toggleView( 'desktop' );
615            } elseif ( $mobileAction === 'toggle_view_mobile' ) {
616                $this->toggleView( 'mobile' );
617            }
618        }
619    }
620
621    /**
622     * Determine whether a given URL is local
623     *
624     * @param string $url URL to check against
625     * @return bool
626     */
627    public function isLocalUrl( $url ) {
628        $urlUtils = MediaWikiServices::getInstance()->getUrlUtils();
629        $parsedTargetHost = $urlUtils->parse( $url )['host'] ?? '';
630        $parsedServerHost = $urlUtils->parse( $this->config->get( MainConfigNames::Server ) )['host'] ?? '';
631        return $parsedTargetHost === $parsedServerHost;
632    }
633
634    /**
635     * Add key/value pairs for analytics purposes to $this->analyticsLogItems. Pre-existing entries
636     * are appended to as sets delimited by commas.
637     * @param string $key for <key> in `X-Analytics: <key>=<value>`
638     * @param string $val for <value> in `X-Analytics: <key>=<value>`
639     */
640    public function addAnalyticsLogItem( $key, $val ) {
641        $key = trim( $key );
642        $val = trim( $val );
643        $items = $this->analyticsLogItems[$key] ?? [];
644        if ( !in_array( $val, $items ) ) {
645            $items[] = $val;
646            $this->analyticsLogItems[$key] = $items;
647        }
648    }
649
650    /**
651     * Read key/value pairs for analytics purposes from $this->analyticsLogItems
652     * @return array
653     */
654    public function getAnalyticsLogItems() {
655        return array_map(
656            static function ( $val ) {
657                return implode( self::ANALYTICS_HEADER_DELIMITER, $val );
658            },
659            $this->analyticsLogItems
660        );
661    }
662
663    /**
664     * Get HTTP header string for X-Analytics
665     *
666     * This is made up of key/value pairs and is used for analytics purposes.
667     *
668     * @return string|bool
669     */
670    public function getXAnalyticsHeader() {
671        $response = $this->getRequest()->response();
672        $currentHeader = method_exists( $response, 'getHeader' ) ?
673            (string)$response->getHeader( 'X-Analytics' ) : '';
674        parse_str( preg_replace( '/; */', '&', $currentHeader ), $logItems );
675        $logItems += $this->getAnalyticsLogItems();
676        if ( !count( $logItems ) ) {
677            return false;
678        }
679
680        $items = [];
681        foreach ( $logItems as $key => $val ) {
682            $items[] = urlencode( $key ) . "=" . urlencode( $val );
683        }
684        $headerValue = implode( ';', $items );
685
686        return "X-Analytics: $headerValue";
687    }
688
689    /**
690     * Take a key/val pair in string format and add it to $this->analyticsLogItems
691     *
692     * @param string $xanalytics_item In the format key=value
693     */
694    public function addAnalyticsLogItemFromXAnalytics( $xanalytics_item ) {
695        [ $key, $val ] = explode( '=', $xanalytics_item, 2 );
696        $this->addAnalyticsLogItem( urldecode( $key ), urldecode( $val ) );
697    }
698
699    /**
700     * Adds analytics log items depending on which modes are enabled for the user
701     *
702     * Invoked from MobileFrontendHooks::onRequestContextCreateSkin()
703     *
704     * Making changes to what this method logs? Make sure you update the
705     * documentation for the X-Analytics header: https://wikitech.wikimedia.org/wiki/X-Analytics
706     */
707    public function logMobileMode() {
708        if ( self::isAmcUser() ) {
709            $this->addAnalyticsLogItem( self::ANALYTICS_HEADER_KEY, self::ANALYTICS_HEADER_VALUE_AMC );
710        }
711    }
712
713    /**
714     * Gets whether Wikibase descriptions should be rendered as taglines on article pages.
715     * Doesn't take into account whether the wikidata descriptions
716     * feature has been enabled.
717     *
718     * @param string $feature which description to show?
719     * @param Config $config
720     * @return bool
721     * @throws DomainException If `feature` isn't one that shows Wikidata descriptions. See the
722     *  `wgMFDisplayWikibaseDescriptions` configuration variable for detail
723     */
724    public function shouldShowWikibaseDescriptions( $feature, Config $config ) {
725        $displayWikibaseDescriptions = $config->get( 'MFDisplayWikibaseDescriptions' );
726        if ( !isset( $displayWikibaseDescriptions[$feature] ) ) {
727            throw new DomainException(
728                "\"{$feature}\" isn't a feature that shows Wikidata descriptions."
729            );
730        }
731
732        return $displayWikibaseDescriptions[$feature];
733    }
734}