← Back
Editing: user-ip-address.php
<?php namespace Uncanny_Automator\Integrations\Common\Tokens; use Uncanny_Automator\Tokens\Token; class User_Ip_Address extends Token { /** * The IP of the visitor whose request sent the running background action, or null outside one. * * A background action runs in the site's own loopback request, whose client is the server. * * @since 8.1.1 * * @var string|null */ private static $dispatching_ip = null; /** * setup * * @return void */ public function setup() { $this->integration = 'COMMON'; $this->id = 'user_ip_address'; $this->name = esc_attr_x( 'User IP address', 'Token', 'uncanny-automator' ); } /** * parse * * @param mixed $replaceable * @param mixed $field_text * @param mixed $match * @param mixed $current_user * @return mixed */ public function parse( $replaceable, $field_text, $match, $current_user ) { if ( null !== self::$dispatching_ip ) { return self::$dispatching_ip; } return self::from_request(); } /** * The first non-empty client IP value from the current request. * * @since 8.1.1 * * @return string The IP, or 'N/A' when the request carries none. */ public static function from_request() { $headers = array( 'HTTP_CLIENT_IP', 'HTTP_X_FORWARDED_FOR', 'HTTP_X_REAL_IP', 'REMOTE_ADDR' ); foreach ( $headers as $header ) { if ( ! isset( $_SERVER[ $header ] ) ) { continue; } $raw = sanitize_text_field( wp_unslash( $_SERVER[ $header ] ) ); $values = 'HTTP_X_FORWARDED_FOR' === $header ? explode( ',', $raw ) : array( $raw ); foreach ( $values as $value ) { $ip = trim( $value ); if ( '' !== $ip ) { return $ip; } } } return 'N/A'; } /** * Makes the token give the dispatching visitor's IP while a background action runs. * * @since 8.1.1 * * @param string|null $ip The IP the dispatching request read, or null to read the current request again. * * @return void */ public static function use_dispatching_ip( $ip ) { self::$dispatching_ip = is_string( $ip ) && '' !== $ip ? sanitize_text_field( $ip ) : null; } }
Save File
Cancel