Merge "Provide command to adjust phpunit.xml for code coverage"
[lhc/web/wiklou.git] / includes / filerepo / file / OldLocalFile.php
1 <?php
2 /**
3 * Old file in the oldimage table.
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 FileAbstraction
22 */
23
24 use MediaWiki\MediaWikiServices;
25
26 /**
27 * Class to represent a file in the oldimage table
28 *
29 * @ingroup FileAbstraction
30 */
31 class OldLocalFile extends LocalFile {
32 /** @var string|int Timestamp */
33 protected $requestedTime;
34
35 /** @var string Archive name */
36 protected $archive_name;
37
38 const CACHE_VERSION = 1;
39 const MAX_CACHE_ROWS = 20;
40
41 /**
42 * @param Title $title
43 * @param FileRepo $repo
44 * @param string|int|null $time
45 * @return static
46 * @throws MWException
47 */
48 static function newFromTitle( $title, $repo, $time = null ) {
49 # The null default value is only here to avoid an E_STRICT
50 if ( $time === null ) {
51 throw new MWException( __METHOD__ . ' got null for $time parameter' );
52 }
53
54 return new static( $title, $repo, $time, null );
55 }
56
57 /**
58 * @param Title $title
59 * @param FileRepo $repo
60 * @param string $archiveName
61 * @return static
62 */
63 static function newFromArchiveName( $title, $repo, $archiveName ) {
64 return new static( $title, $repo, null, $archiveName );
65 }
66
67 /**
68 * @param stdClass $row
69 * @param FileRepo $repo
70 * @return static
71 */
72 static function newFromRow( $row, $repo ) {
73 $title = Title::makeTitle( NS_FILE, $row->oi_name );
74 $file = new static( $title, $repo, null, $row->oi_archive_name );
75 $file->loadFromRow( $row, 'oi_' );
76
77 return $file;
78 }
79
80 /**
81 * Create a OldLocalFile from a SHA-1 key
82 * Do not call this except from inside a repo class.
83 *
84 * @param string $sha1 Base-36 SHA-1
85 * @param LocalRepo $repo
86 * @param string|bool $timestamp MW_timestamp (optional)
87 *
88 * @return bool|OldLocalFile
89 */
90 static function newFromKey( $sha1, $repo, $timestamp = false ) {
91 $dbr = $repo->getReplicaDB();
92
93 $conds = [ 'oi_sha1' => $sha1 ];
94 if ( $timestamp ) {
95 $conds['oi_timestamp'] = $dbr->timestamp( $timestamp );
96 }
97
98 $fileQuery = static::getQueryInfo();
99 $row = $dbr->selectRow(
100 $fileQuery['tables'], $fileQuery['fields'], $conds, __METHOD__, [], $fileQuery['joins']
101 );
102 if ( $row ) {
103 return static::newFromRow( $row, $repo );
104 } else {
105 return false;
106 }
107 }
108
109 /**
110 * Return the tables, fields, and join conditions to be selected to create
111 * a new oldlocalfile object.
112 * @since 1.31
113 * @param string[] $options
114 * - omit-lazy: Omit fields that are lazily cached.
115 * @return array[] With three keys:
116 * - tables: (string[]) to include in the `$table` to `IDatabase->select()`
117 * - fields: (string[]) to include in the `$vars` to `IDatabase->select()`
118 * - joins: (array) to include in the `$join_conds` to `IDatabase->select()`
119 */
120 public static function getQueryInfo( array $options = [] ) {
121 $commentQuery = MediaWikiServices::getInstance()->getCommentStore()->getJoin( 'oi_description' );
122 $actorQuery = ActorMigration::newMigration()->getJoin( 'oi_user' );
123 $ret = [
124 'tables' => [ 'oldimage' ] + $commentQuery['tables'] + $actorQuery['tables'],
125 'fields' => [
126 'oi_name',
127 'oi_archive_name',
128 'oi_size',
129 'oi_width',
130 'oi_height',
131 'oi_bits',
132 'oi_media_type',
133 'oi_major_mime',
134 'oi_minor_mime',
135 'oi_timestamp',
136 'oi_deleted',
137 'oi_sha1',
138 ] + $commentQuery['fields'] + $actorQuery['fields'],
139 'joins' => $commentQuery['joins'] + $actorQuery['joins'],
140 ];
141
142 if ( in_array( 'omit-nonlazy', $options, true ) ) {
143 // Internal use only for getting only the lazy fields
144 $ret['fields'] = [];
145 }
146 if ( !in_array( 'omit-lazy', $options, true ) ) {
147 // Note: Keep this in sync with self::getLazyCacheFields()
148 $ret['fields'][] = 'oi_metadata';
149 }
150
151 return $ret;
152 }
153
154 /**
155 * @param Title $title
156 * @param FileRepo $repo
157 * @param string|int|null $time Timestamp or null to load by archive name
158 * @param string|null $archiveName Archive name or null to load by timestamp
159 * @throws MWException
160 */
161 function __construct( $title, $repo, $time, $archiveName ) {
162 parent::__construct( $title, $repo );
163 $this->requestedTime = $time;
164 $this->archive_name = $archiveName;
165 if ( is_null( $time ) && is_null( $archiveName ) ) {
166 throw new MWException( __METHOD__ . ': must specify at least one of $time or $archiveName' );
167 }
168 }
169
170 /**
171 * @return bool
172 */
173 function getCacheKey() {
174 return false;
175 }
176
177 /**
178 * @return string
179 */
180 function getArchiveName() {
181 if ( !isset( $this->archive_name ) ) {
182 $this->load();
183 }
184
185 return $this->archive_name;
186 }
187
188 /**
189 * @return bool
190 */
191 function isOld() {
192 return true;
193 }
194
195 /**
196 * @return bool
197 */
198 function isVisible() {
199 return $this->exists() && !$this->isDeleted( File::DELETED_FILE );
200 }
201
202 function loadFromDB( $flags = 0 ) {
203 $this->dataLoaded = true;
204
205 $dbr = ( $flags & self::READ_LATEST )
206 ? $this->repo->getMasterDB()
207 : $this->repo->getReplicaDB();
208
209 $conds = [ 'oi_name' => $this->getName() ];
210 if ( is_null( $this->requestedTime ) ) {
211 $conds['oi_archive_name'] = $this->archive_name;
212 } else {
213 $conds['oi_timestamp'] = $dbr->timestamp( $this->requestedTime );
214 }
215 $fileQuery = static::getQueryInfo();
216 $row = $dbr->selectRow(
217 $fileQuery['tables'],
218 $fileQuery['fields'],
219 $conds,
220 __METHOD__,
221 [ 'ORDER BY' => 'oi_timestamp DESC' ],
222 $fileQuery['joins']
223 );
224 if ( $row ) {
225 $this->loadFromRow( $row, 'oi_' );
226 } else {
227 $this->fileExists = false;
228 }
229 }
230
231 /**
232 * Load lazy file metadata from the DB
233 */
234 protected function loadExtraFromDB() {
235 $this->extraDataLoaded = true;
236 $dbr = $this->repo->getReplicaDB();
237 $conds = [ 'oi_name' => $this->getName() ];
238 if ( is_null( $this->requestedTime ) ) {
239 $conds['oi_archive_name'] = $this->archive_name;
240 } else {
241 $conds['oi_timestamp'] = $dbr->timestamp( $this->requestedTime );
242 }
243 $fileQuery = static::getQueryInfo( [ 'omit-nonlazy' ] );
244 // In theory the file could have just been renamed/deleted...oh well
245 $row = $dbr->selectRow(
246 $fileQuery['tables'],
247 $fileQuery['fields'],
248 $conds,
249 __METHOD__,
250 [ 'ORDER BY' => 'oi_timestamp DESC' ],
251 $fileQuery['joins']
252 );
253
254 if ( !$row ) { // fallback to master
255 $dbr = $this->repo->getMasterDB();
256 $row = $dbr->selectRow(
257 $fileQuery['tables'],
258 $fileQuery['fields'],
259 $conds,
260 __METHOD__,
261 [ 'ORDER BY' => 'oi_timestamp DESC' ],
262 $fileQuery['joins']
263 );
264 }
265
266 if ( $row ) {
267 foreach ( $this->unprefixRow( $row, 'oi_' ) as $name => $value ) {
268 $this->$name = $value;
269 }
270 } else {
271 throw new MWException( "Could not find data for image '{$this->archive_name}'." );
272 }
273 }
274
275 /** @inheritDoc */
276 protected function getCacheFields( $prefix = 'img_' ) {
277 $fields = parent::getCacheFields( $prefix );
278 $fields[] = $prefix . 'archive_name';
279 $fields[] = $prefix . 'deleted';
280
281 return $fields;
282 }
283
284 /**
285 * @return string
286 */
287 function getRel() {
288 return $this->getArchiveRel( $this->getArchiveName() );
289 }
290
291 /**
292 * @return string
293 */
294 function getUrlRel() {
295 return $this->getArchiveRel( rawurlencode( $this->getArchiveName() ) );
296 }
297
298 function upgradeRow() {
299 $this->loadFromFile();
300
301 # Don't destroy file info of missing files
302 if ( !$this->fileExists ) {
303 wfDebug( __METHOD__ . ": file does not exist, aborting\n" );
304
305 return;
306 }
307
308 $dbw = $this->repo->getMasterDB();
309 list( $major, $minor ) = self::splitMime( $this->mime );
310
311 wfDebug( __METHOD__ . ': upgrading ' . $this->archive_name . " to the current schema\n" );
312 $dbw->update( 'oldimage',
313 [
314 'oi_size' => $this->size, // sanity
315 'oi_width' => $this->width,
316 'oi_height' => $this->height,
317 'oi_bits' => $this->bits,
318 'oi_media_type' => $this->media_type,
319 'oi_major_mime' => $major,
320 'oi_minor_mime' => $minor,
321 'oi_metadata' => $this->metadata,
322 'oi_sha1' => $this->sha1,
323 ], [
324 'oi_name' => $this->getName(),
325 'oi_archive_name' => $this->archive_name ],
326 __METHOD__
327 );
328 }
329
330 /**
331 * @param int $field One of DELETED_* bitfield constants for file or
332 * revision rows
333 * @return bool
334 */
335 function isDeleted( $field ) {
336 $this->load();
337
338 return ( $this->deleted & $field ) == $field;
339 }
340
341 /**
342 * Returns bitfield value
343 * @return int
344 */
345 function getVisibility() {
346 $this->load();
347
348 return (int)$this->deleted;
349 }
350
351 /**
352 * Determine if the current user is allowed to view a particular
353 * field of this image file, if it's marked as deleted.
354 *
355 * @param int $field
356 * @param User|null $user User object to check, or null to use $wgUser
357 * @return bool
358 */
359 function userCan( $field, User $user = null ) {
360 $this->load();
361
362 return Revision::userCanBitfield( $this->deleted, $field, $user );
363 }
364
365 /**
366 * Upload a file directly into archive. Generally for Special:Import.
367 *
368 * @param string $srcPath File system path of the source file
369 * @param string $timestamp
370 * @param string $comment
371 * @param User $user
372 * @return Status
373 */
374 public function uploadOld( $srcPath, $timestamp, $comment, $user ) {
375 $this->lock();
376
377 $archiveName = $this->getArchiveName();
378 $dstRel = $this->getArchiveRel( $archiveName );
379 $status = $this->publishTo( $srcPath, $dstRel );
380
381 if ( $status->isGood() &&
382 !$this->recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user )
383 ) {
384 $status->fatal( 'filenotfound', $srcPath );
385 }
386
387 $this->unlock();
388
389 return $status;
390 }
391
392 /**
393 * Record a file upload in the oldimage table, without adding log entries.
394 *
395 * @param string $srcPath File system path to the source file
396 * @param string $archiveName The archive name of the file
397 * @param string $timestamp
398 * @param string $comment Upload comment
399 * @param User $user User who did this upload
400 * @return bool
401 */
402 protected function recordOldUpload( $srcPath, $archiveName, $timestamp, $comment, $user ) {
403 $dbw = $this->repo->getMasterDB();
404
405 $dstPath = $this->repo->getZonePath( 'public' ) . '/' . $this->getRel();
406 $props = $this->repo->getFileProps( $dstPath );
407 if ( !$props['fileExists'] ) {
408 return false;
409 }
410
411 $commentFields = MediaWikiServices::getInstance()->getCommentStore()
412 ->insert( $dbw, 'oi_description', $comment );
413 $actorFields = ActorMigration::newMigration()->getInsertValues( $dbw, 'oi_user', $user );
414 $dbw->insert( 'oldimage',
415 [
416 'oi_name' => $this->getName(),
417 'oi_archive_name' => $archiveName,
418 'oi_size' => $props['size'],
419 'oi_width' => intval( $props['width'] ),
420 'oi_height' => intval( $props['height'] ),
421 'oi_bits' => $props['bits'],
422 'oi_timestamp' => $dbw->timestamp( $timestamp ),
423 'oi_metadata' => $props['metadata'],
424 'oi_media_type' => $props['media_type'],
425 'oi_major_mime' => $props['major_mime'],
426 'oi_minor_mime' => $props['minor_mime'],
427 'oi_sha1' => $props['sha1'],
428 ] + $commentFields + $actorFields, __METHOD__
429 );
430
431 return true;
432 }
433
434 /**
435 * If archive name is an empty string, then file does not "exist"
436 *
437 * This is the case for a couple files on Wikimedia servers where
438 * the old version is "lost".
439 * @return bool
440 */
441 public function exists() {
442 $archiveName = $this->getArchiveName();
443 if ( $archiveName === '' || !is_string( $archiveName ) ) {
444 return false;
445 }
446 return parent::exists();
447 }
448 }