Ver Mensaje Individual
  #1 (permalink)  
Antiguo 17/08/2010, 10:59
Avatar de estibaliz2006
estibaliz2006
 
Fecha de Ingreso: noviembre-2006
Mensajes: 439
Antigüedad: 17 años, 5 meses
Puntos: 1
Sistema de Rating de Jack Moore - ColorRating

Hola a todos/as. Estoy tratando de implementar un sistema de ratings en una aplicación. Buscando llegué a la conclusión que el que más me gusta es el que programó Jack Moore que es el que os expongo a continuación. El problema está en que no sé adaptarlo a mis necesidades. Os cuento:

La aplicación para la que lo quiero es un sistema de noticias identificadas cada una de ellas mediante un codigonot, que es un código exclusivo para cada noticia. lo que quiero es implementar este sistema de rating de tal modo que se computen los votos de cada noticia y se almacenen en la base de datos, relacionandolos mediante el codigonot.

bien. los archivos de Jack Moore son los siguientes:

archivo example.php:

Código PHP:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
    <meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <meta name="Description" content="" />
    <title>ColorRating Example</title>

    <!-- Core Files.  Change the hyperlink references to reflect your site structure.  Note, this must also be updated in the ratings.js file. -->
    <link rel="stylesheet" type="text/css" href="rating/rating.css" media="screen"/>
    <script type="text/javascript" src="http://www.google.com/jsapi"></script>
    <script type="text/javascript">google.load("jquery", "1.3.2");</script>
    <script type="text/javascript" src="rating/rating.js"></script>
    <?php include('rating/rating.php'); ?>

</head>
<body>

    <!-- Replace 'test1' with a unique name.  Repeat this for every item you want to score. -->
    <?php rating_form("codigo"); ?>
        <?php rating_form("codigo1"); ?>

</body>
</html>
archivo rating.css:

Código PHP:
.rating_wrapper *{margin:0border:0padding:0;}
.
rating_wrapper {overflow:hiddenheight:16px;}
.
sp_rating{font-family:VerdanaGenevaArialHelveticasans-seriffont-size:11pxline-height:1.7emcolor:#5f5f5f; display:block;}
    
.rating{float:leftpadding-right:4px;}
    .
base{background:url(ratings.gif0 0 no-repeatwidth:85pxheight:100%; float:leftpadding-right:4pxoverflow:hidden;}
    .
average{background:url(ratings.gif-16px no-repeattext-indent:-9999px;}
    .
votes{float:leftpadding-right:4px;}
    .
scorebackground:url(ratings.gif0 0 no-repeatwidth:85pxheight:100%; float:leftposition:relative;}
        .
score a{display:blockheight:100%; float:lefttext-indent:-9999pxposition:absoluteoverflow:hiddenline-height:1em;}
        .
score1 {width:20%; z-index:55;}
        .
score2 {width:40%; z-index:54;}
        .
score3 {width:60%; z-index:53;}
        .
score4 {width:80%; z-index:52;}
        .
score5 {width:100%; z-index:51;}
        .
score a:hoverbackground:url(ratings.gifbottom right no-repeat;}
    .
status {height:16pxwidth:100pxoverflow:hiddenposition:relative;}
        
    .
score_thisheight:100%; overflow:hidden;}
        .
score_this a{color:#f37800;} 
archivo rating.php:

Código PHP:
<?php
class rating{

    public 
$average 0;
    public 
$votes;
    public 
$status;
    public 
$table;
    private 
$path;
    
    function 
__construct($table){
        try{
            
$pathinfo pathinfo(__FILE__);
            
$this->path realpath($pathinfo['dirname']) . "/database/ratings.sqlite";
            
$dbh = new PDO("sqlite:$this->path");
            
$this->table $dbh->quote($table);
            
// check if table needs to be created
            
$table_check $dbh->query("SELECT * FROM $this->table WHERE id='1'");
            if(!
$table_check){
                
// create database table
                
$dbh->query("CREATE TABLE $this->table (id INTEGER PRIMARY KEY, rating FLOAT(3,2), ip VARCHAR(15))");
                
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES (0, 'master')");                
            } else {
                
$this->average $table_check->fetchColumn(1);
            }
            
$this->votes = ($dbh->query("SELECT COUNT(*) FROM $this->table")->fetchColumn()-1);
        }catch( 
PDOException $exception ){
                die(
$exception->getMessage());
        }
        
$dbh NULL;        
    }

    function 
set_score($score$ip){
        try{
            
$dbh = new PDO("sqlite:$this->path");
            
$voted $dbh->query("SELECT id FROM $this->table WHERE ip='$ip'");
            if(
sizeof($voted->fetchAll())==0){
                
                
$dbh->query("INSERT INTO $this->table (rating, ip) VALUES ($score, '$ip')");
                
$this->votes++;
                
                
//cache average in the master row
                
$statement $dbh->query("SELECT rating FROM $this->table");
                
$total $quantity 0;
                
$row $statement->fetch(); //skip the master row
                
while($row $statement->fetch()){
                    
$total $total $row[0];
                    
$quantity++;
                }
                
$this->average round((($total*20)/$quantity),0);
                
$statement $dbh->query("UPDATE $this->table SET rating = $this->average WHERE id=1");
                
$this->status '(gracias por tu participar!)';
            } else {
                
$this->status '(ya has votado)';
            }
            
        }catch( 
PDOException $exception ){
                die(
$exception->getMessage());
        }
        
$dbh NULL;
    }
}

function 
rating_form($table){
    
$ip $_SERVER["REMOTE_ADDR"];
    if(!isset(
$table) && isset($_GET['table'])){
        
$table $_GET['table'];
    }
    
$rating = new rating($table);
    
$status "<div class='score'>
                <a class='score1' href='?score=1&amp;table=$table&amp;user=$ip'>1</a>
                <a class='score2' href='?score=2&amp;table=$table&amp;user=$ip'>2</a>
                <a class='score3' href='?score=3&amp;table=$table&amp;user=$ip'>3</a>
                <a class='score4' href='?score=4&amp;table=$table&amp;user=$ip'>4</a>
                <a class='score5' href='?score=5&amp;table=$table&amp;user=$ip'>5</a>
            </div>
    "
;
    if(isset(
$_GET['score'])){
        
$score $_GET['score'];
        if(
is_numeric($score) && $score <=&& $score >=&& ($table==$_GET['table']) && isset($_GET["user"]) && $ip==$_GET["user"]){
            
$rating->set_score($score$ip);
            
$status $rating->status;
        }
    }
    if(!isset(
$_GET['update'])){ echo "<div class='rating_wrapper'>"; }
    
?>
    <div class="sp_rating">
        <div class="rating">Rating:</div>
        <div class="base"><div class="average" style="width:<?php echo $rating->average?>%"><?php echo $rating->average?></div></div>
        <div class="votes"><?php echo $rating->votes?> votos</div>
        <div class="status">
            <?php echo $status?>
        </div>
    </div>
    <?php
    
if(!isset($_GET['update'])){ echo "</div>"; }
}

if(isset(
$_GET['update'])&&isset($_GET['table'])){
    
rating_form($_GET['table']);
}
archivo rating.js:

Código PHP:
$(document).ready(function() {
    $(
'.status').prepend("<div class='score_this'>(<a href='#'>score this item</a>)</div>");
    $(
'.score_this').click(function(){
        $(
this).slideUp();
        return 
false;
    });
    
    $(
'.score a').click(function() {
        $(
this).parent().parent().parent().addClass('scored');
        $.
get("rating/rating.php" + $(this).attr("href") +"&update=true", {}, function(data){
            $(
'.scored').fadeOut("normal",function() {
                $(
this).html(data);
                $(
this).fadeIn();
                $(
this).removeClass('scored');
            });
        });
        return 
false
    });
}); 
imagen usada:
http://colorpowered.com/colorrating/rating/ratings.gif

Bien. el problema es que no sé enlazar todo esto con mi aplicación, sobre todo, que cada voto se acumule en cada noticia en cuestión. el rating.php viene lo suficientemente avanzado para mí como para no entender su lógica ni donde meter el codigonot necesario que identifique los votos de cada noticia.

Podéis ayudarme? es una aplicación sumamente interesante. de las más llamativas que he visto en cuanto a ratings.

espero vuestra ayuda
__________________
desgraciadamente no conozco php ni la mitad de lo que lo conocen ustedes y eso es menos de la mitad de lo que yo querria y lo que yo querria es menos de la mitad de lo que la mitad de ustedes conocen