MediaWiki  master
SpecialFileDuplicateSearch.php
Go to the documentation of this file.
1 <?php
2 
4 
35  protected $hash = '', $filename = '';
36 
40  protected $file = null;
41 
42  function __construct( $name = 'FileDuplicateSearch' ) {
43  parent::__construct( $name );
44  }
45 
46  function isSyndicated() {
47  return false;
48  }
49 
50  function isCacheable() {
51  return false;
52  }
53 
54  public function isCached() {
55  return false;
56  }
57 
58  function linkParameters() {
59  return [ 'filename' => $this->filename ];
60  }
61 
67  function getDupes() {
68  return RepoGroup::singleton()->findBySha1( $this->hash );
69  }
70 
75  function showList( $dupes ) {
76  $html = [];
77  $html[] = $this->openList( 0 );
78 
79  foreach ( $dupes as $dupe ) {
80  $line = $this->formatResult( null, $dupe );
81  $html[] = "<li>" . $line . "</li>";
82  }
83  $html[] = $this->closeList();
84 
85  $this->getOutput()->addHTML( implode( "\n", $html ) );
86  }
87 
88  public function getQueryInfo() {
89  $imgQuery = LocalFile::getQueryInfo();
90  return [
91  'tables' => $imgQuery['tables'],
92  'fields' => [
93  'title' => 'img_name',
94  'value' => 'img_sha1',
95  'img_user_text' => $imgQuery['fields']['img_user_text'],
96  'img_timestamp'
97  ],
98  'conds' => [ 'img_sha1' => $this->hash ],
99  'join_conds' => $imgQuery['joins'],
100  ];
101  }
102 
103  public function execute( $par ) {
104  $this->setHeaders();
105  $this->outputHeader();
106 
107  $this->filename = $par ?? $this->getRequest()->getText( 'filename' );
108  $this->file = null;
109  $this->hash = '';
110  $title = Title::newFromText( $this->filename, NS_FILE );
111  if ( $title && $title->getText() != '' ) {
112  $this->file = MediaWikiServices::getInstance()->getRepoGroup()->findFile( $title );
113  }
114 
115  $out = $this->getOutput();
116 
117  # Create the input form
118  $formFields = [
119  'filename' => [
120  'type' => 'text',
121  'name' => 'filename',
122  'label-message' => 'fileduplicatesearch-filename',
123  'id' => 'filename',
124  'size' => 50,
125  'default' => $this->filename,
126  ],
127  ];
128  $hiddenFields = [
129  'title' => $this->getPageTitle()->getPrefixedDBkey(),
130  ];
131  $htmlForm = HTMLForm::factory( 'ooui', $formFields, $this->getContext() );
132  $htmlForm->addHiddenFields( $hiddenFields );
133  $htmlForm->setAction( wfScript() );
134  $htmlForm->setMethod( 'get' );
135  $htmlForm->setSubmitTextMsg( $this->msg( 'fileduplicatesearch-submit' ) );
136 
137  // The form should be visible always, even if it was submitted (e.g. to perform another action).
138  // To bypass the callback validation of HTMLForm, use prepareForm() and displayForm().
139  $htmlForm->prepareForm()->displayForm( false );
140 
141  if ( $this->file ) {
142  $this->hash = $this->file->getSha1();
143  } elseif ( $this->filename !== '' ) {
144  $out->wrapWikiMsg(
145  "<p class='mw-fileduplicatesearch-noresults'>\n$1\n</p>",
146  [ 'fileduplicatesearch-noresults', wfEscapeWikiText( $this->filename ) ]
147  );
148  }
149 
150  if ( $this->hash != '' ) {
151  # Show a thumbnail of the file
152  $img = $this->file;
153  if ( $img ) {
154  $thumb = $img->transform( [ 'width' => 120, 'height' => 120 ] );
155  if ( $thumb ) {
156  $out->addModuleStyles( 'mediawiki.special' );
157  $out->addHTML( '<div id="mw-fileduplicatesearch-icon">' .
158  $thumb->toHtml( [ 'desc-link' => false ] ) . '<br />' .
159  $this->msg( 'fileduplicatesearch-info' )->numParams(
160  $img->getWidth(), $img->getHeight() )->params(
161  $this->getLanguage()->formatSize( $img->getSize() ),
162  $img->getMimeType() )->parseAsBlock() .
163  '</div>' );
164  }
165  }
166 
167  $dupes = $this->getDupes();
168  $numRows = count( $dupes );
169 
170  # Show a short summary
171  if ( $numRows == 1 ) {
172  $out->wrapWikiMsg(
173  "<p class='mw-fileduplicatesearch-result-1'>\n$1\n</p>",
174  [ 'fileduplicatesearch-result-1', wfEscapeWikiText( $this->filename ) ]
175  );
176  } elseif ( $numRows ) {
177  $out->wrapWikiMsg(
178  "<p class='mw-fileduplicatesearch-result-n'>\n$1\n</p>",
179  [ 'fileduplicatesearch-result-n', wfEscapeWikiText( $this->filename ),
180  $this->getLanguage()->formatNum( $numRows - 1 ) ]
181  );
182  }
183 
184  $this->doBatchLookups( $dupes );
185  $this->showList( $dupes );
186  }
187  }
188 
189  function doBatchLookups( $list ) {
190  $batch = new LinkBatch();
192  foreach ( $list as $file ) {
193  $batch->addObj( $file->getTitle() );
194  if ( $file->isLocal() ) {
195  $userName = $file->getUser( 'text' );
196  $batch->add( NS_USER, $userName );
197  $batch->add( NS_USER_TALK, $userName );
198  }
199  }
200 
201  $batch->execute();
202  }
203 
210  function formatResult( $skin, $result ) {
211  $linkRenderer = $this->getLinkRenderer();
212  $nt = $result->getTitle();
213  $text = MediaWikiServices::getInstance()->getContentLanguage()->convert(
214  htmlspecialchars( $nt->getText() )
215  );
216  $plink = $linkRenderer->makeLink(
217  $nt,
218  new HtmlArmor( $text )
219  );
220 
221  $userText = $result->getUser( 'text' );
222  if ( $result->isLocal() ) {
223  $userId = $result->getUser( 'id' );
224  $user = Linker::userLink( $userId, $userText );
225  $user .= '<span style="white-space: nowrap;">';
226  $user .= Linker::userToolLinks( $userId, $userText );
227  $user .= '</span>';
228  } else {
229  $user = htmlspecialchars( $userText );
230  }
231 
232  $time = htmlspecialchars( $this->getLanguage()->userTimeAndDate(
233  $result->getTimestamp(), $this->getUser() ) );
234 
235  return "$plink . . $user . . $time";
236  }
237 
246  public function prefixSearchSubpages( $search, $limit, $offset ) {
247  $title = Title::newFromText( $search, NS_FILE );
248  if ( !$title || $title->getNamespace() !== NS_FILE ) {
249  // No prefix suggestion outside of file namespace
250  return [];
251  }
252  $searchEngine = MediaWikiServices::getInstance()->newSearchEngine();
253  $searchEngine->setLimitOffset( $limit, $offset );
254  // Autocomplete subpage the same as a normal search, but just for files
255  $searchEngine->setNamespaces( [ NS_FILE ] );
256  $result = $searchEngine->defaultPrefixSearch( $search );
257 
258  return array_map( function ( Title $t ) {
259  // Remove namespace in search suggestion
260  return $t->getText();
261  }, $result );
262  }
263 
264  protected function getGroupName() {
265  return 'media';
266  }
267 }
wfEscapeWikiText( $text)
Escapes the given text so that it may be output using addWikiText() without any linking, formatting, etc.
getContext()
Gets the context this SpecialPage is executed in.
getText()
Get the text form (spaces not underscores) of the main part.
Definition: Title.php:998
__construct( $name='FileDuplicateSearch')
getOutput()
Get the OutputPage being used for this instance.
This is a class for doing query pages; since they&#39;re almost all the same, we factor out some of the f...
Definition: QueryPage.php:36
wfScript( $script='index')
Get the path to a specified script file, respecting file extensions; this is a wrapper around $wgScri...
Class representing a list of titles The execute() method checks them all for existence and adds them ...
Definition: LinkBatch.php:34
openList( $offset)
Definition: QueryPage.php:771
msg( $key,... $params)
Wrapper around wfMessage that sets the current context.
static factory( $displayFormat,... $arguments)
Construct a HTMLForm object for given display type.
Definition: HTMLForm.php:307
static userToolLinks( $userId, $userText, $redContribsWhenNoEdits=false, $flags=0, $edits=null, $useParentheses=true)
Generate standard user tool links (talk, contributions, block link, etc.)
Definition: Linker.php:943
static singleton()
Definition: RepoGroup.php:60
int $offset
The offset and limit in use, as passed to the query() function.
Definition: QueryPage.php:41
setHeaders()
Sets headers - this should be called from the execute() method of all derived classes! ...
const NS_FILE
Definition: Defines.php:66
static userLink( $userId, $userName, $altUserName=false)
Make user link (or user contributions for unregistered users)
Definition: Linker.php:898
int $numRows
The number of rows returned by the query.
Definition: QueryPage.php:53
getUser()
Shortcut to get the User executing this instance.
$line
Definition: cdb.php:59
Searches the database for files of the requested hash, comparing this with the &#39;img_sha1&#39; field in th...
int $limit
Definition: QueryPage.php:44
getLanguage()
Shortcut to get user&#39;s language.
getRequest()
Get the WebRequest being used for this instance.
static getQueryInfo(array $options=[])
Return the tables, fields, and join conditions to be selected to create a new localfile object...
Definition: LocalFile.php:216
getDupes()
Fetch dupes from all connected file repositories.
const NS_USER_TALK
Definition: Defines.php:63
outputHeader( $summaryMessageKey='')
Outputs a summary message on top of special pages Per default the message key is the canonical name o...
getPageTitle( $subpage=false)
Get a self-referential title object.
prefixSearchSubpages( $search, $limit, $offset)
Return an array of subpages beginning with $search that this special page will accept.
MediaWiki Linker LinkRenderer null $linkRenderer
Definition: SpecialPage.php:67
static newFromText( $text, $defaultNamespace=NS_MAIN)
Create a new Title from text, such as what one would find in a link.
Definition: Title.php:319