Code Coverage
 
Lines
Functions and Methods
Classes and Traits
Total
57.52% covered (warning)
57.52%
65 / 113
50.00% covered (danger)
50.00%
5 / 10
CRAP
0.00% covered (danger)
0.00%
0 / 1
ApiWatch
58.04% covered (warning)
58.04%
65 / 112
50.00% covered (danger)
50.00%
5 / 10
96.51
0.00% covered (danger)
0.00%
0 / 1
 __construct
100.00% covered (success)
100.00%
5 / 5
100.00% covered (success)
100.00%
1 / 1
1
 execute
57.78% covered (warning)
57.78%
26 / 45
0.00% covered (danger)
0.00%
0 / 1
20.11
 watchTitle
52.38% covered (warning)
52.38%
11 / 21
0.00% covered (danger)
0.00%
0 / 1
14.91
 getPageSet
100.00% covered (success)
100.00%
2 / 2
100.00% covered (success)
100.00%
1 / 1
1
 mustBePosted
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 isWriteMode
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 needsToken
100.00% covered (success)
100.00%
1 / 1
100.00% covered (success)
100.00%
1 / 1
1
 getAllowedParams
90.00% covered (success)
90.00%
18 / 20
0.00% covered (danger)
0.00%
0 / 1
3.01
 getExamplesMessages
0.00% covered (danger)
0.00%
0 / 15
0.00% covered (danger)
0.00%
0 / 1
6
 getHelpUrls
0.00% covered (danger)
0.00%
0 / 1
0.00% covered (danger)
0.00%
0 / 1
2
1<?php
2/**
3 * Copyright © 2008 Yuri Astrakhan "<Firstname><Lastname>@gmail.com",
4 *
5 * @license GPL-2.0-or-later
6 * @file
7 */
8
9namespace MediaWiki\Api;
10
11use MediaWiki\MainConfigNames;
12use MediaWiki\Page\PageIdentity;
13use MediaWiki\Title\Title;
14use MediaWiki\Title\TitleFormatter;
15use MediaWiki\User\User;
16use MediaWiki\Watchlist\WatchlistManager;
17use Wikimedia\ParamValidator\ParamValidator;
18use Wikimedia\ParamValidator\TypeDef\ExpiryDef;
19
20/**
21 * API module to allow users to watch a page
22 *
23 * @ingroup API
24 */
25class ApiWatch extends ApiBase {
26    /** @var ApiPageSet|null */
27    private $mPageSet = null;
28
29    /** @var bool Whether watchlist expiries are enabled. */
30    private $expiryEnabled;
31
32    /** @var string Relative maximum expiry. */
33    private $maxDuration;
34
35    protected WatchlistManager $watchlistManager;
36    private TitleFormatter $titleFormatter;
37
38    public function __construct(
39        ApiMain $mainModule,
40        string $moduleName,
41        WatchlistManager $watchlistManager,
42        TitleFormatter $titleFormatter
43    ) {
44        parent::__construct( $mainModule, $moduleName );
45
46        $this->watchlistManager = $watchlistManager;
47        $this->titleFormatter = $titleFormatter;
48        $this->expiryEnabled = $this->getConfig()->get( MainConfigNames::WatchlistExpiry );
49        $this->maxDuration = $this->getConfig()->get( MainConfigNames::WatchlistExpiryMaxDuration );
50    }
51
52    public function execute() {
53        $user = $this->getUser();
54        if ( !$user->isRegistered()
55            || ( $user->isTemp() && !$user->isAllowed( 'editmywatchlist' ) )
56        ) {
57            $this->dieWithError( 'watchlistanontext', 'notloggedin' );
58        }
59
60        $this->checkUserRightsAny( 'editmywatchlist' );
61
62        $params = $this->extractRequestParams();
63
64        $continuationManager = new ApiContinuationManager( $this, [], [] );
65        $this->setContinuationManager( $continuationManager );
66
67        $pageSet = $this->getPageSet();
68        // by default we use pageset to extract the page to work on.
69        // title is still supported for backward compatibility
70        if ( !isset( $params['title'] ) ) {
71            $pageSet->execute();
72            $res = $pageSet->getInvalidTitlesAndRevisions( [
73                'invalidTitles',
74                'special',
75                'missingIds',
76                'missingRevIds',
77                'interwikiTitles'
78            ] );
79
80            foreach ( $pageSet->getMissingPages() as $page ) {
81                $r = $this->watchTitle( $page, $user, $params );
82                $r['missing'] = true;
83                $res[] = $r;
84            }
85
86            foreach ( $pageSet->getGoodPages() as $page ) {
87                $r = $this->watchTitle( $page, $user, $params );
88                $res[] = $r;
89            }
90            ApiResult::setIndexedTagName( $res, 'w' );
91        } else {
92            // dont allow use of old title parameter with new pageset parameters.
93            $extraParams = array_keys( array_filter( $pageSet->extractRequestParams(), static function ( $x ) {
94                return $x !== null && $x !== false;
95            } ) );
96
97            if ( $extraParams ) {
98                $this->dieWithError(
99                    [
100                        'apierror-invalidparammix-cannotusewith',
101                        $this->encodeParamName( 'title' ),
102                        $pageSet->encodeParamName( $extraParams[0] )
103                    ],
104                    'invalidparammix'
105                );
106            }
107
108            $title = Title::newFromText( $params['title'] );
109            if ( !$title || !$this->watchlistManager->isWatchable( $title ) ) {
110                $this->dieWithError( [ 'invalidtitle', $params['title'] ] );
111            }
112            $res = $this->watchTitle( $title, $user, $params, true );
113        }
114        $this->getResult()->addValue( null, $this->getModuleName(), $res );
115
116        $this->setContinuationManager( null );
117        $continuationManager->setContinuationIntoResult( $this->getResult() );
118    }
119
120    private function watchTitle( PageIdentity $page, User $user, array $params,
121        bool $compatibilityMode = false
122    ): array {
123        $res = [ 'title' => $this->titleFormatter->getPrefixedText( $page ), 'ns' => $page->getNamespace() ];
124
125        if ( !$this->watchlistManager->isWatchable( $page ) ) {
126            $res['watchable'] = 0;
127            return $res;
128        }
129
130        if ( $params['unwatch'] ) {
131            $status = $this->watchlistManager->removeWatch( $user, $page );
132            $res['unwatched'] = $status->isOK();
133        } else {
134            $expiry = null;
135
136            // NOTE: If an expiry parameter isn't given, any existing expiries remain unchanged.
137            if ( $this->expiryEnabled && isset( $params['expiry'] ) ) {
138                $expiry = $params['expiry'];
139                $res['expiry'] = ApiResult::formatExpiry( $expiry );
140            }
141
142            $status = $this->watchlistManager->addWatch( $user, $page, $expiry );
143            $res['watched'] = $status->isOK();
144        }
145
146        if ( !$status->isOK() ) {
147            if ( $compatibilityMode ) {
148                $this->dieStatus( $status );
149            }
150            $res['errors'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'error' );
151            $res['warnings'] = $this->getErrorFormatter()->arrayFromStatus( $status, 'warning' );
152            if ( !$res['warnings'] ) {
153                unset( $res['warnings'] );
154            }
155        }
156
157        return $res;
158    }
159
160    /**
161     * Get a cached instance of an ApiPageSet object
162     * @return ApiPageSet
163     */
164    private function getPageSet() {
165        $this->mPageSet ??= new ApiPageSet( $this );
166
167        return $this->mPageSet;
168    }
169
170    /** @inheritDoc */
171    public function mustBePosted() {
172        return true;
173    }
174
175    /** @inheritDoc */
176    public function isWriteMode() {
177        return true;
178    }
179
180    /** @inheritDoc */
181    public function needsToken() {
182        return 'watch';
183    }
184
185    /** @inheritDoc */
186    public function getAllowedParams( $flags = 0 ) {
187        $result = [
188            'title' => [
189                ParamValidator::PARAM_TYPE => 'string',
190                ParamValidator::PARAM_DEPRECATED => true,
191            ],
192            'expiry' => [
193                ParamValidator::PARAM_TYPE => 'expiry',
194                ExpiryDef::PARAM_MAX => $this->maxDuration,
195                ExpiryDef::PARAM_USE_MAX => true,
196            ],
197            'unwatch' => false,
198            'continue' => [
199                ApiBase::PARAM_HELP_MSG => 'api-help-param-continue',
200            ],
201        ];
202
203        // If expiry is not enabled, don't accept the parameter.
204        if ( !$this->expiryEnabled ) {
205            unset( $result['expiry'] );
206        }
207
208        if ( $flags ) {
209            $result += $this->getPageSet()->getFinalParams( $flags );
210        }
211
212        return $result;
213    }
214
215    /** @inheritDoc */
216    protected function getExamplesMessages() {
217        $title = Title::newMainPage()->getPrefixedText();
218        $mp = rawurlencode( $title );
219
220        // Logically expiry example should go before unwatch examples.
221        $examples = [
222            "action=watch&titles={$mp}&token=123ABC"
223                => 'apihelp-watch-example-watch',
224        ];
225        if ( $this->expiryEnabled ) {
226            $examples["action=watch&titles={$mp}|Foo|Bar&expiry=1%20month&token=123ABC"]
227                = 'apihelp-watch-example-watch-expiry';
228        }
229
230        return array_merge( $examples, [
231            "action=watch&titles={$mp}&unwatch=&token=123ABC"
232                => 'apihelp-watch-example-unwatch',
233            'action=watch&generator=allpages&gapnamespace=0&token=123ABC'
234                => 'apihelp-watch-example-generator',
235        ] );
236    }
237
238    /** @inheritDoc */
239    public function getHelpUrls() {
240        return 'https://www.mediawiki.org/wiki/Special:MyLanguage/API:Watch';
241    }
242}
243
244/** @deprecated class alias since 1.43 */
245class_alias( ApiWatch::class, 'ApiWatch' );