Duplicate code is one of the most pungent code smells. A rule that is often used is to re-structure code once it is duplicated in three or more places.
Common duplication problems, and corresponding solutions are:
Complex classes like LocalFile often do a lot of different things. To break such a class down, we need to identify a cohesive component within that class. A common approach to find such a component is to look for fields/methods that share the same prefixes, or suffixes. You can also have a look at the cohesion graph to spot any un-connected, or weakly-connected components.
Once you have determined the fields that belong together, you can apply the Extract Class refactoring. If the component makes sense as a sub-class, Extract Subclass is also a candidate, and is often faster.
While breaking up the class, it is a good idea to analyze how other classes use LocalFile, and based on these observations, apply Extract Interface, too.
1 | <?php |
||
43 | class LocalFile extends File { |
||
44 | const VERSION = 10; // cache version |
||
45 | |||
46 | const CACHE_FIELD_MAX_LEN = 1000; |
||
47 | |||
48 | /** @var bool Does the file exist on disk? (loadFromXxx) */ |
||
49 | protected $fileExists; |
||
50 | |||
51 | /** @var int Image width */ |
||
52 | protected $width; |
||
53 | |||
54 | /** @var int Image height */ |
||
55 | protected $height; |
||
56 | |||
57 | /** @var int Returned by getimagesize (loadFromXxx) */ |
||
58 | protected $bits; |
||
59 | |||
60 | /** @var string MEDIATYPE_xxx (bitmap, drawing, audio...) */ |
||
61 | protected $media_type; |
||
62 | |||
63 | /** @var string MIME type, determined by MimeMagic::guessMimeType */ |
||
64 | protected $mime; |
||
65 | |||
66 | /** @var int Size in bytes (loadFromXxx) */ |
||
67 | protected $size; |
||
68 | |||
69 | /** @var string Handler-specific metadata */ |
||
70 | protected $metadata; |
||
71 | |||
72 | /** @var string SHA-1 base 36 content hash */ |
||
73 | protected $sha1; |
||
74 | |||
75 | /** @var bool Whether or not core data has been loaded from the database (loadFromXxx) */ |
||
76 | protected $dataLoaded; |
||
77 | |||
78 | /** @var bool Whether or not lazy-loaded data has been loaded from the database */ |
||
79 | protected $extraDataLoaded; |
||
80 | |||
81 | /** @var int Bitfield akin to rev_deleted */ |
||
82 | protected $deleted; |
||
83 | |||
84 | /** @var string */ |
||
85 | protected $repoClass = 'LocalRepo'; |
||
86 | |||
87 | /** @var int Number of line to return by nextHistoryLine() (constructor) */ |
||
88 | private $historyLine; |
||
89 | |||
90 | /** @var int Result of the query for the file's history (nextHistoryLine) */ |
||
91 | private $historyRes; |
||
92 | |||
93 | /** @var string Major MIME type */ |
||
94 | private $major_mime; |
||
95 | |||
96 | /** @var string Minor MIME type */ |
||
97 | private $minor_mime; |
||
98 | |||
99 | /** @var string Upload timestamp */ |
||
100 | private $timestamp; |
||
101 | |||
102 | /** @var int User ID of uploader */ |
||
103 | private $user; |
||
104 | |||
105 | /** @var string User name of uploader */ |
||
106 | private $user_text; |
||
107 | |||
108 | /** @var string Description of current revision of the file */ |
||
109 | private $description; |
||
110 | |||
111 | /** @var string TS_MW timestamp of the last change of the file description */ |
||
112 | private $descriptionTouched; |
||
113 | |||
114 | /** @var bool Whether the row was upgraded on load */ |
||
115 | private $upgraded; |
||
116 | |||
117 | /** @var bool Whether the row was scheduled to upgrade on load */ |
||
118 | private $upgrading; |
||
119 | |||
120 | /** @var bool True if the image row is locked */ |
||
121 | private $locked; |
||
122 | |||
123 | /** @var bool True if the image row is locked with a lock initiated transaction */ |
||
124 | private $lockedOwnTrx; |
||
125 | |||
126 | /** @var bool True if file is not present in file system. Not to be cached in memcached */ |
||
127 | private $missing; |
||
128 | |||
129 | // @note: higher than IDBAccessObject constants |
||
130 | const LOAD_ALL = 16; // integer; load all the lazy fields too (like metadata) |
||
131 | |||
132 | const ATOMIC_SECTION_LOCK = 'LocalFile::lockingTransaction'; |
||
133 | |||
134 | /** |
||
135 | * Create a LocalFile from a title |
||
136 | * Do not call this except from inside a repo class. |
||
137 | * |
||
138 | * Note: $unused param is only here to avoid an E_STRICT |
||
139 | * |
||
140 | * @param Title $title |
||
141 | * @param FileRepo $repo |
||
142 | * @param null $unused |
||
143 | * |
||
144 | * @return LocalFile |
||
145 | */ |
||
146 | static function newFromTitle( $title, $repo, $unused = null ) { |
||
149 | |||
150 | /** |
||
151 | * Create a LocalFile from a title |
||
152 | * Do not call this except from inside a repo class. |
||
153 | * |
||
154 | * @param stdClass $row |
||
155 | * @param FileRepo $repo |
||
156 | * |
||
157 | * @return LocalFile |
||
158 | */ |
||
159 | View Code Duplication | static function newFromRow( $row, $repo ) { |
|
166 | |||
167 | /** |
||
168 | * Create a LocalFile from a SHA-1 key |
||
169 | * Do not call this except from inside a repo class. |
||
170 | * |
||
171 | * @param string $sha1 Base-36 SHA-1 |
||
172 | * @param LocalRepo $repo |
||
173 | * @param string|bool $timestamp MW_timestamp (optional) |
||
174 | * @return bool|LocalFile |
||
175 | */ |
||
176 | View Code Duplication | static function newFromKey( $sha1, $repo, $timestamp = false ) { |
|
191 | |||
192 | /** |
||
193 | * Fields in the image table |
||
194 | * @return array |
||
195 | */ |
||
196 | static function selectFields() { |
||
214 | |||
215 | /** |
||
216 | * Constructor. |
||
217 | * Do not call this except from inside a repo class. |
||
218 | * @param Title $title |
||
219 | * @param FileRepo $repo |
||
220 | */ |
||
221 | function __construct( $title, $repo ) { |
||
233 | |||
234 | /** |
||
235 | * Get the memcached key for the main data for this file, or false if |
||
236 | * there is no access to the shared cache. |
||
237 | * @return string|bool |
||
238 | */ |
||
239 | function getCacheKey() { |
||
240 | return $this->repo->getSharedCacheKey( 'file', sha1( $this->getName() ) ); |
||
241 | } |
||
242 | |||
243 | /** |
||
244 | * Try to load file metadata from memcached, falling back to the database |
||
245 | */ |
||
246 | private function loadFromCache() { |
||
247 | $this->dataLoaded = false; |
||
248 | $this->extraDataLoaded = false; |
||
249 | |||
250 | $key = $this->getCacheKey(); |
||
251 | if ( !$key ) { |
||
252 | $this->loadFromDB( self::READ_NORMAL ); |
||
253 | |||
254 | return; |
||
255 | } |
||
256 | |||
257 | $cache = ObjectCache::getMainWANInstance(); |
||
258 | $cachedValues = $cache->getWithSetCallback( |
||
259 | $key, |
||
|
|||
260 | $cache::TTL_WEEK, |
||
261 | function ( $oldValue, &$ttl, array &$setOpts ) use ( $cache ) { |
||
262 | $setOpts += Database::getCacheSetOptions( $this->repo->getSlaveDB() ); |
||
263 | |||
264 | $this->loadFromDB( self::READ_NORMAL ); |
||
265 | |||
266 | $fields = $this->getCacheFields( '' ); |
||
267 | $cacheVal['fileExists'] = $this->fileExists; |
||
268 | if ( $this->fileExists ) { |
||
269 | foreach ( $fields as $field ) { |
||
270 | $cacheVal[$field] = $this->$field; |
||
271 | } |
||
272 | } |
||
273 | // Strip off excessive entries from the subset of fields that can become large. |
||
274 | // If the cache value gets to large it will not fit in memcached and nothing will |
||
275 | // get cached at all, causing master queries for any file access. |
||
276 | foreach ( $this->getLazyCacheFields( '' ) as $field ) { |
||
277 | if ( isset( $cacheVal[$field] ) |
||
278 | && strlen( $cacheVal[$field] ) > 100 * 1024 |
||
279 | ) { |
||
280 | unset( $cacheVal[$field] ); // don't let the value get too big |
||
281 | } |
||
282 | } |
||
283 | |||
284 | if ( $this->fileExists ) { |
||
285 | $ttl = $cache->adaptiveTTL( wfTimestamp( TS_UNIX, $this->timestamp ), $ttl ); |
||
286 | } else { |
||
287 | $ttl = $cache::TTL_DAY; |
||
288 | } |
||
289 | |||
290 | return $cacheVal; |
||
291 | }, |
||
292 | [ 'version' => self::VERSION ] |
||
293 | ); |
||
294 | |||
295 | $this->fileExists = $cachedValues['fileExists']; |
||
296 | if ( $this->fileExists ) { |
||
297 | $this->setProps( $cachedValues ); |
||
298 | } |
||
299 | |||
300 | $this->dataLoaded = true; |
||
301 | $this->extraDataLoaded = true; |
||
302 | foreach ( $this->getLazyCacheFields( '' ) as $field ) { |
||
303 | $this->extraDataLoaded = $this->extraDataLoaded && isset( $cachedValues[$field] ); |
||
304 | } |
||
305 | } |
||
306 | |||
307 | /** |
||
308 | * Purge the file object/metadata cache |
||
309 | */ |
||
310 | public function invalidateCache() { |
||
311 | $key = $this->getCacheKey(); |
||
312 | if ( !$key ) { |
||
313 | return; |
||
314 | } |
||
315 | |||
316 | $this->repo->getMasterDB()->onTransactionPreCommitOrIdle( |
||
317 | function () use ( $key ) { |
||
318 | ObjectCache::getMainWANInstance()->delete( $key ); |
||
319 | }, |
||
320 | __METHOD__ |
||
321 | ); |
||
322 | } |
||
323 | |||
324 | /** |
||
325 | * Load metadata from the file itself |
||
326 | */ |
||
327 | function loadFromFile() { |
||
328 | $props = $this->repo->getFileProps( $this->getVirtualUrl() ); |
||
329 | $this->setProps( $props ); |
||
330 | } |
||
331 | |||
332 | /** |
||
333 | * @param string $prefix |
||
334 | * @return array |
||
335 | */ |
||
336 | function getCacheFields( $prefix = 'img_' ) { |
||
337 | static $fields = [ 'size', 'width', 'height', 'bits', 'media_type', |
||
338 | 'major_mime', 'minor_mime', 'metadata', 'timestamp', 'sha1', 'user', |
||
339 | 'user_text', 'description' ]; |
||
340 | static $results = []; |
||
341 | |||
342 | if ( $prefix == '' ) { |
||
343 | return $fields; |
||
344 | } |
||
345 | |||
346 | View Code Duplication | if ( !isset( $results[$prefix] ) ) { |
|
347 | $prefixedFields = []; |
||
348 | foreach ( $fields as $field ) { |
||
349 | $prefixedFields[] = $prefix . $field; |
||
350 | } |
||
351 | $results[$prefix] = $prefixedFields; |
||
352 | } |
||
353 | |||
354 | return $results[$prefix]; |
||
355 | } |
||
356 | |||
357 | /** |
||
358 | * @param string $prefix |
||
359 | * @return array |
||
360 | */ |
||
361 | function getLazyCacheFields( $prefix = 'img_' ) { |
||
362 | static $fields = [ 'metadata' ]; |
||
363 | static $results = []; |
||
364 | |||
365 | if ( $prefix == '' ) { |
||
366 | return $fields; |
||
367 | } |
||
368 | |||
369 | View Code Duplication | if ( !isset( $results[$prefix] ) ) { |
|
370 | $prefixedFields = []; |
||
371 | foreach ( $fields as $field ) { |
||
372 | $prefixedFields[] = $prefix . $field; |
||
373 | } |
||
374 | $results[$prefix] = $prefixedFields; |
||
375 | } |
||
376 | |||
377 | return $results[$prefix]; |
||
378 | } |
||
379 | |||
380 | /** |
||
381 | * Load file metadata from the DB |
||
382 | * @param int $flags |
||
383 | */ |
||
384 | function loadFromDB( $flags = 0 ) { |
||
385 | $fname = get_class( $this ) . '::' . __FUNCTION__; |
||
386 | |||
387 | # Unconditionally set loaded=true, we don't want the accessors constantly rechecking |
||
388 | $this->dataLoaded = true; |
||
389 | $this->extraDataLoaded = true; |
||
390 | |||
391 | $dbr = ( $flags & self::READ_LATEST ) |
||
392 | ? $this->repo->getMasterDB() |
||
393 | : $this->repo->getSlaveDB(); |
||
394 | |||
395 | $row = $dbr->selectRow( 'image', $this->getCacheFields( 'img_' ), |
||
396 | [ 'img_name' => $this->getName() ], $fname ); |
||
397 | |||
398 | if ( $row ) { |
||
399 | $this->loadFromRow( $row ); |
||
400 | } else { |
||
401 | $this->fileExists = false; |
||
402 | } |
||
403 | } |
||
404 | |||
405 | /** |
||
406 | * Load lazy file metadata from the DB. |
||
407 | * This covers fields that are sometimes not cached. |
||
408 | */ |
||
409 | protected function loadExtraFromDB() { |
||
410 | $fname = get_class( $this ) . '::' . __FUNCTION__; |
||
411 | |||
412 | # Unconditionally set loaded=true, we don't want the accessors constantly rechecking |
||
413 | $this->extraDataLoaded = true; |
||
414 | |||
415 | $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getSlaveDB(), $fname ); |
||
416 | if ( !$fieldMap ) { |
||
417 | $fieldMap = $this->loadFieldsWithTimestamp( $this->repo->getMasterDB(), $fname ); |
||
418 | } |
||
419 | |||
420 | if ( $fieldMap ) { |
||
421 | foreach ( $fieldMap as $name => $value ) { |
||
422 | $this->$name = $value; |
||
423 | } |
||
424 | } else { |
||
425 | throw new MWException( "Could not find data for image '{$this->getName()}'." ); |
||
426 | } |
||
427 | } |
||
428 | |||
429 | /** |
||
430 | * @param IDatabase $dbr |
||
431 | * @param string $fname |
||
432 | * @return array|bool |
||
433 | */ |
||
434 | private function loadFieldsWithTimestamp( $dbr, $fname ) { |
||
435 | $fieldMap = false; |
||
436 | |||
437 | $row = $dbr->selectRow( 'image', $this->getLazyCacheFields( 'img_' ), [ |
||
438 | 'img_name' => $this->getName(), |
||
439 | 'img_timestamp' => $dbr->timestamp( $this->getTimestamp() ) |
||
440 | ], $fname ); |
||
441 | if ( $row ) { |
||
442 | $fieldMap = $this->unprefixRow( $row, 'img_' ); |
||
443 | } else { |
||
444 | # File may have been uploaded over in the meantime; check the old versions |
||
445 | $row = $dbr->selectRow( 'oldimage', $this->getLazyCacheFields( 'oi_' ), [ |
||
446 | 'oi_name' => $this->getName(), |
||
447 | 'oi_timestamp' => $dbr->timestamp( $this->getTimestamp() ) |
||
448 | ], $fname ); |
||
449 | if ( $row ) { |
||
450 | $fieldMap = $this->unprefixRow( $row, 'oi_' ); |
||
451 | } |
||
452 | } |
||
453 | |||
454 | return $fieldMap; |
||
455 | } |
||
456 | |||
457 | /** |
||
458 | * @param array|object $row |
||
459 | * @param string $prefix |
||
460 | * @throws MWException |
||
461 | * @return array |
||
462 | */ |
||
463 | protected function unprefixRow( $row, $prefix = 'img_' ) { |
||
464 | $array = (array)$row; |
||
465 | $prefixLength = strlen( $prefix ); |
||
466 | |||
467 | // Sanity check prefix once |
||
468 | if ( substr( key( $array ), 0, $prefixLength ) !== $prefix ) { |
||
469 | throw new MWException( __METHOD__ . ': incorrect $prefix parameter' ); |
||
470 | } |
||
471 | |||
472 | $decoded = []; |
||
473 | foreach ( $array as $name => $value ) { |
||
474 | $decoded[substr( $name, $prefixLength )] = $value; |
||
475 | } |
||
476 | |||
477 | return $decoded; |
||
478 | } |
||
479 | |||
480 | /** |
||
481 | * Decode a row from the database (either object or array) to an array |
||
482 | * with timestamps and MIME types decoded, and the field prefix removed. |
||
483 | * @param object $row |
||
484 | * @param string $prefix |
||
485 | * @throws MWException |
||
486 | * @return array |
||
487 | */ |
||
488 | function decodeRow( $row, $prefix = 'img_' ) { |
||
489 | $decoded = $this->unprefixRow( $row, $prefix ); |
||
490 | |||
491 | $decoded['timestamp'] = wfTimestamp( TS_MW, $decoded['timestamp'] ); |
||
492 | |||
493 | $decoded['metadata'] = $this->repo->getSlaveDB()->decodeBlob( $decoded['metadata'] ); |
||
494 | |||
495 | if ( empty( $decoded['major_mime'] ) ) { |
||
496 | $decoded['mime'] = 'unknown/unknown'; |
||
497 | } else { |
||
498 | if ( !$decoded['minor_mime'] ) { |
||
499 | $decoded['minor_mime'] = 'unknown'; |
||
500 | } |
||
501 | $decoded['mime'] = $decoded['major_mime'] . '/' . $decoded['minor_mime']; |
||
502 | } |
||
503 | |||
504 | // Trim zero padding from char/binary field |
||
505 | $decoded['sha1'] = rtrim( $decoded['sha1'], "\0" ); |
||
506 | |||
507 | // Normalize some fields to integer type, per their database definition. |
||
508 | // Use unary + so that overflows will be upgraded to double instead of |
||
509 | // being trucated as with intval(). This is important to allow >2GB |
||
510 | // files on 32-bit systems. |
||
511 | foreach ( [ 'size', 'width', 'height', 'bits' ] as $field ) { |
||
512 | $decoded[$field] = +$decoded[$field]; |
||
513 | } |
||
514 | |||
515 | return $decoded; |
||
516 | } |
||
517 | |||
518 | /** |
||
519 | * Load file metadata from a DB result row |
||
520 | * |
||
521 | * @param object $row |
||
522 | * @param string $prefix |
||
523 | */ |
||
524 | function loadFromRow( $row, $prefix = 'img_' ) { |
||
525 | $this->dataLoaded = true; |
||
526 | $this->extraDataLoaded = true; |
||
527 | |||
528 | $array = $this->decodeRow( $row, $prefix ); |
||
529 | |||
530 | foreach ( $array as $name => $value ) { |
||
531 | $this->$name = $value; |
||
532 | } |
||
533 | |||
534 | $this->fileExists = true; |
||
535 | $this->maybeUpgradeRow(); |
||
536 | } |
||
537 | |||
538 | /** |
||
539 | * Load file metadata from cache or DB, unless already loaded |
||
540 | * @param int $flags |
||
541 | */ |
||
542 | function load( $flags = 0 ) { |
||
543 | if ( !$this->dataLoaded ) { |
||
544 | if ( $flags & self::READ_LATEST ) { |
||
545 | $this->loadFromDB( $flags ); |
||
546 | } else { |
||
547 | $this->loadFromCache(); |
||
548 | } |
||
549 | } |
||
550 | |||
551 | if ( ( $flags & self::LOAD_ALL ) && !$this->extraDataLoaded ) { |
||
552 | // @note: loads on name/timestamp to reduce race condition problems |
||
553 | $this->loadExtraFromDB(); |
||
554 | } |
||
555 | } |
||
556 | |||
557 | /** |
||
558 | * Upgrade a row if it needs it |
||
559 | */ |
||
560 | function maybeUpgradeRow() { |
||
561 | global $wgUpdateCompatibleMetadata; |
||
562 | |||
563 | if ( wfReadOnly() || $this->upgrading ) { |
||
564 | return; |
||
565 | } |
||
566 | |||
567 | $upgrade = false; |
||
568 | if ( is_null( $this->media_type ) || $this->mime == 'image/svg' ) { |
||
569 | $upgrade = true; |
||
570 | } else { |
||
571 | $handler = $this->getHandler(); |
||
572 | if ( $handler ) { |
||
573 | $validity = $handler->isMetadataValid( $this, $this->getMetadata() ); |
||
574 | if ( $validity === MediaHandler::METADATA_BAD ) { |
||
575 | $upgrade = true; |
||
576 | } elseif ( $validity === MediaHandler::METADATA_COMPATIBLE ) { |
||
577 | $upgrade = $wgUpdateCompatibleMetadata; |
||
578 | } |
||
579 | } |
||
580 | } |
||
581 | |||
582 | if ( $upgrade ) { |
||
583 | $this->upgrading = true; |
||
584 | // Defer updates unless in auto-commit CLI mode |
||
585 | DeferredUpdates::addCallableUpdate( function() { |
||
586 | $this->upgrading = false; // avoid duplicate updates |
||
587 | try { |
||
588 | $this->upgradeRow(); |
||
589 | } catch ( LocalFileLockError $e ) { |
||
590 | // let the other process handle it (or do it next time) |
||
591 | } |
||
592 | } ); |
||
593 | } |
||
594 | } |
||
595 | |||
596 | /** |
||
597 | * @return bool Whether upgradeRow() ran for this object |
||
598 | */ |
||
599 | function getUpgraded() { |
||
600 | return $this->upgraded; |
||
601 | } |
||
602 | |||
603 | /** |
||
604 | * Fix assorted version-related problems with the image row by reloading it from the file |
||
605 | */ |
||
606 | function upgradeRow() { |
||
607 | $this->lock(); // begin |
||
608 | |||
609 | $this->loadFromFile(); |
||
610 | |||
611 | # Don't destroy file info of missing files |
||
612 | if ( !$this->fileExists ) { |
||
613 | $this->unlock(); |
||
614 | wfDebug( __METHOD__ . ": file does not exist, aborting\n" ); |
||
615 | |||
616 | return; |
||
617 | } |
||
618 | |||
619 | $dbw = $this->repo->getMasterDB(); |
||
620 | list( $major, $minor ) = self::splitMime( $this->mime ); |
||
621 | |||
622 | if ( wfReadOnly() ) { |
||
623 | $this->unlock(); |
||
624 | |||
625 | return; |
||
626 | } |
||
627 | wfDebug( __METHOD__ . ': upgrading ' . $this->getName() . " to the current schema\n" ); |
||
628 | |||
629 | $dbw->update( 'image', |
||
630 | [ |
||
631 | 'img_size' => $this->size, // sanity |
||
632 | 'img_width' => $this->width, |
||
633 | 'img_height' => $this->height, |
||
634 | 'img_bits' => $this->bits, |
||
635 | 'img_media_type' => $this->media_type, |
||
636 | 'img_major_mime' => $major, |
||
637 | 'img_minor_mime' => $minor, |
||
638 | 'img_metadata' => $dbw->encodeBlob( $this->metadata ), |
||
639 | 'img_sha1' => $this->sha1, |
||
640 | ], |
||
641 | [ 'img_name' => $this->getName() ], |
||
642 | __METHOD__ |
||
643 | ); |
||
644 | |||
645 | $this->invalidateCache(); |
||
646 | |||
647 | $this->unlock(); // done |
||
648 | $this->upgraded = true; // avoid rework/retries |
||
649 | } |
||
650 | |||
651 | /** |
||
652 | * Set properties in this object to be equal to those given in the |
||
653 | * associative array $info. Only cacheable fields can be set. |
||
654 | * All fields *must* be set in $info except for getLazyCacheFields(). |
||
655 | * |
||
656 | * If 'mime' is given, it will be split into major_mime/minor_mime. |
||
657 | * If major_mime/minor_mime are given, $this->mime will also be set. |
||
658 | * |
||
659 | * @param array $info |
||
660 | */ |
||
661 | function setProps( $info ) { |
||
662 | $this->dataLoaded = true; |
||
663 | $fields = $this->getCacheFields( '' ); |
||
664 | $fields[] = 'fileExists'; |
||
665 | |||
666 | foreach ( $fields as $field ) { |
||
667 | if ( isset( $info[$field] ) ) { |
||
668 | $this->$field = $info[$field]; |
||
669 | } |
||
670 | } |
||
671 | |||
672 | // Fix up mime fields |
||
673 | if ( isset( $info['major_mime'] ) ) { |
||
674 | $this->mime = "{$info['major_mime']}/{$info['minor_mime']}"; |
||
675 | } elseif ( isset( $info['mime'] ) ) { |
||
676 | $this->mime = $info['mime']; |
||
677 | list( $this->major_mime, $this->minor_mime ) = self::splitMime( $this->mime ); |
||
678 | } |
||
679 | } |
||
680 | |||
681 | /** splitMime inherited */ |
||
682 | /** getName inherited */ |
||
683 | /** getTitle inherited */ |
||
684 | /** getURL inherited */ |
||
685 | /** getViewURL inherited */ |
||
686 | /** getPath inherited */ |
||
687 | /** isVisible inherited */ |
||
688 | |||
689 | /** |
||
690 | * @return bool |
||
691 | */ |
||
692 | function isMissing() { |
||
693 | if ( $this->missing === null ) { |
||
694 | list( $fileExists ) = $this->repo->fileExists( $this->getVirtualUrl() ); |
||
695 | $this->missing = !$fileExists; |
||
696 | } |
||
697 | |||
698 | return $this->missing; |
||
699 | } |
||
700 | |||
701 | /** |
||
702 | * Return the width of the image |
||
703 | * |
||
704 | * @param int $page |
||
705 | * @return int |
||
706 | */ |
||
707 | View Code Duplication | public function getWidth( $page = 1 ) { |
|
708 | $this->load(); |
||
709 | |||
710 | if ( $this->isMultipage() ) { |
||
711 | $handler = $this->getHandler(); |
||
712 | if ( !$handler ) { |
||
713 | return 0; |
||
714 | } |
||
715 | $dim = $handler->getPageDimensions( $this, $page ); |
||
716 | if ( $dim ) { |
||
717 | return $dim['width']; |
||
718 | } else { |
||
719 | // For non-paged media, the false goes through an |
||
720 | // intval, turning failure into 0, so do same here. |
||
721 | return 0; |
||
722 | } |
||
723 | } else { |
||
724 | return $this->width; |
||
725 | } |
||
726 | } |
||
727 | |||
728 | /** |
||
729 | * Return the height of the image |
||
730 | * |
||
731 | * @param int $page |
||
732 | * @return int |
||
733 | */ |
||
734 | View Code Duplication | public function getHeight( $page = 1 ) { |
|
735 | $this->load(); |
||
736 | |||
737 | if ( $this->isMultipage() ) { |
||
738 | $handler = $this->getHandler(); |
||
739 | if ( !$handler ) { |
||
740 | return 0; |
||
741 | } |
||
742 | $dim = $handler->getPageDimensions( $this, $page ); |
||
743 | if ( $dim ) { |
||
744 | return $dim['height']; |
||
745 | } else { |
||
746 | // For non-paged media, the false goes through an |
||
747 | // intval, turning failure into 0, so do same here. |
||
748 | return 0; |
||
749 | } |
||
750 | } else { |
||
751 | return $this->height; |
||
752 | } |
||
753 | } |
||
754 | |||
755 | /** |
||
756 | * Returns ID or name of user who uploaded the file |
||
757 | * |
||
758 | * @param string $type 'text' or 'id' |
||
759 | * @return int|string |
||
760 | */ |
||
761 | function getUser( $type = 'text' ) { |
||
762 | $this->load(); |
||
763 | |||
764 | if ( $type == 'text' ) { |
||
765 | return $this->user_text; |
||
766 | } else { // id |
||
767 | return (int)$this->user; |
||
768 | } |
||
769 | } |
||
770 | |||
771 | /** |
||
772 | * Get short description URL for a file based on the page ID. |
||
773 | * |
||
774 | * @return string|null |
||
775 | * @throws MWException |
||
776 | * @since 1.27 |
||
777 | */ |
||
778 | public function getDescriptionShortUrl() { |
||
779 | $pageId = $this->title->getArticleID(); |
||
780 | |||
781 | View Code Duplication | if ( $pageId !== null ) { |
|
782 | $url = $this->repo->makeUrl( [ 'curid' => $pageId ] ); |
||
783 | if ( $url !== false ) { |
||
784 | return $url; |
||
785 | } |
||
786 | } |
||
787 | return null; |
||
788 | } |
||
789 | |||
790 | /** |
||
791 | * Get handler-specific metadata |
||
792 | * @return string |
||
793 | */ |
||
794 | function getMetadata() { |
||
795 | $this->load( self::LOAD_ALL ); // large metadata is loaded in another step |
||
796 | return $this->metadata; |
||
797 | } |
||
798 | |||
799 | /** |
||
800 | * @return int |
||
801 | */ |
||
802 | function getBitDepth() { |
||
803 | $this->load(); |
||
804 | |||
805 | return (int)$this->bits; |
||
806 | } |
||
807 | |||
808 | /** |
||
809 | * Returns the size of the image file, in bytes |
||
810 | * @return int |
||
811 | */ |
||
812 | public function getSize() { |
||
813 | $this->load(); |
||
814 | |||
815 | return $this->size; |
||
816 | } |
||
817 | |||
818 | /** |
||
819 | * Returns the MIME type of the file. |
||
820 | * @return string |
||
821 | */ |
||
822 | function getMimeType() { |
||
823 | $this->load(); |
||
824 | |||
825 | return $this->mime; |
||
826 | } |
||
827 | |||
828 | /** |
||
829 | * Returns the type of the media in the file. |
||
830 | * Use the value returned by this function with the MEDIATYPE_xxx constants. |
||
831 | * @return string |
||
832 | */ |
||
833 | function getMediaType() { |
||
834 | $this->load(); |
||
835 | |||
836 | return $this->media_type; |
||
837 | } |
||
838 | |||
839 | /** canRender inherited */ |
||
840 | /** mustRender inherited */ |
||
841 | /** allowInlineDisplay inherited */ |
||
842 | /** isSafeFile inherited */ |
||
843 | /** isTrustedFile inherited */ |
||
844 | |||
845 | /** |
||
846 | * Returns true if the file exists on disk. |
||
847 | * @return bool Whether file exist on disk. |
||
848 | */ |
||
849 | public function exists() { |
||
850 | $this->load(); |
||
851 | |||
852 | return $this->fileExists; |
||
853 | } |
||
854 | |||
855 | /** getTransformScript inherited */ |
||
856 | /** getUnscaledThumb inherited */ |
||
857 | /** thumbName inherited */ |
||
858 | /** createThumb inherited */ |
||
859 | /** transform inherited */ |
||
860 | |||
861 | /** getHandler inherited */ |
||
862 | /** iconThumb inherited */ |
||
863 | /** getLastError inherited */ |
||
864 | |||
865 | /** |
||
866 | * Get all thumbnail names previously generated for this file |
||
867 | * @param string|bool $archiveName Name of an archive file, default false |
||
868 | * @return array First element is the base dir, then files in that base dir. |
||
869 | */ |
||
870 | function getThumbnails( $archiveName = false ) { |
||
871 | if ( $archiveName ) { |
||
872 | $dir = $this->getArchiveThumbPath( $archiveName ); |
||
873 | } else { |
||
874 | $dir = $this->getThumbPath(); |
||
875 | } |
||
876 | |||
877 | $backend = $this->repo->getBackend(); |
||
878 | $files = [ $dir ]; |
||
879 | try { |
||
880 | $iterator = $backend->getFileList( [ 'dir' => $dir ] ); |
||
881 | foreach ( $iterator as $file ) { |
||
882 | $files[] = $file; |
||
883 | } |
||
884 | } catch ( FileBackendError $e ) { |
||
885 | } // suppress (bug 54674) |
||
886 | |||
887 | return $files; |
||
888 | } |
||
889 | |||
890 | /** |
||
891 | * Refresh metadata in memcached, but don't touch thumbnails or CDN |
||
892 | */ |
||
893 | function purgeMetadataCache() { |
||
894 | $this->invalidateCache(); |
||
895 | } |
||
896 | |||
897 | /** |
||
898 | * Delete all previously generated thumbnails, refresh metadata in memcached and purge the CDN. |
||
899 | * |
||
900 | * @param array $options An array potentially with the key forThumbRefresh. |
||
901 | * |
||
902 | * @note This used to purge old thumbnails by default as well, but doesn't anymore. |
||
903 | */ |
||
904 | function purgeCache( $options = [] ) { |
||
905 | // Refresh metadata cache |
||
906 | $this->purgeMetadataCache(); |
||
907 | |||
908 | // Delete thumbnails |
||
909 | $this->purgeThumbnails( $options ); |
||
910 | |||
911 | // Purge CDN cache for this file |
||
912 | DeferredUpdates::addUpdate( |
||
913 | new CdnCacheUpdate( [ $this->getUrl() ] ), |
||
914 | DeferredUpdates::PRESEND |
||
915 | ); |
||
916 | } |
||
917 | |||
918 | /** |
||
919 | * Delete cached transformed files for an archived version only. |
||
920 | * @param string $archiveName Name of the archived file |
||
921 | */ |
||
922 | function purgeOldThumbnails( $archiveName ) { |
||
923 | // Get a list of old thumbnails and URLs |
||
924 | $files = $this->getThumbnails( $archiveName ); |
||
925 | |||
926 | // Purge any custom thumbnail caches |
||
927 | Hooks::run( 'LocalFilePurgeThumbnails', [ $this, $archiveName ] ); |
||
928 | |||
929 | // Delete thumbnails |
||
930 | $dir = array_shift( $files ); |
||
931 | $this->purgeThumbList( $dir, $files ); |
||
932 | |||
933 | // Purge the CDN |
||
934 | $urls = []; |
||
935 | foreach ( $files as $file ) { |
||
936 | $urls[] = $this->getArchiveThumbUrl( $archiveName, $file ); |
||
937 | } |
||
938 | DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND ); |
||
939 | } |
||
940 | |||
941 | /** |
||
942 | * Delete cached transformed files for the current version only. |
||
943 | * @param array $options |
||
944 | */ |
||
945 | public function purgeThumbnails( $options = [] ) { |
||
946 | $files = $this->getThumbnails(); |
||
947 | // Always purge all files from CDN regardless of handler filters |
||
948 | $urls = []; |
||
949 | foreach ( $files as $file ) { |
||
950 | $urls[] = $this->getThumbUrl( $file ); |
||
951 | } |
||
952 | array_shift( $urls ); // don't purge directory |
||
953 | |||
954 | // Give media handler a chance to filter the file purge list |
||
955 | if ( !empty( $options['forThumbRefresh'] ) ) { |
||
956 | $handler = $this->getHandler(); |
||
957 | if ( $handler ) { |
||
958 | $handler->filterThumbnailPurgeList( $files, $options ); |
||
959 | } |
||
960 | } |
||
961 | |||
962 | // Purge any custom thumbnail caches |
||
963 | Hooks::run( 'LocalFilePurgeThumbnails', [ $this, false ] ); |
||
964 | |||
965 | // Delete thumbnails |
||
966 | $dir = array_shift( $files ); |
||
967 | $this->purgeThumbList( $dir, $files ); |
||
968 | |||
969 | // Purge the CDN |
||
970 | DeferredUpdates::addUpdate( new CdnCacheUpdate( $urls ), DeferredUpdates::PRESEND ); |
||
971 | } |
||
972 | |||
973 | /** |
||
974 | * Prerenders a configurable set of thumbnails |
||
975 | * |
||
976 | * @since 1.28 |
||
977 | */ |
||
978 | public function prerenderThumbnails() { |
||
979 | global $wgUploadThumbnailRenderMap; |
||
980 | |||
981 | $jobs = []; |
||
982 | |||
983 | $sizes = $wgUploadThumbnailRenderMap; |
||
984 | rsort( $sizes ); |
||
985 | |||
986 | foreach ( $sizes as $size ) { |
||
987 | if ( $this->isVectorized() || $this->getWidth() > $size ) { |
||
988 | $jobs[] = new ThumbnailRenderJob( |
||
989 | $this->getTitle(), |
||
990 | [ 'transformParams' => [ 'width' => $size ] ] |
||
991 | ); |
||
992 | } |
||
993 | } |
||
994 | |||
995 | if ( $jobs ) { |
||
996 | JobQueueGroup::singleton()->lazyPush( $jobs ); |
||
997 | } |
||
998 | } |
||
999 | |||
1000 | /** |
||
1001 | * Delete a list of thumbnails visible at urls |
||
1002 | * @param string $dir Base dir of the files. |
||
1003 | * @param array $files Array of strings: relative filenames (to $dir) |
||
1004 | */ |
||
1005 | protected function purgeThumbList( $dir, $files ) { |
||
1006 | $fileListDebug = strtr( |
||
1007 | var_export( $files, true ), |
||
1008 | [ "\n" => '' ] |
||
1009 | ); |
||
1010 | wfDebug( __METHOD__ . ": $fileListDebug\n" ); |
||
1011 | |||
1012 | $purgeList = []; |
||
1013 | foreach ( $files as $file ) { |
||
1014 | # Check that the base file name is part of the thumb name |
||
1015 | # This is a basic sanity check to avoid erasing unrelated directories |
||
1016 | if ( strpos( $file, $this->getName() ) !== false |
||
1017 | || strpos( $file, "-thumbnail" ) !== false // "short" thumb name |
||
1018 | ) { |
||
1019 | $purgeList[] = "{$dir}/{$file}"; |
||
1020 | } |
||
1021 | } |
||
1022 | |||
1023 | # Delete the thumbnails |
||
1024 | $this->repo->quickPurgeBatch( $purgeList ); |
||
1025 | # Clear out the thumbnail directory if empty |
||
1026 | $this->repo->quickCleanDir( $dir ); |
||
1027 | } |
||
1028 | |||
1029 | /** purgeDescription inherited */ |
||
1030 | /** purgeEverything inherited */ |
||
1031 | |||
1032 | /** |
||
1033 | * @param int $limit Optional: Limit to number of results |
||
1034 | * @param int $start Optional: Timestamp, start from |
||
1035 | * @param int $end Optional: Timestamp, end at |
||
1036 | * @param bool $inc |
||
1037 | * @return OldLocalFile[] |
||
1038 | */ |
||
1039 | function getHistory( $limit = null, $start = null, $end = null, $inc = true ) { |
||
1040 | $dbr = $this->repo->getSlaveDB(); |
||
1041 | $tables = [ 'oldimage' ]; |
||
1042 | $fields = OldLocalFile::selectFields(); |
||
1043 | $conds = $opts = $join_conds = []; |
||
1044 | $eq = $inc ? '=' : ''; |
||
1045 | $conds[] = "oi_name = " . $dbr->addQuotes( $this->title->getDBkey() ); |
||
1046 | |||
1047 | if ( $start ) { |
||
1048 | $conds[] = "oi_timestamp <$eq " . $dbr->addQuotes( $dbr->timestamp( $start ) ); |
||
1049 | } |
||
1050 | |||
1051 | if ( $end ) { |
||
1052 | $conds[] = "oi_timestamp >$eq " . $dbr->addQuotes( $dbr->timestamp( $end ) ); |
||
1053 | } |
||
1054 | |||
1055 | if ( $limit ) { |
||
1056 | $opts['LIMIT'] = $limit; |
||
1057 | } |
||
1058 | |||
1059 | // Search backwards for time > x queries |
||
1060 | $order = ( !$start && $end !== null ) ? 'ASC' : 'DESC'; |
||
1061 | $opts['ORDER BY'] = "oi_timestamp $order"; |
||
1062 | $opts['USE INDEX'] = [ 'oldimage' => 'oi_name_timestamp' ]; |
||
1063 | |||
1064 | Hooks::run( 'LocalFile::getHistory', [ &$this, &$tables, &$fields, |
||
1065 | &$conds, &$opts, &$join_conds ] ); |
||
1066 | |||
1067 | $res = $dbr->select( $tables, $fields, $conds, __METHOD__, $opts, $join_conds ); |
||
1068 | $r = []; |
||
1069 | |||
1070 | foreach ( $res as $row ) { |
||
1071 | $r[] = $this->repo->newFileFromRow( $row ); |
||
1072 | } |
||
1073 | |||
1074 | if ( $order == 'ASC' ) { |
||
1075 | $r = array_reverse( $r ); // make sure it ends up descending |
||
1076 | } |
||
1077 | |||
1078 | return $r; |
||
1079 | } |
||
1080 | |||
1081 | /** |
||
1082 | * Returns the history of this file, line by line. |
||
1083 | * starts with current version, then old versions. |
||
1084 | * uses $this->historyLine to check which line to return: |
||
1085 | * 0 return line for current version |
||
1086 | * 1 query for old versions, return first one |
||
1087 | * 2, ... return next old version from above query |
||
1088 | * @return bool |
||
1089 | */ |
||
1090 | public function nextHistoryLine() { |
||
1091 | # Polymorphic function name to distinguish foreign and local fetches |
||
1092 | $fname = get_class( $this ) . '::' . __FUNCTION__; |
||
1093 | |||
1094 | $dbr = $this->repo->getSlaveDB(); |
||
1095 | |||
1096 | if ( $this->historyLine == 0 ) { // called for the first time, return line from cur |
||
1097 | $this->historyRes = $dbr->select( 'image', |
||
1098 | [ |
||
1099 | '*', |
||
1100 | "'' AS oi_archive_name", |
||
1101 | '0 as oi_deleted', |
||
1102 | 'img_sha1' |
||
1103 | ], |
||
1104 | [ 'img_name' => $this->title->getDBkey() ], |
||
1105 | $fname |
||
1106 | ); |
||
1107 | |||
1108 | if ( 0 == $dbr->numRows( $this->historyRes ) ) { |
||
1109 | $this->historyRes = null; |
||
1110 | |||
1111 | return false; |
||
1112 | } |
||
1113 | } elseif ( $this->historyLine == 1 ) { |
||
1114 | $this->historyRes = $dbr->select( 'oldimage', '*', |
||
1115 | [ 'oi_name' => $this->title->getDBkey() ], |
||
1116 | $fname, |
||
1117 | [ 'ORDER BY' => 'oi_timestamp DESC' ] |
||
1118 | ); |
||
1119 | } |
||
1120 | $this->historyLine++; |
||
1121 | |||
1122 | return $dbr->fetchObject( $this->historyRes ); |
||
1123 | } |
||
1124 | |||
1125 | /** |
||
1126 | * Reset the history pointer to the first element of the history |
||
1127 | */ |
||
1128 | public function resetHistory() { |
||
1129 | $this->historyLine = 0; |
||
1130 | |||
1131 | if ( !is_null( $this->historyRes ) ) { |
||
1132 | $this->historyRes = null; |
||
1133 | } |
||
1134 | } |
||
1135 | |||
1136 | /** getHashPath inherited */ |
||
1137 | /** getRel inherited */ |
||
1138 | /** getUrlRel inherited */ |
||
1139 | /** getArchiveRel inherited */ |
||
1140 | /** getArchivePath inherited */ |
||
1141 | /** getThumbPath inherited */ |
||
1142 | /** getArchiveUrl inherited */ |
||
1143 | /** getThumbUrl inherited */ |
||
1144 | /** getArchiveVirtualUrl inherited */ |
||
1145 | /** getThumbVirtualUrl inherited */ |
||
1146 | /** isHashed inherited */ |
||
1147 | |||
1148 | /** |
||
1149 | * Upload a file and record it in the DB |
||
1150 | * @param string|FSFile $src Source storage path, virtual URL, or filesystem path |
||
1151 | * @param string $comment Upload description |
||
1152 | * @param string $pageText Text to use for the new description page, |
||
1153 | * if a new description page is created |
||
1154 | * @param int|bool $flags Flags for publish() |
||
1155 | * @param array|bool $props File properties, if known. This can be used to |
||
1156 | * reduce the upload time when uploading virtual URLs for which the file |
||
1157 | * info is already known |
||
1158 | * @param string|bool $timestamp Timestamp for img_timestamp, or false to use the |
||
1159 | * current time |
||
1160 | * @param User|null $user User object or null to use $wgUser |
||
1161 | * @param string[] $tags Change tags to add to the log entry and page revision. |
||
1162 | * (This doesn't check $user's permissions.) |
||
1163 | * @return Status On success, the value member contains the |
||
1164 | * archive name, or an empty string if it was a new file. |
||
1165 | */ |
||
1166 | function upload( $src, $comment, $pageText, $flags = 0, $props = false, |
||
1167 | $timestamp = false, $user = null, $tags = [] |
||
1168 | ) { |
||
1169 | global $wgContLang; |
||
1170 | |||
1171 | if ( $this->getRepo()->getReadOnlyReason() !== false ) { |
||
1172 | return $this->readOnlyFatalStatus(); |
||
1173 | } |
||
1174 | |||
1175 | $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src; |
||
1176 | if ( !$props ) { |
||
1177 | if ( $this->repo->isVirtualUrl( $srcPath ) |
||
1178 | || FileBackend::isStoragePath( $srcPath ) |
||
1179 | ) { |
||
1180 | $props = $this->repo->getFileProps( $srcPath ); |
||
1181 | } else { |
||
1182 | $mwProps = new MWFileProps( MimeMagic::singleton() ); |
||
1183 | $props = $mwProps->getPropsFromPath( $srcPath, true ); |
||
1184 | } |
||
1185 | } |
||
1186 | |||
1187 | $options = []; |
||
1188 | $handler = MediaHandler::getHandler( $props['mime'] ); |
||
1189 | View Code Duplication | if ( $handler ) { |
|
1190 | $options['headers'] = $handler->getStreamHeaders( $props['metadata'] ); |
||
1191 | } else { |
||
1192 | $options['headers'] = []; |
||
1193 | } |
||
1194 | |||
1195 | // Trim spaces on user supplied text |
||
1196 | $comment = trim( $comment ); |
||
1197 | |||
1198 | // Truncate nicely or the DB will do it for us |
||
1199 | // non-nicely (dangling multi-byte chars, non-truncated version in cache). |
||
1200 | $comment = $wgContLang->truncate( $comment, 255 ); |
||
1201 | $this->lock(); // begin |
||
1202 | $status = $this->publish( $src, $flags, $options ); |
||
1203 | |||
1204 | if ( $status->successCount >= 2 ) { |
||
1205 | // There will be a copy+(one of move,copy,store). |
||
1206 | // The first succeeding does not commit us to updating the DB |
||
1207 | // since it simply copied the current version to a timestamped file name. |
||
1208 | // It is only *preferable* to avoid leaving such files orphaned. |
||
1209 | // Once the second operation goes through, then the current version was |
||
1210 | // updated and we must therefore update the DB too. |
||
1211 | $oldver = $status->value; |
||
1212 | if ( !$this->recordUpload2( $oldver, $comment, $pageText, $props, $timestamp, $user, $tags ) ) { |
||
1213 | $status->fatal( 'filenotfound', $srcPath ); |
||
1214 | } |
||
1215 | } |
||
1216 | |||
1217 | $this->unlock(); // done |
||
1218 | |||
1219 | return $status; |
||
1220 | } |
||
1221 | |||
1222 | /** |
||
1223 | * Record a file upload in the upload log and the image table |
||
1224 | * @param string $oldver |
||
1225 | * @param string $desc |
||
1226 | * @param string $license |
||
1227 | * @param string $copyStatus |
||
1228 | * @param string $source |
||
1229 | * @param bool $watch |
||
1230 | * @param string|bool $timestamp |
||
1231 | * @param User|null $user User object or null to use $wgUser |
||
1232 | * @return bool |
||
1233 | */ |
||
1234 | function recordUpload( $oldver, $desc, $license = '', $copyStatus = '', $source = '', |
||
1235 | $watch = false, $timestamp = false, User $user = null ) { |
||
1236 | if ( !$user ) { |
||
1237 | global $wgUser; |
||
1238 | $user = $wgUser; |
||
1239 | } |
||
1240 | |||
1241 | $pageText = SpecialUpload::getInitialPageText( $desc, $license, $copyStatus, $source ); |
||
1242 | |||
1243 | if ( !$this->recordUpload2( $oldver, $desc, $pageText, false, $timestamp, $user ) ) { |
||
1244 | return false; |
||
1245 | } |
||
1246 | |||
1247 | if ( $watch ) { |
||
1248 | $user->addWatch( $this->getTitle() ); |
||
1249 | } |
||
1250 | |||
1251 | return true; |
||
1252 | } |
||
1253 | |||
1254 | /** |
||
1255 | * Record a file upload in the upload log and the image table |
||
1256 | * @param string $oldver |
||
1257 | * @param string $comment |
||
1258 | * @param string $pageText |
||
1259 | * @param bool|array $props |
||
1260 | * @param string|bool $timestamp |
||
1261 | * @param null|User $user |
||
1262 | * @param string[] $tags |
||
1263 | * @return bool |
||
1264 | */ |
||
1265 | function recordUpload2( |
||
1266 | $oldver, $comment, $pageText, $props = false, $timestamp = false, $user = null, $tags = [] |
||
1267 | ) { |
||
1268 | if ( is_null( $user ) ) { |
||
1269 | global $wgUser; |
||
1270 | $user = $wgUser; |
||
1271 | } |
||
1272 | |||
1273 | $dbw = $this->repo->getMasterDB(); |
||
1274 | |||
1275 | # Imports or such might force a certain timestamp; otherwise we generate |
||
1276 | # it and can fudge it slightly to keep (name,timestamp) unique on re-upload. |
||
1277 | if ( $timestamp === false ) { |
||
1278 | $timestamp = $dbw->timestamp(); |
||
1279 | $allowTimeKludge = true; |
||
1280 | } else { |
||
1281 | $allowTimeKludge = false; |
||
1282 | } |
||
1283 | |||
1284 | $props = $props ?: $this->repo->getFileProps( $this->getVirtualUrl() ); |
||
1285 | $props['description'] = $comment; |
||
1286 | $props['user'] = $user->getId(); |
||
1287 | $props['user_text'] = $user->getName(); |
||
1288 | $props['timestamp'] = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW |
||
1289 | $this->setProps( $props ); |
||
1290 | |||
1291 | # Fail now if the file isn't there |
||
1292 | if ( !$this->fileExists ) { |
||
1293 | wfDebug( __METHOD__ . ": File " . $this->getRel() . " went missing!\n" ); |
||
1294 | |||
1295 | return false; |
||
1296 | } |
||
1297 | |||
1298 | $dbw->startAtomic( __METHOD__ ); |
||
1299 | |||
1300 | # Test to see if the row exists using INSERT IGNORE |
||
1301 | # This avoids race conditions by locking the row until the commit, and also |
||
1302 | # doesn't deadlock. SELECT FOR UPDATE causes a deadlock for every race condition. |
||
1303 | $dbw->insert( 'image', |
||
1304 | [ |
||
1305 | 'img_name' => $this->getName(), |
||
1306 | 'img_size' => $this->size, |
||
1307 | 'img_width' => intval( $this->width ), |
||
1308 | 'img_height' => intval( $this->height ), |
||
1309 | 'img_bits' => $this->bits, |
||
1310 | 'img_media_type' => $this->media_type, |
||
1311 | 'img_major_mime' => $this->major_mime, |
||
1312 | 'img_minor_mime' => $this->minor_mime, |
||
1313 | 'img_timestamp' => $timestamp, |
||
1314 | 'img_description' => $comment, |
||
1315 | 'img_user' => $user->getId(), |
||
1316 | 'img_user_text' => $user->getName(), |
||
1317 | 'img_metadata' => $dbw->encodeBlob( $this->metadata ), |
||
1318 | 'img_sha1' => $this->sha1 |
||
1319 | ], |
||
1320 | __METHOD__, |
||
1321 | 'IGNORE' |
||
1322 | ); |
||
1323 | |||
1324 | $reupload = ( $dbw->affectedRows() == 0 ); |
||
1325 | if ( $reupload ) { |
||
1326 | if ( $allowTimeKludge ) { |
||
1327 | # Use LOCK IN SHARE MODE to ignore any transaction snapshotting |
||
1328 | $ltimestamp = $dbw->selectField( |
||
1329 | 'image', |
||
1330 | 'img_timestamp', |
||
1331 | [ 'img_name' => $this->getName() ], |
||
1332 | __METHOD__, |
||
1333 | [ 'LOCK IN SHARE MODE' ] |
||
1334 | ); |
||
1335 | $lUnixtime = $ltimestamp ? wfTimestamp( TS_UNIX, $ltimestamp ) : false; |
||
1336 | # Avoid a timestamp that is not newer than the last version |
||
1337 | # TODO: the image/oldimage tables should be like page/revision with an ID field |
||
1338 | if ( $lUnixtime && wfTimestamp( TS_UNIX, $timestamp ) <= $lUnixtime ) { |
||
1339 | sleep( 1 ); // fast enough re-uploads would go far in the future otherwise |
||
1340 | $timestamp = $dbw->timestamp( $lUnixtime + 1 ); |
||
1341 | $this->timestamp = wfTimestamp( TS_MW, $timestamp ); // DB -> TS_MW |
||
1342 | } |
||
1343 | } |
||
1344 | |||
1345 | # (bug 34993) Note: $oldver can be empty here, if the previous |
||
1346 | # version of the file was broken. Allow registration of the new |
||
1347 | # version to continue anyway, because that's better than having |
||
1348 | # an image that's not fixable by user operations. |
||
1349 | # Collision, this is an update of a file |
||
1350 | # Insert previous contents into oldimage |
||
1351 | $dbw->insertSelect( 'oldimage', 'image', |
||
1352 | [ |
||
1353 | 'oi_name' => 'img_name', |
||
1354 | 'oi_archive_name' => $dbw->addQuotes( $oldver ), |
||
1355 | 'oi_size' => 'img_size', |
||
1356 | 'oi_width' => 'img_width', |
||
1357 | 'oi_height' => 'img_height', |
||
1358 | 'oi_bits' => 'img_bits', |
||
1359 | 'oi_timestamp' => 'img_timestamp', |
||
1360 | 'oi_description' => 'img_description', |
||
1361 | 'oi_user' => 'img_user', |
||
1362 | 'oi_user_text' => 'img_user_text', |
||
1363 | 'oi_metadata' => 'img_metadata', |
||
1364 | 'oi_media_type' => 'img_media_type', |
||
1365 | 'oi_major_mime' => 'img_major_mime', |
||
1366 | 'oi_minor_mime' => 'img_minor_mime', |
||
1367 | 'oi_sha1' => 'img_sha1' |
||
1368 | ], |
||
1369 | [ 'img_name' => $this->getName() ], |
||
1370 | __METHOD__ |
||
1371 | ); |
||
1372 | |||
1373 | # Update the current image row |
||
1374 | $dbw->update( 'image', |
||
1375 | [ |
||
1376 | 'img_size' => $this->size, |
||
1377 | 'img_width' => intval( $this->width ), |
||
1378 | 'img_height' => intval( $this->height ), |
||
1379 | 'img_bits' => $this->bits, |
||
1380 | 'img_media_type' => $this->media_type, |
||
1381 | 'img_major_mime' => $this->major_mime, |
||
1382 | 'img_minor_mime' => $this->minor_mime, |
||
1383 | 'img_timestamp' => $timestamp, |
||
1384 | 'img_description' => $comment, |
||
1385 | 'img_user' => $user->getId(), |
||
1386 | 'img_user_text' => $user->getName(), |
||
1387 | 'img_metadata' => $dbw->encodeBlob( $this->metadata ), |
||
1388 | 'img_sha1' => $this->sha1 |
||
1389 | ], |
||
1390 | [ 'img_name' => $this->getName() ], |
||
1391 | __METHOD__ |
||
1392 | ); |
||
1393 | } |
||
1394 | |||
1395 | $descTitle = $this->getTitle(); |
||
1396 | $descId = $descTitle->getArticleID(); |
||
1397 | $wikiPage = new WikiFilePage( $descTitle ); |
||
1398 | $wikiPage->setFile( $this ); |
||
1399 | |||
1400 | // Add the log entry... |
||
1401 | $logEntry = new ManualLogEntry( 'upload', $reupload ? 'overwrite' : 'upload' ); |
||
1402 | $logEntry->setTimestamp( $this->timestamp ); |
||
1403 | $logEntry->setPerformer( $user ); |
||
1404 | $logEntry->setComment( $comment ); |
||
1405 | $logEntry->setTarget( $descTitle ); |
||
1406 | // Allow people using the api to associate log entries with the upload. |
||
1407 | // Log has a timestamp, but sometimes different from upload timestamp. |
||
1408 | $logEntry->setParameters( |
||
1409 | [ |
||
1410 | 'img_sha1' => $this->sha1, |
||
1411 | 'img_timestamp' => $timestamp, |
||
1412 | ] |
||
1413 | ); |
||
1414 | // Note we keep $logId around since during new image |
||
1415 | // creation, page doesn't exist yet, so log_page = 0 |
||
1416 | // but we want it to point to the page we're making, |
||
1417 | // so we later modify the log entry. |
||
1418 | // For a similar reason, we avoid making an RC entry |
||
1419 | // now and wait until the page exists. |
||
1420 | $logId = $logEntry->insert(); |
||
1421 | |||
1422 | if ( $descTitle->exists() ) { |
||
1423 | // Use own context to get the action text in content language |
||
1424 | $formatter = LogFormatter::newFromEntry( $logEntry ); |
||
1425 | $formatter->setContext( RequestContext::newExtraneousContext( $descTitle ) ); |
||
1426 | $editSummary = $formatter->getPlainActionText(); |
||
1427 | |||
1428 | $nullRevision = Revision::newNullRevision( |
||
1429 | $dbw, |
||
1430 | $descId, |
||
1431 | $editSummary, |
||
1432 | false, |
||
1433 | $user |
||
1434 | ); |
||
1435 | if ( $nullRevision ) { |
||
1436 | $nullRevision->insertOn( $dbw ); |
||
1437 | Hooks::run( |
||
1438 | 'NewRevisionFromEditComplete', |
||
1439 | [ $wikiPage, $nullRevision, $nullRevision->getParentId(), $user ] |
||
1440 | ); |
||
1441 | $wikiPage->updateRevisionOn( $dbw, $nullRevision ); |
||
1442 | // Associate null revision id |
||
1443 | $logEntry->setAssociatedRevId( $nullRevision->getId() ); |
||
1444 | } |
||
1445 | |||
1446 | $newPageContent = null; |
||
1447 | } else { |
||
1448 | // Make the description page and RC log entry post-commit |
||
1449 | $newPageContent = ContentHandler::makeContent( $pageText, $descTitle ); |
||
1450 | } |
||
1451 | |||
1452 | # Defer purges, page creation, and link updates in case they error out. |
||
1453 | # The most important thing is that files and the DB registry stay synced. |
||
1454 | $dbw->endAtomic( __METHOD__ ); |
||
1455 | |||
1456 | # Do some cache purges after final commit so that: |
||
1457 | # a) Changes are more likely to be seen post-purge |
||
1458 | # b) They won't cause rollback of the log publish/update above |
||
1459 | DeferredUpdates::addUpdate( |
||
1460 | new AutoCommitUpdate( |
||
1461 | $dbw, |
||
1462 | __METHOD__, |
||
1463 | function () use ( |
||
1464 | $reupload, $wikiPage, $newPageContent, $comment, $user, |
||
1465 | $logEntry, $logId, $descId, $tags |
||
1466 | ) { |
||
1467 | # Update memcache after the commit |
||
1468 | $this->invalidateCache(); |
||
1469 | |||
1470 | $updateLogPage = false; |
||
1471 | if ( $newPageContent ) { |
||
1472 | # New file page; create the description page. |
||
1473 | # There's already a log entry, so don't make a second RC entry |
||
1474 | # CDN and file cache for the description page are purged by doEditContent. |
||
1475 | $status = $wikiPage->doEditContent( |
||
1476 | $newPageContent, |
||
1477 | $comment, |
||
1478 | EDIT_NEW | EDIT_SUPPRESS_RC, |
||
1479 | false, |
||
1480 | $user |
||
1481 | ); |
||
1482 | |||
1483 | if ( isset( $status->value['revision'] ) ) { |
||
1484 | /** @var $rev Revision */ |
||
1485 | $rev = $status->value['revision']; |
||
1486 | // Associate new page revision id |
||
1487 | $logEntry->setAssociatedRevId( $rev->getId() ); |
||
1488 | } |
||
1489 | // This relies on the resetArticleID() call in WikiPage::insertOn(), |
||
1490 | // which is triggered on $descTitle by doEditContent() above. |
||
1491 | if ( isset( $status->value['revision'] ) ) { |
||
1492 | /** @var $rev Revision */ |
||
1493 | $rev = $status->value['revision']; |
||
1494 | $updateLogPage = $rev->getPage(); |
||
1495 | } |
||
1496 | } else { |
||
1497 | # Existing file page: invalidate description page cache |
||
1498 | $wikiPage->getTitle()->invalidateCache(); |
||
1499 | $wikiPage->getTitle()->purgeSquid(); |
||
1500 | # Allow the new file version to be patrolled from the page footer |
||
1501 | Article::purgePatrolFooterCache( $descId ); |
||
1502 | } |
||
1503 | |||
1504 | # Update associated rev id. This should be done by $logEntry->insert() earlier, |
||
1505 | # but setAssociatedRevId() wasn't called at that point yet... |
||
1506 | $logParams = $logEntry->getParameters(); |
||
1507 | $logParams['associated_rev_id'] = $logEntry->getAssociatedRevId(); |
||
1508 | $update = [ 'log_params' => LogEntryBase::makeParamBlob( $logParams ) ]; |
||
1509 | if ( $updateLogPage ) { |
||
1510 | # Also log page, in case where we just created it above |
||
1511 | $update['log_page'] = $updateLogPage; |
||
1512 | } |
||
1513 | $this->getRepo()->getMasterDB()->update( |
||
1514 | 'logging', |
||
1515 | $update, |
||
1516 | [ 'log_id' => $logId ], |
||
1517 | __METHOD__ |
||
1518 | ); |
||
1519 | $this->getRepo()->getMasterDB()->insert( |
||
1520 | 'log_search', |
||
1521 | [ |
||
1522 | 'ls_field' => 'associated_rev_id', |
||
1523 | 'ls_value' => $logEntry->getAssociatedRevId(), |
||
1524 | 'ls_log_id' => $logId, |
||
1525 | ], |
||
1526 | __METHOD__ |
||
1527 | ); |
||
1528 | |||
1529 | # Add change tags, if any |
||
1530 | if ( $tags ) { |
||
1531 | $logEntry->setTags( $tags ); |
||
1532 | } |
||
1533 | |||
1534 | # Uploads can be patrolled |
||
1535 | $logEntry->setIsPatrollable( true ); |
||
1536 | |||
1537 | # Now that the log entry is up-to-date, make an RC entry. |
||
1538 | $logEntry->publish( $logId ); |
||
1539 | |||
1540 | # Run hook for other updates (typically more cache purging) |
||
1541 | Hooks::run( 'FileUpload', [ $this, $reupload, !$newPageContent ] ); |
||
1542 | |||
1543 | if ( $reupload ) { |
||
1544 | # Delete old thumbnails |
||
1545 | $this->purgeThumbnails(); |
||
1546 | # Remove the old file from the CDN cache |
||
1547 | DeferredUpdates::addUpdate( |
||
1548 | new CdnCacheUpdate( [ $this->getUrl() ] ), |
||
1549 | DeferredUpdates::PRESEND |
||
1550 | ); |
||
1551 | } else { |
||
1552 | # Update backlink pages pointing to this title if created |
||
1553 | LinksUpdate::queueRecursiveJobsForTable( $this->getTitle(), 'imagelinks' ); |
||
1554 | } |
||
1555 | |||
1556 | $this->prerenderThumbnails(); |
||
1557 | } |
||
1558 | ), |
||
1559 | DeferredUpdates::PRESEND |
||
1560 | ); |
||
1561 | |||
1562 | if ( !$reupload ) { |
||
1563 | # This is a new file, so update the image count |
||
1564 | DeferredUpdates::addUpdate( SiteStatsUpdate::factory( [ 'images' => 1 ] ) ); |
||
1565 | } |
||
1566 | |||
1567 | # Invalidate cache for all pages using this file |
||
1568 | DeferredUpdates::addUpdate( new HTMLCacheUpdate( $this->getTitle(), 'imagelinks' ) ); |
||
1569 | |||
1570 | return true; |
||
1571 | } |
||
1572 | |||
1573 | /** |
||
1574 | * Move or copy a file to its public location. If a file exists at the |
||
1575 | * destination, move it to an archive. Returns a FileRepoStatus object with |
||
1576 | * the archive name in the "value" member on success. |
||
1577 | * |
||
1578 | * The archive name should be passed through to recordUpload for database |
||
1579 | * registration. |
||
1580 | * |
||
1581 | * @param string|FSFile $src Local filesystem path or virtual URL to the source image |
||
1582 | * @param int $flags A bitwise combination of: |
||
1583 | * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy |
||
1584 | * @param array $options Optional additional parameters |
||
1585 | * @return Status On success, the value member contains the |
||
1586 | * archive name, or an empty string if it was a new file. |
||
1587 | */ |
||
1588 | function publish( $src, $flags = 0, array $options = [] ) { |
||
1591 | |||
1592 | /** |
||
1593 | * Move or copy a file to a specified location. Returns a FileRepoStatus |
||
1594 | * object with the archive name in the "value" member on success. |
||
1595 | * |
||
1596 | * The archive name should be passed through to recordUpload for database |
||
1597 | * registration. |
||
1598 | * |
||
1599 | * @param string|FSFile $src Local filesystem path or virtual URL to the source image |
||
1600 | * @param string $dstRel Target relative path |
||
1601 | * @param int $flags A bitwise combination of: |
||
1602 | * File::DELETE_SOURCE Delete the source file, i.e. move rather than copy |
||
1603 | * @param array $options Optional additional parameters |
||
1604 | * @return Status On success, the value member contains the |
||
1605 | * archive name, or an empty string if it was a new file. |
||
1606 | */ |
||
1607 | function publishTo( $src, $dstRel, $flags = 0, array $options = [] ) { |
||
1608 | $srcPath = ( $src instanceof FSFile ) ? $src->getPath() : $src; |
||
1609 | |||
1610 | $repo = $this->getRepo(); |
||
1611 | if ( $repo->getReadOnlyReason() !== false ) { |
||
1612 | return $this->readOnlyFatalStatus(); |
||
1613 | } |
||
1614 | |||
1615 | $this->lock(); // begin |
||
1616 | |||
1617 | $archiveName = wfTimestamp( TS_MW ) . '!' . $this->getName(); |
||
1618 | $archiveRel = 'archive/' . $this->getHashPath() . $archiveName; |
||
1619 | |||
1620 | if ( $repo->hasSha1Storage() ) { |
||
1621 | $sha1 = $repo->isVirtualUrl( $srcPath ) |
||
1622 | ? $repo->getFileSha1( $srcPath ) |
||
1623 | : FSFile::getSha1Base36FromPath( $srcPath ); |
||
1624 | /** @var FileBackendDBRepoWrapper $wrapperBackend */ |
||
1625 | $wrapperBackend = $repo->getBackend(); |
||
1626 | $dst = $wrapperBackend->getPathForSHA1( $sha1 ); |
||
1627 | $status = $repo->quickImport( $src, $dst ); |
||
1628 | if ( $flags & File::DELETE_SOURCE ) { |
||
1629 | unlink( $srcPath ); |
||
1630 | } |
||
1631 | |||
1632 | if ( $this->exists() ) { |
||
1650 | |||
1651 | /** getLinksTo inherited */ |
||
1652 | /** getExifData inherited */ |
||
1653 | /** isLocal inherited */ |
||
1654 | /** wasDeleted inherited */ |
||
1655 | |||
1656 | /** |
||
1657 | * Move file to the new title |
||
1658 | * |
||
1659 | * Move current, old version and all thumbnails |
||
1660 | * to the new filename. Old file is deleted. |
||
1661 | * |
||
1662 | * Cache purging is done; checks for validity |
||
1663 | * and logging are caller's responsibility |
||
1664 | * |
||
1665 | * @param Title $target New file name |
||
1666 | * @return Status |
||
1667 | */ |
||
1668 | function move( $target ) { |
||
1713 | |||
1714 | /** |
||
1715 | * Delete all versions of the file. |
||
1716 | * |
||
1717 | * Moves the files into an archive directory (or deletes them) |
||
1718 | * and removes the database rows. |
||
1719 | * |
||
1720 | * Cache purging is done; logging is caller's responsibility. |
||
1721 | * |
||
1722 | * @param string $reason |
||
1723 | * @param bool $suppress |
||
1724 | * @param User|null $user |
||
1725 | * @return Status |
||
1726 | */ |
||
1727 | function delete( $reason, $suppress = false, $user = null ) { |
||
1769 | |||
1770 | /** |
||
1771 | * Delete an old version of the file. |
||
1772 | * |
||
1773 | * Moves the file into an archive directory (or deletes it) |
||
1774 | * and removes the database row. |
||
1775 | * |
||
1776 | * Cache purging is done; logging is caller's responsibility. |
||
1777 | * |
||
1778 | * @param string $archiveName |
||
1779 | * @param string $reason |
||
1780 | * @param bool $suppress |
||
1781 | * @param User|null $user |
||
1782 | * @throws MWException Exception on database or file store failure |
||
1783 | * @return Status |
||
1784 | */ |
||
1785 | function deleteOld( $archiveName, $reason, $suppress = false, $user = null ) { |
||
1809 | |||
1810 | /** |
||
1811 | * Restore all or specified deleted revisions to the given file. |
||
1812 | * Permissions and logging are left to the caller. |
||
1813 | * |
||
1814 | * May throw database exceptions on error. |
||
1815 | * |
||
1816 | * @param array $versions Set of record ids of deleted items to restore, |
||
1817 | * or empty to restore all revisions. |
||
1818 | * @param bool $unsuppress |
||
1819 | * @return Status |
||
1820 | */ |
||
1821 | function restore( $versions = [], $unsuppress = false ) { |
||
1845 | |||
1846 | /** isMultipage inherited */ |
||
1847 | /** pageCount inherited */ |
||
1848 | /** scaleHeight inherited */ |
||
1849 | /** getImageSize inherited */ |
||
1850 | |||
1851 | /** |
||
1852 | * Get the URL of the file description page. |
||
1853 | * @return string |
||
1854 | */ |
||
1855 | function getDescriptionUrl() { |
||
1858 | |||
1859 | /** |
||
1860 | * Get the HTML text of the description page |
||
1861 | * This is not used by ImagePage for local files, since (among other things) |
||
1862 | * it skips the parser cache. |
||
1863 | * |
||
1864 | * @param Language $lang What language to get description in (Optional) |
||
1865 | * @return bool|mixed |
||
1866 | */ |
||
1867 | function getDescriptionText( $lang = null ) { |
||
1880 | |||
1881 | /** |
||
1882 | * @param int $audience |
||
1883 | * @param User $user |
||
1884 | * @return string |
||
1885 | */ |
||
1886 | View Code Duplication | function getDescription( $audience = self::FOR_PUBLIC, User $user = null ) { |
|
1898 | |||
1899 | /** |
||
1900 | * @return bool|string |
||
1901 | */ |
||
1902 | function getTimestamp() { |
||
1907 | |||
1908 | /** |
||
1909 | * @return bool|string |
||
1910 | */ |
||
1911 | public function getDescriptionTouched() { |
||
1926 | |||
1927 | /** |
||
1928 | * @return string |
||
1929 | */ |
||
1930 | function getSha1() { |
||
1951 | |||
1952 | /** |
||
1953 | * @return bool Whether to cache in RepoGroup (this avoids OOMs) |
||
1954 | */ |
||
1955 | function isCacheable() { |
||
1962 | |||
1963 | /** |
||
1964 | * @return Status |
||
1965 | * @since 1.28 |
||
1966 | */ |
||
1967 | public function acquireFileLock() { |
||
1972 | |||
1973 | /** |
||
1974 | * @return Status |
||
1975 | * @since 1.28 |
||
1976 | */ |
||
1977 | public function releaseFileLock() { |
||
1982 | |||
1983 | /** |
||
1984 | * Start an atomic DB section and lock the image for update |
||
1985 | * or increments a reference counter if the lock is already held |
||
1986 | * |
||
1987 | * This method should not be used outside of LocalFile/LocalFile*Batch |
||
1988 | * |
||
1989 | * @throws LocalFileLockError Throws an error if the lock was not acquired |
||
1990 | * @return bool Whether the file lock owns/spawned the DB transaction |
||
1991 | */ |
||
1992 | public function lock() { |
||
2028 | |||
2029 | /** |
||
2030 | * Decrement the lock reference count and end the atomic section if it reaches zero |
||
2031 | * |
||
2032 | * This method should not be used outside of LocalFile/LocalFile*Batch |
||
2033 | * |
||
2034 | * The commit and loc release will happen when no atomic sections are active, which |
||
2035 | * may happen immediately or at some point after calling this |
||
2036 | */ |
||
2037 | public function unlock() { |
||
2047 | |||
2048 | /** |
||
2049 | * @return Status |
||
2050 | */ |
||
2051 | protected function readOnlyFatalStatus() { |
||
2055 | |||
2056 | /** |
||
2057 | * Clean up any dangling locks |
||
2058 | */ |
||
2059 | function __destruct() { |
||
2062 | } // LocalFile class |
||
2063 | |||
3162 |
If a method or function can return multiple different values and unless you are sure that you only can receive a single value in this context, we recommend to add an additional type check:
If this a common case that PHP Analyzer should handle natively, please let us know by opening an issue.