<?php
/*
Plugin Name: Create Topic Slugs
Description:  Creates topic slugs where previously there weren't any. Outputs into error log, only works on plugin activation.
Plugin URI:  http://simonwheatley.co.uk/bbpress/create-topic-slugs
Author: simonwheatley
Author URI: http://simonwheatley.co.uk
Version: 1
*/

class CreateTopicSlugs
{
    function 
__construct()
    {
        global 
$bbdb;
        
$this->db = & $bbdb;
    }
    
    public function 
create_slugs()
    {
        
$topics $this->slugless_topics();
        if ( ! 
count$topics ) ) {
            echo 
"All topics now have slugs, you can disable the create topic slugs plugin by removing it from the plugins directory.";
            exit;
        }
        foreach( 
$topics AS $topic ) {
            
$new_topic_slug $this->generate_topic_slug$topic->topic_id$topic->topic_title );
            
$this->update_topic_slug$topic->topic_id$new_topic_slug );
        }
    }
    
    protected function 
slugless_topics()
    {
        
// Just do 300 at a time for now
        
$topics_table $this->db->topics;
        
$sql " SELECT topic_id, topic_title FROM $topics_table WHERE topic_slug IS NULL OR topic_slug = '' LIMIT 1000 ";
        
// No need to prepared the SQL, no user input
        
return $this->db->get_results$sql );
    }
    
    protected function 
generate_topic_slug$topic_id$topic_title )
    {
        
$topic_slug $_topic_slug bb_slug_sanitizewp_specialchars_decode$topic_titleENT_QUOTES ) );
        if ( 
strlen$_topic_slug ) < $topic_slug $_topic_slug '0';

        
// Ensure the slug is unique
        
while ( is_numeric$topic_slug ) || $existing_slug $this->existing_slug$topic_id$topic_slug ) ) {
            
$topic_slug bb_slug_increment$_topic_slug$existing_slug );
        }
        return 
$topic_slug;
    }
    
    protected function 
existing_slug$topic_id$topic_slug )
    {
        
$topics_table $this->db->topics;
        
$sql "SELECT topic_slug FROM $topics_table WHERE topic_slug = %s AND topic_id != %d";
        
$prepared_sql $this->db->prepare$sql$topic_slug$topic_id );
        return 
$this->db->get_var$prepared_sql );
    }
    
    protected function 
update_topic_slug$topic_id$topic_slug )
    {
        
$topic_table $this->db->topics;
        
$data = array( 'topic_slug' => $topic_slug );
        
$where = array( 'topic_id' => $topic_id );
        
$this->db->update$topic_table$data$where );
    }

}

$create_topic_slugs = new CreateTopicSlugs();

add_action'bb_init', array( & $create_topic_slugs'create_slugs' ) );

?>