35 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
46 protected function __construct( ?array $restrictions =
null ) {
47 $this->validity = StatusValue::newGood();
48 if ( $restrictions !==
null ) {
49 $this->loadFromArray( $restrictions );
66 return new self( $restrictions );
75 $restrictions = FormatJson::decode( $json,
true );
76 if ( !is_array( $restrictions ) ) {
77 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
79 return new self( $restrictions );
82 private function loadFromArray( array $restrictions ) {
83 static $neededKeys = [
'IPAddresses' ];
85 $keys = array_keys( $restrictions );
86 $missingKeys = array_diff( $neededKeys, $keys );
88 throw new InvalidArgumentException(
89 'Array is missing required keys: ' . implode(
', ', $missingKeys )
93 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
94 throw new InvalidArgumentException(
'IPAddresses is not an array' );
96 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
97 if ( !IPUtils::isIPAddress( $ip ) ) {
98 $this->validity->fatal(
'restrictionsfield-badip', $ip );
101 $this->ipAddresses = $restrictions[
'IPAddresses'];
103 if ( isset( $restrictions[
'Pages'] ) ) {
104 if ( !is_array( $restrictions[
'Pages'] ) ) {
105 throw new InvalidArgumentException(
'Pages is not an array of page names' );
107 foreach ( $restrictions[
'Pages'] as $page ) {
108 if ( !is_string( $page ) ) {
109 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
112 $this->pages = $restrictions[
'Pages'];
121 $arr = [
'IPAddresses' => $this->ipAddresses ];
122 if ( count( $this->pages ) ) {
123 $arr[
'Pages'] = $this->pages;
133 public function toJson( $pretty =
false ) {
134 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
150 $status = Status::newGood();
151 $status->setResult( $ok === array_filter( $ok ), $ok );
163 if ( !$this->checkPage( $target ) ) {
164 return StatusValue::newFatal(
'session-page-restricted' );
166 return StatusValue::newGood();
175 $set =
new IPSet( $this->ipAddresses );
176 return $set->match( $ip );
185 private function checkPage(
LinkTarget $target ) {
186 if ( count( $this->pages ) === 0 ) {
189 $pagesNormalized = array_map(
static function ( $titleText ) {
190 $title = Title::newFromText( $titleText );
191 return $title ? $title->getPrefixedText() :
'';
193 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );