1000 ) { return false; } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- this plugin's own table; one atomic add to the row of its kind. $done = $wpdb->query( $wpdb->prepare( 'INSERT INTO %i ( day, source, outcome, n ) VALUES ( %s, %s, %s, %d ) ON DUPLICATE KEY UPDATE n = n + %d', Schema::table( 'tally' ), $day, $source, $outcome, $n, $n ) ); return false !== $done && $done > 0; } /** * A visitor's browser reports what the gate asked or heard — the public path. * * Only the gate's outcomes, only while the gate is on, only 1 at a time, and * nothing at all once this minute's site-wide brake is reached. * * @param mixed $outcome The word the browser sent. * @return string counted · bad · off · limit · error */ public static function report( $outcome ) { if ( ! is_string( $outcome ) || ! in_array( $outcome, self::OUTCOMES, true ) ) { return 'bad'; } if ( ! Settings::get()['gate'] ) { return 'off'; } $minute = gmdate( 'YmdHi' ); $seen = get_transient( self::BRAKE ); $count = is_array( $seen ) && isset( $seen['m'], $seen['n'] ) && $minute === $seen['m'] ? (int) $seen['n'] : 0; if ( $count >= self::limit() ) { return 'limit'; } set_transient( self::BRAKE, array( 'm' => $minute, 'n' => $count + 1, ), 2 * MINUTE_IN_SECONDS ); return self::add( 'gate', $outcome ) ? 'counted' : 'error'; } /** * The brake: reports written per minute, site-wide. * * @return int */ public static function limit() { /** * Filters how many gate reports the site writes per minute before it stops. * * @param int $limit Default 600. */ $limit = apply_filters( 'agevow_tally_brake', self::DEFAULT_LIMIT ); return is_int( $limit ) && $limit >= 1 ? $limit : self::DEFAULT_LIMIT; } /** * The counts of a range of the site's days, oldest first, one entry per day * that has any: { day, gate: {asked, pass, under, left}, checkout: {…} }. * * @param string $from First day (Y-m-d). * @param string $to Last day (Y-m-d). * @return array> */ public static function read( $from, $to ) { global $wpdb; if ( ! Dates::is_day( $from ) || ! Dates::is_day( $to ) || $from > $to ) { return array(); } // phpcs:ignore WordPress.DB.DirectDatabaseQuery.DirectQuery, WordPress.DB.DirectDatabaseQuery.NoCaching -- this plugin's own table; counts that change all day. $rows = $wpdb->get_results( $wpdb->prepare( 'SELECT day, source, outcome, n FROM %i WHERE day >= %s AND day <= %s ORDER BY day ASC', Schema::table( 'tally' ), $from, $to ), ARRAY_A ); $zero = array_fill_keys( self::OUTCOMES, 0 ); $days = array(); foreach ( (array) $rows as $row ) { $day = (string) $row['day']; if ( ! isset( $days[ $day ] ) ) { $days[ $day ] = array( 'day' => $day, 'gate' => $zero, 'checkout' => $zero, ); } if ( in_array( $row['source'], self::SOURCES, true ) && in_array( $row['outcome'], self::OUTCOMES, true ) ) { $days[ $day ][ $row['source'] ][ $row['outcome'] ] = (int) $row['n']; } } return array_values( $days ); } }