<?php
function addComment( $aForm, $iLink, $sFileDb = null ){
	if( !isset( $sFileDb ) ) $sFileDb = DB_PAGES_COMMENTS;
	$oDB = DataBase::getInstance( );
	$aForm['sComment'] = nl2br( $aForm['sComment'] );
	$aForm = changeMassTxt( $aForm, 'HLen', Array( 'sContent', 'HBrLen' ) );
	$aForm['iTime'] = time( );
	$aForm['iLink'] = $iLink;
	$aForm['sIp'] = $_SERVER['REMOTE_ADDR'];
	$aForm['iStatus'] = 1;
	if( isset( $_SESSION['iUserClient'] ) && is_numeric( $_SESSION['iUserClient'] ) && ( $_SESSION['iUserClient'] > 0 ) && defined( 'CUSTOMER_PAGE' ) ){
		$sUserId = intval( $_SESSION['iUserClient'] );
	} else{
		$sUserId = false;
	}
	$aForm['iAccepted'] = $GLOBALS['config']['comments_auto_accept'] || ( $GLOBALS['config']['comments_auto_accept_logged'] && $sUserId ) ? 1 : 0;
	$oDB->save( $sFileDb, $aForm, null, 'rsort' );
}
function commentInfo( $iComment, $sFileDb = null ){
	if( !isset( $sFileDb ) ){
		$sFileDb = DB_PAGES_COMMENTS;
		$bPages = true;
	}
	$oDB = DataBase::getInstance( );
	if( is_numeric( $iComment ) ){
		$sql = 'SELECT * FROM `' . $oDB->throwTableName( $sFileDb ) . '` WHERE `iComment` = \'' . $iComment . '\';';
		$aComment = $oDB->executeSQL( $sql, true, DataBase::SINGLE_RECORD );
		
		$aComment['sComment'] = nl2br( $aComment['sComment'] );
		
		$aComment['sDate'] = date( 'Y-m-d H:i', $aComment['iTime'] );
		return $aComment;
	}
}
function throwComments( $iLink, $sFileDb = null, &$rating = null, $hide_unaccepted = true, $hide_disabled = true, &$iComments = null, $iCommentsLimit = null ){
	if( !isset( $sFileDb ) ){
		$bPages = true;
		$sFileDb = DB_PAGES_COMMENTS;
	}
	$oDB = DataBase::getInstance( );
	if( !isset( $iCommentsLimit ) ) $iCommentsLimit = 100;
	if( isset( $iLink ) && is_numeric( $iLink ) ) $sql = 'SELECT * FROM `' . $oDB->throwTableName( $sFileDb ) . '` WHERE `iLink` = \'' . $iLink . '\'' . ( $hide_unaccepted ? ' AND `iAccepted` = \'1\'' : '' ) . ' ' . ( $hide_disabled ? ' AND `iStatus` = \'1\'' : '' ) . ' ORDER BY `iComment` DESC LIMIT ' . $iCommentsLimit . ';';
	else $sql = 'SELECT * FROM `' . $oDB->throwTableName( $sFileDb ) . '`' . ( $hide_unaccepted ? ' WHERE `iAccepted` = \'1\'' : '' ) . ' ORDER BY `iComment` DESC LIMIT ' . $iCommentsLimit . ';';
	$aComments = $oDB->executeSQL( $sql, true );
	$iComments = count( $aComments );
	$rating = 0;
	$rating_count = 0;
	foreach( $aComments as &$aData ){
		$aData['sLinkName'] = isset( $bPages ) ? $GLOBALS['oPage']->aPages[$aData['iLink']]['sName'] : $GLOBALS['oProduct']->aProducts[$aData['iLink']]['sName'];
		$aData['sDate'] = date( 'Y-m-d H:i', $aData['iTime'] );
		if( isset( $aData['iRating'] ) && !empty( $aData['iRating'] ) ){
			$rating+= $aData['iRating'];
			$rating_count++;
		}
	}
	if( $rating_count > 0 ) $rating = (float)$rating / $rating_count;
	return $aComments;
}
?>