Skip to content
Browse files

added init script, mysql pdo class, utils. started rewriting mysql la…

…yer to use pdo class, added debug mode
  • Loading branch information...
1 parent 17dbee0 commit e42562b12456cd383705bfc3d95e1e12d6bff685 @koopa committed Oct 20, 2012
Showing with 305 additions and 47 deletions.
  1. +2 −0 .gitignore
  2. +2 −2 courses/course.php
  3. +3 −5 courses/index.php
  4. +18 −21 courses/overview.php
  5. +113 −0 dump.sql
  6. +12 −13 getsmfuser.php
  7. +2 −3 index.php
  8. +64 −0 lib/db/PDOMySQL.class.php
  9. +9 −0 lib/utils/Utils.class.php
  10. +57 −0 scripts/init.php
  11. +23 −3 settings.php
View
2 .gitignore
@@ -1,2 +1,4 @@
+.idea
+log.lua
private_settings.php
forum/cache/data*
View
4 courses/course.php
@@ -27,7 +27,7 @@
// Description: Load the course file specified by the GET variable 'id'
//
- $courseid = $_GET['id'];
+ $courseid = isset($_GET['id']) ? $_GET['id'] : 0;
$errorstring = "<p class=\"center\"><img alt=\"Y U NO GIVE ID\" src=\"images/yuno.png\" /><br /><br />No active course, select a valid course from the overview!</p>";
$filename = "courses/course".$courseid.".php";
$mincourseid = 0;
@@ -43,4 +43,4 @@
echo $errorstring;
}
?>
-</div>
+</div>
View
8 courses/index.php
@@ -33,9 +33,7 @@
// format date for display in header bar
$showdate = date('F d, o, h:i:s A');
-?>
-
-<!DOCTYPE html>
+?><!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
@@ -109,8 +107,8 @@ function showCourse(id){
$("#course").load("course.php?id="+id);
$("#tabs").tabs( "select" , "tab-course" )
}
- <? echo $loadcourse; ?>
+ <? echo isset($loadcourse) ? $loadcourse : ''; ?>
</script>
-
+<?php Utils::queryLog(); ?>
</body>
</html>
View
39 courses/overview.php
@@ -19,8 +19,6 @@
// //
///////////////////////////////////////////////////////////////////////////////////
-require("../settings.php");
-
?>
<div id="courses">
<?
@@ -48,32 +46,32 @@
10 => 'Cryptography Description');
// Make database connection
- $link = mysql_connect($dbhost, $dbreaduser, $dbreadpass);
- mysql_select_db($dbname);
// Display the courses
foreach($categories as $id => $name) {
$nrtotal = 0;
$nrcompleted = 0;
- $courses = mysql_query("SELECT * FROM `hackits_courses` WHERE `category`='".$id."';");
+ $courses = $db->getAll("SELECT * FROM `hackits_courses` WHERE `category`=:category", array(':category' => $id));
$output = "";
- if(mysql_num_rows($courses)>0) {
- while ($course = mysql_fetch_assoc($courses)) {
- $nrtotal++;
- $author = mysql_result(mysql_query("SELECT member_name FROM `smf_members` WHERE `id_member`='".$course['author']."';"),0,0);
- $finished = mysql_result(mysql_query("SELECT finished FROM `hackits_courseresults` WHERE `userid`='".$usernameid."' AND `courseid`='".$course['id']."';"),0,0);
- if(!$finished==NULL) {
- $checked = "<em class=\"checked\"></em>";
- $nrcompleted++;
- }
- else
- {
- $checked = "";
- }
- $output .= "<tr><td class=\"check\">".$checked."</td><td><a onClick=\"showCourse('".$course['id']."')\">".$course['title']."</a></td><td>".$course['points']."</td><td>".$course['level']."</td><td>".$author."</td><td>".$course['completed']."</td></tr>";
- }
+ if($courses) foreach($courses as $index => $course) {
+ $nrtotal++;
+ $author = DEVMODE ? 'DEVMODE' : $db->getOne(
+ "SELECT member_name FROM `smf_members` WHERE `id_member`=':id'",
+ array(':id' => $course['author']));
+ $finished = $db->getOne(
+ "SELECT finished FROM `hackits_courseresults` WHERE `userid`=:userid AND `courseid`=:courseid",
+ array(
+ ':userid' => $usernameid,
+ ':courseid' => $course['id']));
+ if($finished) {
+ $checked = "<em class=\"checked\"></em>";
+ $nrcompleted++;
+ } else {
+ $checked = "";
+ }
+ $output .= "<tr><td class=\"check\">".$checked."</td><td><a onClick=\"showCourse('".$course['id']."')\">".$course['title']."</a></td><td>".$course['points']."</td><td>".$course['level']."</td><td>".$author."</td><td>".$course['completed']."</td></tr>";
}
echo "<h3><a href=\"#\">".$name." (".$nrcompleted."/".$nrtotal.")</a></h3><div>";
@@ -84,7 +82,6 @@
echo "</div>";
}
- mysql_close($link);
?>
</div>
View
113 dump.sql
@@ -0,0 +1,113 @@
+drop database hackits;
+create database hackits default character set utf8 collate utf8_unicode_ci;
+use hackits;
+grant select on hackits.* to `hackits-read` identified by 'readpass';
+grant delete,update,insert,select on hackits.* to `hackits-write` identified by 'writepass';
+flush privileges;
+
+SET SQL_MODE="NO_AUTO_VALUE_ON_ZERO";
+SET time_zone = "+00:00";
+
+/*!40101 SET @OLD_CHARACTER_SET_CLIENT=@@CHARACTER_SET_CLIENT */;
+/*!40101 SET @OLD_CHARACTER_SET_RESULTS=@@CHARACTER_SET_RESULTS */;
+/*!40101 SET @OLD_COLLATION_CONNECTION=@@COLLATION_CONNECTION */;
+/*!40101 SET NAMES utf8 */;
+
+CREATE TABLE IF NOT EXISTS `hackits_challengeresults` (
+ `userid` int(11) NOT NULL,
+ `challengeid` int(11) NOT NULL,
+ `finished` int(11) DEFAULT NULL,
+ `lastattempt` int(11) NOT NULL,
+ `penultimateattempt` int(11) DEFAULT NULL,
+ `lastsolution` varchar(250) NOT NULL
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT INTO `hackits_challengeresults` (`userid`, `challengeid`, `finished`, `lastattempt`, `penultimateattempt`, `lastsolution`) VALUES
+(2, 2, 1332529594, 0, 0, '0'),
+(7, 2, 0, 1330783944, 0, 'jhsdfkjs'),
+(1, 2, 0, 1330791052, 1330791038, 'lorem ipsum'),
+(2, 1, 0, 1330798732, 1330798728, '567245727'),
+(5, 2, 0, 1343163301, 1343163292, 'ddf'''),
+(5, 1, 0, 1330866874, 1330866852, 'asdf'' or ''''='''),
+(34, 2, 0, 1330875493, 1330872658, 'asd'),
+(34, 1, 0, 1330872627, 0, 'Derp'),
+(23, 2, 0, 1330875528, 1330875512, 'testchallenge'),
+(23, 1, 0, 1330875531, 0, 'test'),
+(6, 2, 0, 1330898143, 1330898124, 'answer1'),
+(35, 2, 0, 1330907295, 1330907290, '$answer[1]'),
+(3, 2, 0, 1332098694, 1332098676, '3'),
+(4, 2, 0, 1334507240, 0, 'asd'),
+(39, 2, 0, 1335388939, 0, 'sdf'),
+(41, 2, 0, 1338991657, 1338991537, '-1 OR 1=1'),
+(41, 1, 0, 1338991565, 0, '''OR 1=1 /*'''),
+(43, 2, 1341697380, 0, 0, '0'),
+(43, 1, 0, 1341697355, 0, '123'),
+(44, 2, 0, 1343372445, 0, '"--;echo ''hello''"');
+
+CREATE TABLE IF NOT EXISTS `hackits_challenges` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `type` tinyint(4) NOT NULL,
+ `answer` varchar(250) NOT NULL,
+ `completed` int(11) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=3 ;
+
+INSERT INTO `hackits_challenges` (`id`, `type`, `answer`, `completed`) VALUES
+(1, 2, 'c237450bc9b83f379b73d24940bfdd76b814548c82ca5154bab45dcb86827dd8f13e09a7841653732efb48337f0ecc29757758e7f1903ffe78d14516c1fa0f8c', 1),
+(2, 1, '123', 4);
+
+CREATE TABLE IF NOT EXISTS `hackits_courseresults` (
+ `userid` int(11) NOT NULL,
+ `courseid` int(11) NOT NULL,
+ `finished` int(11) DEFAULT NULL,
+ `lastattempt` int(11) NOT NULL,
+ PRIMARY KEY (`userid`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT INTO `hackits_courseresults` (`userid`, `courseid`, `finished`, `lastattempt`) VALUES
+(1, 1, 1329816181, 1329816181),
+(2, 1, 1330040584, 1330040584),
+(23, 1, 1329835195, 1329835195),
+(5, 1, 1329851222, 1329851222),
+(6, 1, 1329947909, 1329947909),
+(35, 1, 1330608569, 1330608569),
+(4, 1, 1331047151, 1331047151),
+(34, 1, 1333903601, 1333903601),
+(43, 1, 1341697156, 1341697156);
+
+CREATE TABLE IF NOT EXISTS `hackits_courses` (
+ `id` int(11) NOT NULL AUTO_INCREMENT,
+ `points` int(11) NOT NULL,
+ `level` tinyint(4) NOT NULL,
+ `category` tinyint(4) NOT NULL,
+ `author` int(11) NOT NULL COMMENT 'id from smf_members',
+ `title` char(100) NOT NULL,
+ `solution` text CHARACTER SET utf32 NOT NULL,
+ `completed` int(11) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;
+
+
+INSERT INTO `hackits_courses` (`id`, `points`, `level`, `category`, `author`, `title`, `solution`, `completed`) VALUES
+(1, 1, 1, 1, 2, 'Intro to Hackits Courses', 'cc', 9),
+(2, 1, 2, 2, 1, 'Practical Network', 'jfdshflquhlfurflruhga²', 0),
+(3, 5, 2, 1, 2, 'Internet Relay Chat (IRC)', 'xxxx', 0);
+
+CREATE TABLE IF NOT EXISTS `hackits_users` (
+ `id` int(11) NOT NULL,
+ `challengescore` int(11) NOT NULL,
+ `coursescore` int(11) NOT NULL,
+ PRIMARY KEY (`id`)
+) ENGINE=InnoDB DEFAULT CHARSET=utf8;
+
+INSERT INTO `hackits_users` (`id`, `challengescore`, `coursescore`) VALUES
+(2, 5, 1),
+(1, 0, 1),
+(23, 0, 1),
+(5, 0, 1),
+(6, 0, 1),
+(35, 0, 1),
+(4, 0, 1),
+(34, 0, 1),
+(43, 0, 1);
+
View
25 getsmfuser.php
@@ -1,4 +1,5 @@
<?
+require_once('settings.php');
///////////////////////////////////////////////////////////////////////////////////
// 888 888 d8888 .d8888b. 888 d8P 8888888 88888888888 .d8888b. //
@@ -22,8 +23,11 @@
// //
///////////////////////////////////////////////////////////////////////////////////
-require("settings.php");
-
+if(constant('DEVMODE')){
+ $usernametext = "DEVMODE";
+ $loggedin = $usernameid = 1;
+ return;
+}
$sessionid = $_COOKIE['PHPSESSID'];
if($sessionid=="")
@@ -33,16 +37,11 @@
}
else
{
- $link = mysql_connect($dbhost,$dbreaduser,$dbreadpass);
- if (!$link) {
- die('Server made a whoops: ' . mysql_error());
- }
- mysql_select_db($dbname);
- $sessionid = mysql_real_escape_string($sessionid);
- $query = "SELECT `member_name`,`id_member` FROM `smf_members` WHERE `id_member` = (SELECT `id_member` FROM `smf_log_online` WHERE `session`='".$sessionid."');";
- $usernametext = mysql_result(mysql_query($query), 0, 0);
- $usernameid = mysql_result(mysql_query($query), 0, 1);
- mysql_close($link);
+
+ $query = "SELECT `member_name`,`id_member` FROM `smf_members` WHERE `id_member` = (SELECT `id_member` FROM `smf_log_online` WHERE `session`=':session')";
+ $res = $db->getOne($query, array(':session' => $sessionid));
+ $usernametext = $res['member_name'];
+ $usernameid = $res['id_member'];
if($usernametext=="")
{
@@ -55,4 +54,4 @@
}
}
-?>
+?>
View
5 index.php
@@ -23,9 +23,7 @@
require("settings.php");
require("getsmfuser.php");
-?>
-
-<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
+?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
@@ -288,5 +286,6 @@
</div>
</div>
+<?php Utils::queryLog(); ?>
</body>
</html>
View
64 lib/db/PDOMySQL.class.php
@@ -0,0 +1,64 @@
+<?php
+
+if(!class_exists('PDO')){
+ throw new Exception('PDO not found');
+}
+
+class PDOMySQL {
+ private static $log = array();
+
+ private static $rConn;
+ private static $wConn;
+
+ public function __construct($o){
+ try {
+ self::$rConn = new PDO("mysql:host={$o['host']};port={$o['port']};dbname={$o['db']}", $o['readuser'], $o['readpass']);
+ self::$wConn = new PDO("mysql:host={$o['host']};port={$o['port']};dbname={$o['db']}", $o['writeuser'], $o['writepass']);
+ } catch(Exception $e){
+ trigger_error($e->getMessage(), E_USER_WARNING);
+ }
+ }
+
+ public function __destruct(){
+
+ }
+
+ public static function getLog(){
+ return self::$log;
+ }
+
+ private static function log($log){
+ self::$log[] = $log;
+ }
+
+ public function getOne($query, $params){
+ $r = $this->getAll($query, $params, 1);
+ return $r ? $r[0] : null;
+ }
+
+ public function getAll($query, $params = null, $limit = null){
+ $query = $query[count($query)-1] === ';'
+ ? substr($query, 0, -1)
+ : $query;
+ $now = microtime(true);
+ $query .= $limit ? " LIMIT $limit" : '';
+ try{
+ $st = self::$rConn->prepare($query, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
+ $st->setFetchMode(PDO::FETCH_ASSOC);
+ if($params) array_walk($params, function($val, $key) use ($st){
+ $st->bindParam($key, $val);
+ });
+ if($st->execute()){
+ self::log(array('query' => $query, 'time' => microtime(true) - $now));
+ return $st->fetchAll();
+ }
+ } catch(Exception $e){
+ trigger_error($e->getMessage(), E_USER_WARNING);
+ }
+ $error = $st->errorInfo();
+ if(intval($error[0]) > 0){// catch sql syntax errors
+ trigger_error($error[2], E_USER_WARNING);
+ }
+ $st->closeCursor();
+ }
+}
View
9 lib/utils/Utils.class.php
@@ -0,0 +1,9 @@
+<?php
+class Utils {
+ public static function queryLog(){
+ if(DEVMODE) printf("
+ <script>
+ %s.map(function(a){console.log(a.time, a.query)});
+ </script>", json_encode(PDOMySQL::getLog()));
+ }
+}
View
57 scripts/init.php
@@ -0,0 +1,57 @@
+<?php
+// so we don't have to manually include classes, move classes that
+// should be autoloaded into lib/*/ and name the file [className].class.php
+function init(){
+ global $__DEVS;
+ spl_autoload_register(function($class){
+ foreach(glob(dirname(__FILE__).'/../lib/*') as $path){
+ $file = $path.'/'.$class.'.class.php';
+ if(file_exists($file)){
+ return require_once($file);
+ }
+ }
+ });
+
+//figure out if dev mode should be enabled
+ foreach($__DEVS as $range){
+ //check if remote client is in a dev range
+ list ($subnet, $bits) = explode('/', $range);
+ $subnet = ip2long($subnet);
+ $mask = -1 << (32 - $bits);
+ //go to next range unless client ip matches range
+ if((ip2long($_SERVER['REMOTE_ADDR']) & $mask) !== $subnet &= $mask){ continue; }
+ define('DEVMODE', true);
+ error_reporting(E_ALL | E_STRICT);
+ ini_set('display_errors', 1);
+ $error_handler = function($no, $str, $file, $line, $context){ //show nicer errors and stack trace
+ while(ob_get_level() > 1) ob_end_clean();
+ printf('<pre style="padding:5px;background:#fbb;border:1px solid #f33;font-size: 1.2em;color:#000"
+ >ERR: %s - %s in %s:%s',
+ $no, $str, $file, $line);
+ echo "\n\nSTACKTRACE:\n";
+ array_map(function($a){
+ printf("<b style='display:inline-block;width: 50%%;'>%s %s</b> fn: <b>%s</b>\n\n",
+ isset($a['file'])?$a['file']:'',
+ isset($a['line'])?$a['line']:'',
+ isset($a['function'])?$a['function']:'');
+ }, debug_backtrace());
+ echo '</pre>';
+// printf('
+// <div onclick="this.childNodes[0].style.display=\'block\'"><pre style="display:none;"> %s</pre>
+// Show ENV
+// </div>', print_r($context, true));
+ ob_end_flush();
+ exit(1);
+ };
+ set_error_handler($error_handler, E_ALL | E_STRICT);
+ register_shutdown_function(function() use ($error_handler){
+ while(ob_get_level() > 1) ob_end_clean();
+ $error = error_get_last();
+ if($error && ($error['type'] & (E_ERROR | E_USER_ERROR | E_PARSE | E_CORE_ERROR
+ | E_COMPILE_ERROR | E_RECOVERABLE_ERROR))){
+ $error_handler($error['type'], $error['message'], $error['file'], $error['line'], $_ENV);
+ }
+ });
+ }
+}
+init();
View
26 settings.php
@@ -1,5 +1,4 @@
<?
-
///////////////////////////////////////////////////////////////////////////////////
// 888 888 d8888 .d8888b. 888 d8P 8888888 88888888888 .d8888b. //
// 888 888 d88888 d88P Y88b 888 d8P 888 888 d88P Y88b //
@@ -22,9 +21,20 @@
// //
///////////////////////////////////////////////////////////////////////////////////
+/* add ipv4 ranges where debug mode should be enabled */
+$__DEVS = array(
+ '192.168.0.0/16',
+ '172.16.0.0/12',
+ '10.0.0.0/8',
+);
+
+require_once('scripts/init.php');
+
+
// MySQL settings
$dbhost = "localhost";
-$dbname = "hackits.be";
+$dbport = 3306;
+$dbname = "hackits";
$dbwriteuser = "hackits-write";
$dbreaduser = "hackits-read";
@@ -57,4 +67,14 @@
// Fill private settings with secret data
require("private_settings.php");
-?>
+$db = new PDOMySQL(array(
+ 'host' => $dbhost,
+ 'port' => $dbport,
+ 'db' => $dbname,
+ 'readuser' => $dbreaduser,
+ 'readpass' => $dbreadpass,
+ 'writeuser' => $dbwriteuser,
+ 'writepass' => $dbwritepass,
+));
+
+require_once('getsmfuser.php');

0 comments on commit e42562b

Please sign in to comment.
Something went wrong with that request. Please try again.