ConfiguredReadOnlyMode.php 2.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. /**
  3. * A read-only mode service which does not depend on LoadBalancer.
  4. * To obtain an instance, use MediaWikiServices::getInstance()->getConfiguredReadOnlyMode().
  5. *
  6. * @since 1.29
  7. */
  8. class ConfiguredReadOnlyMode {
  9. /** @var string|boolean|null */
  10. private $reason;
  11. /** @var string|null */
  12. private $reasonFile;
  13. /**
  14. * @param string|bool|null $reason Current reason for read-only mode, if known. null means look
  15. * in $reasonFile instead.
  16. * @param string|null $reasonFile A file to look in for a reason, if $reason is null. If it
  17. * exists and is non-empty, its contents are treated as the reason for read-only mode.
  18. * Otherwise, the wiki is not read-only.
  19. */
  20. public function __construct( $reason, $reasonFile = null ) {
  21. if ( $reason instanceof Config ) {
  22. // Before 1.34 we passed a whole Config object, which was overkill
  23. wfDeprecated( __METHOD__ . ' with Config passed to constructor', '1.34' );
  24. $reason = $reason->get( 'ReadOnly' );
  25. $reasonFile = $reason->get( 'ReadOnlyFile' );
  26. }
  27. $this->reason = $reason;
  28. $this->reasonFile = $reasonFile;
  29. }
  30. /**
  31. * Check whether the wiki is in read-only mode.
  32. *
  33. * @return bool
  34. */
  35. public function isReadOnly() {
  36. return $this->getReason() !== false;
  37. }
  38. /**
  39. * Get the value of $wgReadOnly or the contents of $wgReadOnlyFile.
  40. *
  41. * @return string|bool String when in read-only mode; false otherwise
  42. */
  43. public function getReason() {
  44. if ( $this->reason !== null ) {
  45. return $this->reason;
  46. }
  47. if ( $this->reasonFile === null ) {
  48. return false;
  49. }
  50. // Try the reason file
  51. if ( is_file( $this->reasonFile ) && filesize( $this->reasonFile ) > 0 ) {
  52. $this->reason = file_get_contents( $this->reasonFile );
  53. }
  54. // No need to try the reason file again
  55. $this->reasonFile = null;
  56. return $this->reason ?? false;
  57. }
  58. /**
  59. * Set the read-only mode, which will apply for the remainder of the
  60. * request or until a service reset.
  61. *
  62. * @param string|null $msg
  63. */
  64. public function setReason( $msg ) {
  65. $this->reason = $msg;
  66. }
  67. }