<?php
/*
Plugin Name: Resolve Topic Slug Collisions
Description: Resolves long topic slug collisions in Memcached due to the 250 chars key length.
Author: wordpressdotorg
Author URI: http://wordpress.org/
Version: 1.0
License: GPLv2
License URI: http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
*/

/**
 * Resolves long topic slug collisions by pre-matching topic slugs to IDs
 * in order to bypass the 'bb_topic_slug' cache group in get_topic(),
 * which produces erroneous results for slugs close to 250 chars length
 * due to Memcached key size limit.
 *
 * @param string|int $topic_slug Requested topic slug or ID.
 * @return int|string Topic ID if resolved, topic slug otherwise.
 */
function wporg_resolve_topic_slug_collisions( $topic_slug ) {
	if ( is_numeric( $topic_slug ) ) {
		return $topic_slug;
	}

	$location = bb_get_location();

	if ( ! in_array( $location, array( 'topic-page', 'topic-edit-page' ) ) ) {
		return $topic_slug;
	}

	$topic_id = wp_cache_get( md5( $topic_slug ), 'bb_topic_slug_md5' );

	if ( false === $topic_id ) {
		$topic_id = bb_get_id_from_slug( 'topic', $topic_slug );

		wp_cache_add( md5( $topic_slug ), $topic_id, 'bb_topic_slug_md5' );
	}

	return $topic_id;
}
add_filter( 'bb_repermalink', 'wporg_resolve_topic_slug_collisions' );
