| 225 | |
| 226 | /** |
| 227 | * Get the HTTP Origin of the current request. |
| 228 | * |
| 229 | * @since 3.4.0 |
| 230 | * |
| 231 | * @return string URL of the origin. Empty string if no origin. |
| 232 | */ |
| 233 | function get_http_origin() { |
| 234 | $origin = ''; |
| 235 | if ( ! empty ( $_SERVER[ 'HTTP_ORIGIN' ] ) ) |
| 236 | $origin = $_SERVER[ 'HTTP_ORIGIN' ]; |
| 237 | |
| 238 | return apply_filters( 'http_origin', $origin ); |
| 239 | } |
| 240 | |
| 241 | /** |
| 242 | * Retrieve list of allowed http origins. |
| 243 | * |
| 244 | * @since 3.4.0 |
| 245 | * |
| 246 | * @return array Array of origin URLs. |
| 247 | */ |
| 248 | function get_allowed_http_origins() { |
| 249 | $admin_origin = parse_url( admin_url() ); |
| 250 | $home_origin = parse_url( home_url() ); |
| 251 | |
| 252 | // @todo preserve port? |
| 253 | $allowed_origins = array_unique( array( |
| 254 | 'http://' . $admin_origin[ 'host' ], |
| 255 | 'https://' . $admin_origin[ 'host' ], |
| 256 | 'http://' . $home_origin[ 'host' ], |
| 257 | 'https://' . $home_origin[ 'host' ], |
| 258 | ) ); |
| 259 | |
| 260 | return apply_filters( 'allowed_http_origins' , $allowed_origins ); |
| 261 | } |
| 262 | |
| 263 | /** |
| 264 | * Determines if the http origin is an authorized one. |
| 265 | * |
| 266 | * @since 3.4.0 |
| 267 | * |
| 268 | * @param string Origin URL. If not provided, the value of get_http_origin() is used. |
| 269 | * @return bool True if the origin is allowed. False otherwise. |
| 270 | */ |
| 271 | function is_allowed_http_origin( $origin = null ) { |
| 272 | $origin_arg = $origin; |
| 273 | |
| 274 | if ( null === $origin ) |
| 275 | $origin = get_http_origin(); |
| 276 | |
| 277 | if ( $origin && ! in_array( $origin, get_allowed_http_origins() ) ) |
| 278 | $origin = ''; |
| 279 | |
| 280 | return apply_filters( 'allowed_http_origin', $origin, $origin_arg ); |
| 281 | } |
| 282 | |
| 283 | /** |
| 284 | * Send Access-Control-Allow-Origin and related headers if the current request |
| 285 | * is from an allowed origin. |
| 286 | * |
| 287 | * @since 3.4.0 |
| 288 | * |
| 289 | * @return bool|string Returns the origin URL if headers are sent. Returns false |
| 290 | * if headers are not sent. |
| 291 | */ |
| 292 | function send_origin_headers() { |
| 293 | $origin = get_http_origin(); |
| 294 | if ( ! is_allowed_http_origin( $origin ) ) |
| 295 | return false; |
| 296 | |
| 297 | @header( 'Access-Control-Allow-Origin: ' . $origin ); |
| 298 | @header( 'Access-Control-Allow-Credentials: true' ); |
| 299 | |
| 300 | return $origin; |
| 301 | } |
| 302 | No newline at end of file |