Skip to content

Instantly share code, notes, and snippets.

@bls1999
Last active June 5, 2020 20:02
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bls1999/df10c7021a8d93da187ce2b552825b30 to your computer and use it in GitHub Desktop.
Save bls1999/df10c7021a8d93da187ce2b552825b30 to your computer and use it in GitHub Desktop.
Time-based raffle program (w/ mybb integration)
<?php
/*
MIT License
Copyright (c) 2020 Ben Schwartz
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
* * * * *
-- Purpose --
The following script is a MyBB-integrated PHP/MySQL raffle program that shows a list of entrants and their total entries in the raffle to date.
This script also automatically enters the user in the raffle a specified amount of times when they visit (10 here). This is restricted to once per day, but can be changed depending on the terms of the raffle.
* * * * *
-- Example MySQL Table Structure --
CREATE TABLE `raffle` (
`raffle_participant_id` int(4) NOT NULL AUTO_INCREMENT,
`user_id` int(9) NOT NULL,
`user_name` varchar(20) NOT NULL,
`last_time` bigint(11) NOT NULL,
`entries` int(6) NOT NULL,
PRIMARY KEY (`raffle_participant_id`),
UNIQUE KEY `user_id` (`user_id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;
*/
// db connection function
require_once __DIR__ . '/link/to/db/fn.php';
// mybb things
define('IN_MYBB', 1);
require_once $_SERVER['DOCUMENT_ROOT'] . "/global.php";
add_breadcrumb("Raffle Contest", "/showthread.php?tid=mythreadid");
add_breadcrumb("Participants", "thispage.php");
$recorded = false; // variable for data being recorded
$contest_closed = time() > 1593500400; // contest end time -- false until then
$contest_host = $mybb->user['uid'] == 1; // contest host -- true if the connecting user is the contest host
try {
// don't let guests participate
if (empty($mybb->user['uid']) || $mybb->user['uid'] == 0) {
error_no_permission();
die();
}
// generic function to instantiate a db connection via PDO
$pdo = pdo_connect();
// get user info
$stmt = $pdo->prepare('SELECT * FROM raffle WHERE user_id = :uid');
$stmt->bindValue(':uid', $mybb->user['uid'], PDO::PARAM_INT);
if ($stmt->execute() === false) {
throw new Exception('Could not retrieve user status from the db.');
}
// handle user info
$user = $stmt->fetch(PDO::FETCH_OBJ);
if ((empty($user) || $user->last_time + 86400 < time()) && !$contest_closed && !$contest_host && $mybb->user['uid'] > 0) {
$stmt = $pdo->prepare('
INSERT INTO raffle
SET user_id = :uid,
user_name = :insert_name,
last_time = UNIX_TIMESTAMP(NOW()),
entries = 10
ON DUPLICATE KEY UPDATE
user_name = :update_name,
last_time = UNIX_TIMESTAMP(NOW()),
entries = entries + 10
');
$stmt->bindValue(':uid', $mybb->user['uid'], PDO::PARAM_INT);
$stmt->bindValue(':insert_name', $mybb->user['username'], PDO::PARAM_STR);
$stmt->bindValue(':update_name', $mybb->user['username'], PDO::PARAM_STR); // in case of name change
if ($stmt->execute() === false) {
throw new Exception('Could not update user entries.');
}
$time_remaining = format_duration(86400);
$recorded = true;
} else {
$time_remaining = format_duration($user->last_time + 86400 - time());
}
// get all contest data
$stmt = $pdo->query('SELECT * FROM raffle ORDER BY entries DESC');
if (!$stmt) {
throw new Exception('Could not retrieve contest data.');
}
$users = $stmt->fetchAll(PDO::FETCH_OBJ);
// example of displaying the list via MyBB templates
eval('$headerinclude = "'.$templates->get('headerinclude').'";');
eval('$header = "'.$templates->get('header').'";');
eval('$footer = "'.$templates->get('footer').'";');
eval('$raffle = "'.$templates->get('raffle').'";');
output_page($raffle); // see below for eval'd PHP code in templates
die();
} catch (Exception $e) {
die('Error: ' . $e->getMessage());
}
// simple seconds to readable time function
function format_duration($seconds)
{
if ($seconds < 60) {
$time_left = "$seconds second";
if ($seconds != 1) {
$time_left .= 's';
}
} elseif ($seconds < 60*60) {
$minutes = round($seconds/60, 0);
$time_left = "$minutes minute";
if ($minutes != 1) {
$time_left .= 's';
}
} elseif ($seconds < 60*60*24) {
$hours = round($seconds/60/60, 0);
$time_left = "$hours hour";
if ($hours != 1) {
$time_left .= 's';
}
} elseif ($seconds < 60*60*24*30) {
$days = round($seconds/60/60/24, 0);
$time_left = "$days day";
if ($days != 1) {
$time_left .= 's';
}
} elseif ($seconds < 60*60*24*30*12) {
$months = round($seconds/60/60/24/30, 0);
$time_left = "$months month";
if ($months != 1) {
$time_left .= 's';
}
} else {
$years = round($seconds/60/60/24/30/12, 0);
$time_left = "$years year";
if ($years != 1) {
$time_left .= 's';
}
}
return $time_left;
}
?>
<!--
-- Raffle Template --
* IMPORTANT: "PHP in Templates and Template Conditionals" plugin must be installed. More: https://community.mybb.com/thread-31860.html
-->
<html>
<head>
<title>Raffle Contest</title>
<link type="text/css" rel="stylesheet" href="{$mybb->settings['homeurl']}/style/scores-table.css" />
<script type="text/javascript" src="{$mybb->settings['homeurl']}/games/-scripts.js" />
{$headerinclude}
</head>
<body>
{$header}
<br />
<div id="content">
<div class="wrapper">
<navigation>
<br />
<?php
echo '<table border="0" cellspacing="' . $theme["borderwidth"] . '" cellpadding="' . $theme["tablespace"] . '" class="tborder" style="text-align: left;">'
."<tr>"
."<td class='thead' style='text-align: left;'><strong>Automatic Entry</strong></td>"
."</tr>"
."<tr>"
."<td class='trow1' style='text-align: left;'>";
if ($contest_host) {
echo "You're the contest host, so you can't participate. You'll be able to see the entry totals below.";
} elseif ($contest_closed) {
echo "This contest is closed. Please check with the contest host for further information.";
} else {
$my_entries = $user->entries + 10;
if ($recorded === true) {
if ($my_entries === 10) {
echo "Welcome to the contest! You've been entered into the raffle 10 times. Open this page again tomorrow to be entered 10 more times!";
} else {
echo "Great success! Your raffle entries for today were recorded, bringing your total to $my_entries. Open this page again tomorrow to be entered 10 more times!";
}
} else {
echo "You've already claimed your entries for today. You can participate again in $time_remaining. Open this page then to be entered 10 more times!";
}
}
echo '</td></tr></table><br />';
echo '<table border="0" cellspacing="' . $theme["borderwidth"] . '" cellpadding="' . $theme["tablespace"] . '" class="tborder" style="text-align: left;">'
."<tr>"
."<td class='thead' style='text-align: left;'><strong>Participants</strong></td>"
."</tr>"
."<tr>"
."<td class='trow1' style='text-align: left;'>";
// start full table
echo "<table class='noborder' width='100%'>";
// header row for whole table
echo "<tr>"
."<th class='noborder' style='text-align: left'>Rank</th>"
."<th class='noborder' style='text-align: left'>Name</th>"
."<th class='noborder' style='text-align: left'>Entries</th>";
echo $contest_host ? "<th class='noborder' style='text-align: left'>Next Eligible</th></tr>" : "</tr>";
// make table
$i = 1;
foreach ($users as $user) {
$next_eligible = $user->last_time + 86400 - time();
$next_eligible = $next_eligible <= 0 ? "<b>Now</b>" : format_duration($next_eligible);
$user_name = htmlspecialchars($user->user_name, ENT_QUOTES);
echo "<tr>"
."<td class='noborder'>$i</td>"
."<td class='noborder'><a href='/forums/member.php?action=profile&uid=$user->user_id'>$user_name</a></td>"
."<td class='noborder'>$user->entries</td>";
echo $contest_host ? "<td class='noborder'>$next_eligible</td>" : "";
echo "</tr>";
$i++;
}
// end tables row and entire table
echo "</table></table>";
?>
<debugstuff>
</div>
</div>
<br />
{$footer}
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment