code:
<?php

namespace Mitsuba;

/**
 * Common
 * Insert description here
 *
 * @category
 * @package
 * @author
 * @copyright
 * @license
 * @version
 * @link
 * @see
 * @since
 */
class Common {

    private $conn;

    private $mitsuba;

    /**
     * __construct
     * Insert description here
     *
     * @param $connection
     * @param $mitsuba
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function __construct($connection, &$mitsuba) {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

    }

    /**
     * getEmbed
     * Insert description here
     *
     * @param $url
     * @param $embed_table
     * @param $s
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getEmbed($url, $embed_table = null, $s = 250) {

        foreach ($embed_table as $row) {

            if (preg_match($row['regex'], $url, $vresult)) {

                $vresult[0] = $s;

                foreach ($vresult as $k => $v) {

                    $vresult[$k] = htmlspecialchars($v);

                }

                return vsprintf($row['code'], $vresult);

            }

        }

        return 0;

    }

    /**
     * addSystemBan
     * Insert description here
     *
     * @param $IPAddress
     * @param $reason
     * @param $note
     * @param $expires
     * @param $boards
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function addSystemBan($IPAddress, $reason, $note, $expires, $boards) {

        if (!empty($IPAddress)) {

            $IPAddress = $this->conn->real_escape_string($IPAddress);

            $reason = $this->conn->real_escape_string($reason);

            $note = $this->conn->real_escape_string($note);

            $boards = $this->conn->real_escape_string($boards);

            $created = time();

            $perma = 1;

            if (($expires == "0") || ($expires == "never") || ($expires == "") || ($expires == "perm") || ($expires == "permaban")) {

                $expires = 0;

                $perma = 1;

            } else {

                $expires = $this->parse_time($expires);

                $perma = 0;

            }

            if (($expires == false) && ($perma == 0)) {

                return -2;

            }

            $this->conn->query("INSERT INTO bans (ip, mod_id, reason, note, created, expires, boards) VALUES ('" . $IPAddress . "', 0, '" . $reason . "', '" . $note . "', " . $created . ", " . $expires . ", '" . $boards . "');");

            return 1;

        }

    }

    /**
     * isEmbed
     * Insert description here
     *
     * @param $url
     * @param $embed_table
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isEmbed($url, $embed_table = null) {

        foreach ($embed_table as $row) {

            if (preg_match($row['regex'], $url, $vresult)) {

                return 1;

            }

        }

        return 0;

    }

    /**
     * human_filesize
     * Insert description here
     *
     * @param $bytes
     * @param $decimals
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function human_filesize($bytes, $decimals = 2) {

        $size = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');

        $factor = floor((strlen($bytes) - 1) / 3);

        return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$size[$factor];

    }

    /**
     * mkid
     * Insert description here
     *
     * @param $IPAddress
     * @param $topic
     * @param $board
     * @param $junk
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function mkid($IPAddress, $topic, $board, $junk = "") {

        global $id_salt;

        return substr(crypt(md5($IPAddress . 't' . $board . $topic . $junk . $id_salt), $id_salt), -8);

    }

    /**
     * getIP
     * Insert description here
     *
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getIP(){
    $fields = array('HTTP_X_FORWARDED_FOR',
                    'REMOTE_ADDR',
                    'HTTP_CF_CONNECTING_IP',
                    'HTTP_X_CLUSTER_CLIENT_IP');

    foreach($fields as $f)
    {
        $tries = isset($_SERVER[$f]) ? $_SERVER[$f] : '';
        if (empty($tries))
            continue;
        $tries = explode(',',$tries);
        foreach($tries as $try)
        {
            $r = filter_var($try,
                            FILTER_VALIDATE_IP, FILTER_FLAG_IPV4 |
                            FILTER_FLAG_NO_PRIV_RANGE |
                            FILTER_FLAG_NO_RES_RANGE);

            if ($r !== false)
            {
                return $try;
            }else {
              return '0.0.0.0';
            }
        }
    }
    return false;
}

    /**
     * getGraphicsExtension
     * Insert description here
     *
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getGraphicsExtension() {

        if (extension_loaded('imagick')) {

            return "imagick";

        } elseif (extension_loaded('gd')) {

            return "gd";

        } else {

            return 0;

        }

    }

    /**
     * getBoardData
     * Insert description here
     *
     * @param $short
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getBoardData($short) {

        return $this->isBoard($short); //yeah, yeah, I know...

    }

    /**
     * isLocked
     * Insert description here
     *
     * @param $short
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */

    function isLocked($id){
      $result = $this->conn->query("SELECT * FROM posts WHERE `id`='".$this->conn->real_escape_string($id)."' AND `locked`=1");
      if ($result->num_rows == 1){
        return true;
      }else{
        return false;
      }
    }

    /**
     * isBoard
     * Insert description here
     *
     * @param $short
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isBoard($short) {
        $result = $this->conn->query("SELECT * FROM boards WHERE short='" . $this->conn->real_escape_string($short) . "'");
        if ($result->num_rows == 1) {
            return $result->fetch_assoc();
        } else {
            return false;
        }
    }

    /**
     * showMsg
     * Insert description here
     *
     * @param $title
     * @param $text
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function showMsg($title, $text) {

        global $lang;

?>

		<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

		<title><?php echo $title; ?></title>

		<?php echo $text; ?>

<?php if (isset($_POST['board'])) { ?>
		[<a href="/<?php echo $_POST['board']; ?>/"><?php echo $lang['img/return']; ?>]
  <?php
} else { ?>
		[<?php echo $lang['img/return']; ?>]
    <?php } ?>

		<?php

    }

    /**
     * thumb
     * Insert description here
     *
     * @param $board
     * @param $filename
     * @param $ext
     * @param $s
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function thumb($board, $filename, $ext, $s = 250) {
      $filename = $filename;
      $extension = $this->getGraphicsExtension();
      if ($ext == ".webm") {
        $fname = './'.$board.'/src/'.$filename.$ext;
        $thumb_dir = './'.$board.'/src/thumb/';

        require_once dirname(__FILE__) . '/webm.class.php';

        $movie = new \webm($fname);

        if ($movie->thumbnail($thumb_dir.$filename.'.gif', $s, $s))
				return array("width" => $s, "height" => $s);
      }

        if($ext == ".swf"){
	        //swf files don't have thumbnails...yet.
	       return 0;
        }

        if ($ext == ".mp4") {
          $fname = './'.$board.'/src/'.$filename.$ext;
          $thumb_dir = './'.$board.'/src/thumb/';

          require_once dirname(__FILE__) . '/webm.class.php';

          $movie = new \webm($fname);

          if ($movie->thumbnail($thumb_dir.$filename.'.gif', $s, $s))
  				return array("width" => $s, "height" => $s);
        }

        if (!(strpos($filename, "url:") === false)) {
            //dont make thumbnails of links
            return 0;
        }

        if (($extension == "imagick") && !($ext == ".webm") && !($ext == ".mp4")) {
            $fname = './' . $board . '/src/' . $filename;
            $thumb_dir = './' . $board . '/src/thumb/'; //thumbnail directory
            $width = $s; //output width
            $height = $s; //output height

            $img = new \Imagick($fname.$ext);
            $img = $img->coalesceImages();

            foreach ($img as $frame) {
                $frame->thumbnailImage($width, $height, true);
            }

            $img->writeImages($thumb_dir . $filename . $ext, true);

            $ig = $img->getImageGeometry();
            $img->destroy();
            return $ig;
        } elseif ($extension == "gd") {
            if (!function_exists("ImageCreate") || !function_exists("ImageCreateFromJPEG")) return;
            $fname = './' . $board . '/src/' . $filename.$ext;
            $thumb_dir = './' . $board . '/src/thumb/'; //thumbnail directory
            $width = $s; //output width
            $height = $s; //output height

            // width, height, and type are aquired
            $size = GetImageSize($fname);
            $type = "jpg";

            try {
                switch ($size[2]) {
                    case 1:
                        if (!function_exists("ImageCreateFromGIF")) return;
                        $im_in = ImageCreateFromGIF($fname);
                        $type = "gif";
                        if (!$im_in) {
                            return -1;
                        }

                        break;

                    case 2:
                        $im_in = ImageCreateFromJPEG($fname);
                        $type = "jpg";
                        if (!$im_in) {
                            return -1;
                        }

                        break;

                    case 3:
                        if (!function_exists("ImageCreateFromPNG")) return;
                        $im_in = ImageCreateFromPNG($fname);
                        $type = "png";
                        if (!$im_in) {
                            return -1;
                        }

                        break;

                    default:
                        return -2;
                }
            }catch(Exception $e) {
                    return -1;
            }
                // Resizing
                if ($size[0] > $width || $size[1] > $height) {
                    $key_w = $width / $size[0];
                    $key_h = $height / $size[1];
                    ($key_w < $key_h) ? $keys = $key_w : $keys = $key_h;
                    $out_w = ceil($size[0] * $keys) + 1;
                    $out_h = ceil($size[1] * $keys) + 1;
                } else {
                    $out_w = $size[0];
                    $out_h = $size[1];
                }

                // the thumbnail is created
                if (function_exists("ImageCreateTrueColor")) {
                    $im_out = ImageCreateTrueColor($out_w, $out_h);
                } else {
                    $im_out = ImageCreate($out_w, $out_h);
                }

                //adds transparency [devnote: this took me fucking 3-4 days to figure out how to do it... why isn't there better documentation?]
                imagealphablending($im_out, false);
                imagesavealpha($im_out, true);
                $trans_layer_overlay = imagecolorallocatealpha($im_in, 220, 220, 220, 127);
                imagefill($im_out, 0, 0, $trans_layer_overlay);

                // copy resized original
                imagecopyresampled($im_out, $im_in, 0, 0, 0, 0, $out_w, $out_h, $size[0], $size[1]);

                // thumbnail saved

                switch ($type) {
                    case "jpg":
                        ImageJPEG($im_out, $thumb_dir . $filename . $ext, 70);
                    break;

                    case "png":
                        ImagePNG($im_out, $thumb_dir . $filename . $ext, 9);
                    break;

                    case "gif":
                        ImageGIF($im_out, $thumb_dir . $filename . $ext);
                    break;
                }

                chmod($thumb_dir . $filename, 0666);

                // created image is destroyed

                ImageDestroy($im_in);
                ImageDestroy($im_out);
                return array("width" => $out_w, "height" => $out_h);
        }
    }

    /**
     * delTree
     * Insert description here
     *
     * @param $dir
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function delTree($dir) {

        $files = array_diff(scandir($dir), array('.', '..'));

        foreach ($files as $file) {

            (is_dir("$dir/$file")) ? $this->delTree("$dir/$file") : unlink("$dir/$file");

        }

        return rmdir($dir);

    }

    /**
     * isWhitelisted
     * Insert description here
     *
     * @param $IPAddress
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isWhitelisted($IPAddress) {

        $whitelist = $this->conn->query("SELECT * FROM whitelist WHERE ip='" . $IPAddress . "' ORDER BY id DESC LIMIT 0, 1");

        if ($whitelist->num_rows >= 1) {

            $wlistdata = $whitelist->fetch_assoc();

            if ($wlistdata['nolimits'] == 1) {

                return 2;

            }

            return 1;

        } else {

            return 0;

        }

    }
    //thanks Rijndael. Easily en/decrypting your PMs since whenever.
    /**
     * dec_enc
     * Insert description here
     *
     * @param $action
     * @param $string
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
     function dec_enc($action, $string) {
       global $securetrip_salt, $id_salt;
         $output = false;

         $encrypt_method = "AES-256-CBC";
         $secret_key = $securetrip_salt;
         $secret_iv = $id_salt;

         // hash
         $key = hash('sha256', $secret_key);

         // iv - encrypt method AES-256-CBC expects 16 bytes - else you will get a warning
         $iv = substr(hash('sha256', $secret_iv), 0, 16);

         if( $action == 'encrypt' ) {
             $output = openssl_encrypt($string, $encrypt_method, $key, 0, $iv);
             $output = base64_encode($output);
         }
         else if( $action == 'decrypt' ){
             $output = openssl_decrypt(base64_decode($string), $encrypt_method, $key, 0, $iv);
         }

         return $output;
     }
    /**
     * startsWith
     * Insert description here
     *
     * @param $haystack
     * @param $needle
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function startsWith($haystack, $needle) {

        return !strncmp($haystack, $needle, strlen($needle));

    }

    /**
     * endsWith
     * Insert description here
     *
     * @param $haystack
     * @param $needle
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function endsWith($haystack, $needle) {

        $length = strlen($needle);

        if ($length == 0) {

            return true;

        }

        return (substr($haystack, -$length) === $needle);

    }

    /*function randomPassword() {

    $alphabet = "abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789";

    $pass = array();

    $alphaLength = strlen($alphabet) - 1;

    for ($i = 0; $i < 8; $i++) {

    $n = rand(0, $alphaLength);

    $pass[] = $alphabet[$n];

    }

    return implode($pass);

    }*/

    /**
     * randomPassword
     * Insert description here
     *
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function randomPassword() {

        $fp = @fopen('/dev/urandom', 'rb');

        $result = '';

        if ($fp !== FALSE) {

            $result.= @fread($fp, 8);

            @fclose($fp);

        } else {

            trigger_error('Can not open /dev/urandom.');

        }

        // convert from binary to string

        $result = base64_encode($result);

        // remove none url chars

        $result = strtr($result, '+/', '-_');

        // Remove = from the end

        $result = str_replace('=', ' ', $result);

        return $result;

    }

    /**
     * randomSalt
     * Insert description here
     *
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function randomSalt() {

        $alphabet = 'abcdefghijklmnopqrstuwxyzABCDEFGHIJKLMNOPQRSTUWXYZ0123456789+_-)(*&^%$#@!~|';

        $pass = array();

        $alphaLength = strlen($alphabet) - 1;

        for ($i = 0;$i < 15;$i++) {

            $n = rand(0, $alphaLength);

            $pass[] = $alphabet[$n];

        }

        return implode($pass);

    }

    /**
     * getsecuretripcode
     * Insert description here
     *
     * @param $pwd
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getsecuretripcode($pwd) {

        $striphash = $this->mktripcode(substr($pwd, 1));

        $strips = $this->conn->query("SELECT * FROM tripcodes WHERE hash='" . $striphash . "' AND secure=1");

        if ($strips->num_rows >= 1) {

            $row = $strips->fetch_assoc();

            return $row['replace'];

        } else {

            $strip = $this->mksecuretripcode($pwd);

            $this->conn->query("INSERT INTO tripcodes (`hash`, `replace`, `secure`) VALUES ('" . $striphash . "', '" . $strip . "', 1);");

            return $strip;

        }

    }

    /**
     * processName
     * Insert description here
     *
     * @param $string
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function processName($string) {

        $arr = array();

        $new = $string;

        //$new = str_replace("##", "#", $new);

        $exploded = explode("#", $new, 2);

        $arr['trip'] = "";

        $arr['name'] = "";

        $arr['strip'] = "";

        //$arr['striphash'] = "";

        if (count($exploded) > 1) {

            $arr['name'] = $exploded[0];

            if (substr($exploded[1], 0, 1) == "#") {

                $moretrips = explode("#", substr($exploded[1], 1), 2);

                if (count($moretrips) > 1) {

                    $arr['strip'] = $this->getsecuretripcode($moretrips[0]);

                    $arr['trip'] = $this->mktripcode($moretrips[1]);

                } else {

                    $arr['strip'] = $this->getsecuretripcode(substr($exploded[1], 1));

                }

            } else {

                $moretrips = explode("#", $exploded[1], 2);

                if (count($moretrips) > 1) {

                    if (substr($moretrips[1], 0, 1) == "#") {

                        $arr['strip'] = $this->getsecuretripcode(substr($moretrips[1], 1));

                    } else {

                        $arr['strip'] = $this->getsecuretripcode($moretrips[1]);

                    }

                    $arr['trip'] = $this->mktripcode($moretrips[0]);

                } else {

                    $arr['trip'] = $this->mktripcode($exploded[1]);

                }

            }

        } else {

            $arr['name'] = $new;

            $arr['trip'] = "";

        }

        $arr['name'] = $this->conn->real_escape_string($arr['name']);

        $arr['name'] = htmlspecialchars($arr['name']);

        return $arr;

    }

    /**
     * processString
     * Insert description here
     *
     * @param $string
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function processString($string) {

        $new = $string;

        $new = $this->conn->real_escape_string($new);

        $new = htmlspecialchars($new);

        return $new;

    }

    /**
     * preprocessComment
     * Insert description here
     *
     * @param $string
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function preprocessComment($string) {

        $new = str_replace("\r", "", $string);

        $new = $this->conn->real_escape_string($new);

        return $new;

    }

    /**
     * isFile
     * Insert description here
     *
     * @param $path
     * @param $board_files
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isFile($path, $board_files = "%") {

        $mime = "";

        if (empty($board_files)) {

            $board_files = "%";

        }

        if (function_exists("finfo_file")) {

            $finfo = finfo_open();

            $mime = finfo_file($finfo, $path, FILEINFO_MIME_TYPE);

        } elseif (function_exists("mime_content_type")) {

            $mime = mime_content_type($path);

        } else {

            if (function_exists("getimagesize")) {

                $a = getimagesize($path);

                $image_type = $a[2];

                /*if ($image_type == IMAGETYPE_GIF)

                {

                $mime = "image/gif";

                }

                if ($image_type == IMAGETYPE_PNG)

                {

                $mime = "image/png";

                }

                if ($image_type == IMAGETYPE_JPEG)

                {

                $mime = "image/jpeg";

                }*/

                $mime = image_type_to_mime_type($image_type);

            } else {

                return false;

            }

        }

        $extensions = $this->conn->query("SELECT * FROM extensions WHERE mimetype='" . $this->conn->real_escape_string($mime) . "'");

        if ($extensions->num_rows == 1) {

            $ext = $extensions->fetch_assoc();

            if (($board_files == "%") || (in_array($ext['ext'], explode(",", $board_files)))) //If the extensions in $board_files are in $ext['ext']

            {

                $nfo['extension'] = $ext['ext'];

                $nfo['image'] = $ext['image'];

                $nfo['mimetype'] = $mime;

                return $nfo;

            } else {

                return false;

            }

        } else {

            return false;

        }

    }

    /**
     * mktripcode
     * Insert description here
     *
     * @param $pw
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function mktripcode($pw) {

        $pw = mb_convert_encoding($pw, 'SJIS', 'UTF-8');

        $salt = substr($pw . 'H.', 1, 2);

        $salt = preg_replace('/[^\.-z]/', '.', $salt);

        $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef');

        $trip = substr(crypt($pw, $salt), -10);

        return $trip;

    }

    /**
     * mksecuretripcode
     * Insert description here
     *
     * @param $pw
     * @param $junk
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function mksecuretripcode($pw, $junk = "r3volution") {

        global $securetrip_salt;

        $pw = mb_convert_encoding($pw, 'SJIS', 'UTF-8');

        $pw = str_replace('&', '&', $pw);

        $pw = str_replace('"', '"', $pw);

        $pw = str_replace("'", ''', $pw);

        $pw = str_replace('<', '<', $pw);

        $pw = str_replace('>', '>', $pw);

        $randomstring = "";

        $poststring = "";

        foreach ($_POST as $key => $value) {

            $poststring.= $key . "!" . $value;

        }

        $poststring = strtr($poststring, ':;<=>?@[\]^_`', 'ABCDEFGabcdef');

        $randomstring = md5($poststring) . time() . rand(90, 1681018501) . $junk;

        $salt = substr($pw . 'H!' . $randomstring, 1, 2);

        $salt = preg_replace('/[^.\/0-9:;<=>?@A-Z\[\\\]\^_`a-z]/', '.', $salt);

        $salt = strtr($salt, ':;<=>?@[\]^_`', 'ABCDEFGabcdef');

        $trip = crypt($pw . $randomstring . $securetrip_salt, $salt);

        return $trip;

    }

    /**
     * isBanned
     * Insert description here
     *
     * @param $IPAddress
     * @param $board
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isBanned($IPAddress, $board) {

        $IPAddressbans = $this->conn->query("SELECT * FROM bans WHERE ip='" . $IPAddress . "' AND (expires>" . time() . " OR expires=0) ORDER BY expires DESC;");

        $rangebans = $this->conn->query("SELECT * FROM rangebans ORDER BY expires DESC;");

        $IPAddressbandata = null;

        $rangebandata = null;

        $bandata = null;

        $otherbans = array();

        while ($row = $rangebans->fetch_assoc()) {

            $range = str_replace('*', '(.*)', $row['ip']);

            if ($this->startsWith($range, ".")) {

                if ((strpos($IPAddress, $range) !== FALSE)) {

                    if ($row['boards'] == "%") {

                        $rangebandata = $row;

                        $rangebandata['range'] = 1;

                    } else {

                        if ($board == "%") {

                            $rangebandata = $row;

                            $rangebandata['range'] = 1;

                        } else {

                            $boards = explode(",", $row['boards']);

                            if (in_array($board, $boards)) {

                                $rangebandata = $row;

                                $rangebandata['range'] = 1;

                            }

                        }

                    }

                    $otherbans[] = $row;

                    $otherbans[count($otherbans) - 1]['range'] = 1;

                }

            } elseif ($this->startsWith($IPAddress, $range)) {

                if ($row['boards'] == "%") {

                    $rangebandata = $row;

                    $rangebandata['range'] = 1;

                } else {

                    if ($board == "%") {

                        $rangebandata = $row;

                        $rangebandata['range'] = 1;

                    } else {

                        $boards = explode(",", $row['boards']);

                        if (in_array($board, $boards)) {

                            $rangebandata = $row;

                            $rangebandata['range'] = 1;

                        }

                    }

                }

                $otherbans[] = $row;

                $otherbans[count($otherbans) - 1]['range'] = 1;

            } elseif (preg_match('/' . $range . '/', $IPAddress)) {

                if ($row['boards'] == "%") {

                    $rangebandata = $row;

                    $rangebandata['range'] = 1;

                } else {

                    if ($board == "%") {

                        $rangebandata = $row;

                        $rangebandata['range'] = 1;

                    } else {

                        $boards = explode(",", $row['boards']);

                        if (in_array($board, $boards)) {

                            $rangebandata = $row;

                            $rangebandata['range'] = 1;

                        }

                    }

                }

                $otherbans[] = $row;

                $otherbans[count($otherbans) - 1]['range'] = 1;

            }

        }

        while ($row = $IPAddressbans->fetch_assoc()) {

            if ((empty($IPAddressbandata)) || ($IPAddressbandata['expires'] < $row['expires'])) {

                if ($row['boards'] == "%") {

                    $IPAddressbandata = $row;

                } else {

                    if ($board == "%") {

                        $IPAddressbandata = $row;

                    } else {

                        $boards = explode(",", $row['boards']);

                        if (in_array($board, $boards)) {

                            $IPAddressbandata = $row;

                        }

                    }

                }

            }

            $otherbans[] = $row;

            $otherbans[count($otherbans) - 1]['range'] = 0;

        }

        if (($IPAddressbandata != null) && ($rangebandata != null)) {

            if (($IPAddressbandata['expires'] == 0) || ($IPAddressbandata['expires'] > $rangebandata['expires'])) {

                $bandata = $IPAddressbandata;

            } elseif (($rangebandata['expires'] == 0) || ($rangebandata['expires'] > $IPAddressbandata['expires'])) {

                $bandata = $rangebandata;

            } else {

                $bandata = $IPAddressbandata;

            }

        } elseif (($IPAddressbandata != null) || ($rangebandata != null)) {

            if ($IPAddressbandata != null) {

                $bandata = $IPAddressbandata;

            } elseif ($rangebandata != null) {

                $bandata = $rangebandata;

            } else {

                return 0;

            }

        } else {

            return 0; //not banned

        }

        if (!empty($bandata)) {

            if (count($otherbans) >= 1) {

                $bandata['more'] = $otherbans;

            }

            return $bandata;

        }

        return 0;

    }

    /**
     * isWarned
     * Insert description here
     *
     * @param $IPAddress
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function isWarned($IPAddress) {

        $warns = $this->conn->query("SELECT * FROM warnings WHERE ip='" . $IPAddress . "' AND seen=0 ORDER BY created ASC LIMIT 0, 1;");

        if ($warns->num_rows == 1) {

            $warndata = $warns->fetch_assoc();

            return $warndata;

        } else {

            return 0;

        }

        return 0;

    }

    /**
     * banInfo
     * Insert description here
     *
     * @param $bandata
     * @param $board
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function banInfo($bandata, $board) {

        if ((empty($bandata['range'])) && ($bandata['seen'] == 0)) {

            $this->conn->query("UPDATE bans SET seen=1 WHERE id=" . $bandata['id']);

        }

        if ($bandata['boards'] == "%") {

            $boards = 1;

        } else {

            $boards = 0;

        }

        if ($bandata['expires'] != 0) {

            $left = floor(($bandata['expires'] - time()) / (60 * 60 * 24));
            if ($left == 0) {
              $left = self::seconds2human($bandata['expires']- time());
            }
            $days = floor(($bandata['expires'] - $bandata['created']) / (60 * 60 * 24));

        } else {

            $left = - 1;

            $days = - 1;

        }

?>

You have been <?php if ($left == - 1) {

            echo "permanently";

        } ?> <?php if (!empty($bandata['range'])) {

            echo "range-";

        } ?>banned from <?php if ($boards == 1) {

            echo "all ";

        } else {

            echo "few ";

        } ?>boards for the following reason:

<?php echo $bandata['reason']; ?>

You were banned on <?php echo date("d/m/Y (D) H:i:s", $bandata['created']); ?> and your ban expires

		<?php if ($left != - 1) {

            echo " on " . date("d/m/Y (D) H:i:s", $bandata['expires']) . ", which is " . $left . " from now.";

        } else {

            echo " never";

        }; ?>

According to our server your IP is: <?php echo self::getIP(); ?>

		<?php

        $range = 0;

        if (!empty($bandata['range_ip'])) {

            $range = 1;

        }

        $appeals = $this->conn->query("SELECT * FROM appeals WHERE ban_id=" . $bandata['id'] . " AND rangeban=" . $range);

        //Your appeal has been sent and is waiting until review, you can change it here.

        $appeal = ($bandata['appeal'] - time()) / (60 * 60 * 24);

        if (($bandata['appeal'] != 0) && ($appeal < 0)) {

?>

You may appeal your ban in the form below. Please explain why you deserve to be unbanned.

			<?php

            $app_msg = "";

            $app_mail = "";

            if ($appeals->num_rows == 1) {

                $appealdata = $appeals->fetch_assoc();

                $app_msg = $appealdata['msg'];

                $app_mail = $appealdata['email'];

                echo "Your appeal has been sent and is waiting until review, you can change it here.";

            }

?>

			<form action="/imgboard.php" method="POST" class="col s12">
			<input type="hidden" name="mode" value="usrapp" />
			<input type="hidden" name="banid" value="<?php echo $bandata['id']; ?>" />
			<input type="hidden" name="banrange" value="<?php echo $range; ?>" />

			<textarea id="appeal" class="materialize-textarea" rows="6" name="msg"><?php echo $app_msg; ?></textarea>
			Appeal Message

			<button type="submit" class="btn-floating btn-large waves-effect waves-light red">send</button>
			</form>

			<?php

        } elseif ($bandata['appeal'] != 0) {

?>

You'll be allowed to appeal your ban in <?php echo floor(($bandata['appeal'] - time()) / (60 * 60 * 24)); ?> days.

			<?php

        } else {

?>

You may not appeal your ban.

			<?php

        }

    }

    /**
     * banMessage
     * Insert description here
     *
     * @param $board
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function banMessage($board = "%") {

        $bandata = $this->isBanned(self::getIP(), $board);

        if ($bandata != 0) {

?>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
		<meta charset="UTF-8">
		<title>You are banned ;-;</title>
		<link href="/css/MIcons.css" rel="stylesheet">
		<link href="/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
		<link href="/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

					314chan

Rules

FAQ

News

IRC

Rules

FAQ

News

IRC

					menu

You are banned ;_;

				<?php
					$this->banInfo($bandata, $board);
					if ((!empty($bandata['more'])) && (count($bandata['more']) > 1)) {
				?>

There's more than one ban placed on your IP.

					<?php
						foreach ($bandata['more'] as $ban) {
							echo "
";
							$this->banInfo($ban, $board);
						}
					}
				?>

	<?php
            die();
        }

    }

    /**
     * verifyBan
     * Insert description here
     *
     * @param $IPAddress
     * @param $ban_id
     * @param $range
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function verifyBan($IPAddress, $ban_id, $range) {

        if ((!is_numeric($ban_id)) || (!is_numeric($range))) {

            return false;

        }

        if ($range == 0) {

            $ban = $this->conn->query("SELECT * FROM bans WHERE id=" . $ban_id);

            if ($ban->num_rows == 1) {

                $binfo = $ban->fetch_assoc();

                if ($binfo['ip'] == $IPAddress) {

                    return true;

                }

            }

        } else {

            $ban = $this->conn->query("SELECT * FROM rangebans WHERE id=" . $ban_id);

            if ($ban->num_rows == 1) {

                $binfo = $ban->fetch_assoc();

                $range = str_replace('*', '(.*)', $binfo['ip']);

                if ($this->startsWith($range, ".")) {

                    if ((strpos($IPAddress, $range) !== FALSE)) {

                        return true;

                    }

                } elseif ($this->startsWith($IPAddress, $range)) {

                    return true;

                } elseif (preg_match('/' . $range . '/', $IPAddress)) {

                    return true;

                }

            }

        }

        return false;

    }

    /**
     * warningMessage
     * Insert description here
     *
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function warningMessage() {

        $warndata = $this->isWarned(self::getIP());

        if ($warndata != 0) {

?>

		<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>
		<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>
		<meta charset="UTF-8">
		<title>You have been warned!</title>
		<link href="/css/MIcons.css" rel="stylesheet">
		<link href="/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>
		<link href="/css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

					314chan

Rules

FAQ

News

IRC

Rules

FAQ

News

IRC

					menu

You were issued a warning! ;_;

<?php echo $warndata['reason']; ?>

Your warning was issued on <?php echo date("d/m/Y (D) H:i:s", $warndata['created']); ?>.

Now that you have seen this message, you should be able to post again. Click here to return.

	<?php

            $this->conn->query("UPDATE warnings SET seen=1 WHERE id=" . $warndata['id']);

            die();

        }

    }

    /**
     * pruneOld
     * Insert description here
     *
     * @param $board
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function pruneOld($board) {

        $board = $this->conn->real_escape_string($board);

        if (!$this->isBoard($board)) {

            return -16;

        }

        $bdata = $this->getBoardData($board);

        $toremove = 9001;

        if ($bdata['type'] == "fileboard") {

            $toremove = $bdata['files'] + 1;

        } elseif (($bdata['type'] == "imageboard") || ($bdata['type'] == "textboard")) {

            $toremove = ($bdata['pages'] + 2) * 10;

        } else {

            return 0;

        }

        $threads = $this->conn->query("SELECT * FROM posts WHERE resto=0 AND board='" . $board . "' AND deleted=0 ORDER BY sticky DESC, lastbumped DESC LIMIT " . $toremove . ", 2000");

        while ($row = $threads->fetch_assoc()) {

            $files = $this->conn->query("SELECT * FROM posts WHERE filename != '' AND resto=" . $row['id'] . " AND board='" . $board . "'");

            while ($file = $files->fetch_assoc()) {

                $filename = $file['filename'];

                if (substr($filename, 0, 8) == "spoiler:") {

                    $filename = substr($filename, 8);

                }

                if ((substr($filename, 0, 6) != "embed:") && ($filename != "deleted")) {

                    unlink("./" . $board . "/src/" . $filename);

                    if (file_exists("./" . $board . "/src/thumb/" . $filename)) {

                        unlink("./" . $board . "/src/thumb/" . $filename);

                    }

                }

            }

            $filename = $row['filename'];

            if (substr($filename, 0, 8) == "spoiler:") {

                $filename = substr($filename, 8);

            }

            if ((substr($filename, 0, 6) != "embed:") && ($filename != "deleted")) {

                unlink("./" . $board . "/src/" . $filename);

                if (file_exists("./" . $board . "/src/thumb/" . $filename)) {

                    unlink("./" . $board . "/src/thumb/" . $filename);

                }

            }

            $this->conn->query("DELETE FROM posts WHERE resto=" . $row['id'] . " AND board='" . $board . "'");

            $this->conn->query("DELETE FROM posts WHERE id=" . $row['id'] . " AND board='" . $board . "'");

            if ($bdata['hidden'] == 0) {

                unlink("./" . $board . "/res/" . $row['id'] . ".html");

            }

        }

        $deleted_posts = $this->conn->query("SELECT * FROM posts WHERE board='" . $board . "' AND deleted<" . (time() - 3600 * $this->mitsuba->config['keep_hours']) . " AND deleted<>0");

        while ($row = $deleted_posts->fetch_assoc()) {

            if ($row['resto'] == 0) {

                $files = $this->conn->query("SELECT * FROM posts WHERE filename != '' AND resto=" . $row['id'] . " AND board='" . $board . "'");

                while ($file = $files->fetch_assoc()) {

                    $filename = $file['filename'];

                    if (substr($filename, 0, 8) == "spoiler:") {

                        $filename = substr($filename, 8);

                    }

                    if ((substr($filename, 0, 6) != "embed:") && ($filename != "deleted")) {

                        unlink("./" . $board . "/src/" . $filename);

                        if (file_exists("./" . $board . "/src/thumb/" . $filename)) {

                            unlink("./" . $board . "/src/thumb/" . $filename);

                        }

                    }

                }

            }

            $filename = $row['filename'];

            if (substr($filename, 0, 8) == "spoiler:") {

                $filename = substr($filename, 8);

            }

            if ((substr($filename, 0, 6) != "embed:") && ($filename != "deleted")) {

                unlink("./" . $board . "/src/" . $filename);

                if (file_exists("./" . $board . "/src/thumb/" . $filename)) {

                    unlink("./" . $board . "/src/thumb/" . $filename);

                }

            }

            $this->conn->query("DELETE FROM posts WHERE resto=" . $row['id'] . " AND board='" . $board . "'");

            $this->conn->query("DELETE FROM posts WHERE id=" . $row['id'] . " AND board='" . $board . "'");

            if ($bdata['hidden'] == 0) {

                unlink("./" . $board . "/res/" . $row['id'] . ".html");

            }

        }

    }
    /**
     * seconds2human
     * Insert description here
     *
     * @param $str
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function seconds2human($ss) {
      $s = $ss%60;
      $m = floor(($ss%3600)/60);
      $h = floor(($ss%86400)/3600);
      $d = floor(($ss%2592000)/86400);
      $M = floor($ss/2592000);
      if(!empty($M)){
        $M = $M." months";
      }else {
        $M = "";
      }
      if(!empty($d)){
        $d = $d." days";
      }else {
        $d = "";
      }
      if(!empty($h)){
        $h = $h." hours";
      }else {
        $h = "";
      }
      if(!empty($m)){
        $m = $m." minutes";
      }else {
        $m = "";
      }
      if(!empty($s)){
        $s = "and ". $s." seconds";
      }else {
        $s = "";
      }
    return "$M $d $h $m $s ";
    }

    /**
     * parse_time
     * Insert description here
     *
     * @param $str
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function parse_time($str) {

        if (empty($str)) return false;

        if (($time = @strtotime($str)) !== false) return $time;

        if (!preg_match('/^((\d+)\s?ye?a?r?s?)?\s?+((\d+)\s?mon?t?h?s?)?\s?+((\d+)\s?we?e?k?s?)?\s?+((\d+)\s?da?y?s?)?((\d+)\s?ho?u?r?s?)?\s?+((\d+)\s?mi?n?u?t?e?s?)?\s?+((\d+)\s?se?c?o?n?d?s?)?$/', $str, $matches)) return false;

        $expire = 0;

        if (isset($matches[2])) {

            // Years

            $expire+= $matches[2] * 60 * 60 * 24 * 365;

        }

        if (isset($matches[4])) {

            // Months

            $expire+= $matches[4] * 60 * 60 * 24 * 30;

        }

        if (isset($matches[6])) {

            // Weeks

            $expire+= $matches[6] * 60 * 60 * 24 * 7;

        }

        if (isset($matches[8])) {

            // Days

            $expire+= $matches[8] * 60 * 60 * 24;

        }

        if (isset($matches[10])) {

            // Hours

            $expire+= $matches[10] * 60 * 60;

        }

        if (isset($matches[12])) {

            // Minutes

            $expire+= $matches[12] * 60;

        }

        if (isset($matches[14])) {

            // Seconds

            $expire+= $matches[14];

        }

        return time() + $expire;

    }

}

?>

license: mit


code:
<?php

namespace Mitsuba;

class Frontpage
{

    private $conn;

    private $config;

    private $mitsuba;

    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

        $this->config = $this->mitsuba->config;

    }

    function generateFrontpage($action = "none")
    {

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

        $file .= '

	<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

	<title>'.$this->config['sitename'].'</title>';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc())

        {

            if ($first_default == 1) {

                $file .= '<link rel="stylesheet" id="switch" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'">';

                $first_default = 0;

            }

            $file .= '<link rel="alternate stylesheet" style="text/css" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'" title="'.$row['name'].'">';

        }

        $file .= "

";

        $file .= '

'.$this->config['sitename'].'

';

        $file .= '

Boards

';

        $cats = $this->conn->query("SELECT * FROM links WHERE parent=-1 ORDER BY short ASC;");

        while ($row = $cats->fetch_assoc())

        {

            $file .= '
';

            $file .= '
'.$row['title'].'
';

            $file .= '
';

            $children = $this->conn->query("SELECT * FROM links WHERE parent=".$row['id']." ORDER BY short ASC");

            while ($child = $children->fetch_assoc())

            {

                if (!empty($child['url_index'])) {

                    $file .= '

						'.$child['title'].'

';

                } else {

                    $file .= '

						'.$child['title'].'

';

                }

            }

            $file .= '
';

        }

        $file .= '

';

        $file .= '

Recent Images

';

        $recent_images = $this->conn->query("SELECT posts.*, boards.hidden, boards.unlisted FROM posts LEFT JOIN boards ON posts.board=boards.short WHERE boards.hidden=0 AND boards.unlisted=0 AND filename<>'' AND filename<>'deleted' AND filename NOT LIKE 'embed%' AND filename NOT LIKE 'spoiler%' AND deleted=0 ORDER BY date DESC LIMIT 0, 3;");

        while ($row = $recent_images->fetch_assoc())

        {

            $postfile = $row['id'].".html#p".$row['id'];

            if (!empty($row['resto'])) { $postfile = $row['resto'].".html#p".$row['id'];
            }

            $file .= '

';

        }

        $file .= '

';

        $file .= '

Latest Posts

';

        $recent_posts = $this->conn->query("SELECT posts.*, boards.hidden, boards.unlisted, boards.name AS bname FROM posts LEFT JOIN boards ON posts.board=boards.short WHERE boards.hidden=0 AND boards.unlisted=0 AND deleted=0 ORDER BY date DESC LIMIT 0, 15;");

        while ($row = $recent_posts->fetch_assoc())

        {

            $postfile = $row['id'].".html#p".$row['id'];

            if (!empty($row['resto'])) { $postfile = $row['resto'].".html#p".$row['id'];
            }

            $file .= '

'.$row['bname'].': '.htmlspecialchars(substr($row['comment'], 0, 30)).'...

';

        }

        $file .= '

';

        $file .= '

News

';

        $result = $this->conn->query("SELECT * FROM news ORDER BY date DESC;");

        while ($row = $result->fetch_assoc())

        {

            $file .= '
';

            $file .= '
'.$row['title'].' by '.$row['who'].' - '.date("d/m/Y @ H:i", $row['date']).'
';

            $file .= $row['text'];

            $file .= '
';

        }

        $file .= '

			';

        $file .= '

Stats

';

        $result = $this->conn->query("SELECT * FROM posts");

        $num_rows = $result->num_rows;

        $result = $this->conn->query("SELECT DISTINCT ip FROM posts");

        $num_users = $result->num_rows;

        $result = $this->conn->query("SELECT sum(orig_filesize) FROM posts");

        $num_bytes = $result->fetch_array()[0];

        {

        $file .= '
Total posts: '.$num_rows.'

Unique posters: '.$num_users.'

Active content: '.$this->mitsuba->common->human_filesize($num_bytes).'

			';

        }

        $file .= '

';

        $file .= '

- mitsuba + homepage made with butter -

';

        $handle = fopen("./".$this->config['frontpage_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

    function generateNews()
    {

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

			"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';

        $file .= '

			<title>'.$this->config['sitename'].'</title>';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc())

        {

            if ($first_default == 1) {

                $file .= '<link rel="stylesheet" id="switch" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'">';

                $first_default = 0;

            }

            $file .= '<link rel="alternate stylesheet" style="text/css" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'" title="'.$row['name'].'">';

        }

        $file .= "

			";

        $file .= '

';

        $file .= '

News

';

        $result = $this->conn->query("SELECT * FROM news ORDER BY date DESC;");

        while ($row = $result->fetch_assoc())

        {

            $file .= '
';

            $file .= '
'.$row['title'].' by '.$row['who'].' - '.date("d/m/Y @ H:i", $row['date']).'
';

            $file .= $row['text'];

            $file .= '
';

        }

        $file .= '

			';

        $handle = fopen("./".$this->config['news_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

}

?>


code:
<?php

namespace Mitsuba;

class Frontpage
{

    private $conn;

    private $config;

    private $mitsuba;

    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

        $this->config = $this->mitsuba->config;

    }

    function generateFrontpage($action = "none")
    {

        $file = '<!doctype html>';

        $file.= '

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>

						<meta charset="UTF-8">

						<title>' . $this->config['sitename'] . ' - The Only Imageboard That Cares!</title>
						<meta name="description" content="314chan is an imageboard forum with no registration required established in 2011. We\'re the only *chan that cares!" />

            <link href="css/MIcons.css" rel="stylesheet">

            <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>

            <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

                  ' . $this->config['sitename'] . '
            '.

            //put an if statement on weather the sitename equals "314chan" here"

            '

Rules

FAQ

News

Matrix Chat

Boards List

              '.

              //end if statement

              '

Our Boards

Create Board   View All Boards

              ';
              $cats = $this->conn->query("SELECT * FROM links WHERE parent=-1 ORDER BY short ASC;");

        while ($row = $cats->fetch_assoc())

              {

            $file .= '
';

            $file .= '
'.$row['title'].'
';

            $file .= '
';

            $children = $this->conn->query("SELECT * FROM links WHERE parent=".$row['id']." ORDER BY short ASC");

            while ($child = $children->fetch_assoc())

            {

                if (!empty($child['url_index'])) {

                    $file .= '

                      /'.$child['url_index'].'/ - '.$child['title'].'

';

                } else {

                    $file .= '

                      '.$child['title'].'

';

                }

            }

            $file .= '
';

        }
            $file .='

Recent Posts

';
                 // $posts = $this->conn->query("SELECT * FROM posts ORDER BY date AND `board`<>'b' DESC LIMIT 4");
                 $posts = $this->conn->query("SELECT * FROM posts WHERE `posts`.`deleted` = 0 AND `board`<>'test' ORDER BY date DESC LIMIT 4");
        while ($row = $posts->fetch_assoc()){
            $file .='

';
            if (!empty($row['filename'])) {
                if ($row['filename'] == "deleted") {
                    $file.='';
                } elseif (substr($row['filename'], 0, 8) == "spoiler:") {
                    $file.='';
                } elseif (substr($row['filename'], 0, 6) == "embed:") {
                    $file.='
Embedded Content
';
                }else{
                    // $file.='';
                    //var_dump($row['filename']);
                    //if(preg_match("/^.*\.(webm|mp4)$/i", $row['filename'])) {
                    if ((strpos($row['mimetype'],"video/") === 0)) {
                      $vid_info = pathinfo($row['filename']);
                      $vid_name = $vid_info["filename"];
                      $vid_merge = $vid_name.".gif";

                      $file.='';
                        //$file.='<video src="/'.$row['board'].'/src/'.$row['filename'].'" width="100%"/>';
                    }else if(preg_match("/^.*\.(mp3)$/i", $row['filename'])) {
                        $file.='<audio controls><source src="/'.$row['board'].'/src/'.$row['filename'].'"></audio>';
                    }else{
                        $file.='';
                    }
                }
            }else{
                $file.='';
            }
            if (!empty($row['subject'])) {
                $file.=''.$row['subject'].'';
            }else{
                $file.='';
            }
            $file.='

'.$row["comment"].'

                    ';
            if($row['resto']!= 0) {
                $file .='View';
            }else{
                $file .='View';
            }
            if($row['resto']!= 0) {
                $file .='Reply';
            }else{
                $file .='Reply';
            }

            $file .='

';
        }
             $file.='

Statistics

';

        $result = $this->conn->query("SELECT * FROM posts");

        $num_rows = $result->num_rows;

        $result = $this->conn->query("SELECT DISTINCT ip FROM posts");

        $num_users = $result->num_rows;

        $result = $this->conn->query("SELECT sum(orig_filesize) FROM posts");

        $num_bytes = $result->fetch_array()[0];

        $result = $this->conn->query("SELECT * FROM `bans`");

        $num_bans = $result->num_rows;

        {

        $file .= '
Total posts: '.$num_rows.'

Unique posters: '.$num_users.'

Active content: '.$this->mitsuba->common->human_filesize($num_bytes).'

Active Bans: '.$num_bans.'

			';

        }

                $file .= '

The Constitutional Monarchy.

314chan would like to be as open as possible. We employ a system in which the boards are controlled by the users, and for the users. I will explain more in depth here

Our Friends

Why 314chan?

Permanent U.S. Ownership. We will never sell out to any company.

Head staff that cares. Our staff have never ignored a user in its 7 year run.

No Ads. Parley will never host ads on the server (unless need for money is dire.)

Captcha as a last resort. We will never enable Captchas (unless there are ongoing spam attacks.)

              Site © ' . date("Y") . ' '.$this->config['sitename'].'

All posts are the responsibility of the original poster.

					';

        $handle = fopen("./" . $this->config['frontpage_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

    function generateNews()
    {

        $file = '<!doctype html>';

        $file.= '

            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"/>

            <meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1.0"/>

						<meta charset="UTF-8">

						<title>' . $this->config['sitename'] . ' - News</title>

            <link href="css/MIcons.css" rel="stylesheet">

            <link href="css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/>

            <link href="css/style.css" type="text/css" rel="stylesheet" media="screen,projection"/>

        ';

        $file.= '

' . $this->config['sitename'] . '

            '.

            //put an if statement on weather the sitename equals "314chan" here"

            '

Rules

FAQ

News

Matrix Chat

              '.

              //end if statement

              '

        ';

        $file.= '

        ';

        $result = $this->conn->query("SELECT * FROM news ORDER BY date DESC;");

        while ($row = $result->fetch_assoc()) {

            $file.= '
';

            $file.= '
' . $row['title'] . ' by ' . $row['who'] . ' - ' . date("d/m/Y h:i", $row['date']) . '

';

            $file.= $row['text'];

            $file.= '
';

        }

        $file.= '

			';

        $handle = fopen("./" . $this->config['news_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

}

?>


code:
<?php

namespace Mitsuba;

class Frontpage
{

    private $conn;

    private $config;

    private $mitsuba;

    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

        $this->config = $this->mitsuba->config;

    }

    function generateFrontpage($action = "none")
    {

        if ($action != "none") {

            return;

        }

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

				"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';

        $file.= '

			<title>' . $this->config['sitename'] . '</title>

			<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

			<frameset cols="200px,*" frameborder="1" border="1">

			<frame src="' . $this->config['frontpage_menu_url'] . '" id="nav">

			<frame src="' . $this->config['news_url'] . '" name="main" id="main">

			<noframes>

' . $this->config['sitename'] . '

This page uses frames!

			</noframes>

			</frameset>

			';

        $handle = fopen("./" . $this->config['frontpage_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

        $menu = '<title>Mitsuba Navigation</title>';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc()) {

            if ($first_default == 1) {

                $menu.= '<link rel="stylesheet" id="switch" href="' . $this->mitsuba->getPath($row['path'], "index", $row['relative']) . '">';

                $first_default = 0;

            }

            $menu.= '<link rel="alternate stylesheet" style="text/css" href="' . $this->mitsuba->getPath($row['path'], "index", $row['relative']) . '" title="' . $row['name'] . '">';

        }

        $menu.= "

	";

        $menu.= '';

        $menu.= $this->mitsuba->caching->getMenu("index", "main");

        $handle = fopen("./" . $this->config['frontpage_menu_url'], "w");

        fwrite($handle, $menu);

        fclose($handle);

    }

    function generateNews()
    {

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

			"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';

        $file.= '

			<title>' . $this->config['sitename'] . '</title>

		';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc()) {

            if ($first_default == 1) {

                $file.= '<link rel="stylesheet" id="switch" href="' . $this->mitsuba->getPath($row['path'], "index", $row['relative']) . '">';

                $first_default = 0;

            }

            $file.= '<link rel="alternate stylesheet" style="text/css" href="' . $this->mitsuba->getPath($row['path'], "index", $row['relative']) . '" title="' . $row['name'] . '">';

        }

        $file.= "

			";

        $file.= '

';

        $file.= '

News

';

        $result = $this->conn->query("SELECT * FROM news ORDER BY date DESC;");

        while ($row = $result->fetch_assoc()) {

            $file.= '
';

            $file.= '
' . $row['title'] . ' by ' . $row['who'] . ' - ' . date("d/m/Y @ H:i", $row['date']) . '
';

            $file.= $row['text'];

            $file.= '
';

        }

        $file.= '

			';

        $handle = fopen("./" . $this->config['news_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

}

?>


code:
<?php

namespace Mitsuba;

class Frontpage
{

    private $conn;

    private $config;

    private $mitsuba;

    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

        $this->config = $this->mitsuba->config;

    }

    function generateFrontpage($action = "none")
    {

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"

	"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">';

        $file .= '

	<meta content="text/html; charset=utf-8" http-equiv="Content-Type" />

	<title>'.$this->config['sitename'].'</title>';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc())

        {

            if ($first_default == 1) {

                $file .= '<link rel="stylesheet" id="switch" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'">';

                $first_default = 0;

            }

            $file .= '<link rel="alternate stylesheet" style="text/css" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'" title="'.$row['name'].'">';

        }

        $file .= "

";

        $file .= '

';

        $file .= '

Boards

';

        $cats = $this->conn->query("SELECT * FROM links WHERE parent=-1 ORDER BY short ASC;");

        while ($row = $cats->fetch_assoc())

        {

            $file .= '
';

            $file .= '
'.$row['title'].'
';

            $file .= '
';

            $children = $this->conn->query("SELECT * FROM links WHERE parent=".$row['id']." ORDER BY short ASC");

            while ($child = $children->fetch_assoc())

            {

                if (!empty($child['url_index'])) {

                    $file .= '

						'.$child['title'].'

';

                } else {

                    $file .= '

						'.$child['title'].'

';

                }

            }

            $file .= '
';

        }

        $file .= '

';

        $file .= '

Recent Images

';

        $recent_images = $this->conn->query("SELECT posts.*, boards.hidden, boards.unlisted FROM posts LEFT JOIN boards ON posts.board=boards.short WHERE boards.hidden=0 AND boards.unlisted=0 AND filename<>'' AND filename<>'deleted' AND filename NOT LIKE 'embed%' AND filename NOT LIKE 'spoiler%' AND deleted=0 ORDER BY date DESC LIMIT 0, 3;");

        while ($row = $recent_images->fetch_assoc())

        {

            $postfile = $row['id'].".html#p".$row['id'];

            if (!empty($row['resto'])) { $postfile = $row['resto'].".html#p".$row['id'];
            }

            $file .= '

';

        }

        $file .= '

';

        $file .= '

Latest Posts

';

        $recent_posts = $this->conn->query("SELECT posts.*, boards.hidden, boards.unlisted, boards.name AS bname FROM posts LEFT JOIN boards ON posts.board=boards.short WHERE boards.hidden=0 AND boards.unlisted=0 AND deleted=0 ORDER BY date DESC LIMIT 0, 15;");

        while ($row = $recent_posts->fetch_assoc())

        {

            $postfile = $row['id'].".html#p".$row['id'];

            if (!empty($row['resto'])) { $postfile = $row['resto'].".html#p".$row['id'];
            }

            $file .= '

'.$row['bname'].': '.htmlspecialchars(substr($row['comment'], 0, 30)).'...

';

        }

        $file .= '

';

        $file .= '

Stats

';

        $result = $this->conn->query("SELECT * FROM posts");

        $num_rows = $result->num_rows;

        $result = $this->conn->query("SELECT DISTINCT ip FROM posts");

        $num_users = $result->num_rows;

        $result = $this->conn->query("SELECT sum(orig_filesize) FROM posts");

        $num_bytes = $result->fetch_array()[0];

        {

        $file .= '
Total posts: '.$num_rows.'

Unique posters: '.$num_users.'

Active content: '.$this->mitsuba->common->human_filesize($num_bytes).'

			';

        }

        $file .= '

';

        $file .= '

- Haruko + mitsuba -

';

        $handle = fopen("./".$this->config['frontpage_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

    function generateNews()
    {

        $file = '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"

			"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">';

        $file .= '

			<title>'.$this->config['sitename'].'</title>';

        $first_default = 1;

        $styles = $this->conn->query("SELECT * FROM styles ORDER BY `default` DESC");

        while ($row = $styles->fetch_assoc())

        {

            if ($first_default == 1) {

                $file .= '<link rel="stylesheet" id="switch" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'">';

                $first_default = 0;

            }

            $file .= '<link rel="alternate stylesheet" style="text/css" href="'.$this->mitsuba->getPath($row['path'], "index", $row['relative']).'" title="'.$row['name'].'">';

        }

        $file .= "

			";

        $file .= '

';

        $file .= '

News

';

        $result = $this->conn->query("SELECT * FROM news ORDER BY date DESC;");

        while ($row = $result->fetch_assoc())

        {

            $file .= '
';

            $file .= '
'.$row['title'].' by '.$row['who'].' - '.date("d/m/Y @ H:i", $row['date']).'
';

            $file .= $row['text'];

            $file .= '
';

        }

        $file .= '

			';

        $handle = fopen("./".$this->config['news_url'], "w");

        fwrite($handle, $file);

        fclose($handle);

    }

}

?>


code:
<?php

function parseGetServiceName()
{

    return "Youtube";

}

function parseGetTitle($url)
{

    parse_str(parse_url($url, PHP_URL_QUERY), $var);

    $xmlData = simplexml_load_string(file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$var['v']}?fields=title"));

    $title = (string)$xmlData->title;

    return $title;

}

function parseGetSize($url)
{

    parse_str(parse_url($url, PHP_URL_QUERY), $var);

    $data = @file_get_contents("http://gdata.youtube.com/feeds/api/videos/{$var['v']}?v=2&alt=jsonc");

    if (($data) && ($obj = json_decode($data))) {

        return gmdate("H:i:s", $obj->data->duration);

    } else {

        return "00:00:00";

    }

}

?>


code:
<?php

namespace Mitsuba;

/**
 * Linkshare
 * Insert description here
 *
 * @category
 * @package
 * @author
 * @copyright
 * @license
 * @version
 * @link
 * @see
 * @since
 */
class Linkshare
{

    private $conn;

    private $mitsuba;

    /**
     * __construct
     * Insert description here
     *
     * @param $connection
     * @param $mitsuba
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

    }

    /**
     * prepareUrl
     * Insert description here
     *
     * @param $url
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function prepareUrl($url)
    {

        $retn = $url;

        if (strncmp($url, "www", 3) == 0) {

            $retn = "http://" . $url;

        }

        if (strncmp($url, "https://", 8) == 0) {

            $retn = str_ireplace("https://", "http://", $url);

        }

        if (!filter_var($retn, FILTER_VALIDATE_URL)) {

            $retn = false;

        }

        return $retn;

    }

    /**
     * checkUrl
     * Insert description here
     *
     * @param $url
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function checkUrl($url)
    {

        $parserFile = false;

        if (strncmp($url, 'http', 4) != 0) {

            return false;

        }

        $result = $this->conn->query("SELECT * FROM `link`");

        while ($row = $result->fetch_row()) {

            if (preg_match($row[1], $url)) {

                $parserFile = $row[2];

                break;

            }

        }

        return $parserFile;

    }

    /**
     * getStatus
     * Insert description here
     *
     * @param $url
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getStatus($url)
    {

        if (strncmp($url, 'http', 4) != 0) {

            return false;

        }

        $test = get_headers($url);

        $test = strstr($test[0], "200"); //HTTP OK

        return ($test == true);

    }

    /**
     * openLinkParser
     * Insert description here
     *
     * @param $parser
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function openLinkParser($parser)
    {

        if (file_exists("inc/links/" . $parser)) {

            //parser isn't working at this time

            include "links/" . $parser;

            //echo('dbg: exist');

            return true;

        } else {

            return false;

        }

    }

    /**
     * getTitle
     * Insert description here
     *
     * @param $url
     * @param $parserOpened
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getTitle($url, $parserOpened)
    {

        $title = "";

        if ($parserOpened) {

            $title = parseGetTitle($url);

        }

        if (!$title) {

            $page = file_get_contents($url);

            if (strlen($page) > 0) {

                preg_match("/\<title\>(.*)\<\/title\>/", $page, $pt);

                $title = $pt[1];

            } else {

                $title = "None";

            }

        }

        return $title;

    }

    /**
     * getSize
     * Insert description here
     *
     * @param $url
     * @param $parserOpened
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getSize($url, $parserOpened)
    {

        if ($parserOpened) {

            return parseGetSize($url);

        } else {

            return false;

        }

    }

    /**
     * getServiceName
     * Insert description here
     *
     * @param $url
     * @param $parserOpened
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getServiceName($url, $parserOpened)
    {

        if ($parserOpened) {

            return parseGetServiceName();

        } else {

            $parse = parse_url($url);

            return $parse['host'];

        }

    }

}

?>


code:
<?php

/**
 * Admin
 * Insert description here
 *
 * @category
 * @package
 * @author
 * @copyright
 * @license
 * @version
 * @link
 * @see
 * @since
 */
class Admin
{

    private $conn;

    private $mitsuba;

    private $user_permissions;

    public $bans;

    public $boards;

    public $groups;

    public $links;

    public $ui;

    public $users;

    /**
     * __construct
     * Insert description here
     *
     * @param $connection
     * @param $mitsuba
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function __construct($connection, &$mitsuba)
    {

        $this->conn = $connection;

        $this->mitsuba = $mitsuba;

        include "admin.bans.php";

        $this->bans = new \Mitsuba\Admin\Bans($this->conn, $this->mitsuba);

        include "admin.boards.php";

        $this->boards = new \Mitsuba\Admin\Boards($this->conn, $this->mitsuba);

        include "admin.groups.php";

        $this->groups = new \Mitsuba\Admin\Groups($this->conn, $this->mitsuba);

        include "admin.links.php";

        $this->links = new \Mitsuba\Admin\Links($this->conn, $this->mitsuba);

        include "admin.ui.php";

        $this->ui = new \Mitsuba\Admin\UI($this->conn, $this->mitsuba);

        include "admin.users.php";

        $this->users = new \Mitsuba\Admin\Users($this->conn, $this->mitsuba);

    }

    /**
     * reqPermission
     * Insert description here
     *
     * @param $permission
     * @param $uid
     * @param 1
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function reqPermission($permission, $uid = - 1)
    {

        $groupid = 0;

        if ($uid != - 1) {

            if (!is_numeric($uid)) {

                die("Insufficient permissions");

            }

            $user = $this->conn->query("SELECT * FROM users WHERE id=" . $uid);

            if ($user->num_rows != 1) {

                die("Insufficient permissions");

            }

            $userrow = $user->fetch_assoc();

            $groupid = $userrow['group'];

        } else {

            $groupid = $_SESSION['group'];

        }

        $e = array("permission" => $permission);

        $this->mitsuba->emitEvent("permission", $e);

        if (!$this->checkPermission($permission, $groupid)) {

            die("Insufficient permissions");

        }

    }

    /**
     * listPermissions
     * Insert description here
     *
     * @param $groupid
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function listPermissions($groupid = false)
    {

        if ($groupid == false) {

            if (empty($_SESSION['group'])) {

                return false;

            }

            $groupid = $_SESSION['group'];

        }

        $permissions = $this->conn->query("SELECT * FROM group_permissions INNER JOIN permissions ON group_permissions.pid=permissions.id WHERE gid=" . $groupid);

        $list = array();

        while ($row = $permissions->fetch_assoc()) {

            $list[$row['name']] = 1;

        }

        return $list;

    }

    /**
     * checkPermission
     * Insert description here
     *
     * @param $permission
     * @param $groupid
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function checkPermission($permission, $groupid = false)
    {

        if ($groupid == false) {

            if (!empty($this->user_permissions)) {

                $groupid = $this->user_permissions;

            } else {

                $groupid = $this->listPermissions();

                if ($groupid == false) {

                    return false;

                }

            }

        }

        if (is_array($groupid)) {

            $p = explode(".", $permission);

            if (!empty($groupid[$permission])) {

                return true;

            } elseif (count($p) > 1) {

                array_pop($p);

                return $this->checkPermission(implode(".", $p), $groupid);

            } else {

                return false;

            }

        }

        $p = explode(".", $permission);

        $permission = $this->conn->query("SELECT * FROM group_permissions INNER JOIN permissions ON group_permissions.pid=permissions.id AND permissions.name='" . $this->conn->real_escape_string($permission) . "' WHERE gid=" . $groupid);

        if ($permission->num_rows == 1) {

            return true;

        } elseif (count($p) > 1) {

            array_pop($p);

            return $this->checkPermission(implode(".", $p), $groupid);

        } else {

            return false;

        }

    }

    /**
     * appendToPost
     * Insert description here
     *
     * @param $board
     * @param $postid
     * @param $text
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function appendToPost($board, $postid, $text)
    {

        if (is_numeric($postid)) {

            $config = $this->mitsuba->config;

            $post = $this->conn->query("SELECT * FROM posts WHERE id=" . $postid . " AND board='" . $board . "'");

            if ($post->num_rows == 1) {

                $pdata = $post->fetch_assoc();

                $text = $this->conn->real_escape_string($text);

                $new_text = $this->conn->real_escape_string($pdata['comment']) . "\n\n<+" . $text . "+>";

                $this->conn->query("UPDATE posts SET comment='" . $new_text . "', raw=2 WHERE id=" . $postid . " AND board='" . $board . "'");

                if ($pdata['resto'] == 0) {

                    $this->mitsuba->caching->generateView($board, $pdata['id']);

                    if ($config['caching_mode'] == 1) {

                        $this->mitsuba->caching->forceGetThread($board, $pdata['id']);

                    }

                } else {

                    $this->mitsuba->caching->generateView($board, $pdata['resto']);

                    if ($config['caching_mode'] == 1) {

                        $this->mitsuba->caching->forceGetThread($board, $pdata['resto']);

                    }

                }

                $this->mitsuba->caching->generateView($board);

            }

        }

    }

    /**
     * canBoard
     * Insert description here
     *
     * @param $board
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function canBoard($board)
    {

        if (empty($_SESSION['logged'])) {
            session_destroy();
            die("NOT LOGGED IN");

        }

        if ($_SESSION['boards'] != "%" && $this->conn->query("SELECT * FROM `users` WHERE `users`.`boards` = '%' AND `users`.`username` = '".$_SESSION['username']."'")) {

            $boards = explode(",", $_SESSION['boards']);

            if (in_array($board, $boards)) {

                return 1;

            } else {

                return;

            }

        } else {

            return 1;

        }

    }

    /**
     * checkForUpdates
     * Insert description here
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function checkForUpdates()
    {

        if ((defined(MITSUBA_VERSION)) && (MITSUBA_VERSION != "disabled")) {

            //magic here

        }

    }

    /**
     * logAction
     * Insert description here
     *
     * @param $text
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function logAction($text)
    {

        $this->conn->query("DELETE FROM log WHERE date<" . (time() - (60 * 60 * 24 * 7)));

        $text = $this->conn->real_escape_string($text);

        $this->conn->query("INSERT INTO log (date, event, mod_id) VALUES (" . time() . ", '" . $text . "', " . $_SESSION['id'] . ")");

    }

    /**
     * updateConfig
     * Insert description here
     *
     * @param $config
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function updateConfig($config)
    {

        foreach ($config as $key => $value) {

            $this->conn->query("UPDATE config SET value='" . $this->conn->real_escape_string($value) . "' WHERE name='" . $key . "';");

        }

    }

}

/**
 * Mitsuba
 * Insert description here
 *
 * @category
 * @package
 * @author
 * @copyright
 * @license
 * @version
 * @link
 * @see
 * @since
 */
class Mitsuba
{

    private $plugins_array = array();

    private $conn;

    public $board;

    public $config;

    public $caching;

    public $common;

    public $module_config;

    public $posting;

    public $admin;

    /**
     * __construct
     * Insert description here
     *
     * @param $connection
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function __construct($connection)
    {

        $this->conn = $connection;

        $this->config = $this->getConfig();

        $this->module_config = $this->getModuleConfig();

        include "board.php";

        $this->board = new \Mitsuba\Board($this->conn, $this);

        include "caching.php";

        $this->caching = new \Mitsuba\Caching($this->conn, $this);

        include "common.php";

        $this->common = new \Mitsuba\Common($this->conn, $this);

        include "posting.php";

        $this->posting = new \Mitsuba\Posting($this->conn, $this);

        $this->admin = new Admin($this->conn, $this);

        $modules = $this->conn->query("SELECT * FROM module_classes");

        while ($module = $modules->fetch_assoc()) {

            include "./" . $module['namespace'] . "/" . $module['file'];

            $this->$module['name'] = new $module['class']($this->conn, $this->mitsuba);

        }

    }

    /**
     * getConfig
     * Insert description here
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getConfig()
    {

        $result = $this->conn->query("SELECT * FROM config;");

        $array = array();

        while ($row = $result->fetch_assoc()) {

            $array[$row['name']] = $row['value'];

        }

        return $array;

    }

    /**
     * getModuleConfig
     * Insert description here
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getModuleConfig()
    {

        $result = $this->conn->query("SELECT * FROM module_config;");

        $array = array();

        while ($row = $result->fetch_assoc()) {

            $array[$row['namespace'] . "." . $row['name']] = $row['value'];

        }

        return $array;

    }

    /**
     * getConfigValue
     * Insert description here
     *
     * @param $name
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getConfigValue($name)
    {

        $name = $this->conn->real_escape_string($name);

        $result = $this->conn->query("SELECT * FROM config WHERE name='" . $name . "';");

        if ($result->num_rows == 1) {

            return $result->fetch_assoc();

        } else {

            return 0;

        }

    }

    /**
     * updateConfigValue
     * Insert description here
     *
     * @param $name
     * @param $value
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function updateConfigValue($name, $value)
    {

        $name = $this->conn->real_escape_string($name);

        $value = $this->conn->real_escape_string($value);

        $this->conn->query("UPDATE config SET value='" . $value . "' WHERE name='" . $name . "';");

    }

    /**
     * updateModuleConfigValue
     * Insert description here
     *
     * @param $namespace
     * @param $name
     * @param $value
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function updateModuleConfigValue($namespace, $name, $value)
    {

        $namespace = $this->conn->real_escape_string($namespace);

        $name = $this->conn->real_escape_string($name);

        $value = $this->conn->real_escape_string($value);

        $this->conn->query("UPDATE module_config SET value='" . $value . "' WHERE name='" . $name . "' AND namespace='" . $namespace . "';");

    }

    /**
     * emitEvent
     * Insert description here
     *
     * @param $name
     * @param $data
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function emitEvent($name, &$data)
    {

        $modules = $this->conn->query("SELECT * FROM module_events WHERE event='" . $this->conn->real_escape_string($name) . "'");

        while ($module = $modules->fetch_assoc()) {

            include "./modules/" . $module['namespace'] . "/" . $module['file'];

            $eventclass = new $module['class']($this->conn, $this);

            $eventclass->$module['method']($name, $data);

        }

    }

    /**
     * getPath
     * Insert description here
     *
     * @param $path
     * @param $location
     * @param $relative
     *
     * @return
     *
     * @access
     * @static
     * @see
     * @since
     */
    function getPath($path, $location, $relative)
    {

        if ($relative == 0) {

            return $path;

        }

        switch ($location)

        {

        case "index":

            return $path;

          break;

        case "board":

            return ".".$path;

          break;

        case "thread":

            return "../.".$path;

          break;

        default:

            return $path;

          break;

        }

    }
}


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}
if($mitsuba->admin->canBoard("%")) {
    $mitsuba->admin->reqPermission("ads.update");

    if ((!empty($_GET['i'])) && (is_numeric($_GET['i']))) {

        $addata = $conn->query("SELECT * FROM ads WHERE id=".$_GET['i']);

        if ($addata->num_rows == 1) { $addata = $addata->fetch_assoc();
        } else {

              $mitsuba->admin->ui->startSection($lang['mod/ad_not_found']);

              $mitsuba->admin->ui->endSection();

        }

    ?>

    <?php $mitsuba->admin->ui->startSection($lang['mod/edit_ad']); ?>

<form action="?/ads" method="POST">

<?php $mitsuba->admin->ui->getToken($path); ?>

<input type="hidden" name="mode" value="edit">

<input type="hidden" name="id" value="<?php echo $addata['id']; ?>">

<?php echo $lang['mod/board']; ?>:

<select name="board">

<option value='%'>All boards</option>

<?php

$result = $conn->query("SELECT * FROM boards;");

while ($row = $result->fetch_assoc())

{

    $selected = "";

    if ($addata['board'] == $row['short']) {

        $selected = " selected='selected'";

    }

    echo "<option value='".$row['short']."'".$selected.">/".$row['short']."/ - ".$row['name']."</option>";

}

?>

</select>

<?php echo $lang['mod/position']; ?>:

<select name="position">

<option value='head'<?php if ($addata['position']=="head") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_head']; ?></option>

<option value='aboveform'<?php if ($addata['position']=="aboveform") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_aboveform']; ?></option>

<option value='underform'<?php if ($addata['position']=="underform") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_underform']; ?></option>

<option value='footer'<?php if ($addata['position']=="footer") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_footer']; ?></option>

<option value='bottom'<?php if ($addata['position']=="bottom") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_bottom']; ?></option>

<option value='rules'<?php if ($addata['position']=="rules") { echo " selected='selected'";
}?>><?php echo $lang['mod/pos_rules']; ?></option>

</select>

<?php echo $lang['mod/text']; ?>:

<textarea name="text" cols="70" rows="10"><?php echo $addata['text']; ?></textarea>

<?php echo $lang['mod/shown']; ?>: <input type="checkbox" name="shown" value="1" <?php if ($addata['show']==1) { echo " checked";
}?> />

<input type="submit" value="<?php echo $lang['mod/submit']; ?>" />

</form>

<?php $mitsuba->admin->ui->endSection(); ?>

<?php

    } else {

        $mitsuba->admin->ui->startSection($lang['mod/ad_not_found']);

        $mitsuba->admin->ui->endSection();

    }
}else{
    echo "Sorry. Global Admins only.";
}
?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}
if($mitsuba->admin->canBoard("%")) {
    $mitsuba->admin->reqPermission("ads.list");

    if (isset($_POST['mode'])) {

        switch($_POST['mode'])

        {

        case "add":

            $mitsuba->admin->reqPermission("ads.add");

            $mitsuba->admin->ui->checkToken($_POST['token']);

            $shown = 0;

            if ((!empty($_POST['shown'])) && (is_numeric($_POST['shown'])) && ($_POST['shown']==1)) { $shown = 1;
            }

            $text = "";

            $board = "%";

            $position = "head";

            if (!empty($_POST['text'])) { $text = $conn->real_escape_string($_POST['text']);
            }

            if (!empty($_POST['board'])) { $board = $conn->real_escape_string($_POST['board']);
            }

            if (!empty($_POST['position'])) { $position = $conn->real_escape_string($_POST['position']);
            }

            $conn->query("INSERT INTO ads (`text`, `board`, `position`, `show`) VALUES ('".$text."', '".$board."', '".$position."', ".$shown.")");

            echo $conn->error;

            break;

        case "edit":

            $mitsuba->admin->reqPermission("ads.update");

            $mitsuba->admin->ui->checkToken($_POST['token']);

            if (is_numeric($_POST['id'])) {

                $shown = 0;

                if ((!empty($_POST['shown'])) && (is_numeric($_POST['shown'])) && ($_POST['shown']==1)) { $shown = 1;
                }

                $text = "";

                $board = "%";

                $position = "head";

                if (!empty($_POST['text'])) { $text = $conn->real_escape_string($_POST['text']);
                }

                if (!empty($_POST['board'])) { $board = $conn->real_escape_string($_POST['board']);
                }

                if (!empty($_POST['position'])) { $position = $conn->real_escape_string($_POST['position']);
                }

                $conn->query("UPDATE ads SET board='".$board."', `text`='".$text."', position='".$position."', `show`=".$shown." WHERE id=".$_POST['id']);

            }

            break;

        }

    }

    if (isset($_GET['mode'])) {

        switch($_GET['mode'])

        {

        case "delete":

            $mitsuba->admin->reqPermission("ads.delete");

            if (is_numeric($_GET['i'])) {

                $conn->query("DELETE FROM ads WHERE id=".$_GET['i']);

            }

            break;

        }

    }

?>

<?php $mitsuba->admin->ui->startSection($lang['mod/manage_ads']); ?>

<?php echo $lang['mod/board']; ?>

<?php echo $lang['mod/position']; ?>

<?php echo $lang['mod/text']; ?>

<?php echo $lang['mod/shown']; ?>

<?php echo $lang['mod/actions']; ?>

<?php

$result = $conn->query("SELECT * FROM ads");

while ($row = $result->fetch_assoc())

{

    echo "
";

    if ($row['board']=="%") {

        echo "All boards	";

    } else {

        echo "/".$row['board']."/	";

    }

    echo "";

    switch ($row['position'])

    {

    case "head":

        echo $lang['mod/pos_head'];

        break;

    case "aboveform":

        echo $lang['mod/pos_aboveform'];

        break;

    case "underform":

        echo $lang['mod/pos_underform'];

        break;

    case "footer":

        echo $lang['mod/pos_footer'];

        break;

    case "bottom":

        echo $lang['mod/pos_bottom'];

        break;

    case "rules":

        echo $lang['mod/pos_rules'];

        break;

    default:

        echo "WRONG POSITION: ".$row['position']."";

        break;

    }

    echo "	";

    echo "".htmlspecialchars($row['text'])."	";

    if ($row['show']==1) {

        echo "YES	";

    } else {

        echo "NO	";

    }

    echo "Edit / Delete	";

    echo "
";

}

?>

<?php $mitsuba->admin->ui->endSection(); ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/add_ad']); ?>

<form action="?/ads" method="POST">

<?php $mitsuba->admin->ui->getToken($path); ?>

<input type="hidden" name="mode" value="add">

<?php echo $lang['mod/board']; ?>:

<select name="board">

<option value='%'>All boards</option>

<?php

$result = $conn->query("SELECT * FROM boards;");

while ($row = $result->fetch_assoc())

{

    echo "<option value='".$row['short']."'>/".$row['short']."/ - ".$row['name']."</option>";

}

?>

</select>

<?php echo $lang['mod/position']; ?>:

<select name="position">

<option value='head'><?php echo $lang['mod/pos_head']; ?></option>

<option value='aboveform'><?php echo $lang['mod/pos_aboveform']; ?></option>

<option value='underform'><?php echo $lang['mod/pos_underform']; ?></option>

<option value='footer'><?php echo $lang['mod/pos_footer']; ?></option>

<option value='bottom'><?php echo $lang['mod/pos_bottom']; ?></option>

</select>

<?php echo $lang['mod/text']; ?>:

<textarea name="text" cols="70" rows="10"></textarea>

<?php echo $lang['mod/shown']; ?>: <input type="checkbox" name="shown" value="1" checked />

<input type="submit" value="<?php echo $lang['mod/submit']; ?>" />

</form>

<?php $mitsuba->admin->ui->endSection();
}else{
    echo "Sorry, Global Admins only.";
}
?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}

$mitsuba->admin->reqPermission("announcements.add");

if (empty($_POST['text'])) {

    ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/new_announcement']); ?>

<form action="?/announcements/add" method="POST">

<?php $mitsuba->admin->ui->getToken($path); ?>

<?php echo $lang['mod/by']; ?>: <input type="text" name="who" value="<?php echo $_SESSION['username']; ?>" />

<?php echo $lang['mod/title']; ?>: <input type="text" name="title"/>

<?php echo $lang['mod/text']; ?>:

<textarea name="text" cols="70" rows="10"></textarea>

<input type="submit" value="<?php echo $lang['mod/submit']; ?>" />

</form>

<?php $mitsuba->admin->ui->endSection(); ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/your_entries']); ?>

<?php echo $lang['mod/title']; ?>

<?php echo $lang['mod/date']; ?>

<?php echo $lang['mod/edit']; ?>

<?php echo $lang['mod/delete']; ?>

<?php

$result = $conn->query("SELECT * FROM announcements WHERE mod_id=".$_SESSION['id']." ORDER BY date DESC;");

while ($row = $result->fetch_assoc())

{

    echo "
";

    echo "".$row['title']."	";

    echo "".date("d/m/Y @ H:i", $row['date'])."	";

    echo "".$lang['mod/edit']."	";

    echo "".$lang['mod/delete']."	";

    echo "
";

}

?>

<?php $mitsuba->admin->ui->endSection(); ?>

<?php

} else {

    $mitsuba->admin->ui->checkToken($_POST['token']);

    $text = processEntry($conn, $_POST['text']);

    $who = $_SESSION['username'];

    if (!empty($_POST['who'])) { $who = $_POST['who'];
    }

    $conn->query("INSERT INTO announcements (`date`, `who`, `title`, `text`, `mod_id`) VALUES (".time().", '".$who."', '".$conn->real_escape_string(htmlspecialchars($_POST['title']))."', '".$text."', ".$_SESSION['id'].");");

    ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/post_added']); ?>

<?php echo $lang['mod/back']; ?><?php $mitsuba->admin->ui->endSection(); ?>

    <?php

}

?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}

if (isset($_GET['b'])) {

    deleteEntry($conn, 0, $_GET['b']);

    ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/post_deleted_short']); ?>

<?php echo $lang['mod/back']; ?><?php $mitsuba->admin->ui->endSection(); ?>

    <?php

}

?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}

if ((isset($_GET['b'])) && (is_numeric($_GET['b']))) {

    $result = $conn->query("SELECT * FROM announcements WHERE id=".$_GET['b']);

    if ($result->num_rows != 0) {

        if (empty($_POST['text'])) {

            $data = $result->fetch_assoc();

        ?>

        <?php $mitsuba->admin->ui->startSection($lang['mod/edit_announcement']); ?>

       <form action="?/announcements/edit&b=<?php echo $_GET['b']; ?>" method="POST">

        <?php $mitsuba->admin->ui->getToken($path); ?>

        <?php echo $lang['mod/by']; ?>: <input type="text" name="who" value="<?php echo $data['who']; ?>" />

        <?php echo $lang['mod/title']; ?>: <input type="text" name="title" value="<?php echo $data['title']; ?>"/>

        <?php echo $lang['mod/text']; ?>:

       <textarea name="text" cols="70" rows="10"><?php echo $data['text']; ?></textarea>

       <input type="submit" value="<?php echo $lang['mod/submit']; ?>" />

       </form>

        <?php $mitsuba->admin->ui->endSection(); ?>

    <?php

        } else {

            $mitsuba->admin->ui->checkToken($_POST['token']);

            updateEntry($conn, 0, $_GET['b'], $_POST['who'], $_POST['title'], $_POST['text']);

            ?>

        <?php $mitsuba->admin->ui->startSection($lang['mod/post_updated']); ?>

       <?php echo $lang['mod/back']; ?><?php $mitsuba->admin->ui->endSection(); ?>

            <?php

        }

    } else {

    ?>

    <meta http-equiv="refresh" content="0;URL='?/announcements'" />

    <?php

    }

} else {

    ?>

    <meta http-equiv="refresh" content="0;URL='?/announcements'" />

    <?php

}

?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}

$mitsuba->admin->reqPermission("announcements.view");

?>

<?php $mitsuba->admin->ui->startSection($lang['mod/announcements']); ?>
<?php if($mitsuba->admin->canBoard("%")) {?>
[Add Announcement / Manage Announcements]
<?php }?>

<?php

$result = $conn->query("SELECT * FROM announcements ORDER BY date DESC;");

while ($row = $result->fetch_assoc())

{

    echo '
';

    echo '
'.$row['title'].' by '.$row['who'].' - '.date("d/m/Y @ H:i", $row['date']).'
';

    echo $row['text'];

    echo '
';

}

?>

<?php $mitsuba->admin->ui->endSection(); ?>


code:
<?php

if (!defined("IN_MOD")) {

    die("Nah, I won't serve that file to you.");

}

$mitsuba->admin->reqPermission("announcements.manage");

    ?>

<?php $mitsuba->admin->ui->startSection($lang['mod/all_announcements']); ?>

<?php echo $lang['mod/title']; ?>

<?php echo $lang['mod/date']; ?>

<?php echo $lang['mod/edit']; ?>

<?php echo $lang['mod/delete']; ?>

<?php

$result = $conn->query("SELECT * FROM announcements ORDER BY date DESC;");

while ($row = $result->fetch_assoc())

{

    echo "
";

    echo "".$row['title']."	";

    echo "".date("d/m/Y @ H:i", $row['date'])."	";

    echo "".$lang['mod/edit']."	";

    echo "".$lang['mod/delete']."	";

    echo "
";

}

?>

<?php $mitsuba->admin->ui->endSection(); ?>