rest_url( WP360_NCA_REST_NAMESPACE . '/hit' ), 'postId' => (int) ( get_queried_object_id() ?: 0 ), ) ); } public static function register_route() { $namespaces = array( WP360_NCA_REST_NAMESPACE ); foreach ( $namespaces as $namespace ) { register_rest_route( $namespace, '/hit', array( 'methods' => 'POST', 'callback' => array( __CLASS__, 'record_hit' ), 'permission_callback' => '__return_true', 'args' => array( 'post_id' => array( 'type' => 'integer', 'required' => false, 'sanitize_callback' => 'absint', ), 'url' => array( 'type' => 'string', 'required' => false, ), ), ) ); } } public static function record_hit( WP_REST_Request $request ) { if ( self::is_bot() ) { return new WP_REST_Response( array( 'ok' => false, 'reason' => 'bot', ), 200 ); } if ( self::is_dnt() ) { return new WP_REST_Response( array( 'ok' => false, 'reason' => 'dnt', ), 200 ); } if ( self::is_rate_limited() ) { return new WP_REST_Response( array( 'ok' => false, 'reason' => 'rate_limited', ), 429 ); } $post_id = self::viewable_post_id( (int) $request->get_param( 'post_id' ) ); $url = self::sanitize_path( (string) $request->get_param( 'url' ) ); global $wpdb; $data = array( 'visitor_id' => self::visitor_id(), 'post_id' => $post_id > 0 ? $post_id : null, 'url' => $url, 'created_at' => current_time( 'mysql' ), ); $formats = array( '%s', '%d', '%s', '%s' ); $wpdb->insert( Wp360_NoCookie_Analytics_Database::table_name(), $data, $formats ); // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery -- Schreiben in die plugineigene Hits-Tabelle, dafuer gibt es keine WordPress-API. return new WP_REST_Response( array( 'ok' => true ), 201 ); } /** Pseudonymer Besucher-Hash: SHA-256 aus IP + User-Agent + geheimem Salt. Die Roh-IP wird nirgends gespeichert. */ private static function visitor_id() { $ip = self::client_ip(); $ua = self::user_agent(); return hash( 'sha256', $ip . '|' . $ua . '|' . Wp360_NoCookie_Analytics_Database::salt() ); } private static function user_agent() { return isset( $_SERVER['HTTP_USER_AGENT'] ) ? sanitize_text_field( wp_unslash( $_SERVER['HTTP_USER_AGENT'] ) ) : ''; } private static function client_ip() { $ip = isset( $_SERVER['REMOTE_ADDR'] ) ? sanitize_text_field( wp_unslash( $_SERVER['REMOTE_ADDR'] ) ) : ''; /** Erlaubt das Anpassen der Client-IP-Ermittlung, falls die Seite hinter einem Reverse-Proxy/CDN laeuft (z. B. X-Forwarded-For auswerten). */ return (string) apply_filters( 'wp360_nca_client_ip', $ip ); } private static function is_bot() { $ua = self::user_agent(); if ( $ua === '' ) { return true; } $is_bot = (bool) preg_match( '/bot|crawl|spider|slurp|mediapartners|facebookexternalhit|embedly|' . 'quora link preview|bitlybot|outbrain|pinterest|developers\.google|' . 'lighthouse|headless|preview|monitor|pingdom|uptime|gtmetrix/i', $ua ); /** Erlaubt zusaetzliche eigene Bot-Erkennung (z. B. projektspezifische Crawler), ohne die eingebaute Liste zu verlieren. */ return (bool) apply_filters( 'wp360_nca_is_bot', $is_bot, $ua ); } /** * Respektiert den Do-Not-Track/Global-Privacy-Control-Wunsch des Browsers * -- serverseitig geprueft (nicht nur in JS), da tracker.js selbst ueber * Seiten-Caches ausgeliefert wird und deshalb auf einer x-beliebig alten * gecachten Version laufen kann; ein clientseitiger Abbruch allein wuerde * so lange nicht greifen, bis der Cache jeder betroffenen Seite ablaeuft. * Beide Header werden vom Browser auf dem eigentlichen Beacon-Request * mitgeschickt (Sec-GPC bzw. DNT), unabhaengig vom Cache-Zustand der Seite. */ private static function is_dnt() { $gpc = isset( $_SERVER['HTTP_SEC_GPC'] ) && '1' === (string) $_SERVER['HTTP_SEC_GPC']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Rohwert wird nur gehasht oder verglichen, nie ausgegeben. $dnt = isset( $_SERVER['HTTP_DNT'] ) && '1' === (string) $_SERVER['HTTP_DNT']; // phpcs:ignore WordPress.Security.ValidatedSanitizedInput.InputNotSanitized, WordPress.Security.ValidatedSanitizedInput.MissingUnslash -- Rohwert wird nur gehasht oder verglichen, nie ausgegeben. /** Erlaubt, das Respektieren von DNT/GPC abzuschalten (Standard: an). */ return (bool) apply_filters( 'wp360_nca_respect_dnt', $gpc || $dnt ); } /** Hits je Besucher-Hash und Minute -- mehr klickt kein Mensch. */ const MAX_HITS_PER_VISITOR_MINUTE = 30; /** * Hits je IP und Minute, nur als Notbremse gegen Fluten mit wechselndem * User-Agent. Bewusst hoch: Hinter einem CDN, bei Shared Hosting ohne * remoteip oder bei Carrier-NAT teilen sich viele echte Besucher eine IP, * und jeder Treffer darueber ginge der Statistik still verloren. */ const MAX_HITS_PER_IP_MINUTE = 600; /** * Der Endpunkt ist oeffentlich; ohne Grenze liesse sich die Tabelle per * Schleife beliebig aufblaehen und die Statistik frei faelschen. */ private static function is_rate_limited() { global $wpdb; $per_visitor = (int) apply_filters( 'wp360_nca_max_hits_per_visitor_minute', self::MAX_HITS_PER_VISITOR_MINUTE ); $recent = (int) $wpdb->get_var( // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- Zaehlung muss aktuell sein. $wpdb->prepare( 'SELECT COUNT(*) FROM ' . Wp360_NoCookie_Analytics_Database::table_name() . ' WHERE visitor_id = %s AND created_at >= %s', // phpcs:ignore WordPress.DB.PreparedSQL.NotPrepared -- Tabellenname ist fest. self::visitor_id(), gmdate( 'Y-m-d H:i:s', strtotime( current_time( 'mysql' ) ) - MINUTE_IN_SECONDS ) ) ); if ( $recent >= $per_visitor ) { return true; } // Der Schluessel ist ein Hash, die Roh-IP landet nirgends. $per_ip = (int) apply_filters( 'wp360_nca_max_hits_per_ip_minute', self::MAX_HITS_PER_IP_MINUTE ); $key = 'wp360_nca_rl_' . substr( hash( 'sha256', self::client_ip() . '|' . Wp360_NoCookie_Analytics_Database::salt() ), 0, 32 ); $count = (int) get_transient( $key ); if ( $count >= $per_ip ) { return true; } set_transient( $key, $count + 1, MINUTE_IN_SECONDS ); return false; } /** Nur oeffentlich sichtbare, veroeffentlichte Inhalte zaehlen -- sonst liessen sich beliebige IDs (Entwuerfe, private Seiten) in die Top-Liste schreiben. */ private static function viewable_post_id( $post_id ) { if ( $post_id <= 0 ) { return 0; } $post_type = get_post_type( $post_id ); if ( ! $post_type || 'publish' !== get_post_status( $post_id ) || ! is_post_type_viewable( $post_type ) ) { return 0; } return $post_id; } private static function sanitize_path( $url ) { if ( $url === '' ) { return ''; } // Queryparameter koennen Tokens, E-Mail-Adressen oder Suchbegriffe // enthalten. Auch alte/gecachte Tracker duerfen sie nicht speichern. $path = wp_parse_url( $url, PHP_URL_PATH ); // Nur Pfade dieser Seite: Ohne fuehrenden "/" machte esc_url_raw() aus // "evil.example/wp-login" einen Link "http://evil.example/wp-login", // der in der Top-Liste im Dashboard als klickbarer Phishing-Link stand. if ( ! is_string( $path ) || '/' !== substr( $path, 0, 1 ) || '//' === substr( $path, 0, 2 ) ) { return ''; } return mb_substr( $path, 0, 255 ); } }