Example #1
0
	/**
	 * Convert an sql date to a unix timestamp in second.
	 * The provided date may be a year, a date, a time or a datetime.
	 * 
	 *     PurSql::toTimestamp('2007-12-45 16:15:00');
	 *     PurSql::toTimestamp('2007-12-45');
	 *     PurSql::toTimestamp('16:15:00');
	 *     PurSql::toTimestamp('2007');
	 * 
	 * @return null if date parameter is invalid or timestamp as int
	 * @param $date String
	 */
	public static function toTimestamp($date){
		if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2}) ([0-9]{2}):([0-9]{2}):([0-9]{2})$/",$date,$regs)){
			return gmmktime($regs[4], $regs[5], $regs[6], $regs[2], $regs[3], $regs[1]);
		}else if(preg_match("/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/",$date,$regs)){
			return gmmktime(0, 0, 0, $regs[2], $regs[3], $regs[1]);
		}else if(preg_match("/^([0-9]{2}):([0-9]{2}):([0-9]{2})$/",$date,$regs)){
			return gmmktime($regs[1], $regs[2], $regs[3], 1, 1, 1970);
		}else if(preg_match("/^([0-9]{4})$/",$date,$regs)){
			return gmmktime(0, 0, 0, 1, 1, $regs[1]);
		}
		throw new InvalidArgumentException('Invalid Date: '.PurLang::toString($date));
	}
Example #2
0
	/**
	 * Converted an array to an XML string.
	 * 
	 * Options may include:
	 * - -*prefix* Prefix string which may be used for indentation-
	 * - *tab* Characteres used for tabulation
	 * - *return* Characteres used for line returns
	 * - *dtd* XML DTD string
	 * - *declaration* XML declaration string
	 * - *instructions* XML instructions array of strings
	 * - *from_encoding* Destination encoding, default to "UTF-8"
	 * - *to_encoding* Source encoding, default to "UTF-8"
	 * - *docktype* Will only return the XML doctype
	 * - *declaration* Will only return the XML declaration
	 * 
	 * Element options may include
	 * - *cdata* Wrap element value in XML CDATA construct
	 * - *no_entities* Disable entities encoding, notice that it may break your XML
	 * 
	 * @param object $source
	 * @param object $options [optional]
	 * @return 
	 */
	public static function toString($source,$options=array()){
		// Some note between htmlspecialchars and htmlentities
		// The 2 functions are identical except with htmlentities(), 
		// all characters which have HTML character entity equivalents 
		// are translated into these entities.
//		if(empty($options['prefix'])){
//			$options['prefix'] = '';
//		}
		if(!isset($options['elements'])){
			$options['elements'] = array();
		}
		if(empty($options['from_encoding'])){
			$options['from_encoding'] = 'UTF-8';
		}
		if(empty($options['return'])){
			$options['return'] = "\n";
		}
		if(empty($options['tab'])){
			$options['tab'] = "\t";
		}
		if(empty($options['to_encoding'])){
			$options['to_encoding'] = 'UTF-8';
		}
		$result = '';
		// Deal with XML declaration
		$declaration = null;
		if(!empty($source['declaration'])){
			switch(gettype($source['declaration'])){
				case 'string':
					if(!empty($options['to_encoding'])&&preg_match('/encoding="(.*)"/i',$source['declaration'])){
						$source['declaration'] = preg_replace('/encoding="(.*)"/i','encoding="'.$options['to_encoding'].'"',$source['declaration']);
					}
					$declaration .= $source['declaration'];
					break;
				case 'boolean':
					$declaration .= '<?xml version="1.0" encoding="'.$options['to_encoding'].'" ?>';
					break;
				case 'array':
					$declaration .= '<?xml';
					if(isset($source['declaration']['version'])){
						$declaration .= ' version="'.$source['declaration']['version'].'"';
					}
					if(isset($source['declaration']['encoding'])){
						$declaration .= ' encoding="'.(!empty($options['to_encoding'])?$options['to_encoding']:$source['declaration']['encoding']).'"';
					}
					if(isset($source['declaration']['standalone'])){
						$declaration .= ' standalone="'.($source['declaration']['standalone']?'yes':'no').'"';
					}
					$declaration .= ' ?>';
					break;
				default:
					throw new Exception('Invalid declaration "'.PurLang::toString($source['declaration']).'"');
			}
		}
		if(!empty($options['declaration'])){
			return $declaration;
		}
		if($declaration){
			$result .= $declaration.$options['return'];
		}
		// Deal with XML doctype
		$doctype = null;
		if(!empty($source['doctype'])){
			switch(gettype($source['doctype'])){
				case 'string':
					$doctype .= $source['doctype'];
					break;
				case 'array':
					$doctype .= '<!DOCTYPE';
					if(isset($source['doctype']['name'])&&is_string($source['doctype']['name'])){
						$doctype .= ' '.$source['doctype']['name'];
					}else{
						throw new Exception('Invalid doctype name "'.PurLang::toString($source['doctype']['name']).'"');
					}
					if(isset($source['doctype']['public'])){
						$doctype .= ' PUBLIC "'.$source['doctype']['public'].'"';
					}
					if(isset($source['doctype']['system'])){
						if(!isset($source['doctype']['public'])){
							$doctype .= ' SYSTEM';
						}
						$doctype .= ' "'.$source['doctype']['system'].'"';
					}
					if(isset($source['doctype']['internal'])){
						$doctype .= ' '.$source['doctype']['internal'].'';
					}
					$doctype .= '>';
					break;
				default:
					throw new Exception('Invalid doctype "'.PurLang::toString($source['doctype']).'"');
			}
		}
		if(!empty($options['doctype'])){
			return $doctype;
		}
		if($doctype){
			$result .= $doctype.$options['return'];
		}
		// Deal with nodes
		$works = array(array(null,array($source),null));
		while(count($works)){
			list(,$work) = $works[0];
			while(list($k,$v) = each($work)){
				unset($work[$k]);
				if(isset($v['name'])){
					if(isset($v['children'])){
						if(!empty($options['no_format'])||!empty($v['no_format'])||!empty($options['elements'][$v['name']]['no_format'])){
							foreach($v['children'] as &$child){
								$child['return'] = '';
								$child['tab'] = '';
							}
							reset($v['children']);
							$v['return_in'] = '';
							$v['tab_in'] = '';
						}else{
							$noFormat = false;
							foreach($v['children'] as $child){
								if(!isset($child['name'])){
									$noFormat = true;
									break;
								}
							}
							reset($v['children']);
							if($noFormat){
								foreach($v['children'] as &$child){
									$child['return'] = '';
									$child['tab'] = '';
								}
								reset($v['children']);
								$v['return_in'] = '';
								$v['tab_in'] = '';
							}
						}
					}
					if(!isset($v['return'])){
						$v['return'] = $options['return'];
					}
					if(!isset($v['return_in'])){
						$v['return_in'] = $options['return'];
					}
					if(!isset($v['tab'])){
						$v['tab'] = $options['tab'];
					}
					if(!isset($v['tab_in'])){
						$v['tab_in'] = $options['tab'];
					}
					$result .=
						implode('',array_pad(array(),count($works)-1,$v['tab']));
					
					$attributes = '';
					if(isset($v['attributes'])){
						foreach($v['attributes'] as $attribute){
							$value = mb_convert_encoding($attribute['value'],$options['to_encoding'],$options['from_encoding']);
							if(empty($attribute['no_entities'])){
								$value = htmlspecialchars($value,ENT_QUOTES,$options['to_encoding']);
							}
							$attributes .= 
								' '.
								(empty($attribute['prefix'])?'':$attribute['prefix'].':').
								$attribute['name'].
								'="'.$value.'"';
							unset($value);
						}
						$attributes = rtrim($attributes);
					}
					$result .= '<'.(empty($v['prefix'])?'':$v['prefix'].':').$v['name'].$attributes;
					if(isset($v['value'])){
						$result .= '>';
						$value = mb_convert_encoding($v['value'],$options['to_encoding'],$options['from_encoding']);
						if(empty($v['cdata'])){
							if(empty($v['no_entities'])){
								$value = htmlspecialchars($value,ENT_QUOTES,$options['to_encoding']);
							}
							$result .= $value;
						}else{
							$result .= '<![CDATA['.$value.']]>';
						}
						unset($value);
						$result .= '</'.(empty($v['prefix'])?'':$v['prefix'].':').$v['name'].'>'.$v['return'];
					}else if(isset($v['children'])){
						$result .= '>'.$v['return_in'];
						$works[0][1] = $work;
						$work = $v['children'];
						array_unshift($works, array($v,$v['children']));
					}else{
						$result .= ' />'.$v['return'];
					}
				}else{
					$value = mb_convert_encoding($v['value'],$options['to_encoding'],$options['from_encoding']);
					if(empty($v['no_entities'])){
						$value = htmlspecialchars($value,ENT_QUOTES,$options['to_encoding']);
					}
					$result .= $value;
				}
			}
			list($parent) = array_shift($works);
			if($parent){
				$result .=
					implode('',array_pad(array(),count($works)-1,$parent['tab_in'])).
					'</'.(empty($parent['prefix'])?'':($parent['prefix'].':')).$parent['name'].'>'.$parent['return'];
			}
		}
		return $result;
	}
Example #3
0
	/**
	 * Return an array representation of the git status command.
	 * 
	 * Options may include:
	 * -   *absolute* Return absolute paths
	 * -   *cwd* Directory from from where the status must be run
	 * -   *bin* Path to the Git command
	 * -   *relative* Relative to the Git project root directory
	 * 
	 * Structure of the returned array:
	 * -   changed_to_be_committed
	 * -   changed_but_not_updated
	 * -   untracked_files
	 * 
	 * @return array Decomposed status
	 * 
	 * @param array $options required Options used to alter the method behavior
	 * @return array Decomposed status
	 * 
	 * @param string $cwd required Path to the directory to initialize
	 * @return array Decomposed status
	 */
	public static function status(){
		$args = func_get_args();
		switch(count($args)){
			case 0:
				$options = array();
				break;
			case 1:
				if(is_string($args[0])){
					$options = array(
						'cwd' => $args[0]);
				}else if(is_array($args[0])){
					$options = $args[0];
				}else{
					throw new InvalidArgumentException('Invalid Arguments: "'.PurLang::toString($args).'"');
				}
				break;
			default:
				throw new InvalidArgumentException('Invalid Arguments Count: '.PurLang::toString($args));
		}
		unset($args);
		$options['return_message'] = 1;
		if(empty($options['bin'])){
			$options['bin'] = self::$bin;
		}
		$command = $options['bin'];
		$command .= ' status';
		$out = PurCli::exec($command,$options);
		$status = array(
			'changed_to_be_committed'=>array(),
			'changed_but_not_updated'=>array(),
			'untracked_files'=>array());
		$type = null;
		foreach($out as $line){
			if($line=='# Changes to be committed:'){
				$type = 'changed_to_be_committed';
			}else if($line=='# Changed but not updated:'){
				$type = 'changed_but_not_updated';
			}else if($line=='# Untracked files:'){
				$type = 'untracked_files';
			}else{
				if(preg_match('/^#\t((new file|modified|deleted): +)?(.*)/',$line,$matches)){
//					if(isset($options['cwd'])){
//						$matches[3] = PurPath::relative($options['cwd'],getcwd().'/'.$matches[3]);
//					}
					if(!empty($options['absolute'])){
						$matches[3] = PurPath::clean($options['cwd'].'/'.$matches[3]);
					}else if(!empty($options['relative'])){
						$matches[3] = PurPath::relative(self::dir($options),$options['cwd'].'/'.$matches[3]);
					}
					if(empty($matches[2])){
						$status[$type][] = $matches[3];
					}else{
						$status[$type][$matches[2]][] = $matches[3];
					}
				}
			} 
		}
		while(list($k,$v) = each($status)){
			if(empty($v)){
				unset($status[$k]);
			}
		}
		reset($status);
		return $status;
	}
Example #4
0
	/**
	 * Print a readable stacktrace. If no strace is provided, will generate a new one.
	 * 
	 * Options may include:
	 * - prefix: string to insert a the beginning of each lines, default to empty
	 * - suffix: string to insert at the end of each lines, default to windows carriage return '\r\n'
	 * - base: transform absolute path to relative
	 * 
	 * @return 
	 * @param object $trace[optional]
	 * @param object $options[optional]
	 */
	public static function traceAsString($trace=null,$options=array()){
		if(is_null($trace)) $trace = PurLang::trace();
		elseif(!is_array($trace)) throw new InvalidArgumentException('Trace must be an array or null: "'.self::toString($trace).'" provided');
		$content = '';
		foreach($trace as $k=>$v){
			if(isset($v['file'])){
				if(isset($options['prefix'])) $content .= $options['prefix'];
				$file = $v['file'];
				if(!empty($options['base'])){
					$_file = PurPath::relative($options['base'],$file);
					if(strpos($_file,'../')!==0){
						$file = $_file;
					}
					unset($_file);
				}
				$content .= $file.':'.$v['line']." ";
				$content .= (array_key_exists('class',$v)?$v['class']:'').(array_key_exists('type',$v)?$v['type']:'').$v['function'].'()';
				$content .= (isset($options['suffix']))?$options['suffix']:"\r\n";
			}
		}
		return $content;
	}
Example #5
0
	/**
	 * Create an image resource base on the provided file path.
	 * 
	 * Options may include:
	 * - *width*: Canvas width of the generated image or resource; "100" and "80+top" (with top defined as 20) for 100 pixels
	 * - *height*: Canvas height of the generated image or resource; "50" and "25+top" (with top defined as 20) for 75 pixels
	 * - *top*: Offset from the top of the source in pixel
	 * - *left*: Offset from the left of the source in pixel
	 * - *bottom*: Offset from the bottom of the source in pixel
	 * - *right*: Offset from the right of the source in pixel
	 * - *temp_dir*: Path to temporary working directory
	 * - *gm_convert*: Path to the gm convert utility (used for psd images, usually "gm convert" or "convert")
	 * 
	 * Create a new transparent resource of 100x75 pixels:
	 * * PurImage::resource(array('width'=>100,'height'=>75));
	 * 
	 * Create a resource from a psd file (with "gm" available in your path as "gm convert...")
	 * * PurImage::resource('path/to/image.psd');
	 * 
	 * Create a resource from a psd file (with "gm" not available but installed)
	 * * PurImage::resource('path/to/image.psd',array('gm_convert'=>'/usr/bin/gm convert'));
	 * 
	 * @return resource Resource associated to the file path
	 * @param mixed $source File path referencing an image or null to create a transparent resource
	 * @param array $options[optional] Configuration array
	 */
	public static function resource($source=null,array $options=array()){
		if(is_array($source)){
			$options = $source;
			$source = null;
		}
		if(empty($source)){
			if(empty($options['width'])||empty($options['height'])){
				throw new InvalidArgumentException('Missing Options: width and height required when creating a new resource');
			}
			$resource = imagecreatetruecolor($options['width'],$options['height']);
			imagesavealpha($resource, true);
			imagefill($resource,0,0,imagecolorallocatealpha($resource,255,255,255,127));
			return $resource;
		}else if(is_string($source)){
			if(!is_readable($source)) throw new InvalidArgumentException('Invalid Source Path: '.PurLang::toString($source).'');
			$type = exif_imagetype($source);
			switch($type){
				case IMAGETYPE_GIF:
					$source = imagecreatefromgif($source);
					break;
				case IMAGETYPE_JPEG:
					$source = imagecreatefromjpeg($source);
					break;
				case IMAGETYPE_PNG:
					$source = imagecreatefrompng($source);
					break;
				case IMAGETYPE_SWF:
					break;
				case IMAGETYPE_PSD:
					if(!isset($options['gm_convert'])){
						throw new Exception('Missing Option For PSD Image Type: gm_convert');
					}
					$temp = (isset($options['temp_dir'])?$options['temp_dir']:sys_get_temp_dir()).'/'.uniqid();
					$cmd = $options['gm_convert'].' -flatten '.escapeshellarg($source).' '.escapeshellarg('png:'.$temp);
					exec($cmd);
					$source = imagecreatefrompng($temp);
					PurFile::delete($temp);
					break;
				case IMAGETYPE_BMP:
					break;
				case IMAGETYPE_TIFF_II:
					break;
				case IMAGETYPE_TIFF_MM:
					break;
				case IMAGETYPE_JPC:
					break;
				case IMAGETYPE_JP2:
					break;
				case IMAGETYPE_JPX:
					break;
				case IMAGETYPE_JB2:
					break;
				case IMAGETYPE_SWC:
					break;
				case IMAGETYPE_IFF:
					break;
				case IMAGETYPE_WBMP:
					$source = imagecreatefromwbmp($source);
					break;
				case IMAGETYPE_XBM:
					$source = imagecreatefromxbm($source);
					break;
			}
			$created = true;
		}else if(is_resource($source)){
			$created = false;
		}else{
			throw new InvalidArgumentException('Invalid Source: empty, string or resource accepted');
		}
//		width
//		height
//		top
//		left
//		bottom
//		right
//		imagecopyresampled($dst_im, $src_im, $dst_x, $dst_y, $src_x, $src_y, $dst_w, $dst_h, $src_w, $src_h)
		$sourceWidth = imagesx($source);
		$sourceHeight = imagesy($source);
		// Sanitize width and height
		if(!empty($options['width'])&&!empty($options['height'])){
			if($options['width']!=$sourceWidth&&$options['height']!=$sourceHeight){
				$resized = true;
			}
		}else if(!empty($options['width'])&&$options['width']!=$sourceWidth){
			$resized = true;
			$options['height'] = $sourceHeight*$options['width']/$sourceWidth;
		}else if(!empty($options['height'])&&$options['height']!=$sourceHeight){
			$resized = true;
			$options['width'] = $sourceWidth*$options['height']/$sourceHeight;
		}
		// Sanitize resize as an array with width and height keys
		if(!empty($options['resize'])){
			$resized = true;
			switch(gettype($options['resize'])){
				case 'string':
					$options['resize'] = explode('x',$options['resize']);
				case 'array':
					if(empty($options['resize'])||count($options['resize'])>2){
						throw new Exception('Invalid "resize": '.PurLang::toString($options['resize']));
					}
					// Deal with map
					if(!empty($options['resize']['width'])){
						$width = $options['resize']['width'];
					}
					if(!empty($options['resize']['height'])){
						$height = $options['resize']['height'];
					}
					// Deal with index
					if(!isset($width)){
						$width = array_shift($options['resize']);
					}
					if(!isset($height)){
						$height = array_shift($options['resize']);
					}
					// Deal with *
					if($width=='*') $width = null;
					if($height=='*') $height = null;
					// Rebuild resize
					$options['resize']['width'] = $width;
					unset($width);
					$options['resize']['height'] = $height;
					unset($height);
					if(empty($options['resize']['width'])){
						$options['resize']['width'] = $sourceWidth*$options['resize']['height']/$sourceHeight;
					}else if(empty($options['resize']['height'])){
						$options['resize']['height'] = $sourceHeight*$options['resize']['width']/$sourceWidth;
					}
					break;
				default:
					throw new Exception('Invalid "resize": '.PurLang::toString($options['resize']));
			}
		}else{
			$options['resize'] = array('width'=>$sourceWidth,'height'=>$sourceHeight);
		}
		if(isset($resized)){
			$destination = self::resource(null,$options);
			imagecopyresampled($destination,$source,0,0,0,0,
				$options['resize']['width'],$options['resize']['height'],
				$sourceWidth,$sourceHeight);
			if($created){
				imagedestroy($source);
			}
			$source = $destination;
		}
		return $source;
	}
 /**
  * Create a new table and associated column families schema.
  * 
  * The first argument is expected to be the table name while the following
  * arguments describle column families.
  * 
  * Usage
  *     $hbase->tables->create(
  *         'table_name',
  *         'column_1',
  *         array('name'=>'column_2'),
  *         array('NAME'=>'column_3'),
  *         array('@NAME'=>'column_4',...);
  * 
  * @param $table string Name of the table to create
  * @param $column string Name of the column family to create
  * @return PopHbase Current instance
  */
 public function create()
 {
     $args = func_get_args();
     if (count($args) === 0) {
         throw new InvalidArgumentException('Missing table schema definition');
     }
     $table = array_shift($args);
     switch (gettype($table)) {
         case 'string':
             $schema = array('name' => $table);
             break;
         case 'array':
             // name is required
             // other keys include IS_META and IS_ROOT
             $schema = array();
             foreach ($table as $k => $v) {
                 if (substr($k, 0, 1) != '@') {
                     $k = substr($k, 1);
                 }
                 if ($k == 'NAME') {
                     $k = 'name';
                 } else {
                     $k = strtoupper($k);
                 }
                 $schema[$k] = $v;
             }
             if (!isset($schema['name'])) {
                 throw new InvalidArgumentException('Table schema definition not correctly defined "' . PurLang::toString($table) . '"');
             }
             break;
         default:
             throw new InvalidArgumentException('Table schema definition not correctly defined: "' . PurLang::toString($table) . '"');
     }
     if (count($args) === 0) {
         throw new InvalidArgumentException('Missing at least one column schema definition');
     }
     $schema['ColumnSchema'] = array();
     foreach ($args as $arg) {
         switch (gettype($arg)) {
             case 'string':
                 $schema['ColumnSchema'][] = array('name' => $arg);
                 break;
             case 'array':
                 // name is required
                 // other keys include BLOCKSIZE, BLOOMFILTER,
                 // BLOCKCACHE, COMPRESSION, LENGTH, VERSIONS,
                 // TTL, and IN_MEMORY
                 $columnSchema = array();
                 foreach ($arg as $k => $v) {
                     if (substr($k, 0, 1) == '@') {
                         $k = substr($k, 1);
                     }
                     if ($k == 'NAME') {
                         $k = 'name';
                     } else {
                         $k = strtoupper($k);
                     }
                     $columnSchema[$k] = $v;
                 }
                 if (!isset($columnSchema['name'])) {
                     throw new InvalidArgumentException('Column schema definition not correctly defined "' . PurLang::toString($table) . '"');
                 }
                 $schema['ColumnSchema'][] = $columnSchema;
                 break;
             default:
                 throw new InvalidArgumentException('Column schema definition not correctly defined: "' . PurLang::toString($table) . '"');
         }
     }
     $this->hbase->request->put($schema['name'] . '/schema', $schema);
     $this->reload();
 }