10use InvalidArgumentException;
27 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
38 protected function __construct( ?array $restrictions =
null ) {
39 $this->validity = StatusValue::newGood();
40 if ( $restrictions !==
null ) {
41 $this->loadFromArray( $restrictions );
58 return new self( $restrictions );
67 $restrictions = FormatJson::decode( $json,
true );
68 if ( !is_array( $restrictions ) ) {
69 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
71 return new self( $restrictions );
74 private function loadFromArray( array $restrictions ) {
75 static $neededKeys = [
'IPAddresses' ];
77 $keys = array_keys( $restrictions );
78 $missingKeys = array_diff( $neededKeys, $keys );
80 throw new InvalidArgumentException(
81 'Array is missing required keys: ' . implode(
', ', $missingKeys )
85 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
86 throw new InvalidArgumentException(
'IPAddresses is not an array' );
88 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
89 if ( !IPUtils::isIPAddress( $ip ) ) {
90 $this->validity->fatal(
'restrictionsfield-badip', $ip );
93 $this->ipAddresses = $restrictions[
'IPAddresses'];
95 if ( isset( $restrictions[
'Pages'] ) ) {
96 if ( !is_array( $restrictions[
'Pages'] ) ) {
97 throw new InvalidArgumentException(
'Pages is not an array of page names' );
99 foreach ( $restrictions[
'Pages'] as $page ) {
100 if ( !is_string( $page ) ) {
101 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
104 $this->pages = $restrictions[
'Pages'];
113 $arr = [
'IPAddresses' => $this->ipAddresses ];
114 if ( count( $this->pages ) ) {
115 $arr[
'Pages'] = $this->pages;
125 public function toJson( $pretty =
false ) {
126 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
142 $status = Status::newGood();
143 $status->setResult( $ok === array_filter( $ok ), $ok );
155 if ( !$this->checkPage( $target ) ) {
156 return StatusValue::newFatal(
'session-page-restricted' );
158 return StatusValue::newGood();
167 $set =
new IPSet( $this->ipAddresses );
168 return $set->match( $ip );
177 private function checkPage(
LinkTarget $target ) {
178 if ( count( $this->pages ) === 0 ) {
181 $pagesNormalized = array_map(
static function ( $titleText ) {
182 $title = Title::newFromText( $titleText );
183 return $title ? $title->getPrefixedText() :
'';
185 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );
190class_alias( MWRestrictions::class,
'MWRestrictions' );
Generic operation result class Has warning/error list, boolean status and arbitrary value.