Debian Codegraph @

extensions/Interwiki/includes/SpecialInterwiki.php

raw symbols SCIP
1 <?php
2
3 namespace MediaWiki\Extension\Interwiki;
4
5 use LogPage;
6 use MediaWiki\Html\Html;
7 use MediaWiki\HTMLForm\HTMLForm;
8 use MediaWiki\MediaWikiServices;
9 use MediaWiki\Message\Message;
10 use MediaWiki\Output\OutputPage;
11 use MediaWiki\SpecialPage\SpecialPage;
12 use MediaWiki\Status\Status;
13 use MediaWiki\Title\Title;
14 use MediaWiki\WikiMap\WikiMap;
15 use PermissionsError;
16 use ReadOnlyError;
17
18 /**
19 * Implements Special:Interwiki
20 * @ingroup SpecialPage
21 */
22 class SpecialInterwiki extends SpecialPage {
23 /**
24 * Constructor - sets up the new special page
25 */
26 public function __construct() {
27 parent::__construct( 'Interwiki' );
28 }
29
30 public function doesWrites() {
31 return true;
32 }
33
34 /**
35 * Different description will be shown on Special:SpecialPage depending on
36 * whether the user can modify the data.
37 *
38 * @return Message
39 */
40 public function getDescription() {
41 return $this->msg( $this->canModify() ? 'interwiki' : 'interwiki-title-norights' );
42 }
43
44 public function getSubpagesForPrefixSearch() {
45 // delete, edit both require the prefix parameter.
46 return [ 'add' ];
47 }
48
49 /**
50 * Show the special page
51 *
52 * @param string|null $par parameter passed to the page or null
53 */
54 public function execute( $par ) {
55 $this->setHeaders();
56 $this->outputHeader();
57
58 $out = $this->getOutput();
59 $request = $this->getRequest();
60
61 $out->addModuleStyles( 'ext.interwiki.specialpage' );
62
63 $action = $par ?: $request->getVal( 'action', $par );
64
65 if ( !in_array( $action, [ 'add', 'edit', 'delete' ] ) || !$this->canModify( $out ) ) {
66 $this->showList();
67 } else {
68 $this->showForm( $action );
69 }
70 }
71
72 /**
73 * Returns boolean whether the user can modify the data.
74 * @param OutputPage|bool $out If $wgOut object given, it adds the respective error message.
75 * @return bool
76 * @throws PermissionsError|ReadOnlyError
77 */
78 public function canModify( $out = false ) {
79 if ( !$this->getUser()->isAllowed( 'interwiki' ) ) {
80 // Check permissions
81 if ( $out ) {
82 throw new PermissionsError( 'interwiki' );
83 }
84
85 return false;
86 } elseif ( $this->getConfig()->get( 'InterwikiCache' ) ) {
87 // Editing the interwiki cache is not supported
88 if ( $out ) {
89 $out->addWikiMsg( 'interwiki-cached' );
90 }
91
92 return false;
93 } else {
94 $this->checkReadOnly();
95 }
96
97 return true;
98 }
99
100 /**
101 * @param string $action The action of the form
102 */
103 protected function showForm( $action ) {
104 $formDescriptor = [];
105 $hiddenFields = [
106 'action' => $action,
107 ];
108
109 $status = Status::newGood();
110 $request = $this->getRequest();
111 $prefix = $request->getVal( 'prefix', $request->getVal( 'hiddenPrefix' ) );
112
113 switch ( $action ) {
114 case 'add':
115 case 'edit':
116 $formDescriptor = [
117 'prefix' => [
118 'type' => 'text',
119 'label-message' => 'interwiki-prefix-label',
120 'name' => 'prefix',
121 'autofocus' => true,
122 ],
123
124 'local' => [
125 'type' => 'check',
126 'id' => 'mw-interwiki-local',
127 'label-message' => 'interwiki-local-label',
128 'name' => 'local',
129 ],
130
131 'trans' => [
132 'type' => 'check',
133 'id' => 'mw-interwiki-trans',
134 'label-message' => 'interwiki-trans-label',
135 'name' => 'trans',
136 ],
137
138 'url' => [
139 'type' => 'url',
140 'id' => 'mw-interwiki-url',
141 'label-message' => 'interwiki-url-label',
142 'maxlength' => 200,
143 'name' => 'wpInterwikiURL',
144 'size' => 60,
145 ],
146
147 'api' => [
148 'type' => 'url',
149 'id' => 'mw-interwiki-api',
150 'label-message' => 'interwiki-api-label',
151 'maxlength' => 200,
152 'name' => 'wpInterwikiAPI',
153 'size' => 60,
154 ],
155
156 'reason' => [
157 'type' => 'text',
158 'id' => "mw-interwiki-{$action}reason",
159 'label-message' => 'interwiki_reasonfield',
160 'maxlength' => 200,
161 'name' => 'wpInterwikiReason',
162 'size' => 60,
163 ],
164 ];
165
166 break;
167 case 'delete':
168 $formDescriptor = [
169 'prefix' => [
170 'type' => 'hidden',
171 'name' => 'prefix',
172 'default' => $prefix,
173 ],
174
175 'reason' => [
176 'type' => 'text',
177 'name' => 'reason',
178 'label-message' => 'interwiki_reasonfield',
179 ],
180 ];
181
182 break;
183 }
184
185 $formDescriptor['hiddenPrefix'] = [
186 'type' => 'hidden',
187 'name' => 'hiddenPrefix',
188 'default' => $prefix,
189 ];
190
191 if ( $action === 'edit' ) {
192 $dbr = MediaWikiServices::getInstance()->getConnectionProvider()->getReplicaDatabase();
193 $row = $dbr->newSelectQueryBuilder()
194 ->select( '*' )
195 ->from( 'interwiki' )
196 ->where( [ 'iw_prefix' => $prefix ] )
197 ->caller( __METHOD__ )
198 ->fetchRow();
199
200 $formDescriptor['prefix']['disabled'] = true;
201 $formDescriptor['prefix']['default'] = $prefix;
202 $hiddenFields['prefix'] = $prefix;
203
204 if ( !$row ) {
205 $status->fatal( 'interwiki_editerror', $prefix );
206 } else {
207 $formDescriptor['url']['default'] = $row->iw_url;
208 $formDescriptor['api']['default'] = $row->iw_api;
209 $formDescriptor['trans']['default'] = $row->iw_trans;
210 $formDescriptor['local']['default'] = $row->iw_local;
211 }
212 }
213
214 if ( !$status->isOK() ) {
215 $formDescriptor = [];
216 }
217
218 $htmlForm = HTMLForm::factory( 'ooui', $formDescriptor, $this->getContext() );
219 $htmlForm
220 ->addHiddenFields( $hiddenFields )
221 ->setSubmitCallback( [ $this, 'onSubmit' ] );
222
223 if ( $status->isOK() ) {
224 if ( $action === 'delete' ) {
225 $htmlForm->setSubmitDestructive();
226 }
227
228 $htmlForm->setSubmitTextMsg( $action !== 'add' ? $action : 'interwiki_addbutton' )
229 ->setPreHtml( $this->msg( $action !== 'delete' ? "interwiki_{$action}intro" :
230 'interwiki_deleting', $prefix )->escaped() )
231 ->show();
232 } else {
233 $htmlForm->suppressDefaultSubmit()
234 ->prepareForm()
235 ->displayForm( $status );
236 }
237
238 $this->getOutput()->addBacklinkSubtitle( $this->getPageTitle() );
239 }
240
241 public function onSubmit( array $data ) {
242 $services = MediaWikiServices::getInstance();
243
244 $status = Status::newGood();
245 $request = $this->getRequest();
246 $config = $this->getConfig();
247 $prefix = $this->getRequest()->getVal( 'prefix', '' );
248 $do = $request->getVal( 'action' );
249 // Show an error if the prefix is invalid (only when adding one).
250 // Invalid characters for a title should also be invalid for a prefix.
251 // Whitespace, ':', '&' and '=' are invalid, too.
252 // (Bug 30599).
253 $validPrefixChars = preg_replace( '/[ :&=]/', '', Title::legalChars() );
254 if ( $do === 'add' && preg_match( "/\s|[^$validPrefixChars]/", $prefix ) ) {
255 $status->fatal( 'interwiki-badprefix', htmlspecialchars( $prefix ) );
256 return $status;
257 }
258 // Disallow adding local interlanguage definitions if using global
259 $interwikiCentralInterlanguageDB = $config->get( 'InterwikiCentralInterlanguageDB' );
260 if (
261 $do === 'add' && $services->getLanguageNameUtils()->getLanguageName( $prefix )
262 && $interwikiCentralInterlanguageDB !== WikiMap::getCurrentWikiId()
263 && $interwikiCentralInterlanguageDB !== null
264 ) {
265 $status->fatal( 'interwiki-cannotaddlocallanguage', htmlspecialchars( $prefix ) );
266 return $status;
267 }
268 $reason = $data['reason'];
269 $selfTitle = $this->getPageTitle();
270 $lookup = $services->getInterwikiLookup();
271 $dbw = $services->getConnectionProvider()->getPrimaryDatabase();
272 switch ( $do ) {
273 case 'delete':
274 $dbw->newDeleteQueryBuilder()
275 ->deleteFrom( 'interwiki' )
276 ->where( [ 'iw_prefix' => $prefix ] )
277 ->caller( __METHOD__ )
278 ->execute();
279
280 if ( $dbw->affectedRows() === 0 ) {
281 $status->fatal( 'interwiki_delfailed', $prefix );
282 } else {
283 $this->getOutput()->addWikiMsg( 'interwiki_deleted', $prefix );
284 $log = new LogPage( 'interwiki' );
285 $log->addEntry(
286 'iw_delete',
287 $selfTitle,
288 $reason,
289 [ $prefix ],
290 $this->getUser()
291 );
292 $lookup->invalidateCache( $prefix );
293 }
294 break;
295 /** @noinspection PhpMissingBreakStatementInspection */
296 case 'add':
297 $contLang = $services->getContentLanguage();
298 $prefix = $contLang->lc( $prefix );
299 // Fall through
300 case 'edit':
301 // T374771: Trim the URL and API URLs to reduce confusion when
302 // the URLs are accidentally provided with extra whitespace
303 $theurl = trim( $data['url'] );
304 $api = trim( $data['api'] ?? '' );
305 $local = $data['local'] ? 1 : 0;
306 $trans = $data['trans'] ? 1 : 0;
307 $rows = [
308 'iw_prefix' => $prefix,
309 'iw_url' => $theurl,
310 'iw_api' => $api,
311 'iw_wikiid' => '',
312 'iw_local' => $local,
313 'iw_trans' => $trans
314 ];
315
316 if ( $prefix === '' || $theurl === '' ) {
317 $status->fatal( 'interwiki-submit-empty' );
318 break;
319 }
320
321 // Simple URL validation: check that the protocol is one of
322 // the supported protocols for this wiki.
323 // (T32600)
324 if ( !$services->getUrlUtils()->parse( $theurl ) ) {
325 $status->fatal( 'interwiki-submit-invalidurl' );
326 break;
327 }
328
329 if ( $do === 'add' ) {
330 $dbw->newInsertQueryBuilder()
331 ->insertInto( 'interwiki' )
332 ->ignore()
333 ->row( $rows )
334 ->caller( __METHOD__ )
335 ->execute();
336 } else { // $do === 'edit'
337 $dbw->newUpdateQueryBuilder()
338 ->update( 'interwiki' )
339 ->ignore()
340 ->set( $rows )
341 ->where( [ 'iw_prefix' => $prefix ] )
342 ->caller( __METHOD__ )
343 ->execute();
344 }
345
346 // used here: interwiki_addfailed, interwiki_added, interwiki_edited
347 if ( $dbw->affectedRows() === 0 ) {
348 $status->fatal( "interwiki_{$do}failed", $prefix );
349 } else {
350 $this->getOutput()->addWikiMsg( "interwiki_{$do}ed", $prefix );
351 $log = new LogPage( 'interwiki' );
352 $log->addEntry(
353 'iw_' . $do,
354 $selfTitle,
355 $reason,
356 [ $prefix, $theurl, $trans, $local ],
357 $this->getUser()
358 );
359 // @phan-suppress-next-line PhanTypeMismatchArgumentNullable
360 $lookup->invalidateCache( $prefix );
361 }
362 break;
363 }
364
365 return $status;
366 }
367
368 protected function showList() {
369 $canModify = $this->canModify();
370
371 // Build lists
372 $services = MediaWikiServices::getInstance();
373
374 $lookup = $services->getInterwikiLookup();
375 $iwPrefixes = $lookup->getAllPrefixes( null );
376 $iwGlobalPrefixes = [];
377 $iwGlobalLanguagePrefixes = [];
378
379 $config = $this->getConfig();
380 $interwikiCentralDB = $config->get( 'InterwikiCentralDB' );
381
382 $languageNameUtils = $services->getLanguageNameUtils();
383
384 $connectionProvider = $services->getConnectionProvider();
385
386 if ( $interwikiCentralDB !== null && $interwikiCentralDB !== WikiMap::getCurrentWikiId() ) {
387 // Fetch list from global table
388 $dbrCentralDB = $connectionProvider->getReplicaDatabase( $interwikiCentralDB );
389
390 $res = $dbrCentralDB->newSelectQueryBuilder()
391 ->select( '*' )
392 ->from( 'interwiki' )
393 ->caller( __METHOD__ )
394 ->fetchResultSet();
395 $retval = [];
396 foreach ( $res as $row ) {
397 $row = (array)$row;
398 if ( !$languageNameUtils->getLanguageName( $row['iw_prefix'] ) ) {
399 $retval[] = $row;
400 }
401 }
402 $iwGlobalPrefixes = $retval;
403 }
404
405 // Almost the same loop as above, but for global inter*language* links, whereas the above is for
406 // global inter*wiki* links
407 $interwikiCentralInterlanguageDB = $config->get( 'InterwikiCentralInterlanguageDB' );
408 $usingGlobalInterlangLinks = ( $interwikiCentralInterlanguageDB !== null );
409 $isGlobalInterlanguageDB = ( $interwikiCentralInterlanguageDB === WikiMap::getCurrentWikiId() );
410 $usingGlobalLanguages = $usingGlobalInterlangLinks && !$isGlobalInterlanguageDB;
411 if ( $usingGlobalLanguages ) {
412 // Fetch list from global table
413 $dbrCentralLangDB = $connectionProvider->getReplicaDatabase( $interwikiCentralInterlanguageDB );
414
415 $res = $dbrCentralLangDB->newSelectQueryBuilder()
416 ->select( '*' )
417 ->from( 'interwiki' )
418 ->caller( __METHOD__ )
419 ->fetchResultSet();
420 $retval2 = [];
421 foreach ( $res as $row ) {
422 $row = (array)$row;
423 // Note that the above DB query explicitly *excludes* interlang ones
424 // (which makes sense), whereas here we _only_ care about interlang ones!
425 if ( $languageNameUtils->getLanguageName( $row['iw_prefix'] ) ) {
426 $retval2[] = $row;
427 }
428 }
429 $iwGlobalLanguagePrefixes = $retval2;
430 }
431
432 // Split out language links
433 $iwLocalPrefixes = [];
434 $iwLanguagePrefixes = [];
435 foreach ( $iwPrefixes as $iwPrefix ) {
436 if ( $languageNameUtils->getLanguageName( $iwPrefix['iw_prefix'] ) ) {
437 $iwLanguagePrefixes[] = $iwPrefix;
438 } else {
439 $iwLocalPrefixes[] = $iwPrefix;
440 }
441 }
442
443 // If using global interlanguage links, just ditch the data coming from the
444 // local table and overwrite it with the global data
445 if ( $usingGlobalInterlangLinks ) {
446 unset( $iwLanguagePrefixes );
447 $iwLanguagePrefixes = $iwGlobalLanguagePrefixes;
448 }
449
450 // Page intro content
451 $this->getOutput()->addWikiMsg( 'interwiki_intro' );
452
453 // Add 'view log' link when possible
454 if ( !$config->get( 'InterwikiViewOnly' ) ) {
455 $logLink = $this->getLinkRenderer()->makeLink(
456 SpecialPage::getTitleFor( 'Log', 'interwiki' ),
457 $this->msg( 'interwiki-logtext' )->text()
458 );
459 $this->getOutput()->addHTML( '<p class="mw-interwiki-log">' . $logLink . '</p>' );
460 }
461
462 // Add 'add' link
463 if ( $canModify ) {
464 if ( count( $iwGlobalPrefixes ) !== 0 ) {
465 if ( $usingGlobalLanguages ) {
466 $addtext = 'interwiki-addtext-local-nolang';
467 } else {
468 $addtext = 'interwiki-addtext-local';
469 }
470 } else {
471 if ( $usingGlobalLanguages ) {
472 $addtext = 'interwiki-addtext-nolang';
473 } else {
474 $addtext = 'interwiki_addtext';
475 }
476 }
477 $addtext = $this->msg( $addtext )->text();
478 $addlink = $this->getLinkRenderer()->makeKnownLink(
479 $this->getPageTitle( 'add' ), $addtext );
480 $this->getOutput()->addHTML(
481 '<p class="mw-interwiki-addlink">' . $addlink . '</p>' );
482 }
483
484 $this->getOutput()->addWikiMsg( 'interwiki-legend' );
485
486 if ( $iwPrefixes === [] && $iwGlobalPrefixes === [] ) {
487 // If the interwiki table(s) are empty, display an error message
488 $this->error( 'interwiki_error' );
489 return;
490 }
491
492 // Add the global table
493 if ( count( $iwGlobalPrefixes ) !== 0 ) {
494 $this->getOutput()->addHTML(
495 '<h2 id="interwikitable-global">' .
496 $this->msg( 'interwiki-global-links' )->parse() .
497 '</h2>'
498 );
499 $this->getOutput()->addWikiMsg( 'interwiki-global-description' );
500
501 // $canModify is false here because this is just a display of remote data
502 $this->makeTable( false, $iwGlobalPrefixes );
503 }
504
505 // Add the local table
506 if ( count( $iwLocalPrefixes ) !== 0 ) {
507 if ( count( $iwGlobalPrefixes ) !== 0 ) {
508 $this->getOutput()->addHTML(
509 '<h2 id="interwikitable-local">' .
510 $this->msg( 'interwiki-local-links' )->parse() .
511 '</h2>'
512 );
513 $this->getOutput()->addWikiMsg( 'interwiki-local-description' );
514 } else {
515 $this->getOutput()->addHTML(
516 '<h2 id="interwikitable-local">' .
517 $this->msg( 'interwiki-links' )->parse() .
518 '</h2>'
519 );
520 $this->getOutput()->addWikiMsg( 'interwiki-description' );
521 }
522 $this->makeTable( $canModify, $iwLocalPrefixes );
523 }
524
525 // Add the language table
526 if ( count( $iwLanguagePrefixes ) !== 0 ) {
527 if ( $usingGlobalLanguages ) {
528 $header = 'interwiki-global-language-links';
529 $description = 'interwiki-global-language-description';
530 } else {
531 $header = 'interwiki-language-links';
532 $description = 'interwiki-language-description';
533 }
534
535 $this->getOutput()->addHTML(
536 '<h2 id="interwikitable-language">' .
537 $this->msg( $header )->parse() .
538 '</h2>'
539 );
540 $this->getOutput()->addWikiMsg( $description );
541
542 // When using global interlanguage links, don't allow them to be modified
543 // except on the source wiki
544 $canModify = ( $usingGlobalLanguages ? false : $canModify );
545 $this->makeTable( $canModify, $iwLanguagePrefixes );
546 }
547 }
548
549 protected function makeTable( $canModify, $iwPrefixes ) {
550 // Output the existing Interwiki prefixes table header
551 $out = Html::openElement(
552 'table',
553 [ 'class' => 'mw-interwikitable wikitable sortable body' ]
554 ) . "\n";
555 $out .= Html::openElement( 'thead' ) .
556 Html::openElement( 'tr', [ 'class' => 'interwikitable-header' ] ) .
557 Html::element( 'th', [], $this->msg( 'interwiki_prefix' )->text() ) .
558 Html::element( 'th', [], $this->msg( 'interwiki_url' )->text() ) .
559 Html::element( 'th', [], $this->msg( 'interwiki_local' )->text() ) .
560 Html::element( 'th', [], $this->msg( 'interwiki_trans' )->text() ) .
561 ( $canModify ?
562 Html::element(
563 'th',
564 [ 'class' => 'unsortable' ],
565 $this->msg( 'interwiki_edit' )->text()
566 ) :
567 ''
568 );
569 $out .= Html::closeElement( 'tr' ) .
570 Html::closeElement( 'thead' ) . "\n" .
571 Html::openElement( 'tbody' );
572
573 $selfTitle = $this->getPageTitle();
574
575 // Output the existing Interwiki prefixes table rows
576 foreach ( $iwPrefixes as $iwPrefix ) {
577 $out .= Html::openElement( 'tr', [ 'class' => 'mw-interwikitable-row' ] );
578 $out .= Html::element( 'td', [ 'class' => 'mw-interwikitable-prefix' ],
579 $iwPrefix['iw_prefix'] );
580 $out .= Html::element(
581 'td',
582 [ 'class' => 'mw-interwikitable-url' ],
583 $iwPrefix['iw_url']
584 );
585 $attribs = [ 'class' => 'mw-interwikitable-local' ];
586 // Green background for cells with "yes".
587 if ( isset( $iwPrefix['iw_local'] ) && $iwPrefix['iw_local'] ) {
588 $attribs['class'] .= ' mw-interwikitable-local-yes';
589 }
590 // The messages interwiki_0 and interwiki_1 are used here.
591 $contents = isset( $iwPrefix['iw_local'] ) ?
592 $this->msg( 'interwiki_' . $iwPrefix['iw_local'] )->text() :
593 '-';
594 $out .= Html::element( 'td', $attribs, $contents );
595 $attribs = [ 'class' => 'mw-interwikitable-trans' ];
596 // Green background for cells with "yes".
597 if ( isset( $iwPrefix['iw_trans'] ) && $iwPrefix['iw_trans'] ) {
598 $attribs['class'] .= ' mw-interwikitable-trans-yes';
599 }
600 // The messages interwiki_0 and interwiki_1 are used here.
601 $contents = isset( $iwPrefix['iw_trans'] ) ?
602 $this->msg( 'interwiki_' . $iwPrefix['iw_trans'] )->text() :
603 '-';
604 $out .= Html::element( 'td', $attribs, $contents );
605
606 // Additional column when the interwiki table can be modified.
607 if ( $canModify ) {
608 $out .= Html::rawElement( 'td', [ 'class' => 'mw-interwikitable-modify' ],
609 $this->getLinkRenderer()->makeKnownLink(
610 $selfTitle,
611 $this->msg( 'edit' )->text(),
612 [],
613 [ 'action' => 'edit', 'prefix' => $iwPrefix['iw_prefix'] ]
614 ) .
615 $this->msg( 'comma-separator' )->escaped() .
616 $this->getLinkRenderer()->makeKnownLink(
617 $selfTitle,
618 $this->msg( 'delete' )->text(),
619 [],
620 [ 'action' => 'delete', 'prefix' => $iwPrefix['iw_prefix'] ]
621 )
622 );
623 }
624 $out .= Html::closeElement( 'tr' ) . "\n";
625 }
626 $out .= Html::closeElement( 'tbody' ) .
627 Html::closeElement( 'table' );
628
629 $this->getOutput()->addHTML( $out );
630 $this->getOutput()->addModuleStyles( 'jquery.tablesorter.styles' );
631 $this->getOutput()->addModules( 'jquery.tablesorter' );
632 }
633
634 /**
635 * @param string ...$args
636 */
637 protected function error( ...$args ) {
638 $this->getOutput()->wrapWikiMsg( "<p class='error'>$1</p>", $args );
639 }
640
641 protected function getGroupName() {
642 return 'wiki';
643 }
644 }