MediaWiki  1.33.0
SpecialCiteThisPage.php
Go to the documentation of this file.
1 <?php
2 
4 
8  private $citationParser;
9 
13  protected $title = false;
14 
15  public function __construct() {
16  parent::__construct( 'CiteThisPage' );
17  }
18 
22  public function execute( $par ) {
23  $this->setHeaders();
25  if ( $this->title instanceof Title ) {
26  $id = $this->getRequest()->getInt( 'id' );
27  $this->showCitations( $this->title, $id );
28  }
29  }
30 
31  protected function alterForm( HTMLForm $form ) {
32  $form->setMethod( 'get' );
33  }
34 
35  protected function getFormFields() {
36  if ( isset( $this->par ) ) {
37  $default = $this->par;
38  } else {
39  $default = '';
40  }
41  return [
42  'page' => [
43  'name' => 'page',
44  'type' => 'title',
45  'default' => $default,
46  'label-message' => 'citethispage-change-target'
47  ]
48  ];
49  }
50 
51  public function onSubmit( array $data ) {
52  // GET forms are "submitted" on every view, so check
53  // that some data was put in for page, as empty string
54  // will pass validation
55  if ( strlen( $data['page'] ) ) {
56  $this->title = Title::newFromText( $data['page'] );
57  }
58  return true;
59  }
60 
69  public function prefixSearchSubpages( $search, $limit, $offset ) {
70  $title = Title::newFromText( $search );
71  if ( !$title || !$title->canExist() ) {
72  // No prefix suggestion in special and media namespace
73  return [];
74  }
75  // Autocomplete subpage the same as a normal search
77  return array_map( function ( $sub ) {
78  return $sub->getSuggestedTitle();
79  }, $result->getSuggestions() );
80  }
81 
82  protected function getGroupName() {
83  return 'pagetools';
84  }
85 
86  private function showCitations( Title $title, $revId ) {
87  if ( !$revId ) {
88  $revId = $title->getLatestRevID();
89  }
90 
91  $out = $this->getOutput();
92 
93  $revision = Revision::newFromTitle( $title, $revId );
94  if ( !$revision ) {
95  $out->wrapWikiMsg( '<div class="errorbox">$1</div>',
96  [ 'citethispage-badrevision', $title->getPrefixedText(), $revId ] );
97  return;
98  }
99 
100  $parserOptions = $this->getParserOptions();
101  // Set the overall timestamp to the revision's timestamp
102  $parserOptions->setTimestamp( $revision->getTimestamp() );
103 
104  $parser = $this->getParser();
105  // Register our <citation> tag which just parses using a different
106  // context
107  $parser->setHook( 'citation', [ $this, 'citationTag' ] );
108  // Also hold on to a separate Parser instance for <citation> tag parsing
109  // since we can't parse in a parse using the same Parser
110  $this->citationParser = $this->getParser();
111 
112  $ret = $parser->parse(
113  $this->getContentText(),
114  $title,
115  $parserOptions,
116  /* $linestart = */ false,
117  /* $clearstate = */ true,
118  $revId
119  );
120 
121  $this->getOutput()->addModuleStyles( 'ext.citeThisPage' );
122  $this->getOutput()->addParserOutputContent( $ret, [
123  'enableSectionEditLinks' => false,
124  ] );
125  }
126 
130  private function getParser() {
131  $parserConf = $this->getConfig()->get( 'ParserConf' );
132  return new $parserConf['class']( $parserConf );
133  }
134 
140  private function getContentText() {
141  $msg = $this->msg( 'citethispage-content' )->inContentLanguage()->plain();
142  if ( $msg == '' ) {
143  # With MediaWiki 1.20 the plain text files were deleted
144  # and the text moved into SpecialCite.i18n.php
145  # This code is kept for b/c in case an installation has its own file "citethispage-content-xx"
146  # for a previously not supported language.
148  $dir = __DIR__ . '/../';
150  if ( file_exists( "${dir}citethispage-content-$code" ) ) {
151  $msg = file_get_contents( "${dir}citethispage-content-$code" );
152  } elseif ( file_exists( "${dir}citethispage-content" ) ) {
153  $msg = file_get_contents( "${dir}citethispage-content" );
154  }
155  }
156 
157  return $msg;
158  }
159 
165  private function getParserOptions() {
166  $parserOptions = ParserOptions::newFromUser( $this->getUser() );
167  $parserOptions->setDateFormat( 'default' );
168  $parserOptions->setInterfaceMessage( true );
169 
170  // Having tidy on causes whitespace and <pre> tags to
171  // be generated around the output of the CiteThisPageOutput
172  // class TODO FIXME.
173  $parserOptions->setTidy( false );
174 
175  return $parserOptions;
176  }
177 
190  public function citationTag( $text, $params, Parser $parser ) {
191  $parserOptions = $this->getParserOptions();
192 
193  $ret = $this->citationParser->parse(
194  $text,
195  $this->getPageTitle(),
196  $parserOptions,
197  /* $linestart = */ false
198  );
199 
200  return $ret->getText( [
201  'enableSectionEditLinks' => false,
202  // This will be inserted into the output of another parser, so there will actually be a wrapper
203  'unwrap' => true,
204  ] );
205  }
206 
207  protected function getDisplayFormat() {
208  return 'ooui';
209  }
210 
211  public function requiresUnblock() {
212  return false;
213  }
214 
215  public function requiresWrite() {
216  return false;
217  }
218 }
SpecialPage\getPageTitle
getPageTitle( $subpage=false)
Get a self-referential title object.
Definition: SpecialPage.php:678
Title\newFromText
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:306
SpecialCiteThisPage\getParser
getParser()
Definition: SpecialCiteThisPage.php:130
SpecialPage\msg
msg( $key)
Wrapper around wfMessage that sets the current context.
Definition: SpecialPage.php:796
SpecialPage\getOutput
getOutput()
Get the OutputPage being used for this instance.
Definition: SpecialPage.php:725
SpecialCiteThisPage\showCitations
showCitations(Title $title, $revId)
Definition: SpecialCiteThisPage.php:86
SpecialCiteThisPage\getContentText
getContentText()
Get the content to parse.
Definition: SpecialCiteThisPage.php:140
$result
The index of the header message $result[1]=The index of the body text message $result[2 through n]=Parameters passed to body text message. Please note the header message cannot receive/use parameters. 'ImportHandleLogItemXMLTag':When parsing a XML tag in a log item. Return false to stop further processing of the tag $reader:XMLReader object $logInfo:Array of information 'ImportHandlePageXMLTag':When parsing a XML tag in a page. Return false to stop further processing of the tag $reader:XMLReader object & $pageInfo:Array of information 'ImportHandleRevisionXMLTag':When parsing a XML tag in a page revision. Return false to stop further processing of the tag $reader:XMLReader object $pageInfo:Array of page information $revisionInfo:Array of revision information 'ImportHandleToplevelXMLTag':When parsing a top level XML tag. Return false to stop further processing of the tag $reader:XMLReader object 'ImportHandleUnknownUser':When a user doesn 't exist locally, this hook is called to give extensions an opportunity to auto-create it. If the auto-creation is successful, return false. $name:User name 'ImportHandleUploadXMLTag':When parsing a XML tag in a file upload. Return false to stop further processing of the tag $reader:XMLReader object $revisionInfo:Array of information 'ImportLogInterwikiLink':Hook to change the interwiki link used in log entries and edit summaries for transwiki imports. & $fullInterwikiPrefix:Interwiki prefix, may contain colons. & $pageTitle:String that contains page title. 'ImportSources':Called when reading from the $wgImportSources configuration variable. Can be used to lazy-load the import sources list. & $importSources:The value of $wgImportSources. Modify as necessary. See the comment in DefaultSettings.php for the detail of how to structure this array. 'InfoAction':When building information to display on the action=info page. $context:IContextSource object & $pageInfo:Array of information 'InitializeArticleMaybeRedirect':MediaWiki check to see if title is a redirect. & $title:Title object for the current page & $request:WebRequest & $ignoreRedirect:boolean to skip redirect check & $target:Title/string of redirect target & $article:Article object 'InternalParseBeforeLinks':during Parser 's internalParse method before links but after nowiki/noinclude/includeonly/onlyinclude and other processings. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InternalParseBeforeSanitize':during Parser 's internalParse method just before the parser removes unwanted/dangerous HTML tags and after nowiki/noinclude/includeonly/onlyinclude and other processings. Ideal for syntax-extensions after template/parser function execution which respect nowiki and HTML-comments. & $parser:Parser object & $text:string containing partially parsed text & $stripState:Parser 's internal StripState object 'InterwikiLoadPrefix':When resolving if a given prefix is an interwiki or not. Return true without providing an interwiki to continue interwiki search. $prefix:interwiki prefix we are looking for. & $iwData:output array describing the interwiki with keys iw_url, iw_local, iw_trans and optionally iw_api and iw_wikiid. 'InvalidateEmailComplete':Called after a user 's email has been invalidated successfully. $user:user(object) whose email is being invalidated 'IRCLineURL':When constructing the URL to use in an IRC notification. Callee may modify $url and $query, URL will be constructed as $url . $query & $url:URL to index.php & $query:Query string $rc:RecentChange object that triggered url generation 'IsFileCacheable':Override the result of Article::isFileCacheable()(if true) & $article:article(object) being checked 'IsTrustedProxy':Override the result of IP::isTrustedProxy() & $ip:IP being check & $result:Change this value to override the result of IP::isTrustedProxy() 'IsUploadAllowedFromUrl':Override the result of UploadFromUrl::isAllowedUrl() $url:URL used to upload from & $allowed:Boolean indicating if uploading is allowed for given URL 'isValidEmailAddr':Override the result of Sanitizer::validateEmail(), for instance to return false if the domain name doesn 't match your organization. $addr:The e-mail address entered by the user & $result:Set this and return false to override the internal checks 'isValidPassword':Override the result of User::isValidPassword() $password:The password entered by the user & $result:Set this and return false to override the internal checks $user:User the password is being validated for 'Language::getMessagesFileName':$code:The language code or the language we 're looking for a messages file for & $file:The messages file path, you can override this to change the location. 'LanguageGetNamespaces':Provide custom ordering for namespaces or remove namespaces. Do not use this hook to add namespaces. Use CanonicalNamespaces for that. & $namespaces:Array of namespaces indexed by their numbers 'LanguageGetTranslatedLanguageNames':Provide translated language names. & $names:array of language code=> language name $code:language of the preferred translations 'LanguageLinks':Manipulate a page 's language links. This is called in various places to allow extensions to define the effective language links for a page. $title:The page 's Title. & $links:Array with elements of the form "language:title" in the order that they will be output. & $linkFlags:Associative array mapping prefixed links to arrays of flags. Currently unused, but planned to provide support for marking individual language links in the UI, e.g. for featured articles. 'LanguageSelector':Hook to change the language selector available on a page. $out:The output page. $cssClassName:CSS class name of the language selector. 'LinkBegin':DEPRECATED since 1.28! Use HtmlPageLinkRendererBegin instead. Used when generating internal and interwiki links in Linker::link(), before processing starts. Return false to skip default processing and return $ret. See documentation for Linker::link() for details on the expected meanings of parameters. $skin:the Skin object $target:the Title that the link is pointing to & $html:the contents that the< a > tag should have(raw HTML) $result
Definition: hooks.txt:1983
SpecialCiteThisPage\citationTag
citationTag( $text, $params, Parser $parser)
Implements the <citation> tag.
Definition: SpecialCiteThisPage.php:190
$out
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output $out
Definition: hooks.txt:780
Title\getPrefixedText
getPrefixedText()
Get the prefixed title with spaces.
Definition: Title.php:1660
SpecialCiteThisPage\onSubmit
onSubmit(array $data)
Process the form on POST submission.
Definition: SpecialCiteThisPage.php:51
$params
$params
Definition: styleTest.css.php:44
FormSpecialPage
Special page which uses an HTMLForm to handle processing.
Definition: FormSpecialPage.php:31
SpecialCiteThisPage\requiresWrite
requiresWrite()
Whether this action requires the wiki not to be locked.
Definition: SpecialCiteThisPage.php:215
HTMLForm\setMethod
setMethod( $method='post')
Set the method used to submit the form.
Definition: HTMLForm.php:1599
php
injection txt This is an overview of how MediaWiki makes use of dependency injection The design described here grew from the discussion of RFC T384 The term dependency this means that anything an object needs to operate should be injected from the the object itself should only know narrow no concrete implementation of the logic it relies on The requirement to inject everything typically results in an architecture that based on two main types of and essentially stateless service objects that use other service objects to operate on the value objects As of the beginning MediaWiki is only starting to use the DI approach Much of the code still relies on global state or direct resulting in a highly cyclical dependency which acts as the top level factory for services in MediaWiki which can be used to gain access to default instances of various services MediaWikiServices however also allows new services to be defined and default services to be redefined Services are defined or redefined by providing a callback the instantiator that will return a new instance of the service When it will create an instance of MediaWikiServices and populate it with the services defined in the files listed by thereby bootstrapping the DI framework Per $wgServiceWiringFiles lists includes ServiceWiring php
Definition: injection.txt:35
Revision\newFromTitle
static newFromTitle(LinkTarget $linkTarget, $id=0, $flags=0)
Load either the current, or a specified, revision that's attached to a given link target.
Definition: Revision.php:137
$data
$data
Utility to generate mapping file used in mw.Title (phpCharToUpper.json)
Definition: generatePhpCharToUpperMappings.php:13
SpecialPage\getConfig
getConfig()
Shortcut to get main config object.
Definition: SpecialPage.php:764
SpecialCiteThisPage
Definition: SpecialCiteThisPage.php:3
$code
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that When $user is not it can be in the form of< username >< more info > e g for bot passwords intended to be added to log contexts Fields it might only if the login was with a bot password it is not rendered in wiki pages or galleries in category pages allow injecting custom HTML after the section Any uses of the hook need to handle escaping see BaseTemplate::getToolbox and BaseTemplate::makeListItem for details on the format of individual items inside of this array or by returning and letting standard HTTP rendering take place modifiable or by returning false and taking over the output modifiable & $code
Definition: hooks.txt:780
SpecialCiteThisPage\getDisplayFormat
getDisplayFormat()
Get display format for the form.
Definition: SpecialCiteThisPage.php:207
$parser
see documentation in includes Linker php for Linker::makeImageLink or false for current used if you return false $parser
Definition: hooks.txt:1802
SpecialPage\setHeaders
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes!
Definition: SpecialPage.php:531
SpecialPage\getUser
getUser()
Shortcut to get the User executing this instance.
Definition: SpecialPage.php:735
SpecialCiteThisPage\requiresUnblock
requiresUnblock()
Whether this action cannot be executed by a blocked user.
Definition: SpecialCiteThisPage.php:211
Title\canExist
canExist()
Is this in a namespace that allows actual pages?
Definition: Title.php:1110
SpecialCiteThisPage\getFormFields
getFormFields()
Get an HTMLForm descriptor array.
Definition: SpecialCiteThisPage.php:35
array
The wiki should then use memcached to cache various data To use multiple just add more items to the array To increase the weight of a make its entry a array("192.168.0.1:11211", 2))
FormSpecialPage\$par
string null $par
The sub-page of the special page.
Definition: FormSpecialPage.php:36
execute
$batch execute()
SpecialCiteThisPage\$title
Title bool $title
Definition: SpecialCiteThisPage.php:13
Title\getLatestRevID
getLatestRevID( $flags=0)
What is the page_latest field for this page?
Definition: Title.php:3041
title
title
Definition: parserTests.txt:245
SpecialPage\getRequest
getRequest()
Get the WebRequest being used for this instance.
Definition: SpecialPage.php:715
$ret
null means default in associative array with keys and values unescaped Should be merged with default with a value of false meaning to suppress the attribute in associative array with keys and values unescaped noclasses & $ret
Definition: hooks.txt:1985
SpecialCiteThisPage\__construct
__construct()
Definition: SpecialCiteThisPage.php:15
SpecialCiteThisPage\getParserOptions
getParserOptions()
Get the common ParserOptions for both parses.
Definition: SpecialCiteThisPage.php:165
SearchEngine\completionSearch
completionSearch( $search)
Perform a completion search.
Definition: SearchEngine.php:592
Title
Represents a title within MediaWiki.
Definition: Title.php:40
SpecialCiteThisPage\$citationParser
Parser $citationParser
Definition: SpecialCiteThisPage.php:8
$wgContLanguageCode
foreach(LanguageCode::getNonstandardLanguageCodeMapping() as $code=> $bcp47) $wgContLanguageCode
Definition: Setup.php:519
SpecialCiteThisPage\execute
execute( $par)
Definition: SpecialCiteThisPage.php:22
SpecialCiteThisPage\getGroupName
getGroupName()
Under which header this special page is listed in Special:SpecialPages See messages 'specialpages-gro...
Definition: SpecialCiteThisPage.php:82
$wgContLang
$wgContLang
Definition: Setup.php:790
SpecialCiteThisPage\prefixSearchSubpages
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
Definition: SpecialCiteThisPage.php:69
SpecialCiteThisPage\alterForm
alterForm(HTMLForm $form)
Play with the HTMLForm if you need to more substantially.
Definition: SpecialCiteThisPage.php:31
ParserOptions\newFromUser
static newFromUser( $user)
Get a ParserOptions object from a given user.
Definition: ParserOptions.php:1018
HTMLForm
Object handling generic submission, CSRF protection, layout and other logic for UI forms.
Definition: HTMLForm.php:133