MediaWiki  1.28.1
SpecialLinkSearch.php
Go to the documentation of this file.
1 <?php
29 class LinkSearchPage extends QueryPage {
31  private $mungedQuery = false;
32 
33  function setParams( $params ) {
34  $this->mQuery = $params['query'];
35  $this->mNs = $params['namespace'];
36  $this->mProt = $params['protocol'];
37  }
38 
39  function __construct( $name = 'LinkSearch' ) {
40  parent::__construct( $name );
41 
42  // Since we don't control the constructor parameters, we can't inject services that way.
43  // Instead, we initialize services in the execute() method, and allow them to be overridden
44  // using the setServices() method.
45  }
46 
47  function isCacheable() {
48  return false;
49  }
50 
51  public function execute( $par ) {
52  $this->setHeaders();
53  $this->outputHeader();
54 
55  $out = $this->getOutput();
56  $out->allowClickjacking();
57 
58  $request = $this->getRequest();
59  $target = $request->getVal( 'target', $par );
60  $namespace = $request->getIntOrNull( 'namespace' );
61 
62  $protocols_list = [];
63  foreach ( $this->getConfig()->get( 'UrlProtocols' ) as $prot ) {
64  if ( $prot !== '//' ) {
65  $protocols_list[] = $prot;
66  }
67  }
68 
69  $target2 = $target;
70  // Get protocol, default is http://
71  $protocol = 'http://';
72  $bits = wfParseUrl( $target );
73  if ( isset( $bits['scheme'] ) && isset( $bits['delimiter'] ) ) {
74  $protocol = $bits['scheme'] . $bits['delimiter'];
75  // Make sure wfParseUrl() didn't make some well-intended correction in the
76  // protocol
77  if ( strcasecmp( $protocol, substr( $target, 0, strlen( $protocol ) ) ) === 0 ) {
78  $target2 = substr( $target, strlen( $protocol ) );
79  } else {
80  // If it did, let LinkFilter::makeLikeArray() handle this
81  $protocol = '';
82  }
83  }
84 
85  $out->addWikiMsg(
86  'linksearch-text',
87  '<nowiki>' . $this->getLanguage()->commaList( $protocols_list ) . '</nowiki>',
88  count( $protocols_list )
89  );
90  $fields = [
91  'target' => [
92  'type' => 'text',
93  'name' => 'target',
94  'id' => 'target',
95  'size' => 50,
96  'label-message' => 'linksearch-pat',
97  'default' => $target,
98  'dir' => 'ltr',
99  ]
100  ];
101  if ( !$this->getConfig()->get( 'MiserMode' ) ) {
102  $fields += [
103  'namespace' => [
104  'type' => 'namespaceselect',
105  'name' => 'namespace',
106  'label-message' => 'linksearch-ns',
107  'default' => $namespace,
108  'id' => 'namespace',
109  'all' => '',
110  'cssclass' => 'namespaceselector',
111  ],
112  ];
113  }
114  $hiddenFields = [
115  'title' => $this->getPageTitle()->getPrefixedDBkey(),
116  ];
117  $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
118  $htmlForm->addHiddenFields( $hiddenFields );
119  $htmlForm->setSubmitTextMsg( 'linksearch-ok' );
120  $htmlForm->setWrapperLegendMsg( 'linksearch' );
121  $htmlForm->setAction( wfScript() );
122  $htmlForm->setMethod( 'get' );
123  $htmlForm->prepareForm()->displayForm( false );
124  $this->addHelpLink( 'Help:Linksearch' );
125 
126  if ( $target != '' ) {
127  $this->setParams( [
128  'query' => Parser::normalizeLinkUrl( $target2 ),
129  'namespace' => $namespace,
130  'protocol' => $protocol ] );
131  parent::execute( $par );
132  if ( $this->mungedQuery === false ) {
133  $out->addWikiMsg( 'linksearch-error' );
134  }
135  }
136  }
137 
142  function isSyndicated() {
143  return false;
144  }
145 
154  static function mungeQuery( $query, $prot ) {
155  $field = 'el_index';
156  $dbr = wfGetDB( DB_REPLICA );
157 
158  if ( $query === '*' && $prot !== '' ) {
159  // Allow queries like 'ftp://*' to find all ftp links
160  $rv = [ $prot, $dbr->anyString() ];
161  } else {
162  $rv = LinkFilter::makeLikeArray( $query, $prot );
163  }
164 
165  if ( $rv === false ) {
166  // LinkFilter doesn't handle wildcard in IP, so we'll have to munge here.
167  $pattern = '/^(:?[0-9]{1,3}\.)+\*\s*$|^(:?[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]*\*\s*$/';
168  if ( preg_match( $pattern, $query ) ) {
169  $rv = [ $prot . rtrim( $query, " \t*" ), $dbr->anyString() ];
170  $field = 'el_to';
171  }
172  }
173 
174  return [ $rv, $field ];
175  }
176 
177  function linkParameters() {
178  $params = [];
179  $params['target'] = $this->mProt . $this->mQuery;
180  if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
181  $params['namespace'] = $this->mNs;
182  }
183 
184  return $params;
185  }
186 
187  public function getQueryInfo() {
188  $dbr = wfGetDB( DB_REPLICA );
189  // strip everything past first wildcard, so that
190  // index-based-only lookup would be done
191  list( $this->mungedQuery, $clause ) = self::mungeQuery( $this->mQuery, $this->mProt );
192  if ( $this->mungedQuery === false ) {
193  // Invalid query; return no results
194  return [ 'tables' => 'page', 'fields' => 'page_id', 'conds' => '0=1' ];
195  }
196 
197  $stripped = LinkFilter::keepOneWildcard( $this->mungedQuery );
198  $like = $dbr->buildLike( $stripped );
199  $retval = [
200  'tables' => [ 'page', 'externallinks' ],
201  'fields' => [
202  'namespace' => 'page_namespace',
203  'title' => 'page_title',
204  'value' => 'el_index',
205  'url' => 'el_to'
206  ],
207  'conds' => [
208  'page_id = el_from',
209  "$clause $like"
210  ],
211  'options' => [ 'USE INDEX' => $clause ]
212  ];
213 
214  if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
215  $retval['conds']['page_namespace'] = $this->mNs;
216  }
217 
218  return $retval;
219  }
220 
227  function preprocessResults( $db, $res ) {
228  if ( $res->numRows() > 0 ) {
229  $linkBatch = new LinkBatch();
230 
231  foreach ( $res as $row ) {
232  $linkBatch->add( $row->namespace, $row->title );
233  }
234 
235  $res->seek( 0 );
236  $linkBatch->execute();
237  }
238  }
239 
245  function formatResult( $skin, $result ) {
246  $title = new TitleValue( (int)$result->namespace, $result->title );
247  $pageLink = $this->getLinkRenderer()->makeLink( $title );
248 
249  $url = $result->url;
250  $urlLink = Linker::makeExternalLink( $url, $url );
251 
252  return $this->msg( 'linksearch-line' )->rawParams( $urlLink, $pageLink )->escaped();
253  }
254 
262  function getOrderFields() {
263  return [];
264  }
265 
266  protected function getGroupName() {
267  return 'redirects';
268  }
269 
276  protected function getMaxResults() {
277  return max( parent::getMaxResults(), 60000 );
278  }
279 }
static makeLikeArray($filterEntry, $protocol= 'http://')
Make an array to be used for calls to Database::buildLike(), which will match the specified string...
Definition: LinkFilter.php:94
Special:LinkSearch to search the external-links table.
deferred txt A few of the database updates required by various functions here can be deferred until after the result page is displayed to the user For updating the view updating the linked to tables after a etc PHP does not yet have any way to tell the server to actually return and disconnect while still running these but it might have such a feature in the future We handle these by creating a deferred update object and putting those objects on a global list
Definition: deferred.txt:11
wfGetDB($db, $groups=[], $wiki=false)
Get a Database object.
this hook is for auditing only or null if authentication failed before getting that far or null if we can t even determine that probably a stub 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:802
null for the local wiki Added should default to null in handler for backwards compatibility add a value to it if you want to add a cookie that have to vary cache options can modify $query
Definition: hooks.txt:1555
getContext()
Gets the context this SpecialPage is executed in.
wfScript($script= 'index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
$batch execute()
static factory($displayFormat)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:275
Represents a page (or page fragment) title within MediaWiki.
Definition: TitleValue.php:36
msg()
Wrapper around wfMessage that sets the current context.
formatResult($skin, $result)
getOutput()
Get the OutputPage being used for this instance.
addHelpLink($to, $overrideBaseUrl=false)
Adds help link with an icon via page indicators.
array bool $mungedQuery
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 '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. 'LanguageGetMagic':DEPRECATED!Use $magicWords in a file listed in $wgExtensionMessagesFiles instead.Use this to define synonyms of magic words depending of the language &$magicExtensions:associative array of magic words synonyms $lang:language code(string) '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 'LanguageGetSpecialPageAliases':DEPRECATED!Use $specialPageAliases in a file listed in $wgExtensionMessagesFiles instead.Use to define aliases of special pages names depending of the language &$specialPageAliases:associative array of magic words synonyms $lang:language code(string) '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:Associative array mapping language codes to prefixed links of the form"language:title".&$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!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:1934
outputHeader($summaryMessageKey= '')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
This is a class for doing query pages; since they're almost all the same, we factor out some of the f...
Definition: QueryPage.php:30
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:32
$res
Definition: database.txt:21
__construct($name= 'LinkSearch')
isSyndicated()
Disable RSS/Atom feeds.
getMaxResults()
enwiki complained about low limits on this special page
$params
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
getOrderFields()
Override to squash the ORDER BY.
namespace and then decline to actually register it file or subcat img or subcat $title
Definition: hooks.txt:953
static mungeQuery($query, $prot)
Return an appropriately formatted LIKE query and the clause.
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 just before the function returns a value If you return an< a > element with HTML attributes $attribs and contents $html will be returned If you return $ret will be returned $skin
Definition: hooks.txt:1936
This document is intended to provide useful advice for parties seeking to redistribute MediaWiki to end users It s targeted particularly at maintainers for Linux since it s been observed that distribution packages of MediaWiki often break We ve consistently had to recommend that users seeking support use official tarballs instead of their distribution s and this often solves whatever problem the user is having It would be nice if this could such as
Definition: distributors.txt:9
static makeExternalLink($url, $text, $escape=true, $linktype= '', $attribs=[], $title=null)
Make an external link.
Definition: Linker.php:934
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
static keepOneWildcard($arr)
Filters an array returned by makeLikeArray(), removing everything past first pattern placeholder...
Definition: LinkFilter.php:177
error also a ContextSource you ll probably need to make sure the header is varied on $request
Definition: hooks.txt:2573
getConfig()
Shortcut to get main config object.
getLanguage()
Shortcut to get user's language.
static normalizeLinkUrl($url)
Replace unusual escape codes in a URL with their equivalent characters.
Definition: Parser.php:1951
const DB_REPLICA
Definition: defines.php:22
getRequest()
Get the WebRequest being used for this instance.
wfParseUrl($url)
parse_url() work-alike, but non-broken.
please add to it if you re going to add events to the MediaWiki code where normally authentication against an external auth plugin would be creating a local account incomplete not yet checked for validity & $retval
Definition: hooks.txt:242
preprocessResults($db, $res)
Pre-fill the link cache.
getPageTitle($subpage=false)
Get a self-referential title object.
Allows to change the fields on the form that will be generated $name
Definition: hooks.txt:300