Never been to DZone Snippets before?

Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

« Newer Snippets
Older Snippets »
Showing 1-10 of 370 total  RSS 

Prepared Statement Emulation

Emulates prepared statements with ":VARIABLE" and "?" replacers

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class PreparedSQL{
   5  	private $params = array();
   6  	private $named = array();
   7  	private $sql = '';
   8  
   9  	const NAMED_SIGN = ':';
  10  	const INDEXED_SIGN = '?';
  11  	const ESCAPE_PREFIX = '\\';
  12  
  13  
  14  	public function __construct($sql){
  15  		for($this->sql = $sql, $q = null, $i = -1, $l = strlen($sql); ++$i < $l;){
  16  			if(($c = $sql[$i]) == self::ESCAPE_PREFIX && $q && ++$i)
  17  				continue;
  18  			if($c == "'" || $c == '"'){
  19  				$q = $c == $q ? null : ($q ? $q : $c);
  20  				continue;
  21  			}
  22  			if(!$q && ($c == self::NAMED_SIGN || $c == self::INDEXED_SIGN)){
  23  				$start = $i;
  24  				if($n = $c == self::NAMED_SIGN){
  25  					for($s = ''; ++$i < $l && preg_match('/\w/', $sql[$i]); $s .= $sql[$i]);
  26  					if(!strlen($s))
  27  						continue;//throw new Exception('Empty named parameter');
  28  					$this->named[$s][] = count($this->params);
  29  				}
  30  				$this->params[] = array($start, +!$n + $i - $start, null);
  31  			}
  32  		}
  33  		if($q)
  34  			throw new Exception('End quote expected');
  35  	}
  36  	public function getParams(){
  37  		$r = array();
  38  		foreach($this->params as $k=>$v)
  39  			$r[$k] = $v[2];
  40  		return $r;
  41  	}
  42  	public function get($n){
  43  		if(is_int($n) && isset($this->params[$n]))
  44  			return $this->params[$n][2];
  45  		elseif($r = isset($this->named[$n])){
  46  			$r = array();
  47  			foreach($this->named[$n] as $i)
  48  				$r[] = $this->get($i);
  49  			return $r;
  50  		}
  51  		else
  52  			return null;
  53  	}
  54  	public function set($n, $value){
  55  		if(is_int($n) && isset($this->params[$n]))
  56  			$this->params[$n][2] = $value;
  57  		else if($r = isset($this->named[$n = strtolower($n)]))
  58  			foreach($this->named[$n] as $i)
  59  				$this->set($i, $value);
  60  	}
  61  	public function replace($replacer){
  62  		for($s = '', $i = -1, $j = 0, $l = count($this->params); ++$i < $l;){
  63  			$s .= substr($this->sql, $j, $this->params[$i][0] - $j) . call_user_func($replacer, $i);
  64  			$j = $this->params[$i][0] + $this->params[$i][1];
  65  		}
  66  		return $s . substr($this->sql, $j);
  67  	}
  68  	private function defaultReplacer($i){
  69  		return $this->get($i);
  70  	}
  71  	public function __toString(){
  72  		return $this->replace(array($this, 'defaultReplacer'));
  73  	}
  74  }

Path class

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class Path implements IteratorAggregate{
   5  	const SEPARATOR = DIRECTORY_SEPARATOR;
   6  	const PATH_SEPARATOR = PATH_SEPARATOR;
   7  
   8  	protected $path;
   9  
  10  	public function __construct($isURL = false){
  11  		$this->path = $this->join(func_get_args());
  12  	}
  13  	public static function create(){
  14  		return new self(func_get_args());
  15  	}
  16  	public static function setCurrentFolder($n){
  17  		chdir($n);
  18  		return new Path($n);
  19  	}
  20  	public static function getCurrentFolder(){
  21  		return new Path(getcwd());
  22  	}
  23  	public function deleteFolder($recursive = false){
  24  		$empty = array($this->path);
  25  		if($recursive)
  26  			for($s = self::SEPARATOR, $stack = array($this->path); $d = array_pop($stack);){
  27  				if(is_dir($d) && !($h = dir($d)))
  28  					throw new Exception('Error while removing folder');
  29  				while(false !== $name = $h->read()){
  30  					if($name == '.' || $name == '..')
  31  						continue;
  32  					if(is_dir($path = $h->path . $s . $name))
  33  						array_push($stack, $path) && array_push($empty, $path);
  34  					elseif(!unlink($path))
  35  						throw new Exception('Error while removing folder');
  36  				}
  37  				$h->close();
  38  			}
  39  		for($i = count($empty); $i--;)
  40  			if(!rmdir($empty[$i]))
  41  				throw new Exception('Error while removing folder');
  42  		return new Path($this);
  43  	}
  44  	public function getIterator(){
  45  		return new RecursiveDirectoryIterator($this->path);
  46  	}
  47  	public function createFolder($recursive = false, $permissions){
  48  		for($d = self::SEPARATOR, $l = count($dir = preg_split('/[' . preg_quote('/\\' . $d, '/') . ']/', $dir)), $i = $l; $i-- && (!strlen($dir[$i]) || !is_dir(implode($d, array_slice($dir, 0, $i + 1)))););
  49  		while(++$i < $l)
  50  			if(!is_dir($path = implode($d, array_slice($dir, 0, $i + 1))) && (!mkdir($path, $permissions) || !chmod($path, $permissions)))
  51  				throw new Exception('Error while creating folder');
  52  		return new Path($this);
  53  	}
  54  	public function createTemporaryFile($permissions){
  55  		return tmpfile();
  56  	}
  57  	public function getTemporaryFilename($prefix = ''){
  58  		return new Path(tempnam($this->path, $prefix));
  59  	}
  60  	public function exists(){
  61  		return file_exists($this->path);
  62  	}
  63  	public function copy($destiny){
  64  		copy($this->path, $destiny);
  65  		return new Path($destiny);
  66  	}
  67  	public function delete($checkExists = true){
  68  		if(!$checkExists || $this->exists())
  69  			unlink($this->path);
  70  		return new Path($this);
  71  	}
  72  	public function rename($destiny){
  73  		rename($this->path, $destiny);
  74  		return new Path($destiny);
  75  	}
  76  	public function setModificationDate($date){
  77  		$date > ($a = $this->getAccessDate()) && $a = $date;
  78  		return touch($this->path, $date, $a);
  79  	}
  80  	public function getModificationDate(){
  81  		return filemtime($this->path);
  82  	}
  83  	public function getAccessDate(){
  84  		return fileatime($this->path);
  85  	}
  86  	public function setAccessDate($date){
  87  		$date < ($m = $this->getModificationDate()) && $m = $date;
  88  		return touch($this->path, $m, $date);
  89  	}
  90  	public function setPermissions($v){
  91  		return chmod($this->path, $v);
  92  	}
  93  	public function getPermissions(){
  94  		return fileperms($this->path);
  95  	}
  96  	public function isFolder(){
  97  		return is_dir($this->path);
  98  	}
  99  	public function isFile(){
 100  		return is_file($this->path);
 101  	}
 102  	public function isReadable(){
 103  		return is_readable($this->path);
 104  	}
 105  	public function isWritable(){
 106  		return is_writable($this->path);
 107  	}
 108  	public function getSize(){
 109  		return +sprintf("%u", filesize($this->path));
 110  	}
 111  	public function getRealPath(){
 112  		return new Path(realpath($this->path));
 113  	}
 114  	public function getFilename(){
 115  		return new Path(basename($this->path));
 116  	}
 117  	public function getFolder(){
 118  		return new Path(dirname($this->path));
 119  	}
 120  	public function getExtension(){
 121  		return pathinfo($this->path, PATHINFO_EXTENSION);
 122  	}
 123  	public function getPath(){
 124  		return $this->path;
 125  	}
 126  	public function setPath($path){
 127  		$this->path = $path;
 128  		return $this;
 129  	}
 130  	public static function join($a, $b = null){
 131  		$c = array(__CLASS__, __METHOD__);
 132  		if(count(func_get_args()) < 2)
 133  			return array_reduce($a, $c);
 134  		is_array($a) && $a = array_reduce($a, $c);
 135  		is_array($b) && $b = array_reduce($b, $c);
 136  		return ($a !== null ? trim($a, self::SEPARATOR) . self::SEPARATOR : '') . trim($b, self::SEPARATOR);
 137  	}
 138  	public function __toString(){
 139  		return $this->path;
 140  	}
 141  }

Object filter

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  
   5  class ObjectFilter{
   6  	protected $o;
   7  	protected $filter;
   8  
   9  	public function __construct($o, $filter){
  10  		$this->o = $o;
  11  		$this->filter = is_array($filter) ? $filter : array($filter);
  12  	}
  13  	public function __get($n){
  14  		$s = $this->o->$n;
  15  		foreach($this->filter as $f)
  16  			$s = call_user_func($f, $s);
  17  		return $s;
  18  	}
  19  	public function __set($n, $v){
  20  		return $this->o->$n = $v;
  21  	}
  22  	public function __call($n, $a){
  23  		return call_user_func_array(array($this->o, $n), $a);
  24  	}
  25  	public function getObject(){
  26  		return $this->o;
  27  	}
  28  }


Example

   1  
   2  $o = new ObjectFilter(new stdClass, 'strip_tags');
   3  $o->blabla = '<b>lala</b>';
   4  echo $o->blabla;

Detect user preferred language

Detects the preferred user language.

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class Language{
   5  	private static $language = null;
   6  
   7  	public static function get(){
   8  		new Language;
   9  		return self::$language;
  10  	}
  11  	public static function getBestMatch($langs = array()){
  12  		foreach($langs as $n => $v)
  13  			$langs[$n] = strtolower($v);
  14  		$r = array();
  15  		foreach(self::get() as $l => $v){
  16  			($s = strtok($l, '-')) != $l && $r[$s] = 0;
  17  			if(in_array($l, $langs))
  18  				return $l;
  19  		}
  20  		foreach($r as $l => $v)
  21  			if(in_array($l, $langs))
  22  				return $l;
  23  		return null;
  24  	}
  25  	private function __construct(){
  26  		if(self::$language !== null)
  27  			return;
  28  		if(($list = strtolower($_SERVER['HTTP_ACCEPT_LANGUAGE']))){
  29  			if(preg_match_all('/([a-z]{1,8}(?:-[a-z]{1,8})?)(?:;q=([0-9.]+))?/', $list, $list)){
  30  				self::$language = array_combine($list[1], $list[2]);
  31  				foreach(self::$language as $n => $v)
  32  					self::$language[$n] = +$v ? +$v : 1;
  33  				arsort(self::$language);
  34  			}
  35  		}
  36  		else
  37  			self::$language = array();
  38  	}
  39  }


example

   1  
   2  print_r(Language::get()); //languages ordered by preference
   3  
   4  print_r(Language::getBestMatch(array('pt-br', 'pt', 'en'))); //retrieves the best match given a list of available languages

Database utilities

Simple functions to build insert/delete/update statements.

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  
   5  class DBUtils{
   6  	public static function insert($table, $fieldset){
   7  		return 'INSERT INTO ' . $table . '(' . implode(',', array_keys($fieldset)) . ') VALUES (' . implode(',', array_values($fieldset)) . ')';
   8  	}
   9  	public static function delete($table, $where = ''){
  10  		return 'DELETE FROM ' . $table . ($where ? ' WHERE ' . $where : '');
  11  	}
  12  	public static function update($table, $fieldset, $where = ''){
  13  		$set = array();
  14  		foreach($fieldset as $field=>$value) $set[] = $field . '=' . $value;
  15  		return 'UPDATE ' . $table . ' SET ' . implode(',', $set) . ($where ? ' WHERE ' . $where : '');
  16  	}

Crypt/decrypt data //PHP

Simple cipher/decipher

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class Crypt{
   5  	protected $key;
   6  
   7  	public function __construct($key){
   8  		$this->key = $key;
   9  	}
  10  	public function decode($data){
  11  		for($k = $this->key, $i = -1, $l = strlen($data); ++$i < $l;){
  12  			$data[$i] = chr(ord($data[$i]) ^ ($k >> 8));
  13  		    $k = (int)((ord($data[$i]) + $k) * 52845 + 22719);
  14  		}
  15  		return $data;
  16  	}
  17  	public function encode($data){
  18  		for($k = $this->key, $r = $data, $i = -1, $l = strlen($r); ++$i < $l;){
  19  			$r[$i] = chr(ord($data[$i]) ^ ($k >> 8));
  20  		    $k = (int)((ord($data[$i]) + $k) * 52845 + 22719);
  21  		}
  22  		return $r;
  23  	}
  24  }

File/Folder joiner/unjoiner

Joins/unjoins files/folders into one unique file.

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  
   5  class Joiner{
   6  	var $header;
   7  
   8  	function Joiner(){
   9  		$this->header = strlen(pack('CVV', 0, 0, 0));
  10  	}
  11  
  12  	function join($dir, $out, $recursive = true){
  13  		if(!$out = fopen($out, 'wb'))
  14  			die('erro ao criar o arquivo');
  15  
  16  		for($s = DIRECTORY_SEPARATOR, $stack = array($dir); $dir = array_pop($stack);){
  17  			if(!($handle = @dir($dir)))
  18  				continue;
  19  			fwrite($out, pack('CVV', 1, strlen($dir), 0) . $dir);
  20  			while(false !== $item = $handle->read())
  21  				if($item != '.' && $item != '..'){
  22  					$path = $handle->path . $s . $item;
  23  					if(!is_dir($path) && ($f = fopen($path, 'rb'))){
  24  						fwrite($out, pack('CVV', 0, strlen($item), $size = filesize($path)) . $item);
  25  						$size && fwrite($out, fread($f, $size));
  26  						fclose($f);
  27  					}
  28  					elseif($recursive)
  29  						array_push($stack, $path);
  30  				}
  31  			$handle->close();
  32  		}
  33  		fclose($out);
  34  	}
  35  
  36  	function unjoin($dir, $in){
  37  		$_ = getcwd();
  38  		$s = DIRECTORY_SEPARATOR;
  39  		if(!$in = fopen($in, 'rb'))
  40  			die('erro ao abrir o arquivo');
  41  		$dir && chdir($dir) && $dir = getcwd() . $s;
  42  		$curdir = '';
  43  		while($h = fread($in, $this->header)){
  44  			$h = unpack('Cdir/Vname/Vsize', $h);
  45  			$name = fread($in, $h['name']);
  46  			if($h['dir']){
  47  				if(!is_dir($curdir = $dir . $name))
  48  					mkdir($curdir, 0777);
  49  				chdir($curdir);
  50  			}
  51  			else{
  52  				$f = fopen($file = $name, 'wb');
  53  				$h['size'] && fwrite($f, fread($in, $h['size']));
  54  				fclose($f);
  55  				chmod($file, 0777);
  56  			}
  57  		}
  58  		fclose($in);
  59  		chdir($_);
  60  	}
  61  }

PHP clear cache

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class Common{
   5  	public static function clearCache(){
   6  		header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
   7  		header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
   8  		header('Cache-Control: no-store, no-cache, must-revalidate');
   9  		header('Cache-Control: post-check=0, pre-check=0', false);
  10  		header('Pragma: no-cache');
  11  	}
  12  }

PHP internal sub request

This code provides a way to make a kind of sub request without opening http connections to the server, just provide a valid php filename as input (you can use get variables too, ex: "blabla.php?id=12&a=2").

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class Common{
   5  	public static function getPage($path){
   6  		static $stack;
   7  		$stack[] = '';
   8  		$i = count($stack) - 1;
   9  
  10  		if(strlen($s = ob_get_contents())){
  11  			$i ? $stack[$i - 1] .= $s : @ob_flush();
  12  			ob_end_clean();
  13  		}
  14  		$get = null; $pt = '';
  15  		if(($qp = strpos($path, '?')) !== false){
  16  			$get = $_GET; $pt = substr($path, 0, $qp);
  17  			foreach(explode('&', substr($path, $qp + 1)) as $qv){
  18  				$tv = explode('=', $qv);
  19  				$_GET[$tv[0]] = count($tv) > 1 ? $tv[1] : '';
  20  			}
  21  		}
  22  		else $pt = $path;
  23  		ob_start();
  24  		include $pt;
  25  		$path = ob_get_contents();
  26  		ob_end_clean();
  27  		if(count($stack) > 1)
  28  			ob_start();
  29  		$get !== null && ($_GET = &$get);
  30  		unset($get);
  31  		return array_pop($stack) . $path;
  32  	}
  33  }

PHP error listener

Error listener for PHP, shows simple errors as exceptions.

   1  
   2  //+ Jonas Raoni Soares Silva
   3  //@ http://jsfromhell.com
   4  class ErrorListener{
   5  	static protected $listening = false;
   6  	static protected $listeningExceptions = false;
   7  
   8  	public static function start(){
   9  		if(self::$listening)
  10  			return;
  11  		set_error_handler(array('ErrorListener', 'dispatcher'));
  12  		self::$listening = true;
  13  	}
  14  	public static function stop(){
  15  		if(!self::$listening)
  16  			return;
  17  		restore_error_handler();
  18  		self::$listening = false;
  19  	}
  20  	public static function dispatcher($code, $message){
  21  		throw new Exception($message, $code);
  22  	}
  23  	public static function setDefaultExceptionHandler($callback){
  24  		if(self::$listeningExceptions)
  25  			return;
  26  		set_exception_handler($callback);
  27  	}
  28  	public static function restoreDefaultExceptionHandler(){
  29  		if(!self::$listeningExceptions)
  30  			return;
  31  		restore_exception_handler();
  32  	}
  33  }
« Newer Snippets
Older Snippets »
Showing 1-10 of 370 total  RSS