MediaWiki  master
WatchAction.php
Go to the documentation of this file.
1 <?php
25 
31 class WatchAction extends FormAction {
32 
34  protected $watchlistExpiry;
35 
37  protected $expiryFormFieldName = 'expiry';
38 
40  protected $watchedItem = false;
41 
48  public function __construct( Page $page, IContextSource $context = null ) {
49  parent::__construct( $page, $context );
50  $this->watchlistExpiry = $this->getContext()->getConfig()->get( 'WatchlistExpiry' );
51  if ( $this->watchlistExpiry ) {
52  // The watchedItem is only used in this action's form if $wgWatchlistExpiry is enabled.
53  $this->watchedItem = MediaWikiServices::getInstance()
54  ->getWatchedItemStore()
55  ->getWatchedItem( $this->getUser(), $this->getTitle() );
56  }
57  }
58 
59  public function getName() {
60  return 'watch';
61  }
62 
63  public function requiresUnblock() {
64  return false;
65  }
66 
67  protected function getDescription() {
68  return '';
69  }
70 
71  public function onSubmit( $data ) {
72  $expiry = $this->getRequest()->getVal( 'wp' . $this->expiryFormFieldName );
73 
74  // Even though we're never unwatching here, use doWatchOrUnwatch() because it also checks for changed expiry.
75  return self::doWatchOrUnwatch( true, $this->getTitle(), $this->getUser(), $expiry );
76  }
77 
78  protected function checkCanExecute( User $user ) {
79  // Must be logged in
80  if ( $user->isAnon() ) {
81  throw new UserNotLoggedIn( 'watchlistanontext', 'watchnologin' );
82  }
83 
84  parent::checkCanExecute( $user );
85  }
86 
87  protected function usesOOUI() {
88  return true;
89  }
90 
91  protected function getFormFields() {
92  // If watchlist expiry is not enabled, return a simple confirmation message.
93  if ( !$this->watchlistExpiry ) {
94  return [
95  'intro' => [
96  'type' => 'info',
97  'vertical-label' => true,
98  'raw' => true,
99  'default' => $this->msg( 'confirm-watch-top' )->parse(),
100  ],
101  ];
102  }
103 
104  // Otherwise, use a select-list of expiries.
105  $expiryOptions = static::getExpiryOptions( $this->getContext(), $this->watchedItem );
106  return [
107  $this->expiryFormFieldName => [
108  'type' => 'select',
109  'label-message' => 'confirm-watch-label',
110  'options' => $expiryOptions['options'],
111  'default' => $expiryOptions['default'],
112  ]
113  ];
114  }
115 
128  public static function getExpiryOptions( MessageLocalizer $msgLocalizer, $watchedItem ) {
129  $expiryOptionsMsg = $msgLocalizer->msg( 'watchlist-expiry-options' );
130  $expiryOptionsMsgText = $expiryOptionsMsg->text();
131  $expiryOptions = XmlSelect::parseOptionsMessage( $expiryOptionsMsgText );
132  $default = 'infinite';
133  if ( $watchedItem instanceof WatchedItem && $watchedItem->getExpiry() ) {
134  // If it's already being temporarily watched,
135  // add the existing expiry as the default option in the dropdown.
136  $default = $watchedItem->getExpiry( TS_ISO_8601 );
137  $daysLeft = $watchedItem->getExpiryInDaysText( $msgLocalizer, true );
138  $expiryOptions = array_merge( [ $daysLeft => $default ], $expiryOptions );
139  }
140  return [
141  'options' => $expiryOptions,
142  'default' => $default,
143  ];
144  }
145 
146  protected function alterForm( HTMLForm $form ) {
147  $msg = $this->watchlistExpiry && $this->watchedItem ? 'updatewatchlist' : 'addwatch';
148  $form->setWrapperLegendMsg( $msg );
149  $submitMsg = $this->watchlistExpiry ? 'confirm-watch-button-expiry' : 'confirm-watch-button';
150  $form->setSubmitTextMsg( $submitMsg );
151  $form->setTokenSalt( 'watch' );
152  }
153 
166  public function onSuccess() {
167  $msgKey = $this->getTitle()->isTalkPage() ? 'addedwatchtext-talk' : 'addedwatchtext';
168  $expiryLabel = null;
169  $submittedExpiry = $this->getContext()->getRequest()->getText( 'wp' . $this->expiryFormFieldName );
170  if ( $submittedExpiry ) {
171  // We can't use $this->watcheditem to get the expiry because it's not been saved at this
172  // point in the request and so its values are those from before saving.
173  $expiry = ExpiryDef::normalizeExpiry( $submittedExpiry, TS_ISO_8601 );
174 
175  // If the expiry label isn't one of the predefined ones in the dropdown, calculate 'x days'.
176  $expiryDays = WatchedItem::calculateExpiryInDays( $expiry );
177  $defaultLabels = static::getExpiryOptions( $this->getContext(), null )['options'];
178  $localizedExpiry = array_search( $submittedExpiry, $defaultLabels );
179  $expiryLabel = $expiryDays && $localizedExpiry === false
180  ? $this->getContext()->msg( 'days', $expiryDays )->text()
181  : $localizedExpiry;
182 
183  // Determine which message to use, depending on whether this is a talk page or not
184  // and whether an expiry was selected.
185  $isTalk = $this->getTitle()->isTalkPage();
186  if ( wfIsInfinity( $expiry ) ) {
187  $msgKey = $isTalk ? 'addedwatchindefinitelytext-talk' : 'addedwatchindefinitelytext';
188  } elseif ( $expiryDays > 0 ) {
189  $msgKey = $isTalk ? 'addedwatchexpirytext-talk' : 'addedwatchexpirytext';
190  } elseif ( $expiryDays < 1 ) {
191  $msgKey = $isTalk ? 'addedwatchexpiryhours-talk' : 'addedwatchexpiryhours';
192  }
193  }
194  $this->getOutput()->addWikiMsg( $msgKey, $this->getTitle()->getPrefixedText(), $expiryLabel );
195  }
196 
208  public static function doWatchOrUnwatch(
209  $watch,
210  Title $title,
211  User $user,
212  string $expiry = null
213  ) {
214  // User must be logged in, and either changing the watch state or at least the expiry.
215  if ( !$user->isLoggedIn() ) {
216  return Status::newGood();
217  }
218 
219  // Only run doWatch() or doUnwatch() if there's been a change in the watched status.
220  $oldWatchedItem = MediaWikiServices::getInstance()->getWatchedItemStore()
221  ->getWatchedItem( $user, $title );
222  $changingWatchStatus = (bool)$oldWatchedItem !== $watch;
223  if ( $oldWatchedItem && $expiry !== null ) {
224  // If there's an old watched item, a non-null change to the expiry requires an UPDATE.
225  $oldWatchPeriod = $oldWatchedItem->getExpiry() === null
226  ? 'infinity'
227  : $oldWatchedItem->getExpiry();
228  $changingWatchStatus = $changingWatchStatus ||
229  $oldWatchPeriod !== ExpiryDef::normalizeExpiry( $expiry, TS_MW );
230  }
231 
232  if ( $changingWatchStatus ) {
233  // If the user doesn't have 'editmywatchlist', we still want to
234  // allow them to add but not remove items via edits and such.
235  if ( $watch ) {
236  return self::doWatch( $title, $user, User::IGNORE_USER_RIGHTS, $expiry );
237  } else {
238  return self::doUnwatch( $title, $user );
239  }
240  }
241 
242  return Status::newGood();
243  }
244 
256  public static function doWatch(
257  Title $title,
258  User $user,
259  $checkRights = User::CHECK_USER_RIGHTS,
260  ?string $expiry = null
261  ) {
262  $permissionManager = MediaWikiServices::getInstance()->getPermissionManager();
263  if ( $checkRights && !$permissionManager->userHasRight( $user, 'editmywatchlist' ) ) {
264  return User::newFatalPermissionDeniedStatus( 'editmywatchlist' );
265  }
266 
268 
269  $status = Status::newFatal( 'hookaborted' );
270  if ( Hooks::runner()->onWatchArticle( $user, $page, $status, $expiry ) ) {
271  $status = Status::newGood();
272  $user->addWatch( $title, $checkRights, $expiry );
273  Hooks::runner()->onWatchArticleComplete( $user, $page );
274  }
275 
276  return $status;
277  }
278 
286  public static function doUnwatch( Title $title, User $user ) {
287  if ( !MediaWikiServices::getInstance()
289  ->userHasRight( $user, 'editmywatchlist' ) ) {
290  return User::newFatalPermissionDeniedStatus( 'editmywatchlist' );
291  }
292 
294 
295  $status = Status::newFatal( 'hookaborted' );
296  if ( Hooks::runner()->onUnwatchArticle( $user, $page, $status ) ) {
297  $status = Status::newGood();
298  $user->removeWatch( $title );
299  Hooks::runner()->onUnwatchArticleComplete( $user, $page );
300  }
301 
302  return $status;
303  }
304 
314  public static function getWatchToken( Title $title, User $user, $action = 'watch' ) {
315  if ( $action != 'unwatch' ) {
316  $action = 'watch';
317  }
318  // This must match ApiWatch and ResourceLoaderUserOptionsModule
319  return $user->getEditToken( $action );
320  }
321 
322  public function doesWrites() {
323  return true;
324  }
325 }
Page
Interface for type hinting (accepts WikiPage, Article, ImagePage, CategoryPage)
Definition: Page.php:29
StatusValue\newFatal
static newFatal( $message,... $parameters)
Factory function for fatal errors.
Definition: StatusValue.php:70
WatchAction\doWatch
static doWatch(Title $title, User $user, $checkRights=User::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch a page.
Definition: WatchAction.php:256
User\isAnon
isAnon()
Get whether the user is anonymous.
Definition: User.php:2963
WatchAction\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially Stable to override.
Definition: WatchAction.php:146
WatchAction\onSuccess
onSuccess()
Show one of 8 possible success messages.
Definition: WatchAction.php:166
MediaWiki\MediaWikiServices
MediaWikiServices is the service locator for the application scope of MediaWiki.
Definition: MediaWikiServices.php:163
Action\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: Action.php:229
User\newFatalPermissionDeniedStatus
static newFatalPermissionDeniedStatus( $permission)
Factory function for fatal permission-denied errors.
Definition: User.php:4354
WatchAction\requiresUnblock
requiresUnblock()
Whether this action can still be executed by a blocked user.
Definition: WatchAction.php:63
WatchAction\doUnwatch
static doUnwatch(Title $title, User $user)
Unwatch a page.
Definition: WatchAction.php:286
UserNotLoggedIn
Redirect a user to the login page.
Definition: UserNotLoggedIn.php:54
WatchAction\$expiryFormFieldName
string $expiryFormFieldName
Definition: WatchAction.php:37
WatchAction\getExpiryOptions
static getExpiryOptions(MessageLocalizer $msgLocalizer, $watchedItem)
Get options and default for a watchlist expiry select list.
Definition: WatchAction.php:128
HTMLForm\setTokenSalt
setTokenSalt( $salt)
Set the salt for the edit token.
Definition: HTMLForm.php:1047
FormAction
An action which shows a form and does something based on the input from the form.
Definition: FormAction.php:30
WatchAction\getDescription
getDescription()
Returns the description that goes below the <h1> tag.
Definition: WatchAction.php:67
WatchAction
Page addition to a user's watchlist.
Definition: WatchAction.php:31
XmlSelect\parseOptionsMessage
static parseOptionsMessage(string $msg)
Parse labels and values out of a comma- and colon-separated list of options, such as is used for expi...
Definition: XmlSelect.php:145
WatchAction\onSubmit
onSubmit( $data)
Process the form on POST submission.
Definition: WatchAction.php:71
MessageLocalizer
Interface for localizing messages in MediaWiki.
Definition: MessageLocalizer.php:29
WatchAction\getFormFields
getFormFields()
Get an HTMLForm descriptor array Stable to override.
Definition: WatchAction.php:91
Action\getContext
getContext()
Get the IContextSource in use here.
Definition: Action.php:215
WatchedItem\getExpiry
getExpiry(?int $style=TS_MW)
When the watched item will expire.
Definition: WatchedItem.php:145
Wikimedia\ParamValidator\TypeDef\ExpiryDef
Type definition for expiry timestamps.
Definition: ExpiryDef.php:17
WatchAction\doesWrites
doesWrites()
Stable to override.
Definition: WatchAction.php:322
WikiPage\factory
static factory(Title $title)
Create a WikiPage object of the appropriate class for the given title.
Definition: WikiPage.php:159
MessageLocalizer\msg
msg( $key,... $params)
This is the method for getting translated interface messages.
WatchAction\checkCanExecute
checkCanExecute(User $user)
Checks if the given user (identified by an object) can perform this action.
Definition: WatchAction.php:78
getPermissionManager
getPermissionManager()
$title
$title
Definition: testCompression.php:38
User\CHECK_USER_RIGHTS
const CHECK_USER_RIGHTS
Definition: User.php:85
WatchedItem\calculateExpiryInDays
static calculateExpiryInDays(?string $expiry)
Get the number of days remaining until the given expiry time.
Definition: WatchedItem.php:187
Action\getUser
getUser()
Shortcut to get the User being used for this instance.
Definition: Action.php:249
Action\$context
IContextSource $context
IContextSource if specified; otherwise we'll use the Context from the Page.
Definition: Action.php:66
WatchAction\$watchlistExpiry
bool $watchlistExpiry
The value of the $wgWatchlistExpiry configuration variable.
Definition: WatchAction.php:34
StatusValue\newGood
static newGood( $value=null)
Factory function for good results.
Definition: StatusValue.php:82
Hooks\runner
static runner()
Get a HookRunner instance for calling hooks using the new interfaces.
Definition: Hooks.php:172
wfIsInfinity
wfIsInfinity( $str)
Determine input string is represents as infinity.
Definition: GlobalFunctions.php:2777
WatchedItem
Representation of a pair of user and title for watchlist entries.
Definition: WatchedItem.php:35
User\addWatch
addWatch( $title, $checkRights=self::CHECK_USER_RIGHTS, ?string $expiry=null)
Watch an article.
Definition: User.php:3134
Action\getTitle
getTitle()
Shortcut to get the Title object from the page.
Definition: Action.php:299
User\removeWatch
removeWatch( $title, $checkRights=self::CHECK_USER_RIGHTS)
Stop watching an article.
Definition: User.php:3156
WatchAction\doWatchOrUnwatch
static doWatchOrUnwatch( $watch, Title $title, User $user, string $expiry=null)
Watch or unwatch a page.
Definition: WatchAction.php:208
WatchAction\__construct
__construct(Page $page, IContextSource $context=null)
Only public since 1.21.
Definition: WatchAction.php:48
IContextSource
Interface for objects which can provide a MediaWiki context on request.
Definition: IContextSource.php:55
WatchAction\getName
getName()
Return the name of the action this object responds to.
Definition: WatchAction.php:59
HTMLForm\setSubmitTextMsg
setSubmitTextMsg( $msg)
Set the text for the submit button to a message.
Definition: HTMLForm.php:1412
Title
Represents a title within MediaWiki.
Definition: Title.php:41
WatchedItem\getExpiryInDaysText
getExpiryInDaysText(MessageLocalizer $msgLocalizer, $isDropdownOption=false)
Get days remaining until a watched item expires as a text.
Definition: WatchedItem.php:213
Action\$page
WikiPage Article ImagePage CategoryPage Page $page
Page on which we're performing the action.
Definition: Action.php:53
User\isLoggedIn
isLoggedIn()
Get whether the user is logged in.
Definition: User.php:2955
Action\msg
msg( $key,... $params)
Get a Message object with context set Parameters are the same as wfMessage()
Definition: Action.php:311
HTMLForm\setWrapperLegendMsg
setWrapperLegendMsg( $msg)
Prompt the whole form to be wrapped in a "<fieldset>", with this message as its "<legend>" element.
Definition: HTMLForm.php:1599
Action\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: Action.php:239
WatchAction\getWatchToken
static getWatchToken(Title $title, User $user, $action='watch')
Get token to watch (or unwatch) a page for a user.
Definition: WatchAction.php:314
User\IGNORE_USER_RIGHTS
const IGNORE_USER_RIGHTS
Definition: User.php:90
WatchAction\$watchedItem
false WatchedItem $watchedItem
Definition: WatchAction.php:40
User\getEditToken
getEditToken( $salt='', $request=null)
Initialize (if necessary) and return a session token value which can be used in edit forms to show th...
Definition: User.php:3735
User
The User object encapsulates all of the user-specific settings (user_id, name, rights,...
Definition: User.php:56
WatchAction\usesOOUI
usesOOUI()
Whether the form should use OOUI Stable to override.
Definition: WatchAction.php:87
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms in a reusabl...
Definition: HTMLForm.php:135