28 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
39 protected function __construct( ?array $restrictions =
null ) {
40 $this->validity = StatusValue::newGood();
41 if ( $restrictions !==
null ) {
42 $this->loadFromArray( $restrictions );
59 return new self( $restrictions );
68 $restrictions = FormatJson::decode( $json,
true );
69 if ( !is_array( $restrictions ) ) {
70 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
72 return new self( $restrictions );
75 private function loadFromArray( array $restrictions ) {
76 static $neededKeys = [
'IPAddresses' ];
78 $keys = array_keys( $restrictions );
79 $missingKeys = array_diff( $neededKeys, $keys );
81 throw new InvalidArgumentException(
82 'Array is missing required keys: ' . implode(
', ', $missingKeys )
86 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
87 throw new InvalidArgumentException(
'IPAddresses is not an array' );
89 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
90 if ( !IPUtils::isIPAddress( $ip ) ) {
91 $this->validity->fatal(
'restrictionsfield-badip', $ip );
94 $this->ipAddresses = $restrictions[
'IPAddresses'];
96 if ( isset( $restrictions[
'Pages'] ) ) {
97 if ( !is_array( $restrictions[
'Pages'] ) ) {
98 throw new InvalidArgumentException(
'Pages is not an array of page names' );
100 foreach ( $restrictions[
'Pages'] as $page ) {
101 if ( !is_string( $page ) ) {
102 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
105 $this->pages = $restrictions[
'Pages'];
114 $arr = [
'IPAddresses' => $this->ipAddresses ];
115 if ( count( $this->pages ) ) {
116 $arr[
'Pages'] = $this->pages;
126 public function toJson( $pretty =
false ) {
127 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
143 $status = Status::newGood();
144 $status->setResult( $ok === array_filter( $ok ), $ok );
156 if ( !$this->checkPage( $target ) ) {
157 return StatusValue::newFatal(
'session-page-restricted' );
159 return StatusValue::newGood();
168 $set =
new IPSet( $this->ipAddresses );
169 return $set->match( $ip );
178 private function checkPage(
LinkTarget $target ) {
179 if ( count( $this->pages ) === 0 ) {
182 $pagesNormalized = array_map(
static function ( $titleText ) {
183 $title = Title::newFromText( $titleText );
184 return $title ? $title->getPrefixedText() :
'';
186 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );