client = $client; } public function register() { add_action( 'admin_post_thisbig_connect', array( $this, 'start' ) ); add_action( 'admin_post_thisbig_disconnect', array( $this, 'disconnect' ) ); } /** ThisBig's page in the admin, with any query args. */ public static function settings_url( $args = array() ) { return add_query_arg( $args, admin_url( 'admin.php?page=' . ThisBig_Settings::PAGE ) ); } /** The portal address the Connect button opens, with a state only this admin's return will match. */ public function connect_url() { $state = wp_generate_password( 32, false ); set_transient( $this->state_key(), $state, self::STATE_TTL ); return add_query_arg( array( 'platform' => 'wordpress', 'site' => rawurlencode( home_url( '/' ) ), 'return' => rawurlencode( self::settings_url() ), 'state' => $state, ), THISBIG_PORTAL . '/connect' ); } public function start() { ThisBig_Plugin::admin_post( 'manage_options', 'thisbig_connect', $this->not_admin() ); add_filter( 'allowed_redirect_hosts', array( $this, 'allow_portal' ) ); wp_safe_redirect( $this->connect_url() ); exit; } /** The portal is the one other host Connect may send an administrator to. */ public function allow_portal( $hosts ) { $hosts[] = (string) wp_parse_url( THISBIG_PORTAL, PHP_URL_HOST ); return $hosts; } /** * Back from the portal with `thisbig_code` and `state`. Called when the * settings page loads; the state must be the one this admin was given. * * @return true|WP_Error|null Null when this isn't a return from the portal. */ public function handle_return( array $query ) { if ( empty( $query['thisbig_code'] ) ) { return null; } if ( ! current_user_can( 'manage_options' ) ) { return new WP_Error( 'thisbig_forbidden', $this->not_admin() ); } $expected = get_transient( $this->state_key() ); delete_transient( $this->state_key() ); $state = isset( $query['state'] ) ? sanitize_text_field( wp_unslash( $query['state'] ) ) : ''; if ( ! is_string( $expected ) || '' === $state || ! hash_equals( $expected, $state ) ) { return new WP_Error( 'thisbig_state', __( 'That connection didn’t start here. Connect again.', 'thisbig' ) ); } return $this->client->exchange( sanitize_text_field( wp_unslash( $query['thisbig_code'] ) ) ); } public function disconnect() { ThisBig_Plugin::admin_post( 'manage_options', 'thisbig_disconnect', __( 'You need to be an administrator to disconnect ThisBig.', 'thisbig' ) ); $this->client->disconnect(); wp_safe_redirect( self::settings_url( array( 'thisbig' => 'disconnected' ) ) ); exit; } /** The state this admin was given, kept until they're back from the portal. */ private function state_key() { return 'thisbig_connect_' . get_current_user_id(); } private function not_admin() { return __( 'You need to be an administrator to connect ThisBig.', 'thisbig' ); } }