<?php
//================================================================
// genarete 100 votedata data for weblinks
// for debug
// 2005-03-28 K.OHWADA
//================================================================

// --- votedata table ---
//  ratingid int(11)
//  lid int(11)
//  ratinguser int(11)
//  rating tinyint(3)
//  ratinghostname varchar(60)
//  ratingtimestamp int(10)

include '../../../../mainfile.php';
include '../../../../include/cp_header.php';

global $xoopsDB, $xoopsUser, $xoopsModule;
xoops_cp_header();

// check permission
$flag = false;
if ($xoopsUser && $xoopsUser->isAdmin($xoopsModule->mid())) 
{	$flag = true;	}

if (!$flag)
{
	echo "<font color=red>you are not admin</font><br>";
	xoops_cp_footer();
	exit();
}

$MAX_VOTE = 100;

$max_lid = intval( $MAX_VOTE / 4 );

// table name
$table_votedata = $xoopsDB->prefix("weblinks_votedata");
$table_link     = $xoopsDB->prefix("weblinks_link");

echo "<h3>start</h3>";

srand( (double)microtime()*1000000 );

for ($i=0; $i<$MAX_VOTE; $i++)
{

// randum data
	$lid = rand(1, $max_lid);
	$ratinguser = rand(1, 10);
	$rating     = rand(0, 10);
	$ratinghostname  = get_randum_ip();
	$ratingtimestamp = get_randum_time();

// votedata table
	$sql  = "INSERT INTO $table_votedata ";
	$sql .= "(lid, ratinguser, rating, ratinghostname, ratingtimestamp)";
	$sql .= "VALUES ";
	$sql .= "($lid, $ratinguser, $rating, '$ratinghostname', $ratingtimestamp)";

	echo "$sql <br>";
	sql_exec($sql);

}

echo "<br>";

$sql2 = "SELECT lid, count(lid), sum(rating) FROM $table_votedata GROUP BY lid ";
$res2 = sql_exec($sql2);

while ( $row2 = $xoopsDB->fetchRow($res2) )
{
	$lid   = $row2[0];
	$count = $row2[1];
	$sum   = $row2[2];

	$rating = $sum / $count;

	$sql = "UPDATE $table_link SET rating=$rating, votes=$count WHERE lid=$lid";

	echo "$sql <br>";
	sql_exec($sql);
}

echo "<h3>end</h3>";
xoops_cp_footer();
exit();
// ---

function get_randum_char()
{
	return chr( rand(97,122) );
}

function get_randum_time()
{
	$time = time() - rand(0, 365*24*60*60);	// 1 year
	return $time;
}

function get_randum_ip()
{
	$ip = "192.168.1." . rand(1,255);
	return $ip;
}

function sql_exec($sql)
{ 
	global $xoopsDB;

	$ret = $xoopsDB->queryF($sql);
	if ($ret != false ) { return $ret; }

	$error = $xoopsDB->error();
	echo "<font color=red>$sql<br>$error</font><br>";

	return false;
}


?>