iZerang

PDO Class, credits: gayflare(foxy)

Jul 13th, 2014
31,137
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.97 KB | None | 0 0
  1. <?php
  2. class Database extends PDO {
  3.     /* Show error messages */ public $debug = true;
  4.     /* Die on error */        public $doe   = true;
  5.     /* Sleep on error */      public $soe   = false;
  6.    
  7.    
  8.     /* Default credentials ( if you just wanna go $x = new Database; ) [ it can be overrided by providing the creds ] { The array keys Must be present } */
  9.         public $creds = array( /* If you want to remove these from here, set them as NULL */
  10.             "host" => 'database_host',
  11.             "user" => 'database_user',
  12.             "pass" => 'database_pass',
  13.             "name" => 'database_name',
  14.         );
  15.    
  16.     /* Initiate the connection */
  17.         /* EG: $pdo = new myPDO('127.0.0.1', 'root', null, 'xxxx'); */
  18.         public function __construct($host = false, $user = false, $pass = false, $name = false) {
  19.             foreach($this->creds as $i => $u)
  20.                 if(${$i} !== false) $this->creds[$i] = ${$i};
  21.             try { parent::__construct("mysql:host={$this->creds["host"]};dbname={$this->creds["name"]};charset=utf8", $this->creds["user"], $this->creds["pass"]); }
  22.             catch (PDOException $e) { $this->exception("Error connecting to database" . ( $this->debug ? ": {$e->getMessage()}" : ".") ); };
  23.             $this->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
  24.             $this->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
  25.         }
  26.        
  27.     /* Insert data derp */
  28.         /* EG: $link->insert("users", array("username" => "nigel_finch", "password" => $link->hash("cunningham1"))); */
  29.         public function insert($table = "users", $values = array()) {
  30.             $query = "insert into `{$table}`(`" . implode("`, `", array_keys($values)) . "`) values(:" . implode(", :", array_keys($values)) . ");";
  31.             $this->query($query, $values);
  32.         }
  33.    
  34.     /* Execute a query ( with the ability to use prepared statements */
  35.         /* EG: $link->query("select * from `users`;"); */
  36.         /* EG: $link->query("select * from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
  37.         public function query($query, $bind = array(), $force = false) {
  38.             if(empty($bind) && $force == false) {
  39.                 try { $result = parent::query($query); } catch (PDOException $e)
  40.                     { $this->exception("Error in SQL query: {$e->getMessage()}"); };
  41.             } else {
  42.                 try {
  43.                     $result = $this->prepare($query);
  44.                     foreach($bind as $key => &$val)
  45.                         $result->bindParam($key, $val);
  46.                     $result->execute();
  47.                 } catch (PDOException $e) {
  48.                     $this->exception("Error in SQL query: {$e->getMessage()}");
  49.                 };
  50.             };
  51.             return $result;
  52.         }
  53.    
  54.     /* As the name states, fetch an array of values */
  55.         /* EG: $link->fetch_array("select * from `users`;"); */
  56.         /* EG: $link->fetch_array("select * from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
  57.         public function fetch_array($query, $bind = array(), $return = array()) {
  58.             $query = $this->query($query, $bind);
  59.             if(method_exists($query, "fetch"))
  60.                 while($row = $query->fetch(PDO::FETCH_ASSOC))
  61.                     $return[] = $row;
  62.             return $return;
  63.         }
  64.    
  65.     /* Get a certain column from a query */
  66.         /* EG: $link->get("count(*)", "select count(*) from `users`;"); */
  67.         /* EG: $link->get("username", "select `username` from `users` where `x`=:furrypowa;", array(":furrypowa" => "y")); */
  68.         public function get($col, $query, $bind = array()) {
  69.             $return = $this->fetch_array($query, $bind);
  70.             return isset($return[0][$col]) ? $return[0][$col] : false;
  71.         }
  72.    
  73.     /* Cause some kids just can't work it out */
  74.         public function insert_id() { return $this->lastInsertId(); }
  75.    
  76.     /* For the people who like to go old school */
  77.         /* EG: $link->query("select * from `users` where `x`='{$link->sanatize('NIG\'":E<<')}';"); */
  78.         public function sanatize($data) {
  79.             if(is_array($data)) return array_map(array($this, "sanatize"), $data);
  80.             if(function_exists("mb_convert_encoding"))
  81.                 $data = @mb_convert_encoding($data, "UTF-8", "auto");
  82.             return substr($this->quote($data), 1, -1);
  83.         }
  84.        
  85.         public function xss($data) {
  86.             if(is_array($data)) return array_map(array($this, "sanatize"), $data);
  87.             if(function_exists("mb_convert_encoding"))
  88.                 $data = @mb_convert_encoding($data, "UTF-8", "auto");
  89.             return htmlentities($data);
  90.         }
  91.    
  92.     /* Encryption / Decryption with randomly generated salting */
  93.         public function encrypt($string) {
  94.             $key  = array( 0 => strlen($string), 1 => time() );
  95.             $salt = hash("SHA256", implode(chr(0), $key), true);
  96.             srand(str_shuffle(time() . rand(1000000, 9999999)));
  97.             $iv = mcrypt_create_iv(mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC), MCRYPT_RAND);
  98.             if(strlen($iv_base64 = rtrim(base64_encode($iv), '=')) != 22) return false;
  99.             $crypt = base64_encode(mcrypt_encrypt(MCRYPT_RIJNDAEL_128, $salt, $string . md5($string), MCRYPT_MODE_CBC, $iv) . ';=;=;=' . base64_encode(implode(chr(0), $key)));
  100.             return $iv_base64 . $crypt;
  101.         }
  102.    
  103.         public function decrypt($string) {
  104.             $str = array( 0 => substr($string, 0, 22) );
  105.             $sub = base64_decode(substr($string, 22));
  106.             $sub = explode(';=;=;=', $sub);
  107.             $string = array_merge($str, $sub);
  108.             $key = hash("SHA256", base64_decode(@$string[2]), true);
  109.             $iv = base64_decode($str[0] . '==');
  110.             $decrypted = rtrim(mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, @$string[1], MCRYPT_MODE_CBC, $iv), "\0\4");
  111.             return md5(substr($decrypted, 0, -32)) == substr($decrypted, -32) ? substr($decrypted, 0, -32) : false;
  112.         }
  113.    
  114.    
  115.     /* Custom string hashing + randomly generated salt && hash authentication */
  116.         public function hash($data = null, $salt = null, $hash = "whirlpool") {
  117.             if(!is_string($data) || is_null($data)) return false;
  118.             if(!@hash($hash, chr(0))) $hash = "whirlpool";
  119.             if(is_null($salt)) {
  120.                 $chars = array_merge(range('a', 'z'), range('A', 'Z'), range(0, 9));
  121.                 for($salt = ""; strlen($salt) < strlen($data); $salt .= $chars[array_rand($chars)]);
  122.             };
  123.             $salt = array($salt, hash("sha1", $salt));
  124.             $data = array(hash("sha1", $data), "");
  125.             foreach(str_split($salt[1], 1) as $i => $u)
  126.                 $data[1] .= $u . $data[0][$i];
  127.             $data[1] = hash($hash, $data[1]);
  128.             return substr_replace($data[1], $salt[0], strlen($salt[0]), 0);
  129.         }
  130.        
  131.         public function validate($input = null, $hash = null, $engine = "whirlpool") {
  132.             if(is_null($hash) ||is_null($input)) return false;
  133.             $location = strlen($input) >= strlen(hash($engine, chr(0))) ? strlen(hash($engine, chr(0))) : strlen($input);
  134.             $salt = substr($hash, $location, strlen($input));
  135.             return $this->hash($input, $salt, $engine) === $hash ? true : false;
  136.         }
  137.    
  138.     /* Random generated string <3 */
  139.         public function rand($length = 32, $low = true, $upp = true, $num = true, $indent = false) {
  140.             $chars = array_merge(
  141.                 $low ? range('a', 'z') : array(),
  142.                 $upp ? range('A', 'Z') : array(),
  143.                 $num ? range('0', '9') : array()
  144.             );
  145.             for($rand = ""; strlen($rand) < $length; $rand .= $chars[ array_rand($chars) ]);
  146.             if($indent != false) $rand = implode('-', str_split($rand, $indent));
  147.             return $rand;
  148.         }
  149.    
  150.     /* Show errors / exit accordingly */
  151.         public function exception($msg = null) {
  152.             if($this->debug) print $msg . PHP_EOL and ($this->soe ? sleep(3) : null);
  153.             if($this->doe == true) exit;
  154.         }
  155.    
  156. };
Advertisement
Add Comment
Please, Sign In to add comment