22 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
33 protected function __construct( ?array $restrictions =
null ) {
34 $this->validity = StatusValue::newGood();
35 if ( $restrictions !==
null ) {
36 $this->loadFromArray( $restrictions );
53 return new self( $restrictions );
62 $restrictions = FormatJson::decode( $json,
true );
63 if ( !is_array( $restrictions ) ) {
64 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
66 return new self( $restrictions );
69 private function loadFromArray( array $restrictions ) {
70 static $neededKeys = [
'IPAddresses' ];
72 $keys = array_keys( $restrictions );
73 $missingKeys = array_diff( $neededKeys, $keys );
75 throw new InvalidArgumentException(
76 'Array is missing required keys: ' . implode(
', ', $missingKeys )
80 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
81 throw new InvalidArgumentException(
'IPAddresses is not an array' );
83 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
84 if ( !IPUtils::isIPAddress( $ip ) ) {
85 $this->validity->fatal(
'restrictionsfield-badip', $ip );
88 $this->ipAddresses = $restrictions[
'IPAddresses'];
90 if ( isset( $restrictions[
'Pages'] ) ) {
91 if ( !is_array( $restrictions[
'Pages'] ) ) {
92 throw new InvalidArgumentException(
'Pages is not an array of page names' );
94 foreach ( $restrictions[
'Pages'] as $page ) {
95 if ( !is_string( $page ) ) {
96 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
99 $this->pages = $restrictions[
'Pages'];
108 $arr = [
'IPAddresses' => $this->ipAddresses ];
109 if ( count( $this->pages ) ) {
110 $arr[
'Pages'] = $this->pages;
120 public function toJson( $pretty =
false ) {
121 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
137 $status = Status::newGood();
138 $status->setResult( $ok === array_filter( $ok ), $ok );
150 if ( !$this->checkPage( $target ) ) {
151 return StatusValue::newFatal(
'session-page-restricted' );
153 return StatusValue::newGood();
162 $set =
new IPSet( $this->ipAddresses );
163 return $set->match( $ip );
172 private function checkPage(
LinkTarget $target ) {
173 if ( count( $this->pages ) === 0 ) {
176 $pagesNormalized = array_map(
static function ( $titleText ) {
177 $title = Title::newFromText( $titleText );
178 return $title ? $title->getPrefixedText() :
'';
180 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );