<?php
/* daCode http://www.dacode.org/
 * src/phplib/hits.php3
 * $Id: hits.php3,v 1.25 2001/07/11 09:22:27 penso Exp $
 * Fabien PENSO <penso@linuxfr.org>
 *
 * Used to count hits on links
 *
 * Depends: Config Db
*/

Class Hits {

	Function Hits() {
//echo '<br>Hits';
		$this->db = LoadClass('Db');
	}

	/* return number of hits */
	Function view($id) {
		global $config;

		$sqlc_q = "SELECT hits FROM ".$config->tables['urls_hits']." WHERE ".
			"news_urls_id='".addslashes($id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "SQL failed: ".$this->db->error();
			return -1;
		}
		if ($this->db->num_rows()) {
			$row = $this->db->fetch_array();
		} else {
			$row[0] = 0;
		}
		if ($row[0] <= 1) {
			$out = $row[0] . " hit";
		} else {
			$out = $row[0] . " hits";
		}
		$this->db->free();

		return $out;
	}

	/* Add hits+1 or create it */
	Function add($id) {
		global $config;

		$sqlc_q = "SELECT hits FROM ".$config->tables['urls_hits']." WHERE news_urls_id='".addslashes($id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "SQL failed: ".$this->db->error();
			return -1;
		}

		if (!$this->db->num_rows()) {
			$sqlc_q = "INSERT INTO ".$config->tables['urls_hits']." (news_urls_id,hits) VALUES".
				" ('".addslashes($id)."', '1')";
		} else {
			$sqlc_q = "UPDATE ".$config->tables['urls_hits']." set hits=hits+1 WHERE ".
				"news_urls_id='".addslashes($id)."'";
		}

		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "SQL failed: ".$this->db->error();
			return -1;
		}
	}

	/* Returns a <a href="url">name</a> link with appropriate redirect */
	Function make($make_tempo) {
		global $config;

		$out = "<a href=\"".
				$config->basehref.
				$config->redirecthref.
				"?i=".$make_tempo['id']."\"".
				" onMouseOver=\"window.status='".
				htmlentities(str_replace("'","\'",$make_tempo['url']))."'; ".
				"return true;\" onMouseOut=\"self.status=''; return ".
				"true;\">".
				$make_tempo['name']."</a> (".$make_tempo['hits']." ";
		if ($make_tempo['hits'] <= 1) {
			$out .= lecho("hit");
		} else {
			$out .= lecho("hits");
		}
		$out .= ")";

		return $out;
	}

	/* Header the url */
	Function header($id) {
		global $config;

		$this->add($id);
		$sqlc_q = "SELECT ".$config->tables['urls'].".url FROM ".
			$config->tables['urls'].",".$config->tables['news_urls']
			." WHERE ".$config->tables['news_urls'].".urls_id=".
			$config->tables['urls'].".id AND ".
			$config->tables['news_urls'].".id='".addslashes($id)."'";
		$ret = $this->db->query($sqlc_q);
		if (!$ret) {
			echo "SQL failed: ".$this->db->error();
			echo "SQL Command was: $sqlc_q";
			return -1;
		}
		$tmp = $this->db->fetch_array();
		Header("Location: $tmp[0]");
	}

}


?>
