<?php
# ************** LICENCE ****************
/*
	Copyright (c) PORTANEO.

	This file is part of POSH (Portaneo Open Source Homepage) http://sourceforge.net/projects/posh/.

	POSH is free software: you can redistribute it and/or modify
	it under the terms of the GNU General Public License as published by
	the Free Software Foundation, either version 3 of the License, or
	(at your option) any later version

	POSH is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with Posh.  If not, see <http://www.gnu.org/licenses/>.
*/
# ***************************************
# restricted modules for a user
#
# !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
#
# ***************************************
/**
*
* \brief Save widget notation
*
*   return xml file
*
*  \relatesalso
*   ajax.js
*   $p.app.menu.widget.setWidgetsRatings
*
* !! be careful, this file must be saved under uft8 format, and display an e accentuated here : é
*
**/

$folder="";
$not_access=1;
$granted="I,A";
$pagename="portal/xml_setwidgetratings.php";
//includes
require_once('includes.php');
require_once('../includes/xml.inc.php');

$file=new xmlFile();

$file->header("channel");

$average_rating = 0;
$total_rating = 0;
$new_average_rating = 0;
$new_total_rating = 0;
$itemid = isset($_GET['itemid'])?$_GET['itemid']:0;
$rating = isset($_GET['rating'])?$_GET['rating']:0;
$rating = ($rating>5)?5:$rating;
$sum_rating = 0;

// check user notation
$DB->getResults($xml_checkUserWidgetsRatings, $DB->escape($_SESSION['user_id']), $DB->escape($itemid));
if ( $DB->nbResults()==0 ) {

	//get current notation
	$DB->getResults($xml_getWidgetsRatings, $DB->escape($itemid));
	$row = $DB->fetch(0);
		$average_rating = $row['average_rating'];
		$total_rating = $row['total_rating'];
		$sum_rating = ($row['sum_rating']>0)?$row['sum_rating']:0;
	$DB->freeResults();
		
	$new_total_rating = $total_rating + 1;
	
	$new_average_rating = ( (float)($rating) + (float)$sum_rating)/((float)$new_total_rating);
	
	$sum_rating = (float)($sum_rating) + (float)($rating);
	
	// Save new info
	$DB->execute($xml_updateNewWidgetsRatings,$DB->quote($new_average_rating), $DB->escape($new_total_rating), $DB->escape($sum_rating), $DB->escape($itemid));
	$DB->execute($xml_insertUserWidgetsRatings,$DB->escape($itemid), $DB->escape($_SESSION['user_id']), $DB->escape($rating));
	
	echo "<item>";
	echo "<itemid>".$itemid."</itemid>";
	echo "<nbratings>".$new_total_rating."</nbratings>";
	echo "<avg>".(round($new_average_rating*2)/2)."</avg>";
	echo "</item>";
			
	$file->footer();

	$DB->close();
}
?>