32 private $ipAddresses = [
'0.0.0.0/0',
'::/0' ];
42 protected function __construct( array $restrictions =
null ) {
43 $this->validity = StatusValue::newGood();
44 if ( $restrictions !==
null ) {
45 $this->loadFromArray( $restrictions );
62 return new self( $restrictions );
71 $restrictions = FormatJson::decode( $json,
true );
72 if ( !is_array( $restrictions ) ) {
73 throw new InvalidArgumentException(
'Invalid restrictions JSON' );
75 return new self( $restrictions );
78 private function loadFromArray( array $restrictions ) {
79 static $neededKeys = [
'IPAddresses' ];
81 $keys = array_keys( $restrictions );
82 $missingKeys = array_diff( $neededKeys, $keys );
84 throw new InvalidArgumentException(
85 'Array is missing required keys: ' . implode(
', ', $missingKeys )
89 if ( !is_array( $restrictions[
'IPAddresses'] ) ) {
90 throw new InvalidArgumentException(
'IPAddresses is not an array' );
92 foreach ( $restrictions[
'IPAddresses'] as $ip ) {
93 if ( !IPUtils::isIPAddress( $ip ) ) {
94 $this->validity->fatal(
'restrictionsfield-badip', $ip );
97 $this->ipAddresses = $restrictions[
'IPAddresses'];
99 if ( isset( $restrictions[
'Pages'] ) ) {
100 if ( !is_array( $restrictions[
'Pages'] ) ) {
101 throw new InvalidArgumentException(
'Pages is not an array of page names' );
103 foreach ( $restrictions[
'Pages'] as $page ) {
104 if ( !is_string( $page ) ) {
105 throw new InvalidArgumentException(
"Pages contains non-string value: $page" );
108 $this->pages = $restrictions[
'Pages'];
117 $arr = [
'IPAddresses' => $this->ipAddresses ];
118 if ( count( $this->pages ) ) {
119 $arr[
'Pages'] = $this->pages;
129 public function toJson( $pretty =
false ) {
130 return FormatJson::encode( $this->
toArray(), $pretty, FormatJson::ALL_OK );
146 $status = Status::newGood();
147 $status->setResult( $ok === array_filter( $ok ), $ok );
159 if ( !$this->checkPage( $target ) ) {
160 return StatusValue::newFatal(
'session-page-restricted' );
162 return StatusValue::newGood();
171 $set =
new IPSet( $this->ipAddresses );
172 return $set->match( $ip );
181 private function checkPage(
LinkTarget $target ) {
182 if ( count( $this->pages ) === 0 ) {
185 $pagesNormalized = array_map(
static function ( $titleText ) {
186 $title = Title::newFromText( $titleText );
187 return $title ? $title->getPrefixedText() :
'';
189 return in_array( Title::newFromLinkTarget( $target )->getPrefixedText(), $pagesNormalized,
true );