Merge "Handle missing namespace prefix in XML dumps more gracefully"
[lhc/web/wiklou.git] / includes / specials / SpecialLinkSearch.php
1 <?php
2 /**
3 * Implements Special:LinkSearch
4 *
5 * This program is free software; you can redistribute it and/or modify
6 * it under the terms of the GNU General Public License as published by
7 * the Free Software Foundation; either version 2 of the License, or
8 * (at your option) any later version.
9 *
10 * This program is distributed in the hope that it will be useful,
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13 * GNU General Public License for more details.
14 *
15 * You should have received a copy of the GNU General Public License along
16 * with this program; if not, write to the Free Software Foundation, Inc.,
17 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
18 * http://www.gnu.org/copyleft/gpl.html
19 *
20 * @file
21 * @ingroup SpecialPage
22 * @author Brion Vibber
23 */
24
25 use Wikimedia\Rdbms\ResultWrapper;
26
27 /**
28 * Special:LinkSearch to search the external-links table.
29 * @ingroup SpecialPage
30 */
31 class LinkSearchPage extends QueryPage {
32 /** @var array|bool */
33 private $mungedQuery = false;
34
35 function setParams( $params ) {
36 $this->mQuery = $params['query'];
37 $this->mNs = $params['namespace'];
38 $this->mProt = $params['protocol'];
39 }
40
41 function __construct( $name = 'LinkSearch' ) {
42 parent::__construct( $name );
43
44 // Since we don't control the constructor parameters, we can't inject services that way.
45 // Instead, we initialize services in the execute() method, and allow them to be overridden
46 // using the setServices() method.
47 }
48
49 function isCacheable() {
50 return false;
51 }
52
53 public function execute( $par ) {
54 $this->setHeaders();
55 $this->outputHeader();
56
57 $out = $this->getOutput();
58 $out->allowClickjacking();
59
60 $request = $this->getRequest();
61 $target = $request->getVal( 'target', $par );
62 $namespace = $request->getIntOrNull( 'namespace' );
63
64 $protocols_list = [];
65 foreach ( $this->getConfig()->get( 'UrlProtocols' ) as $prot ) {
66 if ( $prot !== '//' ) {
67 $protocols_list[] = $prot;
68 }
69 }
70
71 $target2 = $target;
72 // Get protocol, default is http://
73 $protocol = 'http://';
74 $bits = wfParseUrl( $target );
75 if ( isset( $bits['scheme'] ) && isset( $bits['delimiter'] ) ) {
76 $protocol = $bits['scheme'] . $bits['delimiter'];
77 // Make sure wfParseUrl() didn't make some well-intended correction in the
78 // protocol
79 if ( strcasecmp( $protocol, substr( $target, 0, strlen( $protocol ) ) ) === 0 ) {
80 $target2 = substr( $target, strlen( $protocol ) );
81 } else {
82 // If it did, let LinkFilter::makeLikeArray() handle this
83 $protocol = '';
84 }
85 }
86
87 $out->addWikiMsg(
88 'linksearch-text',
89 '<nowiki>' . $this->getLanguage()->commaList( $protocols_list ) . '</nowiki>',
90 count( $protocols_list )
91 );
92 $fields = [
93 'target' => [
94 'type' => 'text',
95 'name' => 'target',
96 'id' => 'target',
97 'size' => 50,
98 'label-message' => 'linksearch-pat',
99 'default' => $target,
100 'dir' => 'ltr',
101 ]
102 ];
103 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
104 $fields += [
105 'namespace' => [
106 'type' => 'namespaceselect',
107 'name' => 'namespace',
108 'label-message' => 'linksearch-ns',
109 'default' => $namespace,
110 'id' => 'namespace',
111 'all' => '',
112 'cssclass' => 'namespaceselector',
113 ],
114 ];
115 }
116 $hiddenFields = [
117 'title' => $this->getPageTitle()->getPrefixedDBkey(),
118 ];
119 $htmlForm = HTMLForm::factory( 'ooui', $fields, $this->getContext() );
120 $htmlForm->addHiddenFields( $hiddenFields );
121 $htmlForm->setSubmitTextMsg( 'linksearch-ok' );
122 $htmlForm->setWrapperLegendMsg( 'linksearch' );
123 $htmlForm->setAction( wfScript() );
124 $htmlForm->setMethod( 'get' );
125 $htmlForm->prepareForm()->displayForm( false );
126 $this->addHelpLink( 'Help:Linksearch' );
127
128 if ( $target != '' ) {
129 $this->setParams( [
130 'query' => Parser::normalizeLinkUrl( $target2 ),
131 'namespace' => $namespace,
132 'protocol' => $protocol ] );
133 parent::execute( $par );
134 if ( $this->mungedQuery === false ) {
135 $out->addWikiMsg( 'linksearch-error' );
136 }
137 }
138 }
139
140 /**
141 * Disable RSS/Atom feeds
142 * @return bool
143 */
144 function isSyndicated() {
145 return false;
146 }
147
148 /**
149 * Return an appropriately formatted LIKE query and the clause
150 *
151 * @param string $query Search pattern to search for
152 * @param string $prot Protocol, e.g. 'http://'
153 *
154 * @return array
155 */
156 static function mungeQuery( $query, $prot ) {
157 $field = 'el_index';
158 $dbr = wfGetDB( DB_REPLICA );
159
160 if ( $query === '*' && $prot !== '' ) {
161 // Allow queries like 'ftp://*' to find all ftp links
162 $rv = [ $prot, $dbr->anyString() ];
163 } else {
164 $rv = LinkFilter::makeLikeArray( $query, $prot );
165 }
166
167 if ( $rv === false ) {
168 // LinkFilter doesn't handle wildcard in IP, so we'll have to munge here.
169 $pattern = '/^(:?[0-9]{1,3}\.)+\*\s*$|^(:?[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]*\*\s*$/';
170 if ( preg_match( $pattern, $query ) ) {
171 $rv = [ $prot . rtrim( $query, " \t*" ), $dbr->anyString() ];
172 $field = 'el_to';
173 }
174 }
175
176 return [ $rv, $field ];
177 }
178
179 function linkParameters() {
180 $params = [];
181 $params['target'] = $this->mProt . $this->mQuery;
182 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
183 $params['namespace'] = $this->mNs;
184 }
185
186 return $params;
187 }
188
189 public function getQueryInfo() {
190 $dbr = wfGetDB( DB_REPLICA );
191 // strip everything past first wildcard, so that
192 // index-based-only lookup would be done
193 list( $this->mungedQuery, $clause ) = self::mungeQuery( $this->mQuery, $this->mProt );
194 if ( $this->mungedQuery === false ) {
195 // Invalid query; return no results
196 return [ 'tables' => 'page', 'fields' => 'page_id', 'conds' => '0=1' ];
197 }
198
199 $stripped = LinkFilter::keepOneWildcard( $this->mungedQuery );
200 $like = $dbr->buildLike( $stripped );
201 $retval = [
202 'tables' => [ 'page', 'externallinks' ],
203 'fields' => [
204 'namespace' => 'page_namespace',
205 'title' => 'page_title',
206 'value' => 'el_index',
207 'url' => 'el_to'
208 ],
209 'conds' => [
210 'page_id = el_from',
211 "$clause $like"
212 ],
213 'options' => [ 'USE INDEX' => $clause ]
214 ];
215
216 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
217 $retval['conds']['page_namespace'] = $this->mNs;
218 }
219
220 return $retval;
221 }
222
223 /**
224 * Pre-fill the link cache
225 *
226 * @param IDatabase $db
227 * @param ResultWrapper $res
228 */
229 function preprocessResults( $db, $res ) {
230 $this->executeLBFromResultWrapper( $res );
231 }
232
233 /**
234 * @param Skin $skin
235 * @param object $result Result row
236 * @return string
237 */
238 function formatResult( $skin, $result ) {
239 $title = new TitleValue( (int)$result->namespace, $result->title );
240 $pageLink = $this->getLinkRenderer()->makeLink( $title );
241
242 $url = $result->url;
243 $urlLink = Linker::makeExternalLink( $url, $url );
244
245 return $this->msg( 'linksearch-line' )->rawParams( $urlLink, $pageLink )->escaped();
246 }
247
248 /**
249 * Override to squash the ORDER BY.
250 * We do a truncated index search, so the optimizer won't trust
251 * it as good enough for optimizing sort. The implicit ordering
252 * from the scan will usually do well enough for our needs.
253 * @return array
254 */
255 function getOrderFields() {
256 return [];
257 }
258
259 protected function getGroupName() {
260 return 'redirects';
261 }
262
263 /**
264 * enwiki complained about low limits on this special page
265 *
266 * @see T130058
267 * @todo FIXME This special page should not use LIMIT for paging
268 */
269 protected function getMaxResults() {
270 return max( parent::getMaxResults(), 60000 );
271 }
272 }