I completely ported "Vouchers" from Netvision Bittorrent-Tracker. This allows user to use voucher codes that they redeem for GBs and other things.
Also includes moderator/admin only links to manage and edit/reset codes, create new vouchers & reset user "last used" list. Works 100% for me, I verified data allowance!
classes/class.vouchers.php
vouchers.php
[ATTACH type="full" width="776px" alt="4.png"]5908[/ATTACH]
[ATTACH type="full" width="777px" alt="3.png"]5907[/ATTACH]
Also includes moderator/admin only links to manage and edit/reset codes, create new vouchers & reset user "last used" list. Works 100% for me, I verified data allowance!
classes/class.vouchers.php
<?
class voucher
{
protected $today;
protected $id;
protected $code;
protected $date;
protected $value;
protected $users_str;
protected $con;
function __construct($code = ""){
$this->today = date("Y-m-d");
// ..
if($code != ""){
$this->code = $code;
$this->loadVoucher($this->code);
}
}
/**
* inserts a new voucher code into the database
*
* @param str $code
* @param str $date
* @param int $value
* @param bool $load
*
* @return bool
*/
public function create($code = "", $date = "", $value = 0, $load = false){
global $db;
if($code == "")
$code = $this->randomString();
else{
if(strlen($code) < 20)
$code = $code . $this->randomString((20-strlen($code)));
}
if($date == "")
$date = $this->today;
if($value == 0)
$value = $this->defaultValue();
else
$value = $this->makeMegaByte($value);
$str = $this->emptyJSON();
$qry = $db->query_params('INSERT INTO vouchers (id, code, date, value, users) VALUES (NULL,:code,:date,:value,:users)', array('code' => $code, 'date' => $date, 'value' => $value, 'users' => $str));
//if($qry->rowCount()){
if($qry){
if($load !== false){
$this->code = $code;
if($this->loadVoucher($this->code) === false)
return false;
}
return true;
}else
return false;
}
public function resetUsers(){
$this->users_str = $this->emptyJSON();
if($this->saveVoucher() === true)
return true;
return false;
}
/**
* uses a voucher
*
* @param int $userid
*
* @return bool
*/
public function useVoucher($userid){
$users_arr = $this->makeUserArray();
if($this->canUse($users_arr,$userid) === true){
$a = $this->insertUser($users_arr, $userid);
$this->makeUsersString($a);
$this->giveReward($userid);
if($this->saveVoucher() === true)
return true;
return false;
}else
return false;
}
/**
* deletes a voucher from the database
*
* @return bool
*/
public function deleteVoucher(){
global $db;
$qry = $db->query_params('DELETE FROM vouchers WHERE code = :code', array('code' => $this->code));
if($qry)
return true;
return false;
}
/**
* returns a "nice" array with userids
*
* @return arr
*/
public function getPrettyUsers(){
return $this->makeUserArray();
}
/**
* saves changes to the voucher
*
* @return bool
*/
public function saveVoucher(){
global $db;
if($this->date == "")
$this->date = $this->today;
if($this->value == 0)
$this->value = $this->defaultValue();
$qry = $db->query_params('UPDATE vouchers SET date = :date, value = :value, users = :users WHERE code = :code', array('code' => $this->code, 'date' => $this->date, 'value' => $this->value, 'users' => $this->users_str));
if($qry)
return true;
return false;
}
/**
* Checks whether a voucher already exists for today or another day and returns it if necessary
*
* @param str $date
*
* @return bool
*/
public function todaysVoucher($date = ""){
global $db;
if($date == "")
$date = $this->today;
$qry = $db->query_params('SELECT code FROM vouchers WHERE date = :date', array('date' => $date));
if($qry){
//$row = $qry->Fetch(PDO::FETCH_ASSOC);
$row = $qry->fetch();
$this->code = $row['code'];
$this->loadVoucher($this->code);
return true;
}else
return false;
}
/**
* checks whether a user can use the voucher
*
* @param arr $uarr
* @param int $userid
*
* @return bool
*/
private function canUse($uarr, $userid){
if(in_array($userid, $uarr))
return false;
if($this->date != "0000-00-00" && $this->date != $this->today)
return false;
return true;
}
/**
* provides the standard value for a voucher (500 MB)
*
* @return int
*/
private function defaultValue(){
return 500 * 1024 * 1024;
}
/**
* returns an empty json string for a voucher
*
* @return str
*/
private function emptyJSON(){
$arr['users'] = 'nan';
return json_encode($arr, JSON_FORCE_OBJECT);
}
/**
* credits the value of the voucher
*
* @param int $userid
*
* @return bool
*/
private function giveReward($userid){
global $db;
$qry = $db->query_params('UPDATE users SET uploaded = uploaded + :value WHERE user_id = :user_id', array('value' => $this->value, 'user_id' => $userid));
if($qry)
return true;
return false;
}
/**
* Returns a random string of length $len made up of numbers and letters
*
* @param int $len
*
* @return str
*/
private function randomString($len = 20){
$zeichen = array('A','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z','1','2','3','4','5','6','7','8','9');
$s = "";
for($i = 0; $i < $len; $i++)
$s .= $zeichen[rand(0,count($zeichen)-1)];
return $s;
}
/**
* multiplies the desired value to MB
*
* @param int $mb
*
* @return int
*/
private function makeMegaByte($mb){
return $mb * 1024 * 1024;
}
/**
* converts the json string into a simple array
*
* @return arr
*/
private function makeUserArray(){
$o = array();
$uarr = json_decode($this->users_str, true);
if($uarr["users"] == "nan")
$o[] = "nan";
else{
$nuarr = explode(";", $uarr["users"]);
foreach($nuarr as $userid)
$o[] = $userid;
}
return $o;
}
/**
* converts the user array into a json string
*
* @param arr $arr
*/
private function makeUsersString($arr){
$narr["users"] = "";
if($arr[0] == "nan")
$narr["users"] = "nan";
elseif($arr[0] != "nan" && !isset($arr[1]))
$narr["users"] = $arr[0];
else
$narr["users"] = implode(";", $arr);
$this->users_str = json_encode($narr, JSON_FORCE_OBJECT);
}
/**
* inserts the userid of the user and returns the extended array
*
* @param arr $arr
* @param int $userid
*
* @return arr
*/
private function insertUser($arr, $userid){
if($arr[0] == "nan")
$arr[0] = $userid;
elseif($arr[0] != "nan")
$arr[] = $userid;
return $arr;
}
/**
* loads the desired voucher
*
* @param str $code
*
* @return bool
*/
private function loadVoucher($code){
global $db;
$qry = $db->query_params('SELECT id, date, value, users FROM vouchers WHERE code = :code', array('code' => $code));
if($qry){
$row = $qry->fetch();
$this->id = $row["id"];
$this->date = $row["date"];
$this->value = $row["value"];
$this->users_str = $row["users"];
return true;
}
return false;
}
/**
* returns property of the object (magic)
*
* @param mixed $name
*
* @return mixed
*/
public function __get($name){
return $this->{$name};
}
/**
* changes property of the object (magic)
*
* @param mixed $name
* @param mixed $value
*/
public function __set($name, $value){
$this->{$name} = $value;
}
}
vouchers.php
<?
if (session_status() == PHP_SESSION_NONE) { session_start(); }
// Vouchers - BETA
require_once '../site.php';
require_once('../classes/class.vouchers.php');
$db->connect();
site_header();
if(isset($_GET['action']))
$action = $_GET['action'];
else
$action = "view";
switch($action){
case "view":
break;
case "use":
if($_SERVER["REQUEST_METHOD"] === "POST"){
if(isset($_POST["code"]) && strlen($_POST["code"]) == 20){
$v = new voucher($_POST["code"]);
$v->useVoucher($account->getId());
header(sprintf('Location: %s/vouchers.php', $CONFIG['base_url']));
}else
echo '<b>' . strtoupper($_POST['code']) . '</b> is not a valid voucher. <a href="/vouchers.php">Back</a>';
}else
print("You can not do that!");
break;
case "create":
if($_SERVER["REQUEST_METHOD"] === "POST"){
if ($account->getUserRole() == 'Administrator'){
$code = ((isset($_POST["code"])) ? $_POST["code"] : "");
$date = ((isset($_POST["date"])) ? $_POST["date"] : "");
$value = ((isset($_POST["value"])) ? $_POST["value"] : 0);
$v = new voucher($code);
$v->create($code,$date,$value);
header(sprintf('Location: %s/vouchers.php', $CONFIG['base_url']));
}else
print("You have no authorization to do this!");
}else
print("You can not do that!");
break;
case "delete":
if ($account->getUserRole() == 'Administrator'){
if(isset($_GET["code"]) && strlen($_GET["code"]) == 20){
if(isset($_GET["sure"]) && $_GET["sure"] == 1){
$v = new voucher($_GET["code"]);
$v->deleteVoucher();
header(sprintf('Location: %s/vouchers.php', $CONFIG['base_url']));
}else
echo "Do you want to delete the code? Click <a href=\"" . $CONFIG['base_url'] . "/vouchers.php?action=delete&code=" . $_GET["code"] . "&sure=1\">here</a>, if you are sure.";
}else
print("Data seems to be missing!");
}else
print("You have no authorization to do this!");
break;
case "edit":
if ($account->getUserRole() == 'Administrator'){
if($_SERVER["REQUEST_METHOD"] === "POST"){
$code = ((isset($_POST["code"])) ? $_POST["code"] : "");
$date = ((isset($_POST["date"])) ? $_POST["date"] : "");
$value = ((isset($_POST["value"])) ? ($_POST["value"]) : 0);
$v = new voucher($code);
$v->date = $date;
$v->value = $value * 1024 * 1024;
$v->saveVoucher();
header(sprintf('Location: %s/vouchers.php', $CONFIG['base_url']));
}else{
if(isset($_GET["code"]) && strlen($_GET["code"]) == 20){
$v = new voucher($_GET["code"]);
}else
print("There appears to be a lack of data!");
}
}else
print("You have no authorization to do this!");
break;
case "wipe":
if ($account->getUserRole() == 'Administrator'){
if(isset($_GET["code"]) && strlen($_GET["code"]) == 20){
if(isset($_GET["sure"]) && $_GET["sure"] == 1){
$v = new voucher($_GET["code"]);
$v->resetUsers();
header(sprintf('Location: %s/vouchers.php', $CONFIG['base_url']));
}else
echo "Do you want to reset the code usage? Click <a href=\"" . $CONFIG['base_url'] . "/vouchers.php?action=wipe&code=" . $_GET["code"] . "&sure=1\">here</a>, if you are sure.";
}else
print("There appears to be a lack of data!");
}else
print("You have no authorization to do this!");
break;
}
if($action == "view"){
echo "<h2>Redeem Voucher</h2>";
echo "<table cellspacing=\"5\" cellpadding=\"0\" border=\"0\" style=\"width:100%\">\n".
" <tr>\n".
" <td valign=\"top\" width=\"50%\">\n".
" <table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" style=\"width:100%\" class=\"tableinborder\">\n".
" <tr class=\"tabletitle\" width=\"100%\">\n".
" <td width=\"100%\"><span class=\"normalfont\">Redeem codes you have received by the site or special events. These codes entitle you to <b>exclusive</b> site perks.</span></td>\n".
" </tr>\n".
" <tr>\n".
" <td width=\"100%\" class=\"tablea\">Voucher Code:<form method=\"post\" action=\"" . $CONFIG['base_url'] . "/vouchers.php?action=use\"><input type=\"text\" size=\"40\" name=\"code\" placeholder=\"___-___-____-XZ8-ST\" /> <input type=\"submit\" value=\"Redeem!\" class=\"btn\"></form></td>\n".
" </tr>".
" </table>\n".
" </td>\n".
" </tr>\n".
"</table>\n".
"<br>\n";
if ($account->getUserRole() == 'Administrator'){
"<table id=\"creator\" cellspacing=\"5\" cellpadding=\"0\" border=\"0\" style=\"width:100%;display:none\">\n".
" <tr>\n".
" <td valign=\"top\" width=\"50%\">\n".
" <table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" style=\"width:100%\" class=\"tableinborder\">\n".
" <form method=\"post\" action=\"" . $CONFIG['base_url'] . "/vouchers.php?action=create\">\n".
" <tr class=\"tabletitle\" width=\"100%\">\n".
" <td width=\"100%\" colspan=\"2\"><span class=\"normalfont\"><b>Create code</b></span></td>\n".
" </tr>\n".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\">Code:</td>\n".
" <td width=\"80%\" class=\"tableb\"><input type=\"text\" size=\"40\" name=\"code\" /><p>Up to 20 characters (A-Z, 0-9).<br>Valid codes are 20 characters long, so missing characters are padded.<br>Leave blank for random code.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\"><b>Valid on:</b></td>\n".
" <td width=\"80%\" class=\"tableb\"><input id=\"creator_input_date\" type=\"text\" size=\"40\" name=\"date\" /> <input type=\"button\" id=\"immer\" class=\"btn\" value=\"Always valid\" /><p>0000-00-00 00:00:00 for \"always\". <br> Holidays are automatically \"supplied\" if there is no voucher available. <br> Leave blank for today's validity.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\"><b>Value:</b></td>\n".
" <td width=\"80%\" class=\"tableb\"><input id=\"creator_input_value\" type=\"text\" size=\"40\" name=\"value\" /> <input type=\"button\" id=\"plus\" class=\"btn\" value=\"Plus 100MB\" /><p>Value in MB. <br> Will be counted towards the user's upload. <br> Leave free for 500MB.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"100%\" class=\"tableb\" colspan=\"2\"><input type=\"submit\" value=\"Create\" class=\"btn\"></td>\n".
" </tr>".
" </form>\n".
" </table>\n".
" </td>\n".
" </tr>\n".
"</table>\n".
"<input type=\"submit\" id=\"creator_show_button\" value=\"Create voucher code?\" />\n".
"<br>\n";
$qry = $db->query_params('SELECT code FROM vouchers ORDER BY id DESC');
if($qry){
echo "<table class=\"responsive-table\" cellspacing=\"5\" cellpadding=\"0\" border=\"0\" style=\"width:100%\">\n".
" <tr>\n".
" <td valign=\"top\" width=\"50%\">\n".
" <table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" style=\"width:100%\" class=\"tableinborder\">\n".
" <tr class=\"tabletitle\" width=\"100%\">\n".
" <td width=\"100%\" colspan=\"6\"><span class=\"normalfont\">Administrator / Manage Codes</span></td>\n".
" </tr>\n".
" <tr class=\"tabletitle\">\n".
" <td width=\"5%\"><b>ID</b></td>\n".
" <td width=\"20%\"><b>Code</b></td>\n".
" <td width=\"10%\"><b>Valid on</b></td>\n".
" <td width=\"7%\"><b>value</b></td>\n".
" <td width=\"48%\"><b>was used by</b></td>\n".
" <td width=\"10%\"><b>Actions</b></td>\n".
" </tr>";
foreach($qry as $vc){
$v = new voucher($vc['code']);
if($v->date == '0000-00-00 00:00:00')
$pretty_date = "<font color=\"green\">Valid</font>";
else{
$pretty_date = $v->date;
if($v->date == date('Y-m-d'))
$pretty_date .= "<br><font color=\"green\">Valid Today</font>";
else
$pretty_date .= "<br><font color=\"red\">Not Valid</font>";
}
$pretty_value = $v->value / 1024 / 1024;
$pretty_unit = " MB";
if($pretty_value >= 1024){
$pretty_value = str_replace(".", ",", round(($pretty_value / 1024),2));
$pretty_unit = " GB";
}
$pua = $v->getPrettyUsers();
$pretty_users_str = "";
foreach($pua as $userid){
if($userid == 'nan'){
$pretty_users_str = true;
break;
}
$qry = $db->query_params('SELECT avatar_thumb AS avatar FROM users WHERE user_id = :uid', array('uid' => $userid));
$u = $qry->fetch();
$pretty_users_str .= "<a href=\"/user/?id=" . $userid . "/\"><img style=\"width:45px;height:45px;border-radius:50%;margin-right:10px\" src=\"https://www.switch-torrents.com/$u[avatar]\" /></a>";
}
if($pretty_users_str)
$pretty_users_str .= "<br><a href=\"" . $CONFIG['base_url'] . "/vouchers.php?action=wipe&code=" . $v->code . "\">Reset to default</a>";
echo " <tr>\n".
" <td class=\"tablea\">" . $v->id . "</td>\n".
" <td class=\"tableb\">" . $v->code . "</td>\n".
" <td class=\"tablea\">" . $pretty_date . "</td>\n".
" <td class=\"tableb\">" . $pretty_value . $pretty_unit . "</td>\n".
" <td class=\"tablea\">" . $pretty_users_str . "</td>\n".
" <td class=\"tableb\"><a href=\"" . $CONFIG['base_url'] . "/vouchers.php?action=edit&code=" . $v->code . "\">Modify</a> <a href=\"" . $CONFIG['base_url'] . "/vouchers.php?action=delete&code=" . $v->code . "\">Clear</a></td>\n".
" </tr>";
}
echo " </table>\n".
" </td>\n".
" </tr>\n".
"</table>\n";
}
}
}elseif($action == "edit"){
echo "<h2>Edit Voucher</h2>";
"<table cellspacing=\"5\" cellpadding=\"0\" border=\"0\" style=\"width:100%\">\n".
" <tr>\n".
" <td valign=\"top\" width=\"50%\">\n".
" <table cellpadding=\"4\" cellspacing=\"1\" border=\"0\" style=\"width:100%\" class=\"tableinborder\">\n".
" <form method=\"post\" action=\"" . $CONFIG['base_url'] . "/vouchers.php?action=edit\">\n".
" <tr class=\"tabletitle\" width=\"100%\">\n".
" <td width=\"100%\" colspan=\"2\"><span class=\"normalfont\"><b>Create code</b></span></td>\n".
" </tr>\n".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\"><b>Code:</b></td>\n".
" <td width=\"80%\" class=\"tableb\"><input type=\"hidden\" name=\"code\" value=\"" . $v->code . "\" /><input type=\"text\" size=\"40\" name=\"code_disp\" value=\"" . $v->code . "\" disabled=\"disabled\"/><p>May not be changed.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\"><b>Valid on:</b></td>\n".
" <td width=\"80%\" class=\"tableb\"><input id=\"creator_input_date\" type=\"text\" size=\"40\" name=\"date\" value=\"" . $v->date . "\"/> <input type=\"submit\" id=\"immer\" class=\"btn\" value=\"Always valid\" /><p>0000-00-00 00:00:00 For \"always\".<br> Holidays are automatically \"supplied\" if no voucher is available. <br> Leave blank for today's validity.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"20%\" class=\"tablea\"><b>Value:</b></td>\n".
" <td width=\"80%\" class=\"tableb\"><input id=\"creator_input_value\" type=\"text\" size=\"40\" name=\"value\" value=\"" . ($v->value / 1024 / 1024) . "\"/> <input type=\"button\" id=\"plus\" class=\"btn\" value=\"Plus 100MB\" /><p>Value in MB. <br> Will be counted towards the user's upload. <br> Leave free for 500MB.</p></td>\n".
" </tr>".
" <tr>\n".
" <td width=\"100%\" class=\"tableb\" colspan=\"2\"><input type=\"submit\" value=\"Update\" class=\"btn\"></td>\n".
" <td width=\"100%\" class=\"tableb\" colspan=\"2\"><input type=\"button\" onclick=\"location.href='" . $CONFIG['base_url'] . "/vouchers.php'\" value=\"Back\" class=\"btn\"></td>\n".
" </tr>".
" </form>\n".
" </table>\n".
" </td>\n".
" </tr>\n".
"</table>\n".
"<br>\n";
}
site_footer();
CREATE TABLE `vouchers` (
`id` int(11) unsigned NOT NULL AUTO_INCREMENT,
`code` varchar(20) DEFAULT '',
`value` int(11) DEFAULT NULL,
`users` varchar(255) DEFAULT NULL,
`date` datetime DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
INSERT INTO `vouchers` (`id`, `code`, `value`, `users`, `date`) VALUES (1, '5HG-DH4Q-VJDJ-XZ8-ST', 524288000, '{\"users\":\"1\"}', '2020-09-27 18:55:21');
[ATTACH type="full" width="776px" alt="4.png"]5908[/ATTACH]
[ATTACH type="full" width="777px" alt="3.png"]5907[/ATTACH]