0c026282f8ca230747c1624020b1815973b6258e
[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 /**
26 * Special:LinkSearch to search the external-links table.
27 * @ingroup SpecialPage
28 */
29 class LinkSearchPage extends QueryPage {
30 /** @var array|bool */
31 private $mungedQuery = false;
32
33 /**
34 * @var PageLinkRenderer
35 */
36 protected $linkRenderer = null;
37
38 function setParams( $params ) {
39 $this->mQuery = $params['query'];
40 $this->mNs = $params['namespace'];
41 $this->mProt = $params['protocol'];
42 }
43
44 function __construct( $name = 'LinkSearch' ) {
45 parent::__construct( $name );
46
47 // Since we don't control the constructor parameters, we can't inject services that way.
48 // Instead, we initialize services in the execute() method, and allow them to be overridden
49 // using the setServices() method.
50 }
51
52 /**
53 * Initialize or override the PageLinkRenderer LinkSearchPage collaborates with.
54 * Useful mainly for testing.
55 *
56 * @todo query logic and rendering logic should be split and also injected
57 *
58 * @param PageLinkRenderer $linkRenderer
59 */
60 public function setPageLinkRenderer(
61 PageLinkRenderer $linkRenderer
62 ) {
63 $this->linkRenderer = $linkRenderer;
64 }
65
66 /**
67 * Initialize any services we'll need (unless it has already been provided via a setter).
68 * This allows for dependency injection even though we don't control object creation.
69 */
70 private function initServices() {
71 global $wgLanguageCode;
72 if ( !$this->linkRenderer ) {
73 $lang = Language::factory( $wgLanguageCode );
74 $titleFormatter = new MediaWikiTitleCodec( $lang, GenderCache::singleton() );
75 $this->linkRenderer = new MediaWikiPageLinkRenderer( $titleFormatter );
76 }
77 }
78
79 function isCacheable() {
80 return false;
81 }
82
83 function execute( $par ) {
84 $this->initServices();
85
86 $this->setHeaders();
87 $this->outputHeader();
88
89 $out = $this->getOutput();
90 $out->allowClickjacking();
91
92 $request = $this->getRequest();
93 $target = $request->getVal( 'target', $par );
94 $namespace = $request->getIntOrNull( 'namespace', null );
95
96 $protocols_list = array();
97 foreach ( $this->getConfig()->get( 'UrlProtocols' ) as $prot ) {
98 if ( $prot !== '//' ) {
99 $protocols_list[] = $prot;
100 }
101 }
102
103 $target2 = $target;
104 // Get protocol, default is http://
105 $protocol = 'http://';
106 $bits = wfParseUrl( $target );
107 if ( isset( $bits['scheme'] ) && isset( $bits['delimiter'] ) ) {
108 $protocol = $bits['scheme'] . $bits['delimiter'];
109 // Make sure wfParseUrl() didn't make some well-intended correction in the
110 // protocol
111 if ( strcasecmp( $protocol, substr( $target, 0, strlen( $protocol ) ) ) === 0 ) {
112 $target2 = substr( $target, strlen( $protocol ) );
113 } else {
114 // If it did, let LinkFilter::makeLikeArray() handle this
115 $protocol = '';
116 }
117 }
118
119 $out->addWikiMsg(
120 'linksearch-text',
121 '<nowiki>' . $this->getLanguage()->commaList( $protocols_list ) . '</nowiki>',
122 count( $protocols_list )
123 );
124 $fields = array(
125 'target' => array(
126 'type' => 'text',
127 'name' => 'target',
128 'id' => 'target',
129 'size' => 50,
130 'label-message' => 'linksearch-pat',
131 'default' => $target,
132 'dir' => 'ltr',
133 )
134 );
135 if ( !$this->getConfig()->get( 'MiserMode' ) ) {
136 $fields += array(
137 'namespace' => array(
138 'class' => 'HTMLSelectNamespace',
139 'name' => 'namespace',
140 'label-message' => 'linksearch-ns',
141 'default' => $namespace,
142 'id' => 'namespace',
143 'cssclass' => 'namespaceselector',
144 ),
145 );
146 }
147 $hiddenFields = array(
148 'title' => $this->getPageTitle()->getPrefixedDBkey(),
149 );
150 $htmlForm = HTMLForm::factory( 'inline', $fields, $this->getContext() );
151 $htmlForm->addHiddenFields( $hiddenFields );
152 $htmlForm->setSubmitTextMsg( 'linksearch-ok' );
153 $htmlForm->setWrapperLegendMsg( 'linksearch' );
154 $htmlForm->setAction( wfScript() );
155 $htmlForm->setMethod( 'get' );
156 $htmlForm->prepareForm()->displayForm( false );
157
158 if ( $target != '' ) {
159 $this->setParams( array(
160 'query' => $target2,
161 'namespace' => $namespace,
162 'protocol' => $protocol ) );
163 parent::execute( $par );
164 if ( $this->mungedQuery === false ) {
165 $out->addWikiMsg( 'linksearch-error' );
166 }
167 }
168 }
169
170 /**
171 * Disable RSS/Atom feeds
172 * @return bool
173 */
174 function isSyndicated() {
175 return false;
176 }
177
178 /**
179 * Return an appropriately formatted LIKE query and the clause
180 *
181 * @param string $query Search pattern to search for
182 * @param string $prot Protocol, e.g. 'http://'
183 *
184 * @return array
185 */
186 static function mungeQuery( $query, $prot ) {
187 $field = 'el_index';
188 $dbr = wfGetDB( DB_SLAVE );
189
190 if ( $query === '*' && $prot !== '' ) {
191 // Allow queries like 'ftp://*' to find all ftp links
192 $rv = array( $prot, $dbr->anyString() );
193 } else {
194 $rv = LinkFilter::makeLikeArray( $query, $prot );
195 }
196
197 if ( $rv === false ) {
198 // LinkFilter doesn't handle wildcard in IP, so we'll have to munge here.
199 $pattern = '/^(:?[0-9]{1,3}\.)+\*\s*$|^(:?[0-9]{1,3}\.){3}[0-9]{1,3}:[0-9]*\*\s*$/';
200 if ( preg_match( $pattern, $query ) ) {
201 $rv = array( $prot . rtrim( $query, " \t*" ), $dbr->anyString() );
202 $field = 'el_to';
203 }
204 }
205
206 return array( $rv, $field );
207 }
208
209 function linkParameters() {
210 $params = array();
211 $params['target'] = $this->mProt . $this->mQuery;
212 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
213 $params['namespace'] = $this->mNs;
214 }
215
216 return $params;
217 }
218
219 function getQueryInfo() {
220 $dbr = wfGetDB( DB_SLAVE );
221 // strip everything past first wildcard, so that
222 // index-based-only lookup would be done
223 list( $this->mungedQuery, $clause ) = self::mungeQuery( $this->mQuery, $this->mProt );
224 if ( $this->mungedQuery === false ) {
225 // Invalid query; return no results
226 return array( 'tables' => 'page', 'fields' => 'page_id', 'conds' => '0=1' );
227 }
228
229 $stripped = LinkFilter::keepOneWildcard( $this->mungedQuery );
230 $like = $dbr->buildLike( $stripped );
231 $retval = array(
232 'tables' => array( 'page', 'externallinks' ),
233 'fields' => array(
234 'namespace' => 'page_namespace',
235 'title' => 'page_title',
236 'value' => 'el_index',
237 'url' => 'el_to'
238 ),
239 'conds' => array(
240 'page_id = el_from',
241 "$clause $like"
242 ),
243 'options' => array( 'USE INDEX' => $clause )
244 );
245
246 if ( $this->mNs !== null && !$this->getConfig()->get( 'MiserMode' ) ) {
247 $retval['conds']['page_namespace'] = $this->mNs;
248 }
249
250 return $retval;
251 }
252
253 /**
254 * Pre-fill the link cache
255 *
256 * @param IDatabase $db
257 * @param ResultWrapper $res
258 */
259 function preprocessResults( $db, $res ) {
260 if ( $res->numRows() > 0 ) {
261 $linkBatch = new LinkBatch();
262
263 foreach ( $res as $row ) {
264 $linkBatch->add( $row->namespace, $row->title );
265 }
266
267 $res->seek( 0 );
268 $linkBatch->execute();
269 }
270 }
271
272 /**
273 * @param Skin $skin
274 * @param object $result Result row
275 * @return string
276 */
277 function formatResult( $skin, $result ) {
278 $title = new TitleValue( (int)$result->namespace, $result->title );
279 $pageLink = $this->linkRenderer->renderHtmlLink( $title );
280
281 $url = $result->url;
282 $urlLink = Linker::makeExternalLink( $url, $url );
283
284 return $this->msg( 'linksearch-line' )->rawParams( $urlLink, $pageLink )->escaped();
285 }
286
287 /**
288 * Override to squash the ORDER BY.
289 * We do a truncated index search, so the optimizer won't trust
290 * it as good enough for optimizing sort. The implicit ordering
291 * from the scan will usually do well enough for our needs.
292 * @return array
293 */
294 function getOrderFields() {
295 return array();
296 }
297
298 protected function getGroupName() {
299 return 'redirects';
300 }
301 }