34 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
44 protected function __construct( array $restrictions =
null ) {
45 $this->validity = StatusValue::newGood();
46 if ( $restrictions !==
null ) {
47 $this->loadFromArray( $restrictions );
64 return new self( $restrictions );
73 $restrictions = FormatJson::decode( $json,
true );
74 if ( !is_array( $restrictions ) ) {
75 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
77 return new self( $restrictions );
80 private function loadFromArray( array $restrictions ) {
81 static $neededKeys = [
'IPAddresses' ];
83 $keys = array_keys( $restrictions );
84 $missingKeys = array_diff( $neededKeys, $keys );
86 throw new InvalidArgumentException(
87 'Array is missing required keys: ' . implode(
', ', $missingKeys )
91 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
92 throw new InvalidArgumentException(
'IPAddresses is not an array' );
94 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
95 if ( !IPUtils::isIPAddress( $ip ) ) {
96 $this->validity->fatal(
'restrictionsfield-badip', $ip );
99 $this->ipAddresses = $restrictions[
'IPAddresses'];
101 if ( isset( $restrictions[
'Pages'] ) ) {
102 if ( !is_array( $restrictions[
'Pages'] ) ) {
103 throw new InvalidArgumentException(
'Pages is not an array of page names' );
105 foreach ( $restrictions[
'Pages'] as $page ) {
106 if ( !is_string( $page ) ) {
107 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
110 $this->pages = $restrictions[
'Pages'];
119 $arr = [
'IPAddresses' => $this->ipAddresses ];
120 if ( count( $this->pages ) ) {
121 $arr[
'Pages'] = $this->pages;
131 public function toJson( $pretty =
false ) {
132 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
148 $status = Status::newGood();
149 $status->setResult( $ok === array_filter( $ok ), $ok );
161 if ( !$this->checkPage( $target ) ) {
162 return StatusValue::newFatal(
'session-page-restricted' );
164 return StatusValue::newGood();
173 $set =
new IPSet( $this->ipAddresses );
174 return $set->match( $ip );
183 private function checkPage(
LinkTarget $target ) {
184 if ( count( $this->pages ) === 0 ) {
187 $pagesNormalized = array_map(
static function ( $titleText ) {
188 $title = Title::newFromText( $titleText );
189 return $title ? $title->getPrefixedText() :
'';
191 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );