3 * Nucleus: PHP/MySQL Weblog CMS (http://nucleuscms.org/)
4 * Copyright (C) 2002-2012 The Nucleus Group
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 * (see nucleus/documentation/index.html#license for more info)
12 * Class representing the karma votes for a certain item
16 // id of item about which this object contains information
19 // indicates if the karma vote info has already been intialized from the DB
22 // amount of positive/negative votes
26 function KARMA($itemid, $initpos = 0, $initneg = 0, $initread = 0) {
28 $this->itemid = intval($itemid);
30 // have we read the karma info yet?
31 $this->inforead = intval($initread);
33 // number of positive and negative votes
34 $this->karmapos = intval($initpos);
35 $this->karmaneg = intval($initneg);
38 function getNbPosVotes() {
39 if (!$this->inforead) $this->readFromDatabase();
40 return $this->karmapos;
42 function getNbNegVotes() {
43 if (!$this->inforead) $this->readFromDatabase();
44 return $this->karmaneg;
46 function getNbOfVotes() {
47 if (!$this->inforead) $this->readFromDatabase();
48 return ($this->karmapos + $this->karmaneg);
50 function getTotalScore() {
51 if (!$this->inforead) $this->readFromDatabase();
52 return ($this->karmapos - $this->karmaneg);
55 function setNbPosVotes($val) {
56 $this->karmapos = intval($val);
58 function setNbNegVotes($val) {
59 $this->karmaneg = intval($val);
63 // adds a positive vote
64 function votePositive() {
65 $newKarma = $this->getNbPosVotes() + 1;
66 $this->setNbPosVotes($newKarma);
67 $this->writeToDatabase();
71 // adds a negative vote
72 function voteNegative() {
73 $newKarma = $this->getNbNegVotes() + 1;
74 $this->setNbNegVotes($newKarma);
75 $this->writeToDatabase();
81 // these methods shouldn't be called directly
82 function readFromDatabase() {
83 $query = 'SELECT ikarmapos, ikarmaneg FROM '.sql_table('item').' WHERE inumber=' . $this->itemid;
84 $res = sql_query($query);
85 $obj = sql_fetch_object($res);
87 $this->karmapos = $obj->ikarmapos;
88 $this->karmaneg = $obj->ikarmaneg;
93 function writeToDatabase() {
94 $query = 'UPDATE '.sql_table('item').' SET ikarmapos=' . $this->karmapos . ', ikarmaneg='.$this->karmaneg.' WHERE inumber=' . $this->itemid;
98 // checks if a vote is still allowed for an IP
99 function isVoteAllowed($ip) {
100 $query = 'SELECT * FROM '.sql_table('karma')." WHERE itemid=$this->itemid and ip='".sql_real_escape_string($ip)."'";
101 $res = sql_query($query);
102 return (sql_num_rows($res) == 0);
105 // save IP in database so no multiple votes are possible
107 $query = 'INSERT INTO '.sql_table('karma').' (itemid, ip) VALUES ('.$this->itemid.",'".sql_real_escape_string(serverVar('REMOTE_ADDR'))."')";