+ /**
+ * Check the &origin= query parameter against the Origin: HTTP header and respond appropriately.
+ *
+ * If no origin parameter is present, nothing happens.
+ * If an origin parameter is present but doesn't match the Origin header, a 403 status code
+ * is set and false is returned.
+ * If the parameter and the header do match, the header is checked against $wgCrossSiteAJAXdomains
+ * and $wgCrossSiteAJAXdomainExceptions, and if the origin qualifies, the appropriate CORS
+ * headers are set.
+ *
+ * @return bool False if the caller should abort (403 case), true otherwise (all other cases)
+ */
+ protected function handleCORS() {
+ global $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions;
+
+ $originParam = $this->getParameter( 'origin' ); // defaults to null
+ if ( $originParam === null ) {
+ // No origin parameter, nothing to do
+ return true;
+ }
+
+ $request = $this->getRequest();
+ $response = $request->response();
+ // Origin: header is a space-separated list of origins, check all of them
+ $originHeader = $request->getHeader( 'Origin' );
+ if ( $originHeader === false ) {
+ $origins = array();
+ } else {
+ $origins = explode( ' ', $originHeader );
+ }
+ if ( !in_array( $originParam, $origins ) ) {
+ // origin parameter set but incorrect
+ // Send a 403 response
+ $message = HttpStatus::getMessage( 403 );
+ $response->header( "HTTP/1.1 403 $message", true, 403 );
+ $response->header( 'Cache-Control: no-cache' );
+ echo "'origin' parameter does not match Origin header\n";
+ return false;
+ }
+ if ( self::matchOrigin( $originParam, $wgCrossSiteAJAXdomains, $wgCrossSiteAJAXdomainExceptions ) ) {
+ $response->header( "Access-Control-Allow-Origin: $originParam" );
+ $response->header( 'Access-Control-Allow-Credentials: true' );
+ $this->getOutput()->addVaryHeader( 'Origin' );
+ }
+ return true;
+ }
+
+ /**
+ * Attempt to match an Origin header against a set of rules and a set of exceptions
+ * @param $value string Origin header
+ * @param $rules array Set of wildcard rules
+ * @param $exceptions array Set of wildcard rules
+ * @return bool True if $value matches a rule in $rules and doesn't match any rules in $exceptions, false otherwise
+ */
+ protected static function matchOrigin( $value, $rules, $exceptions ) {
+ foreach ( $rules as $rule ) {
+ if ( preg_match( self::wildcardToRegex( $rule ), $value ) ) {
+ // Rule matches, check exceptions
+ foreach ( $exceptions as $exc ) {
+ if ( preg_match( self::wildcardToRegex( $exc ), $value ) ) {
+ return false;
+ }
+ }
+ return true;
+ }
+ }
+ return false;
+ }
+
+ /**
+ * Helper function to convert wildcard string into a regex
+ * '*' => '.*?'
+ * '?' => '.'
+ *
+ * @param $wildcard string String with wildcards
+ * @return string Regular expression
+ */
+ protected static function wildcardToRegex( $wildcard ) {
+ $wildcard = preg_quote( $wildcard, '/' );
+ $wildcard = str_replace(
+ array( '\*', '\?' ),
+ array( '.*?', '.' ),
+ $wildcard
+ );
+ return "/https?:\/\/$wildcard/";
+ }
+