Advertisement
Guest User

Untitled

a guest
May 1st, 2017
612
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 28.28 KB | None | 0 0
  1. <?php
  2.     // TODO:
  3.     // title gen
  4.     // age redirect to page
  5.     // merge reply form into current page
  6.     // serparate cookie domain for security
  7.    
  8.     if ( !defined("ALLOWED") ) exit();
  9.    
  10.     error_reporting(5);
  11.     global $db;
  12.     global $error;
  13.     global $page;
  14.    
  15.     class database {
  16.  
  17.         var $link; var $conn; var $res; var $numRows; var $numAffected; var $error;
  18.        
  19.         function database($hostname = '127.0.0.1', $username = "db1", $password = "wot.", $db = "wx") {
  20.                 $this->conn = mysql_connect($hostname, $username, $password);
  21.                 if (!$this->conn) die(mysql_error());
  22.                 mysql_select_db( $db );
  23.                 return $this->conn;
  24.         }
  25.        
  26.         function query($sql) {
  27.                 if (!$this->conn) { echo "not connected"; return false; }
  28.                 $this->res = mysql_query($sql, $this->conn);
  29.                 if (!$this->res) { return false; }
  30.         }
  31.        
  32.         function clean($query) { $nQ = mysql_real_escape_string( $query ); return $nQ; }
  33.         function getNext() { $res = mysql_fetch_assoc($this->res); return $res; }
  34.         function getRow() { $res = mysql_fetch_row($this->res); return $res; }
  35.         function getNumRows() { $res = ($this->numRows ? $this->numRows : mysql_num_rows($this->res)); return $res; }
  36.         function getNumAffected() { $res = ($this->numAffected ? $this->numAffected : mysql_affected_rows($this->conn)); return $res;}
  37.     }  
  38.    
  39.     class ImageBoard {
  40.         function __construct() {
  41.             $db = new database("localhost","db1","wot.","wx");
  42.             if ( !isset($_SESSION['permission'] ) ) session_start();
  43.             ini_set("sendmail_from", "boss@p0x.us");}
  44.        
  45.         function display ( $element ) {
  46.             switch ( $element ) {
  47.                 case "style":
  48.                     // grab from $_SESSION (!!!)
  49.                     echo "/includes/css/base.css";         
  50.                 break;
  51.                
  52.                 case "nav":
  53.                     // determine permissions
  54.                     if ( !isset($_SESSION['permission']) ) { $level = 0; } else { $level = $_SESSION['permission']; }
  55.                     if ( $level == 0 ) { include("/views/nav/guest.php"); }
  56.                     elseif ( $level >= 1 && $level <= 6 ) { include("/views/nav/user.php"); }
  57.                     elseif ( $level >= 7 && $level <= 8 ) { include("/views/nav/mod.php"); }
  58.                     elseif ( $level == 9 ) { include("/views/nav/admin.php"); }
  59.                 break;
  60.             }
  61.            
  62.         }
  63.  
  64.         function action ( $main, $sub ) {
  65.             $main = strtolower($main); $sub = strtolower($sub);
  66.             switch ( $main ) {
  67.                 case "":
  68.                     // list boards
  69.                     $this->ListBoards();
  70.                 break;
  71.                
  72.                 case "login":
  73.                     // if already logged in
  74.                     if ( isset($_SESSION['user']) && $_SESSION['user'] != "" ) $this->ThrowError("logged_in");
  75.                    
  76.                     // if submitting
  77.                     if ( $_GET['b'] == "submit" ) {
  78.                         $this->UserLogin( $_POST['email'], $_POST['password'] );
  79.                     } else {
  80.                         require_once("/views/login.inc.php");
  81.                     }
  82.                 break;
  83.                
  84.                 case "register":
  85.                     // if already logged in
  86.                     if ( isset($_SESSION['user']) && $_SESSION['user'] != "" ) $this->ThrowError("logged_in");
  87.                     if ( $sub == "submit" ) {
  88.                         $this->UserRegister( $_POST['username'], $_POST['email'], $_POST['captcha'] );
  89.                     } else {
  90.                         require_once("/views/register.inc.php");
  91.                     }
  92.                 break;
  93.                
  94.                 case "board":
  95.                     $this->ViewBoard( $sub );
  96.                 break;
  97.                
  98.                 case "topic":
  99.                     $this->ViewTopic( $sub );
  100.                 break;
  101.                
  102.                 case "reply":
  103.                     if ( !isset( $_POST['process'] ) && $this->regex($sub,"id") ) {
  104.                         require_once("/views/reply.inc.php");
  105.                     } elseif ( isset( $_POST['process'] ) && $this->regex($sub,"id") ){
  106.                         $this->TopicReply ($_POST['id'],$_POST['content'],$_POST['who'], null);
  107.                     } else { die("wait, what?"); }                 
  108.                 break;
  109.  
  110.                 case "post":
  111.                     if ( !isset( $_POST['process'] ) ) {
  112.                         require_once("/views/new_topic.inc.php");
  113.                     } else { $this->PostTopic( $_POST['board'], $_POST['title'], $_POST['content'], $_POST['who'] ); }
  114.                 break;
  115.                
  116.                 case "sample":
  117.                     require_once("/views/sample3.inc.php");
  118.                 break;
  119.                
  120.                 case "error":
  121.                     $this->ShowError( $sub );
  122.                 break;
  123.                
  124.                 case "logout":
  125.                     unset($_COOKIE['token'], $_COOKIE['user'], $_SESSION['user'], $_SESSION['permission']);
  126.                     echo "<meta http-equiv=\"refresh\" content=\"0;url=/\" />";
  127.                 break;
  128.                
  129.                 case "settings":
  130.                 if ( $_GET['b'] == "submit" ) ) {
  131.                     $this->UserChangeSettings( $_POST['pwd_unlock'], $_POST['chg_pwd1'], $_POST['chg_pwd2'],
  132.                     $_POST['bio'], $_POST['style'], $_POST['rcvMsg'], $_POST['ntfMsg'] );
  133.                 } else {
  134.                     // pull infos to match!
  135.                     $uP = $this->PullUserSettings();
  136.                     require("/views/settings.inc.php");            
  137.                 }
  138.  
  139.                 break;
  140.                
  141.                 case "captcha":
  142.                     ShowCaptcha();
  143.                 break;
  144.                
  145.                 case "faq":
  146.                     switch ($sub) {
  147.                         case "": require_once("/views/faq/faq.inc.php"); break;
  148.                         case "rules": require_once("/views/faq/rules.inc.php"); break;
  149.                         case "wat": require_once("/views/faq/wat.inc.php"); break;
  150.                         case "privacy": require_once("/views/faq/privacy.inc.php"); break; 
  151.                     }
  152.                 break;
  153.                
  154.                 case "nsfw":
  155.                     if ( $sub == "yes" ) $_SESSION['nsfw'] = "yes";
  156.                     if ( isset($_SESSION['redirect'] ) ) { $rPath = $_SESSION['redirect']; } else { $rPath = "/"; }
  157.                     if ( isset($_SESSION['nsfw'])) { header("Location: $rPath"); } else { require_once("/views/nsfw.inc.php"); }
  158.                 break;
  159.                
  160.                 case "file":
  161.                     $this->FileBank( $sub );
  162.                 break;
  163.             }
  164.         }
  165.        
  166.         function ListBoards() {
  167.             // set variables
  168.             // require template
  169.             $db = new database();
  170.             $permission = $this->GetPermissionLevel();
  171.             $boards = $db->query("SELECT ID, NAME, DESCRIPTION, THREAD_COUNT FROM `boards` WHERE LOCKED = 0 AND ACCESSLEVEL <= $permission ORDER BY THREAD_COUNT DESC");
  172.            
  173.             // pull board data
  174.             $x = array();
  175.             while ( $row = $db->getRow() ) {
  176.                 $id = $row[0];
  177.                 $x[$id] = array( "id" => $id, "name" => $row[1], "desc" => $row[2], "topics" => $row[3], );
  178.             }
  179.            
  180.             include("/views/index.inc.php");
  181.             unset($db, $aLevel, $boards, $x);
  182.         }
  183.        
  184.         function ViewBoard( $board ) {
  185.             // check that board exists, it's not locked, and you can access it
  186.             $db = new database();
  187.             $permission = $this->GetPermissionLevel();
  188.             $boards = $db->query("SELECT NAME, DESCRIPTION, BULLETIN, THREAD_COUNT, SFW FROM `boards` WHERE LOCKED = 0 AND ACCESSLEVEL <= $permission AND NAME = '$board' LIMIT 1");
  189.             if ( $db->getNumRows() == 1 ) {        
  190.                 // pull board data
  191.                 $b = $db->getNext($boards);
  192.                 //Array ( [NAME] => b [DESCRIPTION] => Random discussion, ala 4chan. [BULLETIN] => [THREAD_COUNT] => 0 )
  193.                
  194.                 // check SWF
  195.                 $_SESSION['redirect'] = "/board/$board";
  196.                 if ( $_SESSION['nsfw'] != "yes" && $b['SFW'] == 0 ) $this->ThrowError("nsfw_flag");
  197.                
  198.                 // pull TOPICS
  199.                 //$posts = $db->query(""); //ID BOARD   TITLE   AUTHOR  OP  REPLIES LAST_BUMP
  200.                 $topics = mysql_query("SELECT * FROM `topics` WHERE BOARD='$board' ORDER BY LAST_BUMP ASC LIMIT 40");
  201.                 while ($i = mysql_fetch_assoc($topics)) {
  202.                     $id = $i["ID"];
  203.                     $x[$id] = $i;
  204.                 }
  205.                 require_once("/views/board.inc.php");
  206.             } else {
  207.                 $this->ThrowError("bad_board");
  208.             }
  209.             unset($db, $aLevel, $boards, $x);
  210.         }
  211.        
  212.         function ViewTopic( $id ) {
  213.             // regex input
  214.             if ( !$this->regex( $id, "id" ) ) { $this->ThrowError("bad_id"); }
  215.            
  216.             // pull topic
  217.             $db = new database;
  218.             $topic = $db->query("SELECT * FROM `topics` WHERE ID=$id LIMIT 1");
  219.             if ( $db->getNumRows($topic) != 1 ) { $this->ThrowError("bad_topic"); }
  220.            
  221.             // store topic
  222.             $topic = $db->getNext($topic);
  223.            
  224.             // pull posts
  225.             $posts = $db->query("SELECT * FROM `posts` WHERE TOPIC=$id ORDER BY TIMESTAMP LIMIT 25");
  226.             $count = $db->getNumRows($posts);
  227.             if ( $count <= 0 ) { $this->ThrowError("empty_topic"); }
  228.            
  229.             // store posts
  230.             while ( $i = $db->getNext($posts) ) {
  231.                 $pID = $i['ID'];
  232.                 $p[$pID] = $i;
  233.             }
  234.            
  235.             //echo "<h1>topic</h1>"; print_r($topic); echo "<hr/>";echo "<h1>OP</h1>";print_r($OP); echo "<hr/>";echo "<h1>posts</h1>";print_r($p); echo "<hr/>";
  236.             require_once("/views/topic.inc.php");
  237.            
  238.         }
  239.        
  240.         function PostTopic ( $board, $title, $content, $who ) {
  241.             $db = new database;
  242.            
  243.             // sanitize
  244.             $board = mysql_real_escape_string($board);
  245.             $res = mysql_query("SELECT ACCESSLEVEL, LOCKED FROM `boards` WHERE NAME = '$board' LIMIT 1");
  246.             if ( mysql_num_rows($res) != 1 ) $this->ThrowError("bad_board");
  247.             $res = mysql_fetch_row( $res );
  248.            
  249.             // do you have permission to post in this board? ( !locked, perm <= mine, does exist)
  250.             if ( $res["ACCESSLEVEL"] > $_SESSION['permission'] || $res['LOCKED'] == 1 ) $this->ThrowError("bad_board");
  251.            
  252.            
  253.             if ( !$this->Regex($title, "title") ) $this->ThrowError("bad_title");
  254.             if ( empty($title) ) $this->ThrowError("empty_title");
  255.             $title = mysql_real_escape_string($title);
  256.  
  257.             // are you opting for anonymity?
  258.                 // set you for "anon", no for ("" || "me")
  259.                 if ( $who == "me" ) { $who = $_SESSION['user']; } elseif ( $who != "anon" ) { $this->ThrowError("form_tamper"); }
  260.                
  261.             // gather values
  262.             $time = time();
  263.            
  264.             // insert topic, get ID
  265.             $tINS = mysql_query("INSERT INTO `topics` (BOARD, TITLE, AUTHOR, LAST_BUMP, REPLIES ) VALUES ( '$board', '$title', '$who', $time, -1 )") or die("INSERT INTO `topics` (BOARD, TITLE, AUTHOR) VALUES ('$board', '$title', '$who')");
  266.             $tINS = mysql_fetch_row(mysql_query("SELECT ID FROM `topics` WHERE BOARD = '$board' AND TITLE = '$title' AND AUTHOR = '$who' AND LAST_BUMP=$time LIMIT 1"));
  267.            
  268.             // increment board counter
  269.             $inc = mysql_query("UPDATE `boards` SET THREAD_COUNT=THREAD_COUNT+1 WHERE NAME='$board'");
  270.            
  271.             // make OP
  272.             $this->TopicReply( $tINS[0], $content, $who, $_FILES );
  273.         }
  274.        
  275.         function TopicReply( $id, $content, $who, $filedata ) {
  276.             // validate input
  277.             if ( !$this->regex( $id, "id" ) ) { $this->ThrowError("bad_id"); }
  278.             if ( strlen($content) == 0 ) $this->ThrowError("empty_post");
  279.             if ( strlen($content) > 25000 ) $this->ThrowError("long_post");
  280.            
  281.             // pull topic, make sure it exists!   ( ### DOES NOT CHECK IF YOU HAVE PERMISSION TO ### )
  282.             $db = new database;
  283.             $topic = mysql_query("SELECT ID, REPLIES FROM `topics` WHERE ID=$id LIMIT 1");
  284.             if ( mysql_num_rows($topic) != 1 ) { $this->ThrowError("bad_topic"); }
  285.            
  286.             // time! other necessary info?
  287.             $time = time();
  288.            
  289.             // OH GUTEN TAG, STURMBANFUHRER!
  290.             $ip = $_SERVER['REMOTE_ADDR'];
  291.            
  292.             // capcode content
  293.             $content = $this->gmCode($content);
  294.            
  295.             // nl2br content
  296.             $content = nl2br($content);
  297.  
  298.             // who's posting?
  299.             if ( $who == "me" ) { $who = $_SESSION['user']; } else { $who = "anon"; }
  300.            
  301.             if ( !isset($filedata) ) $filedata = $_FILES;
  302.             // determine if file was uploaded, check for other errors
  303.             if ($filedata["attach"]["error"] == 1) {
  304.                 $this->ThrowError("file_big");
  305.             } elseif ($filedata["attach"]["error"] == 3) {
  306.                 $this->ThrowError("file_part");
  307.             } elseif ($filedata["attach"]["error"] == 6) {
  308.                 $this->ThrowError("file_tmp");
  309.             } elseif ($filedata["attach"]["error"] == 0) {
  310.                
  311.                 // check filesize and type
  312.                 $size = $filedata["attach"]["size"];
  313.                 if ( $size > $this->UploadQuota() ) { $this->ThrowError("file_too_big"); }
  314.                 if ( $size == 0 ) { $this->ThrowError("empty_upload"); }
  315.                 $mime = $this->FindMime($filedata["attach"]["name"] );
  316.  
  317.                 // generate a random id for the attachment
  318.                 $key = "";
  319.                 $pool = "abcdefghkpmnqrtuvwxyz1234567890";
  320.                 for ( $i = 0; $i < 8; $i++ ) { $key = $key . substr( $pool, rand(1, strlen($pool)), 1); }  
  321.                
  322.                 // copy file to permanence, get filename and INSERT
  323.                 $filename = $filedata["attach"]["name"];
  324.                 $ext = substr($filename, strrpos($filename, '.') + 1);
  325.                 $whole_file = $key . "." . substr($filename, strrpos($filename, '.') + 1);
  326.                 $size = $filedata["attach"]["size"];
  327.                 move_uploaded_file ( $filedata["attach"]["tmp_name"] , "./attachments/$key.$ext");
  328.                 mysql_query("INSERT INTO `wx`.`files` (`KEY`, `FILENAME`, `SIZE`, `MIMETYPE`) VALUES ('$key', '$whole_file', $size, '$mime');") or $this->ThrowError("bad_file_insert");
  329.                 mysql_query("INSERT INTO  `wx`.`posts` (`AUTHOR` ,`TOPIC` ,`CONTENT` ,`FILE` ,`TIMESTAMP`, `IP` ) VALUES ('$who', '$id', '$content', '$key.$ext', '$time', '$ip');") or $this->ThrowError("post_fail2");
  330.                
  331.             } else {
  332.                 $db->query("INSERT INTO  `wx`.`posts` (`AUTHOR` ,`TOPIC` ,`CONTENT` ,`FILE` ,`TIMESTAMP`, `IP`) VALUES ('$who', '$id', '$content', '', '$time', '$ip');");
  333.             }
  334.            
  335.             // increment post counter for topic
  336.             $inc = mysql_query("UPDATE `topics` SET REPLIES=REPLIES+1 WHERE ID='$id'");
  337.            
  338.             // redirect
  339.             $_SESSION['redirect'] = "/topic/$id";
  340.             $this->ThrowError("reply_success");            
  341.         }
  342.        
  343.         function FileBank( $file ) {
  344.             $db = new database;
  345.             $file = mysql_real_escape_string( $file );
  346.             $x = mysql_query("SELECT FILENAME, MIMETYPE FROM `files` WHERE `KEY` = '$file' LIMIT 1") or die("#FNF#");
  347.             if ( mysql_num_rows ( $x ) == 1 ) {
  348.                 error_reporting(0);
  349.                 $x = mysql_fetch_assoc( $x );
  350.                 if ( $x['MIMETYPE'] == "" || !isset($x['MIMETYPE'] ) ) $x['MIMETYPE'] = "text/plain";
  351.                 header("Content-type: {$x['MIMETYPE']}");
  352.                 require_once("/attachments/{$x['FILENAME']}");
  353.             } else { die("#FNF0#"); }
  354.             // #TODO: add a "if this file doesn't exist" clause
  355.         }
  356.        
  357.         function UserRegister ( $user, $email, $captcha ) {
  358.             $wx = new ImageBoard;
  359.             $email = strtolower($email);
  360.  
  361.             if ( $captcha != $_SESSION['captcha'] ) $this->ThrowError("bad_captcha");
  362.             unset($_SESSION['captcha']);
  363.  
  364.             // regex
  365.             if ( !$this->Regex( $user, "username") ) $this->ThrowError("bad_user");
  366.             if ( !$this->Regex( $email, "email") ) $this->ThrowError("bad_email");
  367.            
  368.             // check to see if there's already a user there, fail if so
  369.             $db = new database;
  370.             if ($db->getNumRows($db->query("SELECT USERNAME FROM `users` WHERE USERNAME='$user'")) != 0) $this->ThrowError("uname_taken");
  371.            
  372.             // unset CAPTCHA, so as to prevent refresh flooding
  373.             $_SESSION['captcha'] = "00000";
  374.            
  375.             // insert new info, using random password
  376.             $temp_pwd = rand(10000,99999);
  377.             $temp_hash = substr(md5( $temp_pwd ),0,16);
  378.             echo "INSERT INTO `users` ( USERNAME, PASSWORD, EMAIL, PERMISSION, POSTCOUNT ) VALUES ( '$user', '$temp_hash', '$email', 1, 0 )";
  379.             $reg = $db->query("INSERT INTO `users` ( USERNAME, PASSWORD, EMAIL, PERMISSION, POSTCOUNT ) VALUES ( '$user', '$temp_hash', '$email', 1, 0 )");
  380.            
  381.             // mail info
  382.             //mail( $email, "p0x registration", "Thanks for registering with p0x! Here's your account info:\n\nusername:$user\n
  383.             //password: $password \n\n You can change your password form within the 'Panel' section of the board.\n\n
  384.             //(If this message was delivered in error, please disregard it.)") or die("mail_fail");
  385.            
  386.             die("in lieu of registration, here's your password: $temp_pwd");
  387.            
  388.         }
  389.        
  390.         function PullUserSettings() {
  391.             // who are you?
  392.             if ( !isset($_SESSION['user'] ) ) { $this->ThrowError("not_logged_in"); } else { $user = $_SESSION['user']; }
  393.            
  394.             $db = new database;
  395.             $uP = $db->query("SELECT * FROM `users` WHERE USERNAME = '$user' LIMIT 1");
  396.             $uP = $db->getNext($uP);
  397.             return array( $uP['EMAIL'], $uP['BIO'], $uP['THEME'], $uP['MSG_RCV'], $uP['MSG_NTF'] );
  398.         }
  399.        
  400.         function UserChangeSettings( $unlock, $change1, $change2, $bio, $style, $rcvMsg, $ntfMsg ) {
  401.             echo "unlock: $unlock<br/>change1: $change1<br/>change2: $change2<br/>bio: $bio<br/>style: $style<br/>
  402.             rcvMsg: $rcvMsg<br/>ntfMsg: $nsfMsg<br/>";
  403.         }
  404.        
  405.         function GetPermissionLevel() {
  406.             // check session
  407.             if ( isset( $_SESSION['permission']) ) {
  408.                 return $_SESSION['permission'];
  409.             } else {
  410.                 return 0;
  411.             }
  412.         }
  413.        
  414.         function UserLogin( $email, $pass ) {
  415.             // user-called function: assume it's a malicious input
  416.             $db = new database;
  417.             $email = mysql_real_escape_string(strtolower($email));
  418.             $pass = substr( md5( $pass ), 0, 16);
  419.            
  420.             $uInfo = $db->query("SELECT USERNAME, PASSWORD, PERMISSION FROM `users` WHERE EMAIL = '$email' LIMIT 1");
  421.             if ( $db->getNumRows($uInfo) != 1) $this->ThrowError("bad_login");
  422.             $uInfo = $db->getRow($uInfo);
  423.             if ( $uInfo[1] == $pass ) {
  424.                 $this->Login( $uInfo[0], $uInfo[2] );
  425.                 header("Location: /"); //$this->ThrowError("good_login");
  426.             } else {
  427.                 die("bad login. input $pass != stored {$uInfo[2]}");
  428.             }
  429.         }
  430.        
  431.         function Login( $user, $permission ) {
  432.             // the internal function
  433.             $this->CreateCookie( $user );
  434.             $this->CreateSession ( $user, $permission );
  435.         }
  436.        
  437.         function VerifyCookie () {
  438.             // match _COOKIE token with `sessions`
  439.             if ( isset( $_COOKIE['token'] ) && strlen( $_COOKIE['token'] ) == 16 ) {
  440.                 // match up
  441.                 $db = new database;
  442.                 $uInfo = $db->query("SELECT * FROM `sessions` WHERE TOKEN = {$_COOKIE['token']}");
  443.                 if  ( $db->getNumRows($uInfo) != null && substr(md5($_COOKIE['token']), 0, 16 ) == $uInfo['TOKEN'] ) {
  444.                     CreateSession($uInfo['USERNAME']);
  445.                     return true;
  446.                 } else {
  447.                     return false;
  448.                 }
  449.             } else {
  450.                 return false;
  451.             }
  452.         }
  453.        
  454.         function CreateCookie ( $user ) {
  455.             // create a token, store in _COOKIE and `sessions`
  456.             // generate randomness, hash and store
  457.             $key = substr(md5( rand() . "!bReakDanCE!" . time() ), 0, 16);
  458.             $ip = $_SERVER['REMOTE_ADDR'];
  459.             $time = time();
  460.            
  461.             $db = new database;
  462.            
  463.             // look for an existing session
  464.             $r = $db->query("SELECT * FROM `sessions` WHERE USERNAME='$user' LIMIT 1");
  465.             if ($db->getNumRows($r) == 1) {
  466.                 // if one exists, update it
  467.                 $r = $db->query("UPDATE `sessions` SET TOKEN='$key', DATE='$time' WHERE USERNAME = '$user' LIMIT 1");
  468.             } else {
  469.                 // if not, create a new one
  470.                 $db->query("INSERT INTO `sessions` (USERNAME, TOKEN, DATE) VALUES ( '$user', '$key', $time )");
  471.             }
  472.            
  473.             // store
  474.             setcookie( "user" , $user );
  475.             setcookie( "token" , $key );
  476.         }
  477.        
  478.         function CreateSession ( $user, $permission ) {
  479.             $_SESSION['user'] = $user;
  480.             $_SESSION['permission'] = $permission;
  481.         }
  482.        
  483.         function SetBan( $who, $ip, $host, $howLong ) {
  484.             $db = new database;
  485.            
  486.             $ip = mysql_real_escape_string( $ip );
  487.             $who = mysql_real_escape_string( $who );
  488.             $host = mysql_real_escape_string( $host );
  489.             $howLong = $howLong + time();
  490.            
  491.            
  492.             // search for an existing ban
  493.             $ban = $db->query("SELECT * FROM `bans` WHERE IP = '$ip' OR HOSTNAME = '$host' OR USERNAME = '$user' LIMIT 1");
  494.             if ( $db->getNumRows($ban) != 0 ) {
  495.                 $ban = $db->getNext($ban);
  496.                 $db->query("UPDATE `bans` SET EXPIRES = $howLong WHERE ID = {$ban['ID']} LIMIT 1");
  497.             } else {
  498.                 $db->query("INSERT INTO `bans` (IP, USERNAME, HOSTNAME, EXPIRES) VALUES ( '$ip', '$who', '$host', $howLong )");
  499.             }
  500.         }
  501.        
  502.         function BanMe( $length ) {
  503.             if ( $_SESSION != "admin" ) {
  504.                 $this->SetBan( $_SESSION["user"], $_SERVER["REMOTE_ADDR"], $_SERVER["REMOTE_HOST"], $length );
  505.             }
  506.         }
  507.        
  508.         function CheckBan() {
  509.             $db = new database;
  510.            
  511.             // my info
  512.             $ip = $_SERVER['REMOTE_ADDR']; $hostname = $_SERVER['REMOTE_HOST']; $user = $_SESSION['user']; $time = time();
  513.             $ban = $db->query("SELECT * FROM `bans` WHERE IP = '$ip' OR HOSTNAME = '$hostname' OR USERNAME = '$user' LIMIT 1");
  514.             if ( $db->getNumRows($ban) != 0 ) {
  515.             $ban = $db->getRow($ban);
  516.                 if ( ($ban[4] > time()) ) {
  517.                     $banLeftover = $this->nicetime( $ban[4] );
  518.                     die("<h1 style=\"font-size:256px; font-family: georgia; text-align: center;\">b&</h1><h1 style=\"font-family: monospace; font-size: 12px; position: absolute; left: 10px; bottom: 3px; \">You've been banned!<br/>It's set to expire in $banLeftover.</h1>");
  519.                 } else {
  520.                     // ban has already expired. leave it in there, so I can see it later. :P
  521.                 }
  522.             }
  523.         }
  524.        
  525.         /*function Identify() {
  526.             // basically, make a dictionary of everybody who's ever used the imageboard,
  527.             // so that we'll have an IP to provide, in case the FBI ever knocks on our door...
  528.            
  529.             // gather user info
  530.             $ip = $_SERVER['REMOTE_ADDR'];
  531.             $hostname = $_SERVER['REMOTE_HOST'];
  532.             $timestamp = time();
  533.             $user = $_SESSION['user'];
  534.            
  535.             // search by IP
  536.             $db = new database;
  537.             $r = mysql_query("SELECT ID FROM `sessions` WHERE (IP = '$ip' AND HOSTNAME = '$hostname') OR (USERNAME = '$user') LIMIT 1");
  538.             $rNum = mysql_num_rows($r);
  539.            
  540.             // if an entry exists, update // if it doesn't, create it // otherwise crash and burn
  541.             if ( $rNum == 1 ) { $r = mysql_query("UPDATE `sessions` SET TIMESTAMP = '$timestamp', HOSTNAME = '$hostname' WHERE IP = '$ip' LIMIT 1");}
  542.             elseif ( $rNum == 0 ) { $r = mysql_query("INSERT INTO `sessions` ( IP, HOSTNAME, TIMESTAMP, USER ) VALUES ( '$ip', '$hostname', $timestamp, '$user')"); }
  543.             else { die("wot."); }
  544.            
  545.             // TSEELEKT AUF TSESCHUN WORR TAIMSTAMP ES TAIMSTAMP UND
  546.             $r = mysql_fetch_array(mysql_query("SELECT ID FROM `sessions` WHERE TIMESTAMP = $timestamp AND HOSTNAME = '$hostname' AND IP = '$ip' LIMIT 1"));
  547.             $r = $r[0];
  548.         }*/
  549.        
  550.         function ShowCaptcha() {
  551.             error_reporting(0);
  552.             // generate random string and set it in $_SESSION
  553.             $pool = "abcdefghlkpmnqrtuvwxyz1234567890";
  554.             for ( $i = 0; $i < 5; $i++ ) { $pass = $pass . substr( $pool, rand(1, strlen($pool)), 1); }
  555.             $_SESSION['captcha'] = $pass;
  556.        
  557.             // Create image
  558.             $im = imagecreatetruecolor(150, 25);
  559.             $bg = imagecolorallocate($im, 0x14, 0x14, 0x14);
  560.             $fg = imagecolorallocate($im, 0x33, 0xcc, 0xcc);
  561.             imagefilledrectangle($im, 0, 0, 149, 24, $bg);
  562.             imagecolortransparent($im, $bg);
  563.             imagefttext ( $im, 18, rand(-10,10), rand(0,90), 20, $fg, './harabara.ttf', $pass);
  564.             for ( $r = 0; $r < 2; $r++) { imageline( $im, 0, rand(0,24), 149, rand(0,24), $fg ); }
  565.             header('Content-Type: image/png');
  566.  
  567.             imagepng($im);
  568.         }
  569.        
  570.         function ShowError ($code) {
  571.             unset($error);
  572.             $error_list = array(
  573.                 "bad_board" => array("Board Unavailable", "This board is locked, above your permission level, non-existant or otherwise unavailable."),
  574.                 "bad_login" => array("Wrong Username/Password", "The username or password you entered is incorrect."),
  575.                 "bad_email" => array("Bad Email", "I'm not so sure that's a real e-mail address. Don't try to hustle me. :|"),
  576.                 "bad_captcha" => array("Invalid CAPTCHA", "Are you a bot? (Maybe you just don't have cookies enabled.)"),
  577.                 "bad_password" => array("Password did not match defined pattern", "C'mon now, don't be ridiculous."),
  578.                 "uname_taken" => array("Username is taken.", "Pick another."),
  579.                 "mail_fail" => array("can't mail this, yo", "I JUST CAN'T DO IT! D:"),
  580.                 "bad_user" => array("Bad username", "Let's not be ridiculous. :|"),
  581.                 "banned" => array("B&!", ""),
  582.                 "nsfw_flag" => array("Age not verified for adult content","hey now. <meta http-equiv=\"refresh\" content=\"0;url=/nsfw\" />"),
  583.                 "connect_fail" => array("DB MISSING", "WHO BALEETED IT. CMON GUISE. :("),
  584.                 "token_fail" => array("ERROR NO. TK731", "HALP! PUT OUT THE FIRE! :O"),
  585.                 "bad_id" => array("Topic ID failed regex", "Stop tryin' to h4x0r."),
  586.                 "bad_topic" => array("Topic doesn't exist", "What you were looking for has probably already been pruned."),
  587.                 "empty_post" => array("Empty post", "C'mon guy, you can't post nothing. That's just waste."),
  588.                 "file_big" => array("Filesize exceeds limit", "YOUR FILE IS TOO BIG."),
  589.                 "file_part" => array("Upload interrupted","I didn't catch that. What were you saying?"),
  590.                 "file_tmp" => array("ERROR NO. MT994","THIS FIRE IS GETTING HUGE! HALP! :O"),
  591.                 "long_post" => array("Loooong post is loooong.", "Cut back, slim. Cut way back."),
  592.                 "fkey_in_use" => array("File key already in use", "Go back and try it again."),
  593.                 "tampering" => array("Form tampering", "Your request has been squelched because you are a dirty hacker, hacker."),
  594.                 "reply_success" => array("Successfully posted a reply", "Your reply has been made. <a href=\"{$_SESSION['redirect']}\" class=\"button\">Return to topic</a><a href=\"/\" class=\"button\">Return to index</a>"),
  595.                 "reply_failure" => array("Reply failed", "Something broke. <a href=\"{$_SESSION['redirect']}\" class=\"button\">Return to topic</a><a href=\"/\" class=\"button\">Return to index</a>"),
  596.                 "file_too_big" => array("Upload filesize exceeds limit", "That's too big. Refer to the FAQ for more information.<a href=\"{$_SESSION['redirect']}\" class=\"button\">Return to topic</a>"),
  597.                 "bad_file_insert" => array("Generic database error", "Failed to update database with file information."),
  598.                 "empty_upload" => array("Empty file uploaded", "C'mon, dude. Get your life together."),
  599.                 "bad_title" => array("Title failed pattern matching", "...and we were pretty liberal here. You must've done something very wrong to get here."),
  600.                 "form_tamper" => array("Form tampering", "You keep this up and I'mma ban you. :|"),
  601.                 "empty_topic" => array("Topic empty", "OH SHIT YOU BROKE IT. >:O"),
  602.                 "logged_in" => array("User trying non-user action", "You don't need to be here. :|"),
  603.                 "not_logged_in" => array("Non-user trying user action", "You need to be logged in to do that. :|"),
  604.                
  605.                 "good_login" => array("Logged in!", "Welcome back, {$_SESSION['user']}! Click <a href=\"/\">here</a> if you are not forwarded.</p><meta http-equiv=\"refresh\" content=\"0;url=/\" />")
  606.             );
  607.            
  608.             $error = $error_list[$code];
  609.             include("/views/error.inc.php");
  610.         }
  611.        
  612.         function ThrowError ( $code ) {
  613.             die("<p>Click <a href=\"/error/$code\">here</a> if you are not forwarded.</p><meta http-equiv=\"refresh\" content=\"0;url=/error/$code\" />"); 
  614.         }
  615.        
  616.         function UploadQuota() {
  617.             $lvl = $_SESSION['permission'];
  618.             if ( !isset($lvl) || $lvl == "" ) return 1048576;
  619.             switch ( $lvl ) {
  620.                 case 0: return 1048576; break;          // 1MB                  guest
  621.                 case 1: return 2097152; break;          // 2MB                  user
  622.                 case 2: return 5242880; break;          // 5MB                  preferred user
  623.                 case 3: return 10485760; break;         // 10MB                 contributing user
  624.                 case 4: return 10485760; break;         // 10MB                 regular
  625.                 case 5: return 10485760; break;         // 10MB                 regular++
  626.                 case 6: return 10485760; break;         // 10MB                 regular+++
  627.                 case 7: return -1; break;               // unlimited            mod
  628.                 case 8: return -1; break;               // unlimited            mod
  629.                 case 9: return -1; break;       // unlimited            me! :D
  630.             }
  631.         }
  632.        
  633.         function Regex ( $expr, $pattern ) {
  634.             $patterns = array(
  635.                 "username" => "/^[\w\_\~\!\@\#\$\%\^\&\*\(\)\"\;\:\[\{\]\}\/\.\,\?\x20]{3,16}$/",
  636.                 "title" => "/^[\w\n\~\!\@\#\$\%\^\&\*\(\)\"\;\:\[\{\]}\/\.\,\?\x20]{1,64}$/",
  637.                 "password" => "/^(.{4,64})$/",
  638.                 "email" => "/^[A-Za-z0-9._%+-]*\@[A-Za-z0-9._%+-]*\.[A-Za-z]{2,4}$/",
  639.                 "id" => "/^[0-9]{1,6}$/"
  640.             );
  641.            
  642.             if ( preg_match( $patterns[$pattern], $expr ) ) { return true; } else { return false; }
  643.         }
  644.        
  645.         function gmCode ( $content ) {
  646.             return preg_replace(
  647.                 "/\[b\](.*)\[\/b\]/Usi", "<b>\\1</b>", $content);
  648.         }
  649.        
  650.     function FindMime ( $filename ) {
  651.         $e = substr($filename, strrpos($filename, '.') + 1);
  652.         switch ($e) {
  653.             case "": return "text/plain"; break;
  654.             case "txt": return "text/plain"; break;
  655.             case "doc": return "application/msword"; break;
  656.             case "docx": return "application/msword"; break;
  657.             case "rtf": return "application/rtf"; break;
  658.             case "gz": return "application/x-gzip"; break;
  659.             case "zip": return "application/zip"; break;
  660.             case "mid": return "audio/mid"; break;
  661.             case "mp3": return "audio/mpeg"; break;
  662.             case "bmp": return "image/bmp"; break;
  663.             case "gif": return "image/gif"; break;
  664.             case "jpg": return "image/jpeg"; break;
  665.             case "jpeg": return "image/jpeg"; break;
  666.             case "tif": return "image/tiff"; break;
  667.             case "tiff": return "image/tiff"; break;
  668.             case "htm": return "text/html"; break;
  669.             case "html": return "text/html"; break;
  670.         }
  671.     }
  672.    
  673.     function nicetime ( $then ) {
  674.         $then = abs($then);
  675.         $now = time(); $i = 0;
  676.         $interval = array( array( 31104000, 2592000, 86400, 3600, 60, 1 ), array( "year", "month", "day", "hour", "minute", "second" ) );
  677.         if ( $then > $now ) {
  678.             foreach ( $interval[0] as $unit ) {
  679.                 $value = floor(($then - $now) / $unit);
  680.                 $i++;
  681.                 if ( $value > 1 ) return "{$value} {$interval[1][$i-1]}s";         
  682.                 if ( $value == 1 ) return "{$value} {$interval[1][$i-1]}";         
  683.             }      
  684.         } elseif ( $now > $then ) {
  685.             foreach ( $interval[0] as $unit ) {
  686.                 $value = floor(($now - $then) / $unit);
  687.                 $i++;
  688.                 if ( $value > 1 ) return "{$value} {$interval[1][$i-1]}s";         
  689.                 if ( $value == 1 ) return "{$value} {$interval[1][$i-1]}";         
  690.             }      
  691.         } else {
  692.             return "now";
  693.         }
  694.     }
  695.  
  696.     function nicesize($size) {
  697.         // REWRITE THIS, so you can say you did 100% of everything. :D
  698.         $filesizename = array(" bytes", " KB", " MB", " GB", " TB", " PB", " EB", " ZB", " YB");
  699.         return $size ? round($size/pow(1024, ($i = floor(log($size, 1024)))), 2) . $filesizename[$i] : '0 bytes'; }        
  700.     }
  701.  
  702. ?>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement