<?php
/* 
Plugin Name:  MyScoresPresenter
Plugin URI:   http://myarcadeplugin.com
Description:  Shows scores and leaderboards on your blog. Requires MyArcadePlugin Pro
Version:      3.01
Author:       Daniel Bakovic
Author URI:   http://netreview.de
*/


/**
 *******************************************************************************
 *   G L O B A L S
 *******************************************************************************
 */
define('MYSCORE_VERSION', '3.01');

if ( ! defined( 'WP_PLUGIN_URL' ) ) {
  define( 'WP_PLUGIN_URL', WP_CONTENT_URL.'/plugins' );
}

// Define tables if not defined
global $wpdb;
if ( !defined('MYARCADE_GAME_TABLE') ) {    define ('MYARCADE_GAME_TABLE', $wpdb->prefix.'myarcadegames'); }
if ( !defined('MYARCADE_SCORES_TABLE') ) {  define ('MYARCADE_SCORES_TABLE', $wpdb->prefix.'myarcadescores'); }
if ( !defined('MYARCADE_HIGHSCORES_TABLE') ) {  define ('MYARCADE_HIGHSCORES_TABLE', $wpdb->prefix.'myarcadehighscores'); }
if ( !defined('MYARCADE_USER_TABLE') ) {  define ('MYARCADE_USER_TABLE', $wpdb->prefix.'myarcadeuser'); }
if ( !defined('MYARCADE_MEDALS_TABLE') ) {  define ('MYARCADE_MEDALS_TABLE',    $wpdb->prefix.'myarcademedals');}

/**
 *******************************************************************************
 *   H O O K S
 *******************************************************************************
 */
  /* Add the main menu to blog */
add_action('admin_menu', 'myscore_admin_menu');
  /* Add some Widgets */
add_action('widgets_init', 'myscore_init_widgets');

 /* Install / Uninstall */
register_activation_hook  ( __FILE__, 'myscore_install' );


/**
 *******************************************************************************
 *   F U N C T I O N S
 *******************************************************************************
 */


/*
 * @brief: Shows todays scores as list elements orderd by ID
 */
function myscore_get_todays_scores($limit = 10) {
  global $wpdb;
      
  $output = '';
  $template = get_option('myscore_template_today');
   
  $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE date = curdate() ORDER BY id DESC LIMIT ".$limit);

  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  else {
    $output = "<li>There are no score, yet! Play this game to be the <strong>best</strong> player!</li>";
  }
  
  echo $output;
}

function myscore_get_todays_scores_game($limit = 10) {
  global $wpdb, $mypostid;
      
  $output = '';
  $game_tag = '';
  
  $template = get_option('myscore_template_today');
  
  $game_tag = get_post_meta($mypostid, 'mabp_game_tag', true);
  
  if ( empty($game_tag) ) {  
    $game_tag = $wpdb->get_var("SELECT game_tag FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$mypostid."'");
  }
   
  $results = false;
          
  if ( $game_tag )
    $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE date = curdate() AND game_tag = '".$game_tag."' ORDER BY id DESC LIMIT ".$limit);  

  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  else {
    $output = "<li>There are no score, yet! Play this game to be the <strong>best</strong> player!</li>";
  }
  
  echo $output;
}


/*
 * @brief: Shows todays scores as list elements orderd by ID
 */
function myscore_get_weekly_scores($limit = 10) {
  global $wpdb, $mypostid;
      
  $output = '';
  $template = get_option('myscore_template_today');
  
  $game_tag = '';
  $game_tag = get_post_meta($mypostid, 'mabp_game_tag', true);
  
  if ( empty($game_tag) ) {  
    $game_tag = $wpdb->get_var("SELECT game_tag FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$mypostid."'");
  }
  
  $results = false;
  
  if ( $game_tag )
    $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE game_tag = '".$game_tag."' AND DATE_SUB(CURDATE(), INTERVAL 7 DAY) <=  date ORDER BY id DESC LIMIT ".$limit);

  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  else {
    $output = "<li>There are no weekly scores! Play this game to be the <strong>best</strong> player!</li>";
  }
  
  echo $output;
}


/*
 * @brief: Shows most active players as a list of elements ordered by plays count
 */
function myscore_get_most_active_users($limit = 10) {
  global $wpdb;
      
  $output = '';
  $template = get_option('myscore_template_muser');
  
  //$results = $wpdb->get_results("SELECT user_id, COUNT(*) as plays FROM ".MYARCADE_SCORES_TABLE." GROUP BY user_id ORDER BY plays DESC LIMIT ".$limit);
  $results = $wpdb->get_results("SELECT user_id, plays FROM ".MYARCADE_USER_TABLE." ORDER BY plays DESC LIMIT ".$limit);
   
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
   
  echo $output;
}


function myscore_get_leaderboard() {
  global $wpdb;
  
  $output = '';
  
  $results = $wpdb->get_results("SELECT user_id, COUNT(*) as highscores FROM ".MYARCADE_HIGHSCORES_TABLE." GROUP BY user_id ORDER BY highscores DESC LIMIT 3");
    
  if (!empty($results)) {
    $count = 0;
    
    foreach ($results as $result) {
      $count++;
      
      $user_info = get_userdata($result->user_id);
      
      if ( $count <= 3 ) {
        
        if ( $count == 1 ) { 
          ?><li><div class="topplayer"><?php
        }
        ?>
              
        <div class="playerinfo <?php if ($count==3) echo 'last'; ?>">
          <?php echo get_avatar($result->user_id, 50); ?>
          <?php echo myscore_get_user_link($result->user_id); ?>
          <center><div class="award-<?php echo $count; ?>"></div></center>
          <?php echo $result->highscores; ?>          
        </div>
        <?php
        if ( $count == 3) { 
          ?>
          </div>
          <div style="clear:both;padding-bottom:10px"></div>
        </li>
        <?php
        }
      }
      else {
        ?>
        <li>
          <?php echo $count . '. ' . $user_info->user_nicename . __('with', 'fungames') . $result->highscores .' '. __('Highscores', 'fungames'); ?>
        </li>
        <?php
      }      
    }
  }   
}

/*
 * @brief: Shows latest scores as list elements orderd by ID 
 */
function myscore_get_latest_scores($limit = 10) {
  global $wpdb;
  
  $output = '';
  $template = get_option('myscore_template_latest');
   
  $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." ORDER BY id DESC LIMIT ".$limit);
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  
  echo $output;
}


/*
 * @brief: Shows scores of a single game as list elements orderd by highscore 
 */
function myscore_get_game_scores($limit = 10) {
  global $wpdb, $mypostid;
  
  $game_tag = '';
  
  $game_tag = get_post_meta($mypostid, 'mabp_game_tag', true);
  
  if ( empty($game_tag) ) {  
    $game_tag = $wpdb->get_var("SELECT game_tag FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$mypostid."'");
  }
   
  $output = '';
  $template = get_option('myscore_template_game');
  
  $results = false;
  
  if ( $game_tag )
    $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE game_tag = '".$game_tag."' ORDER BY score+0 DESC LIMIT ".$limit);
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  else {
    $output = "<li>There are no best players! Play this game to be the <strong>best</strong> player!</li>";
  }
  
  echo $output;
}


/*
 * @brief: Show last scores of an user on the sidebar
 */
function myscore_show_users_scores($user_id, $limit = 10) {
  global $wpdb;
  
  // Get Scores Of User
  $scores = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE user_id = '".$user_id."' ORDER BY id DESC LIMIT ".$limit);
    
  if ($scores) {
    $output = '<p>';
    foreach ($scores as $score) {
      // Get the Game Informations
      $game = $wpdb->get_row("SELECT * FROM ".MYARCADE_GAME_TABLE." WHERE game_tag = '".$score->game_tag."'");
      $gamelink = '<a href="'.get_permalink($game->postid).'" title ="'.$game->name.'">'.$game->name.'</a>';
      
      // Generate the output
      $output .= $score->date.' - Scored: <strong>'.$score->score.'</strong> on '.$gamelink.'<br />';
    }
    
    $output .= '</p>';
  }
  else {
    $output = '<p>The user has not played any games, yet. :(</p>';
  }
  
  echo $output;
}


/*
 * @brief: Shows the highscores of an user per game on his profile page (BuddyPress)
 *         ordered by Highscore
 */
function myscore_get_users_highscore_per_game($user_id, $limit = 10) {
  global $wpdb;
  
  $output = '';
  $template = get_option('myscore_template_high_buddypress');
    
  // Get Scores Of User
  $results = $wpdb->get_results("SELECT game_tag, date, MAX(score) as score FROM ".MYARCADE_SCORES_TABLE." WHERE user_id = '".$user_id."' GROUP BY game_tag ORDER BY score DESC LIMIT ".$limit);
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= '<li>'.myscore_expand_template($template, $result)."</li>\n";
    }
  }
  
  echo stripslashes($output);
}


/*
 * @brief: Shows the latest scores of an user on his profile page (BuddyPress)
 *         ordered by ID
 */
function myscore_get_users_latest_scores_page($user_id, $limit = 10) {
  global $wpdb;
  
  $output = '';
  $template = get_option('myscore_template_latest_userpage');
  
  // Get latest scores of  the user
  $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_SCORES_TABLE." WHERE user_id = '".$user_id."' ORDER BY id DESC LIMIT ".$limit);
  
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= '<li>'.myscore_expand_template($template, $result)."</li>\n";
    }
  }
  
  echo stripslashes($output);
}


/*
 * @brief: Shows latest medals as list elements orderd by ID
 */
function myscore_get_latest_medals($limit = 10) {
  global $wpdb;
  
  $output = '';
  $template = get_option('myscore_template_latest_medals');
   
  $results = $wpdb->get_results("SELECT * FROM ".MYARCADE_MEDALS_TABLE." ORDER BY id DESC LIMIT ".$limit);
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= "<li>".myscore_expand_template($template, $result)."</li>\n";
    }
  }
  
  echo $output;
}


/*
 * @brief: Shows medals that the displayed user has achieved
 *  $order = type or date
 */
function myscore_get_user_medals ($user_id, $order = 'description', $limit = 10) {
  global $wpdb;
  
  $output = '';
  $template = get_option('myscore_template_user_medals');
  
  //$results = $wpdb->get_results("SELECT * FROM ".MYARCADE_MEDALS_TABLE." WHERE user_id = '".$user_id."' ORDER BY $order DESC LIMIT ".$limit);  
  
  if (!empty($results)) {
    foreach ($results as $result) {
      $output .= '<li>'.myscore_expand_template($template, $result)."</li>\n";
    }
  }  

  echo stripslashes($output);
}


/*
 * @brief: Shows achieved medals of the displayed game
 *  $order = type or date
 */
function myscore_get_game_medals ($limit = 10, $order = 'type') {
  global $wpdb, $mypostid;
  
  $output = '';
  $template = get_option('myscore_template_game_medals');
  
  echo stripslashes($output);
}

function myscore_get_user_link($user_id) {

  $user = get_userdata($user_id);
      
  // Check if mingle is installed
  if (defined('MNGL_PLUGIN_NAME')) {
    // Get mingle options
    $mingl_options = get_option('mngl_options');
    // Get the permalink of the user's profile
    $permalink = get_permalink($mingl_options->profile_page_id);
    // Correct the profile link...
    $param_char = ((preg_match("#\?#",$permalink))?'&':'?');
    $link = $permalink.$param_char.'u='.$user->display_name;

    // Generate a link to users profile
    $userlink = '<a href="'.$link.'" title="'.$row.'" >'.$user->display_name.'</a>';
  }
  else {
    // Check if BuddyPress is installed and get the BuddyPress user link...
    if ( defined('BP_VERSION') ) {
      $userlink = bp_core_get_userlink($user_id);
    }
    else {
      // No Link. Show only the user name
      $userlink = $user->display_name;
    }
  }
  
  return $userlink;  
}


/*
 * @brief Expand Score data
 */
function myscore_expand_template($template, $score_result) {
  global $wpdb;
  
    $value = $template;
    
    if ( isset($score_result->game_tag) ) {
      $game = $wpdb->get_row("SELECT * FROM ".MYARCADE_GAME_TABLE." WHERE game_tag = '".$score_result->game_tag."' LIMIT 1");
    } else { $game = false; }
     
    if (strpos($template, '%USERNAME%') !== false) {
      // Check the UserID
      if ( !empty($score_result->user_id) ) {
        $userlink = myscore_get_user_link($score_result->user_id);
      
        $value = str_replace("%USERNAME%", $userlink, $value);
      }
      else {
        // UserID is empty
        // Check if this is a guest
        if ( !empty($score_result->user_name) ) {
          $value = str_replace("%USERNAME%", $score_result->user_name, $value);
        }
      }
    }

    // Check medal
    
    if( isset($score_result->score) ) $value = str_replace("%SCORE%",     $score_result->score, $value);
    if( isset($score_result->name) )  $value = str_replace("%GAMENAME%",  $game->name, $value);
    if( isset($score_result->plays) ) $value = str_replace("%GAMEPLAYS%", $score_result->plays, $value);
    if( isset($score_result->date) )  $value = str_replace("%DATE%",    $score_result->date, $value);
    
    if (strpos($template, '%GAME%') !== false) {
      $gamelink = '<a href="'.get_permalink($game->postid).'" title ="'.$game->name.'">'.$game->name.'</a>';
      $value = str_replace("%GAME%", $gamelink, $value);
    }
    
    if (strpos($template, '%GAMEIMAGEURL%') !== false) {
      $image = get_post_meta($game->postid, 'mabp_thumbnail_url', true);
      $value = str_replace("%GAMEIMAGEURL%", $image, $value);
    }

    return $value;
}


/*
 * @brief: Check if a game has leaderboard enabled 
 *         Use this function only inside the loop
 */
function myscore_check_leaderboard() {
  global $wpdb, $post;
  
  $lb_enable = get_post_meta($post->ID, 'mabp_leaderboard', true);
  
  if ( !isset($lb_enable) ) {  
    $lb_enable = $wpdb->get_var("SELECT leaderboard_enabled FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$post->ID."' LIMIT 1");
  }
  
  if ($lb_enable) {
    $result = true;
  }
  else $result = false;
  
  return $result;
}


/*
 * @brief: Shows the global scores of a single game
 */
function myscore_get_global_game_scores() {
  global $wpdb, $mypostid;
   
  $game_slug = $wpdb->get_var("SELECT slug FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$mypostid."'");
  $game_type = $wpdb->get_var("SELECT game_type FROM ".MYARCADE_GAME_TABLE." WHERE postid = '".$mypostid."'");
  //$global_scores = $wpdb->get_var("SELECT global_scores FROM ".MYARCADE_SETTINGS_TABLE."");
  
  $global_scores = true;
  
  if ( ($global_scores == 'true') && ($game_type != 'heyzap') ) {
    $output  = '<div id="leaderboard_widget"></div>';
    //$output .= '<script src="http://xs.mochiads.com/static/pub/swf/leaderboard.js" type="text/javascript"></script>';
    $output .= '<script type="text/javascript">';
    $output .= 'var options = {game: "'.$game_slug.'", width: 335, height: 500, id: "leaderboard_widget"};';
    // Select a specific leaderboard for a game - optional (if not included, a selectable list will be used)
    //options.leaderboard = "Level 1";
    // your publisher ID - optional (if not included, ALL scores from all sites will be shown)
    //$output .= 'options.partnerID = "'.$publisher_id.'";';
    // username link prefix - optional
    //options.profileURL = "http://www.example.com/profile/${name}";
    // leaderboard background color - optional
    $output .= 'options.backgroundColor = "#DFE3E6";';
     
    // Show the widget!
    //options.defaultTab = "alltime";
    // Default to the all time tab!
    $output .= 'Mochi.showLeaderboardWidget(options);';
    $output .= '</script>';
    
    echo $output;
  }
}


//
// @brief: This function checks the user level.
//
if (!function_exists('check_user_privilegs')) {
  function check_user_privilegs() {
    if (function_exists('current_user_can')) {
      if (current_user_can('manage_options')) {
        return true;
      }
    } else {
      global $user_level;
      
      get_currentuserinfo();
      
      if ($user_level >= 8) {
        return true;
      }
    }
    
    return false;
  }
}


/**
 * @brief Shows the admin menu
 */
function myscore_admin_menu() {
  if (check_user_privilegs()) {
    if ( defined('MYARCADE_VERSION') ) {
      add_submenu_page('myarcade_admin.php',
         __('MyScoresPresenter',  'myscorespresenter'),
        __('MyScoresPresenter',  'myscorespresenter'), 
        'manage_options',  basename(__FILE__), 'myscore_options');
    }
    else {  
      add_options_page(
        __('MyScoresPresenter',  'myscorespresenter') , 
        __('MyScoresPresenter',  'myscorespresenter'), 
        'manage_options' , 
        basename(__FILE__), 
        'myscore_options');
    }
  }  
}

/**
 * @brief
 */
function myscore_options() {

  // Check, if we have to update templates.. 
  if (isset($_POST['myscore_update'])) {
    update_option('myscore_template_today',       trim($_POST['myscore_template_today']));
    update_option('myscore_template_latest',      trim($_POST['myscore_template_latest']));
    update_option('myscore_template_muser',       trim($_POST['myscore_template_muser']));
    update_option('myscore_template_game',        trim($_POST['myscore_template_game']));
    update_option('myscore_template_high_buddypress', trim($_POST['myscore_template_high_buddypress']));
    update_option('myscore_bp_template',          trim($_POST['myscore_bp_template']));
    update_option('myscore_template_latest_userpage', trim($_POST['myscore_template_latest_userpage']));
    update_option('myscore_template_leaderboard', trim($_POST['myscore_template_leaderboard']));
    
    echo '<div id="message" class="updated fade"><p><strong>Settings saved.</strong></p></div>';
  }

?>
<div class="wrap">
  
  <div id="icon-options-general" class="icon32"><br /></div>
  <h2>MyScoresPresenter</h2>
  
  <br /><br />
  <h3>Available Variables</h3>
    
  <table class="widefat fixed">
    <thead>
    <tr>
      <th scope="col">Variable</th>
      <th scope="col">Description</th>
      <th scope="col"></th>
    </tr>
    </thead>
    <tbody>
      <tr>
        <td><strong>%USERNAME%</strong></td>
        <td>Display the username</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%SCORE%</strong></td>
        <td>Display the score of a game</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%GAMENAME%</strong></td>
        <td>Display the name of a game (without link)</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%GAME%</strong></td>
        <td>Display the game name with the game link</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%GAMEPLAYS%</strong></td>
        <td>Display the game plays of a user</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%GAMEIMAGEURL%</strong></td>
        <td>Gets the thumbnail url of a game</td>
        <td></td>
      </tr>      
      <tr>
        <td><strong>%HIGHSCORE%</strong></td>
        <td>Display how many highscore a user has achieved</td>
        <td></td>
      </tr>
      <tr>
        <td><strong>%DATE%</strong></td>
        <td>Display the date of the score</td>
        <td></td>
      </tr>
    </tbody>      
  </table>
  
  <h3>Scores Templates</h3>
  
  <form method="post" action="<?php echo $_SERVER["REQUEST_URI"]; ?>" name="myscore" id="myscore">
    <input type="hidden" name="myscore_update" id="myscore_update" value="true" />
    
    <table class="widefat fixed">
      <thead>
      <tr>
        <th scope="col">Name</th>
        <th scope="col">Value</th>
        <th scope="col">Allowed Placeholders</th>      
      </tr>
      </thead>  
      <tbody>
        <tr>
          <td>
            <h3>Todays Scores</h3>
            <i>Shows game scores that are scored today.</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_today" name="myscore_template_today"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_today'))); ?></textarea>
            <br />
            Default: %USERNAME% on %GAME% (%SCORE%)
          </td>
          <td>
            %USERNAME%<br />
            %SCORE%<br />
            %GAMENAME%<br />
            %GAME%<br />
          </td>
        </tr>      

        <tr>
          <td>
            <h3>Latest Scores</h3>
            <i>Shows latest scores.</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_latest" name="myscore_template_latest"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_latest'))); ?></textarea>
            <br />
            Default: &lt;strong&gt;%USERNAME%&lt;/strong&gt; on %GAME%
          </td>
          <td>
            %USERNAME%<br />
            %SCORE%<br />
            %GAMENAME%<br />
            %GAME%<br />
          </td>        
        </tr>  

        <tr>
          <td>
            <h3>Most active Players</h3>
            <i>Shows players ordered by game plays.</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_muser" name="myscore_template_muser"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_muser'))); ?></textarea>
            <br />
            Default: &lt;strong&gt;%USERNAME%&lt;/strong&gt; - %GAMEPLAYS% plays
          </td>
          <td>
            %USERNAME%<br />
            %GAMEPLAYS%<br />
          </td>
        </tr> 

        <tr>
          <td>
            <h3>Single Game Scores</h3>
            <i>Shows best player of a single game</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_game" name="myscore_template_game"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_game'))); ?></textarea>
            <br />
            Default: &lt;strong&gt;%USERNAME%&lt;/strong&gt; - %SCORE%
          </td>
          <td>
            %USERNAME%<br />
            %SCORE%<br />
            %GAMENAME%<br />
            %GAME%<br />
          </td>
        </tr>

        <tr>
          <td>
            <h3>Overall Leaderboard</h3>
            <i>Shows the best players on your site ordered by achieved highscores.</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_leaderboard" name="myscore_template_leaderboard"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_leaderboard'))); ?></textarea>
            <br />
            Default: %USERNAME% with %HIGHSCORE% Highscores
          </td>
          <td>
            %USERNAME%<br />
            %HIGHSCORE%<br />
          </td>
        </tr> 

        <tr>
          <td colspan="3">
            <h3>Users Highscores For Profile Pages (BuddyPress)</h3>
          </td>
        </tr>  

        <tr>
          <td>
            <h3>Users Scores</h3>
            <i>Shows users highscores on profile pages</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_high_buddypress" name="myscore_template_high_buddypress"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_high_buddypress'))); ?></textarea>
            <br />
            <input type="checkbox" value="themefile" name="myscore_bp_template" <?php if (get_option('myscore_bp_template') == 'themefile') echo ' checked'; ?> /> Use Custom BudyPress Template File
          </td>
          <td>
            %SCORE%<br />
            %GAMENAME%<br />
            %GAME%<br />
            %GAMEIMAGEURL%<br />
            %DATE%<br />
          </td>
        </tr>

        <tr>
          <td>
            <h3>Latest User Scores</h3>
            <i>Shows latest scores of a user on profile pages</i>
          </td>
          <td>
            <textarea rows="5" style="width:90%" id="myscore_template_latest_userpage" name="myscore_template_latest_userpage"><?php echo htmlspecialchars(stripslashes(get_option('myscore_template_latest_userpage'))); ?></textarea>
          </td>
          <td>
            %SCORE%<br />
            %GAMENAME%<br />
            %GAME%<br />
            %GAMEIMAGEURL%<br />
            %DATE%<br />
          </td>
        </tr>

        <tr>
          <td colspan="3">
            <input type="submit" name="myscore_update" value="Save Settings" class="button-primary" style="margin:20px;">
          </td>
        </tr>      
      </tbody>    
    </table>
                
  </form>
    
  <div style="clear:both"> </div>
  
  <h2>Usage</h2>
  
  <h3>Widgets</h3>
  <p>The easiest way to display scores on your site is to use MyScorePresenter widgets. Go to Appearance -> Widgets and drop the desired widgets to your sidebar.</p>
  
  <h3>Manual Theme Integration And Function Reference</h3>
  
  <p>You are also able to integrate MyScoresPresenter into your theme without widgets. Thereby you will need to edit your template files.</p>
  
  <h4>Display Todays Scores</h4>
  <p>
  Use the function "myscore_get_todays_scores($limit)" to show todays scores. 
  The optional parameter $limit can be used to set the count of displayed scores.
  Default value of $limit is 10.
  </p>
  <p><strong>Example:</strong></p>
  &lt;?php if (function_exists(myscore_get_todays_scores) ) : ?&gt;
  <br />
  &lt;h2&gt;Todays Scores&lt;/h2&gt;
  <br />
  &lt;ul&gt;
  <br />
  &lt;?php echo myscore_get_todays_scores(); ?&gt;
  <br />
  &lt;/ul&gt;
  <br />
  &lt;?php endif; ?&gt;
  <br />
  
  <h4>Display Most Active Players</h4>
  <p>
  Use the function "myscore_get_most_active_users($limit)" to show most active players. 
  The optional parameter $limit can be used to set the count of displayed players.
  Default value of $limit is 10.
  </p>
  <p><strong>Example:</strong></p>
  &lt;?php if (function_exists(myscore_get_most_active_users) ) : ?&gt;
  <br />
  &lt;h2&gt;Top Players&lt;/h2&gt;
  <br />
  &lt;ul&gt;
  <br />
  &lt;?php echo myscore_get_most_active_users(); ?&gt;
  <br />
  &lt;/ul&gt;
  <br />
  &lt;?php endif; ?&gt;
  <br />  
  
  <h4>Display Most Active Players</h4>
  <p>
  Use the function "myscore_get_most_active_users($limit)" to show the latest scores. 
  The optional parameter $limit can be used to set the count of displayed scores.
  Default value of $limit is 10.
  </p>
  <p><strong>Example:</strong></p>
  &lt;?php if (function_exists(myscore_get_latest_scores) ) : ?&gt;
  <br />
  &lt;h2&gt;Latest Scores&lt;/h2&gt;
  <br />
  &lt;ul&gt;
  <br />
  &lt;?php echo myscore_get_latest_scores(); ?&gt;
  <br />
  &lt;/ul&gt;
  <br />
  &lt;?php endif; ?&gt;
  <br />  
  
  <h4>Display Best Scores Of A Single Game</h4>
  <p>
  Use the function "myscore_get_game_scores($limit)" to show the best scores of a
  single game. It make sense to use this function on a singe game page.
  The optional parameter $limit can be used to set the count of displayed scores.
  Default value of $limit is 10.
  </p>
  <p><strong>Example:</strong></p>
  &lt;?php if ( is_single() ) :?&gt;
  &lt;?php if (function_exists(myscore_get_game_scores) ) : ?&gt;
  <br />
  &lt;h2&gt;Best Players&lt;/h2&gt;
  <br />
  &lt;ul&gt;
  <br />
  &lt;?php echo myscore_get_latest_scores(); ?&gt;
  <br />
  &lt;/ul&gt;
  <br />
  &lt;?php endif; ?&gt;
  <br />
  &lt;?php endif; ?&gt;
  <br />  
  
  
  <div style="margin: 20px 0px 20px 0px;padding: 10px;text-align: right;">
    <p>
      MyScoresPresenter v<?php echo MYSCORE_VERSION;?> | 
      <a href="http://myarcadeplugin.com" title="WordPress Arcade" target="_blank">MyArcadePlugin</a>
    </p>
    </div>
  </div>
<div style="clear:both"> </div>
<?php
}


function myscore_install() {
  
  $user_highscores ='<div style="width:300px;height:80px;margin-bottom:10px;">
<div style="float:left;margin-right:10px;"><img src="%GAMEIMAGEURL%" width="75px" alt="%GAMENAME%" /></div>
<div style="float:left">
<p style="font-size:14px;font-wight:bold;">%GAME%</p>
Highscore: <strong>%SCORE%</strong><br/>
Date: %DATE%</div>
</div>';
  
  $latest_user = '<div style="width:300px;height:80px;margin-bottom:10px;">
<div style="float:left;margin-right:10px;"><img src="%GAMEIMAGEURL%" width="75px" alt="%GAMENAME%" /></div>
<div style="float:left">
<p style="font-size:14px;font-wight:bold;">%GAME%</p>
Score: <strong>%SCORE%</strong><br/>
Date: %DATE%</div>
</div>';
    
  if ( !get_option('myscore_template_today') ) {
    add_option('myscore_template_today',       '%USERNAME% on %GAME% (%SCORE%)');
    add_option('myscore_template_latest',      '<strong>%USERNAME%</strong> on %GAME%');
    add_option('myscore_template_muser',       '<strong>%USERNAME%</strong> - %GAMEPLAYS% plays');
    add_option('myscore_template_game',        '<strong>%USERNAME%</strong> - %SCORE%');
    add_option('myscore_template_high_buddypress', $user_highscores);
    add_option('myscore_template_latest_userpage', $latest_user);
    add_option('myscore_template_latest_userscores', '');
    add_option('myscore_bp_template', 'template');
  }
  
  // Update to 2.00
  if ( !get_option('myscore_template_high_buddypress') ) {
    add_option('myscore_template_latest_userscores', '');
    add_option('myscore_template_high_buddypress', $user_highscores);
    add_option('myscore_template_latest_userpage', $latest_user);
    add_option('myscore_bp_template', 'template');
  }
  
  if ( !get_option('myscore_template_leaderboard') ) {
    add_option('myscore_template_leaderboard', '%USERNAME% with %HIGHSCORE% Highscores');
  }
}

/**
 *******************************************************************************
 *   W I D G E T S
 *******************************************************************************
 */
 
/**
 * @brief 
 */
 
function myscore_init_widgets() {

  // Check for the API functions
  if (  !function_exists('wp_register_sidebar_widget') 
     || !function_exists('wp_register_widget_control') ) {
     
     // Functions doesn't exists..
      return;
  }
  
  register_widget('WP_Widget_MyScore_Latest_Scores');
  register_widget('WP_Widget_MyScore_Most_Active_Players');
  register_widget('WP_Widget_MyScore_Todays_Scores');
  register_widget('WP_Widget_MyScore_Game_Scores');
  register_widget('WP_Widget_MyScore_Leaderboard');
  
  // Add  this widget, only if BuddyPress is installed
  if ( function_exists('bp_displayed_user_id') ) {
    register_widget('WP_Widget_MyScore_User_Scores');
  }  
}

if ( class_exists('WP_Widget') ) {

  //
  // Widget: Latest scores
  //
  class WP_Widget_MyScore_Latest_Scores extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_Latest_Scores() {
      
      $widget_ops   = array('description' => 'Show latest scores on your site. Generated by MyScoresPresenter.');
      
      $this->WP_Widget('myscore_latest_scores', 'Latest Scores', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
    
      extract($args);
      
      $title = apply_filters('widget_title', esc_attr($instance['title']));
      $limit = intval($instance['limit']);
      
      echo $before_widget.$before_title.$title.$after_title;
      echo '<ul>'."\n";
      myscore_get_latest_scores($limit);
      echo '</ul>'."\n";
      echo $after_widget;
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Latest Scores', 'limit' => 10));
      
      $title = esc_attr($instance['title']);
      $limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
      
      <p>
        <label for="<?php echo $this->get_field_id('limit'); ?>">
          Limit 
          <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" />
        </label>
      </p>
      
      <?php
    }
  
  } // END class WP_Widget_MyScore_Latest_Scores


  //
  // Widget: Most Active Players
  //
  class WP_Widget_MyScore_Most_Active_Players extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_Most_Active_Players() {
      
      $widget_ops   = array('description' => 'Show the most active players on your site. Generated by MyScoresPresenter.');
      
      $this->WP_Widget('myscore_most_active_players', 'Most Active Players', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
    
      extract($args);
      
      $title = apply_filters('widget_title', esc_attr($instance['title']));
      $limit = intval($instance['limit']);
      
      echo $before_widget.$before_title.$title.$after_title;
      echo '<ul>'."\n";
      myscore_get_most_active_users($limit);
      echo '</ul>'."\n";
      echo $after_widget;
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Most Active Players', 'limit' => 10));
      
      $title = esc_attr($instance['title']);
      $limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
      
      <p>
        <label for="<?php echo $this->get_field_id('limit'); ?>">
          Limit 
          <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" />
        </label>
      </p>
      
      <?php
    }
  
  } // END class WP_Widget_MyScore_Most_Active_Players
  
 //
  // Widget: Site Leaderboard
  //
  class WP_Widget_MyScore_Leaderboard extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_Leaderboard() {
      
      $widget_ops   = array('description' => 'Show best players on your site.');
      
      $this->WP_Widget('myscore_leaderboard', 'MyArcade Leaderboard', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
    
      extract($args);
      
      $title = apply_filters('widget_title', esc_attr($instance['title']));
      //$limit = intval($instance['limit']);
      
      echo $before_widget.$before_title.$title.$after_title;
      echo '<ul>'."\n";
      myscore_get_leaderboard();
      echo '</ul>'."\n";
      echo $after_widget;
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      //$instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Leaderboard'));
      
      $title = esc_attr($instance['title']);
      //$limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
     <?php
    }
  
  }
  
  
  //
  // Widget: Todays Scores
  //
  class WP_Widget_MyScore_Todays_Scores extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_Todays_Scores() {
      
      $widget_ops   = array('description' => 'Shows todays scores on your site. Generated by MyScoresPresenter.');
      
      $this->WP_Widget('myscore_todays_scores', 'Todays Scores', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
    
      extract($args);
      
      $title = apply_filters('widget_title', esc_attr($instance['title']));
      $limit = intval($instance['limit']);
      
      echo $before_widget.$before_title.$title.$after_title;
      echo '<ul>'."\n";
      myscore_get_todays_scores($limit);
      echo '</ul>'."\n";
      echo $after_widget;
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Todays Scores', 'limit' => 10));
      
      $title = esc_attr($instance['title']);
      $limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
      
      <p>
        <label for="<?php echo $this->get_field_id('limit'); ?>">
          Limit 
          <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" />
        </label>
      </p>
      
      <?php
    }
  } // END class WP_Widget_MyScore_Todays_Scores


  //
  // Widget: Show Game Scores
  //
  class WP_Widget_MyScore_Game_Scores extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_Game_Scores() {
      
      $widget_ops   = array('description' => 'Shows the scores of a game. This widget can only be displayed on single post template. Generated by MyScoresPresenter.');
      
      $this->WP_Widget('myscore_game_scores', 'Single Game Scores', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
      global $mypostid;
    
      if ( (is_single() || is_page()) && !empty($mypostid) ) {
        extract($args);
        
        $title = apply_filters('widget_title', esc_attr($instance['title']));
        $limit = intval($instance['limit']);
        
        echo $before_widget.$before_title.$title.$after_title;
        echo '<ul>'."\n";
        myscore_get_game_scores($limit);
        echo '</ul>'."\n";
        echo $after_widget;
      }
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Game Scores', 'limit' => 10));
      
      $title = esc_attr($instance['title']);
      $limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
      
      <p>
        <label for="<?php echo $this->get_field_id('limit'); ?>">
          Limit 
          <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" />
        </label>
      </p>
      
      <?php
    }
  } // END class WP_Widget_MyScore_Game_Scores
  
  
  //
  // Widget: Show User Scores
  //
  class WP_Widget_MyScore_User_Scores extends WP_Widget {
  
    // Constructor
    function WP_Widget_MyScore_User_Scores() {
      
      $widget_ops   = array('description' => 'Shows latest scores of an user (needs BuddyPress). Generated by MyScoresPresenter.');
      
      $this->WP_Widget('myscore_user_scores', 'Latest User Scores', $widget_ops);
    }
    
    // Display Widget
    function widget($args, $instance) {
    
      // Show this only when we are on the users profile pages
      $userid = bp_displayed_user_id();
      if ( !empty($userid) ) {

        extract($args);
        
        $title = apply_filters('widget_title', esc_attr($instance['title']));
        $limit = intval($instance['limit']);
        
        echo $before_widget.$before_title.$title.$after_title;
        echo '<ul>'."\n";
        myscore_show_users_scores($userid, $limit);
        echo '</ul>'."\n";
        echo $after_widget;
      }
    }
    
    // Update Widget
    function update($new_instance, $old_instance) {
    
      $instance = $old_instance;
      $instance['title'] = strip_tags($new_instance['title']);
      $instance['limit'] = intval($new_instance['limit']);
      
      return $instance;
    }
    
    // Display Widget Control Form
    function form($instance) {
      global $wpdb;
      
      $instance = wp_parse_args((array) $instance, array('title' => 'Latest User Scores', 'limit' => 10));
      
      $title = esc_attr($instance['title']);
      $limit = intval($instance['limit']);
      
      ?>
      
      <p>
        <label for="<?php echo $this->get_field_id('title'); ?>">
          Title 
          <input class="widefat" id="<?php echo $this->get_field_id('title'); ?>" name="<?php echo $this->get_field_name('title'); ?>" type="text" value="<?php echo $title; ?>" />
        </label>
      </p>
      
      <p>
        <label for="<?php echo $this->get_field_id('limit'); ?>">
          Limit 
          <input class="widefat" id="<?php echo $this->get_field_id('limit'); ?>" name="<?php echo $this->get_field_name('limit'); ?>" type="text" value="<?php echo $limit; ?>" />
        </label>
      </p>
      
      <?php
    }
  } // END class WP_Widget_MyScore_Game_Scores
    
  
} // END if class_exists WP_Widget


/**
 *******************************************************************************
 *   B U D D Y P R E S S  I N T E G R A T I O N
 *******************************************************************************
 */

/*
 * @brief Only load code that needs BuddyPress to run once BP is loaded and 
 *        initialized.
 */
if ( defined( 'BP_VERSION' ) ) {
  bp_myscore_loader();
} else {
  add_action( 'bp_init', 'bp_myscore_loader' );
}


/*
 * @brief Load the menu and add Profile Code
 */
function bp_myscore_loader() {
  // Extend the Buddypress menu with the MyScoresPrensenters menu
  add_action('wp', 'bp_myscore_extend_profile_navi', 2);

  // add special score content to the public profile
  //add_action('bp_after_profile_content','bp_add_public_profile_content');
  //add_action('bp_before_member_activity_post_form','bp_add_public_profile_content');
  
  // add filter to load and create a special template filter
  add_filter( 'bp_located_template', 'bp_myscore_load_template_filter', 10, 2);
}


/**
 * @brief Define a custom load template filter for the component.
 */
function bp_myscore_load_template_filter($found_template, $templates) {
  global $bp;

  /**
   * Only filter the template location when we're on the score component pages.
   */
  if ($bp->current_component != $bp->myscore->slug)
    return $found_template;

  foreach ((array) $templates as $template) {
    if ( file_exists( STYLESHEETPATH . '/' . $template ) )
      $filtered_templates[] = STYLESHEETPATH . '/' . $template;
    else
      $filtered_templates[] = dirname( __FILE__ ) . '/' . $template;
  }

  $found_template = $filtered_templates[0];

  return apply_filters( 'bp_example_load_template_filter', $found_template);
}


/**
 * @brief Extend the profile navigation menu
 */
function bp_myscore_extend_profile_navi() {
  global $bp;

  /* For internal identification */
  $bp->myscore->id = 'scores';
  $bp->myscore->slug = 'scores';

  /* Register this in the active components array */
  $bp->active_components[$bp->myscore->slug] = $bp->myscore->id;

  /* Add 'Scores' to the main user profile navigation */
  bp_core_new_nav_item( array(
    'name' => __( 'Scores', 'bp-myscores' ),
    'slug' => $bp->myscore->slug,
    'position' => 80,
    'screen_function' => 'bp_myscore_screen_submenu',
    'default_subnav_slug' => 'my-score'
  ) );

  $myscore_link = $bp->loggedin_user->domain . $bp->myscore->slug . '/';

  /* Create 'My Score' sub nav items for this component */
  bp_core_new_subnav_item( array(
    'name' => __( 'My Score', 'bp-myscores' ),
    'slug' => 'my-score',
    'parent_slug' => $bp->myscore->slug,
    'parent_url' => $myscore_link,
    'screen_function' => 'bp_myscore_screen_submenu',
    'position' => 10,
    'user_has_access' => bp_is_my_profile() // Only the logged in user can access this on his/her profile
  ) );
}


/**
 * @brief Create the screen submenu and include it into the template
 */
function bp_myscore_screen_submenu() {
  //Displaying Content
  add_action( 'bp_template_content', 'bp_show_myscore_submenu_content');
  
  // What should we show
  if ( get_option('myscore_bp_template') == 'themefile' ) {
    bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'template/myscoresbptemplate' ) );
  }
  else {
    bp_core_load_template( apply_filters( 'bp_core_template_plugin', 'members/single/plugins' ) );
  }
}


/**
 * @brief Show the submenu content
 */
function bp_show_myscore_submenu_content() {
  
  echo '<h2>High Scores</h2>';
  echo '<ul>';
  myscore_get_users_highscore_per_game(bp_displayed_user_id());
  echo '</ul>';
}

/**
 * @brief Show the public profile content
 */
function bp_add_public_profile_content() {
  //echo 'Public Profile Content';
}
?>