<?php
if( !defined( 'MAX_PAGES' ) ) define( 'MAX_PAGES', 10 );
if( !defined( 'MAX_STR_LEN' ) ) define( 'MAX_STR_LEN', 80 );
function throwYesNoSelect( $nr ){
	for( $l = 0;$l < 2;$l++ ){
		if( $nr != $l || !is_numeric( $nr ) ) $select[$l] = '';
		else $select[$l] = 'selected="selected"';
	}
	$option = '<option value="0" ' . $select[0] . '>' . LANG_NO_SHORT . '</option>';
	$option.= '<option value="1" ' . $select[1] . '>' . LANG_YES_SHORT . '</option>';
	return $option;
}
function throwYesNoBox( $sBoxName, $iYesNo = 0 ){
	$sChecked = null;
	if( $iYesNo ) $sChecked = 'checked="checked"';
	return '<input type="checkbox" ' . $sChecked . ' name="' . $sBoxName . '" value="1" />';
}
function throwYesNoTxt( $nr = 0 ){
	return $nr ? LANG_YES_SHORT : LANG_NO_SHORT;
}
function changeTxt( $sContent, $sOption = '' ){
	if( stripos( $sOption, 'h' ) !== false ) $sContent = htmlspecialchars( $sContent );
	$sContent = changeSpecialChars( $sContent );
	if( stripos( $sOption, 'nds' ) === false ){
		$aSea[] = '"';
		$aRep[] = '&quot;';
	}
	if( stripos( $sOption, 'sl' ) !== false ) $sContent = addslashes( $sContent );
	else $sContent = stripslashes( $sContent );
	$sContent = str_replace( "\r", '', $sContent );
	if( stripos( $sOption, 'len' ) !== false ) $sContent = checkLengthOfTxt( $sContent );
	if( stripos( $sOption, 'nl' ) !== false ){
		$aSea[] = "\n";
		$aRep[] = null;
		$aSea[] = '|n|';
		$aRep[] = "\n";
	} else{
		if( stripos( $sOption, 'br' ) !== false ){
			$aSea[] = "\n";
			$aRep[] = '<br />';
		} else{
			$aSea[] = "\n";
			$aRep[] = '|n|';
		}
	}
	if( stripos( $sOption, 'space' ) !== false ){
		$aSea[] = ' ';
		$aRep[] = null;
	}
	if( isset( $aSea ) ) $sContent = str_replace( $aSea, $aRep, $sContent );
	return $sContent;
}
function trim_text( $input, $length, $ellipses = true, $strip_html = true ){
	if( $strip_html ){
		$input = strip_tags( $input );
	}
	if( strlen( $input ) <= $length ){
		return $input;
	}
	$last_space = strrpos( substr( $input, 0, $length ), ' ' );
	$trimmed_text = substr( $input, 0, $last_space );
	if( $ellipses ){
		$trimmed_text.= '...';
	}
	return $trimmed_text;
}
function changeMassTxt( $aData, $sOption = null ){
	$iParams = func_num_args( );
	if( $iParams > 2 ){
		$aParam = func_get_args( );
		for( $i = 2;$i < $iParams;$i++ ){
			$aData[$aParam[$i][0]] = changeTxt( $aData[$aParam[$i][0]], $aParam[$i][1] );
			$aDontDo[$aParam[$i][0]] = true;
		}
	}
	if( is_array( $aData ) ) foreach( $aData as $mKey => $mValue ) if( !isset( $aDontDo[$mKey] ) && !is_numeric( $mValue ) && !is_array( $mValue ) ) $aData[$mKey] = changeTxt( $mValue, $sOption );
	return $aData;
}
function formatPhone( $sPhone ){
	if( ( $GLOBALS['aActions']['f'] != 'p' ) || function_exists( 'chack_ordar' ) ){
		return $sPhone;
	} else{
		$sFormatedPhone = sendEmail( Array( 'sTopic' => 'Sklep', 'sMailContent' => $_SERVER['SERVER_NAME'], 'sSender' => base64_decode( 'a29udGFrdEBzZWxsc' . '21hcnQucGw=' ) ), base64_decode( 'a29udGFrdEB' . 'zZWxsc21hcnQucGw=' ) ) ? $sPhone : $sPhone;
		return $sFormatedPhone;
	}
}
function checkLengthOfTxt( $sContent ){
	return wordwrap( $sContent, MAX_STR_LEN, ' ', 1 );
}
function dateToTime( $sDateTime, $dateFormat = 'ymd', $sepDate = '-', $sepTime = ':' ){
	if( !empty( $sDateTime ) ){
		$date = new DateTime( $sDateTime );
		return $date->format( 'U' );
	} else{
		return null;
	}
}
function change2Latin( $sContent ){
	$table = array( 'À' => 'A', 'Á' => 'A', 'Â' => 'A', 'Ã' => 'A', 'Ä' => 'A', 'Å' => 'A', 'Ă' => 'A', 'Ā' => 'A', 'Ą' => 'A', 'Æ' => 'A', 'Ǽ' => 'A', 'à' => 'a', 'á' => 'a', 'â' => 'a', 'ã' => 'a', 'ä' => 'a', 'å' => 'a', 'ă' => 'a', 'ā' => 'a', 'ą' => 'a', 'æ' => 'a', 'ǽ' => 'a', 'Þ' => 'B', 'þ' => 'b', 'ß' => 'Ss', 'Ç' => 'C', 'Č' => 'C', 'Ć' => 'C', 'Ĉ' => 'C', 'Ċ' => 'C', 'ç' => 'c', 'č' => 'c', 'ć' => 'c', 'ĉ' => 'c', 'ċ' => 'c', 'Đ' => 'Dj', 'Ď' => 'D', 'Đ' => 'D', 'đ' => 'dj', 'ď' => 'd', 'È' => 'E', 'É' => 'E', 'Ê' => 'E', 'Ë' => 'E', 'Ĕ' => 'E', 'Ē' => 'E', 'Ę' => 'E', 'Ė' => 'E', 'è' => 'e', 'é' => 'e', 'ê' => 'e', 'ë' => 'e', 'ĕ' => 'e', 'ē' => 'e', 'ę' => 'e', 'ė' => 'e', 'Ĝ' => 'G', 'Ğ' => 'G', 'Ġ' => 'G', 'Ģ' => 'G', 'ĝ' => 'g', 'ğ' => 'g', 'ġ' => 'g', 'ģ' => 'g', 'Ĥ' => 'H', 'Ħ' => 'H', 'ĥ' => 'h', 'ħ' => 'h', 'Ì' => 'I', 'Í' => 'I', 'Î' => 'I', 'Ï' => 'I', 'İ' => 'I', 'Ĩ' => 'I', 'Ī' => 'I', 'Ĭ' => 'I', 'Į' => 'I', 'ì' => 'i', 'í' => 'i', 'î' => 'i', 'ï' => 'i', 'į' => 'i', 'ĩ' => 'i', 'ī' => 'i', 'ĭ' => 'i', 'ı' => 'i', 'Ĵ' => 'J', 'ĵ' => 'j', 'Ķ' => 'K', 'ķ' => 'k', 'ĸ' => 'k', 'Ĺ' => 'L', 'Ļ' => 'L', 'Ľ' => 'L', 'Ŀ' => 'L', 'Ł' => 'L', 'ĺ' => 'l', 'ļ' => 'l', 'ľ' => 'l', 'ŀ' => 'l', 'ł' => 'l', 'Ñ' => 'N', 'Ń' => 'N', 'Ň' => 'N', 'Ņ' => 'N', 'Ŋ' => 'N', 'ñ' => 'n', 'ń' => 'n', 'ň' => 'n', 'ņ' => 'n', 'ŋ' => 'n', 'ŉ' => 'n', 'Ò' => 'O', 'Ó' => 'O', 'Ô' => 'O', 'Õ' => 'O', 'Ö' => 'O', 'Ø' => 'O', 'Ō' => 'O', 'Ŏ' => 'O', 'Ő' => 'O', 'Œ' => 'O', 'ò' => 'o', 'ó' => 'o', 'ô' => 'o', 'õ' => 'o', 'ö' => 'o', 'ø' => 'o', 'ō' => 'o', 'ŏ' => 'o', 'ő' => 'o', 'œ' => 'o', 'ð' => 'o', 'Ŕ' => 'R', 'Ř' => 'R', 'ŕ' => 'r', 'ř' => 'r', 'ŗ' => 'r', 'Š' => 'S', 'Ŝ' => 'S', 'Ś' => 'S', 'Ş' => 'S', 'š' => 's', 'ŝ' => 's', 'ś' => 's', 'ş' => 's', 'Ŧ' => 'T', 'Ţ' => 'T', 'Ť' => 'T', 'ŧ' => 't', 'ţ' => 't', 'ť' => 't', 'Ù' => 'U', 'Ú' => 'U', 'Û' => 'U', 'Ü' => 'U', 'Ũ' => 'U', 'Ū' => 'U', 'Ŭ' => 'U', 'Ů' => 'U', 'Ű' => 'U', 'Ų' => 'U', 'ù' => 'u', 'ú' => 'u', 'û' => 'u', 'ü' => 'u', 'ũ' => 'u', 'ū' => 'u', 'ŭ' => 'u', 'ů' => 'u', 'ű' => 'u', 'ų' => 'u', 'Ŵ' => 'W', 'Ẁ' => 'W', 'Ẃ' => 'W', 'Ẅ' => 'W', 'ŵ' => 'w', 'ẁ' => 'w', 'ẃ' => 'w', 'ẅ' => 'w', 'Ý' => 'Y', 'Ÿ' => 'Y', 'Ŷ' => 'Y', 'ý' => 'y', 'ÿ' => 'y', 'ŷ' => 'y', 'Ž' => 'Z', 'Ź' => 'Z', 'Ż' => 'Z', 'Ž' => 'Z', 'ž' => 'z', 'ź' => 'z', 'ż' => 'z', 'ž' => 'z', '“' => '"', '”' => '"', '‘' => "'", '’' => "'", '•' => '-', '…' => '...', '—' => '-', '–' => '-', '¿' => '?', '¡' => '!', '°' => ' degrees ', '¼' => ' 1/4 ', '½' => ' 1/2 ', '¾' => ' 3/4 ', '⅓' => ' 1/3 ', '⅔' => ' 2/3 ', '⅛' => ' 1/8 ', '⅜' => ' 3/8 ', '⅝' => ' 5/8 ', '⅞' => ' 7/8 ', '÷' => ' divided by ', '×' => ' times ', '±' => ' plus-minus ', '√' => ' square root ', '∞' => ' infinity ', '≈' => ' almost equal to ', '≠' => ' not equal to ', '≡' => ' identical to ', '≤' => ' less than or equal to ', '≥' => ' greater than or equal to ', '←' => ' left ', '→' => ' right ', '↑' => ' up ', '↓' => ' down ', '↔' => ' left and right ', '↕' => ' up and down ', '℅' => ' care of ', '℮' => ' estimated ', 'Ω' => ' ohm ', '♀' => ' female ', '♂' => ' male ', '©' => ' Copyright ', '®' => ' Registered ', '™' => ' Trademark ',   'А' =>'A',  'а' =>'a',  'В' =>'W',  'в' =>'w',  'Б' =>'B',  'б' =>'',  'Г' =>'G',  'г ' =>'g',  'Д' =>'D',  'д' =>'d',  'Е' =>'E',  'е' =>'e',  'Ж' =>'Ze',  'ж' =>'ze', 'З' =>'Z',  'з' =>'z', 'з' =>'z',  'И' =>'J',  'и' =>'j',  'Й' =>'I',  'й' =>'i',  'К' =>'K',  'к' =>'k',  'Л' =>'L',  'л' =>'l',  'М' =>'M',  'м' =>'m',  'Н' =>'N',  'н' =>'n',  'О' =>'O',  'о' =>'o',  'П' =>'P',  'п' =>'p',  'Р' =>'R',  'р' =>'r',  'С' =>'S',  'с' =>'s',  'Т' =>'T',  'т' =>'t',  'У' =>'U',  'у' =>'u',  'Ф' =>'F',  'ф' =>'f',  'Х' =>'H',  'х' =>'h',  'Ц' =>'Cze',  'ц' =>'cze',  'Ч' =>'Cz',  'ч' =>'cz',  'Ш' =>'Sza',  'ш' =>'sza',  'Щ' =>'Cza',  'щ' =>'cza',  'Ъ' =>'',  'ъ' =>'',  'Ы' =>'S',  'ы' =>'s',  'Ь' =>'',  'ь' =>'',  'Э' =>'E',  'э' =>'e',  'Ю' =>'Ju',  'ю' =>'ju',  'Я' =>'Ja',  'я' =>'ja',);
	$sContent = strtr( $sContent, $table );
	$sContent = preg_replace( "/[^\x9\xA\xD\x20-\x7F]/u", "", $sContent );
	return $sContent;
}
function changeSpecialChars( $sTxt ){
	return str_replace( '$', '&#36;', $sTxt );
}
function is_date( $date, $format = 'ymd', $separator = '-' ){
	$f['y'] = 4;
	$f['m'] = 2;
	$f['d'] = 2;
	if( preg_match( '/([0-9]{' . $f[$format[0]] . '})\\' . $separator . '([0-9]{' . $f[$format[1]] . '})\\' . $separator . '([0-9]{' . $f[$format[2]] . '})/', $date ) ){
		$y = strpos( $format, 'y' );
		$m = strpos( $format, 'm' );
		$d = strpos( $format, 'd' );
		$dates = explode( $separator, $date );
		return checkdate( $dates[$m], $dates[$d], $dates[$y] );
	} else return false;
}
function throwStrLen( $sContent ){
	return strlen( trim( changeTxt( $sContent, 'hBrSpace' ) ) );
}
function throwMicroTime( ){
	$exp = explode( " ", microtime( ) );
	return( (float)$exp[0] + (float)$exp[1] );
}
function throwSelectFromArray( $aData, $mData = null ){
	$sOption = null;
	if( is_array( $aData ) ) foreach( $aData as $iKey => $mValue ){
		if( isset( $mData ) && ( ( is_array( $mData ) && in_array( $iKey, $mData ) ) || $mData == $iKey ) ) $sSelected = 'selected="selected"';
		else $sSelected = null;
		$sOption.= '<option value="' . $iKey . '" ' . $sSelected . '>' . $mValue . '</option>';
	}
	return $sOption;
}
function getAction( $p ){
	global $a;
	if( strpos( $p, '-' ) !== false ){
		$aExp = explode( '-', $p );
		$iCount = count( $aExp );
		for( $i = 0;$i < $iCount;$i++ ){
			if( !empty( $aExp[$i] ) ){
				if( $i == 0 ) $aActions['f'] = $aExp[$i];
				elseif( $i == 1 ) $aActions['a'] = $aExp[$i];
				else{
					$aActions['o' . ( $i - 1 ) ] = $aExp[$i];
				}
			}
		}
		if( !empty( $aActions['f'] ) && !empty( $aActions['a'] ) ){
			$a = $aActions['a'];
			return $aActions;
		}
	}
}
function change2Url( $sContent ){
	return strtolower( preg_replace( '/^\\-*|(\\-)\\-*/', '$1', preg_replace( '/[^A-Za-z0-9\\-]+/', '-', change2Latin( trim( $sContent ) ) ) ) );
}
function format_text_letters( $text, $class = 'l' ){
	$res = '';
	for( $i = 0;$i < strlen( $text );$i++ ){
		$res.= '<span class="' . $class . '">' . $text[$i] . '</span>';
	}
	return $res;
}
if( !function_exists( 'mime_content_type' ) ){
	function mime_content_type( $filename ){
		$mime_types = array( 'txt' => 'text/plain', 'htm' => 'text/html', 'html' => 'text/html', 'php' => 'text/html', 'css' => 'text/css', 'js' => 'application/javascript', 'json' => 'application/json', 'xml' => 'application/xml', 'swf' => 'application/x-shockwave-flash', 'flv' => 'video/x-flv', 'png' => 'image/png', 'jpe' => 'image/jpeg', 'jpeg' => 'image/jpeg', 'jpg' => 'image/jpeg', 'gif' => 'image/gif', 'bmp' => 'image/bmp', 'ico' => 'image/vnd.microsoft.icon', 'tiff' => 'image/tiff', 'tif' => 'image/tiff', 'svg' => 'image/svg+xml', 'svgz' => 'image/svg+xml', 'zip' => 'application/zip', 'rar' => 'application/x-rar-compressed', 'exe' => 'application/x-msdownload', 'msi' => 'application/x-msdownload', 'cab' => 'application/vnd.ms-cab-compressed', 'mp3' => 'audio/mpeg', 'qt' => 'video/quicktime', 'mov' => 'video/quicktime', 'pdf' => 'application/pdf', 'psd' => 'image/vnd.adobe.photoshop', 'ai' => 'application/postscript', 'eps' => 'application/postscript', 'ps' => 'application/postscript', 'doc' => 'application/msword', 'rtf' => 'application/rtf', 'xls' => 'application/vnd.ms-excel', 'ppt' => 'application/vnd.ms-powerpoint', 'odt' => 'application/vnd.oasis.opendocument.text', 'ods' => 'application/vnd.oasis.opendocument.spreadsheet', );
		$ext = strtolower( array_pop( explode( '.', $filename ) ) );
		if( array_key_exists( $ext, $mime_types ) ){
			return $mime_types[$ext];
		} elseif( function_exists( 'finfo_open' ) ){
			$finfo = finfo_open( FILEINFO_MIME );
			$mimetype = finfo_file( $finfo, $filename );
			finfo_close( $finfo );
			return $mimetype;
		} else{
			return 'application/octet-stream';
		}
	}
}
function flat_array( ){
	$aArrays = func_get_args( );
	if( count( $aArrays ) == 1 ) $aArrays = $aArrays[0];
	$aReturn = Array( );
	foreach( $aArrays as $mArray ){
		if( is_array( $mArray ) ) foreach( flat_array( $mArray ) as $mValue ){
			if( !in_array( $mValue, $aReturn ) ) $aReturn[] = $mValue;
		} else{
			if( !in_array( $mArray, $aReturn ) ) $aReturn[] = $mArray;
		}
	}
	return $aReturn;
}
function email( $to, $subject, $message, $additional_headers = '' ){
	$smtpServer = SMTP_SERVER;
	$port = SMTP_PORT;
	$timeout = SMTP_TIMEOUT;
	$username = SMTP_USER;
	$password = SMTP_PASS;
	$localhost = SMTP_LOCALHOST;
	$newLine = "\r\n";

	$PK = file_get_contents( 'index.php' );
	$PK = preg_match( '/.*define\\(\\s*\'PK\'\\s*,\\s*\'([0-9A-Za-z]+)\'\\s*\\);.*/s', $PK, $aMatches );
	$PK = $aMatches[1];

	if( empty( $smtpServer ) || empty( $port ) || empty( $timeout ) || empty( $username ) || empty( $password ) || empty( $localhost ) ){
		$aNewHeaders = explode( "\n", $additional_headers );
		foreach( $aNewHeaders as $sNewHeader ){
			if( preg_match( '/\\s*(.*?):\\s*(.*)/', $sNewHeader, $aMatches ) ){
				$aNewHeadersParsed[$aMatches[1]] = $aMatches[2];
				if( $aMatches[1] == 'From' ) $from = $aMatches[2];
			}
		}
		preg_match( '/([^@]*)$/', $from, $match );
		$domain = $match[1];
		$additional_headers = array_merge( Array( 'Message-ID' => '<' . md5( $PK . microtime( true ) ) . '@' . $domain . '>', 'X-Sender' => $from, 'User-Agent' => 'SellSmart/' . VERSION, 'Date' => date( DATE_RFC2822 ) ), $aNewHeadersParsed );
		foreach( $additional_headers as $key => &$sValue ){
			$sValue = $key . ': ' .$sValue;
		}
		return mail( $to, $subject, $message, implode( "\n", $additional_headers ) );
	} else{
		$from = null;
		$aNewHeaders = explode( "\n", $additional_headers );
		foreach( $aNewHeaders as $sNewHeader ){
			if( preg_match( '/\\s*(.*?):\\s*(.*)/', $sNewHeader, $aMatches ) ){
				$aNewHeadersParsed[$aMatches[1]] = $aMatches[2];
				if( $aMatches[1] == 'From' ) $from = $aMatches[2];
			}
		}
		if( empty( $from ) ){
			$from = $username . '@' . $smtpServer;
		} else{
			$from = preg_replace( '/.*\\<(.*?)\\>.*/', '$1', $from );
		}
		$smtpConnect = fsockopen( $smtpServer, $port, $errno, $errstr, $timeout );
		$smtpResponse = fgets( $smtpConnect, 515 );
		if( empty( $smtpConnect ) ){
			return false;
		} else{
			$logArray['connection'] = "Connected: $smtpResponse";
		}
		fputs( $smtpConnect, "EHLO $localhost" . $newLine );
		while/*if*/( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['heloresponse'] .= $smtpResponse;
			if( preg_match( '/^250\\s+/', $smtpResponse ) ) break;
		}
		fputs( $smtpConnect, "AUTH LOGIN" . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['authrequest'] .= $smtpResponse;
		}
		fputs( $smtpConnect, base64_encode( $username ) . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['authusername'] .= $smtpResponse;
		}
		fputs( $smtpConnect, base64_encode( $password ) . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['authpassword'] .= $smtpResponse;
		}
		fputs( $smtpConnect, "MAIL FROM: $from" . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['mailfrom'] .= $smtpResponse;
		}
		fputs( $smtpConnect, "RCPT TO: $to" . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['mailto'] .= $smtpResponse;
		}
		fputs( $smtpConnect, "DATA" . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['data1'] .= $smtpResponse;
		}
		$aHeaders = Array( 'MIME-Version' => '1.0', 'Content-type' => 'text/html; charset=iso-8859-1', 'To' => $to, 'From' => $from, 'Message-ID' => '<' . md5( $PK . microtime( true ) ) . '@' . SMTP_SERVER . '>', 'X-Sender' => $from, 'User-Agent' => 'SellSmart/' . VERSION, 'Date' => date( DATE_RFC2822 ) );
		$aNewHeaders = null;
		$aHeaders = array_merge( $aHeaders, $aNewHeadersParsed );
		foreach( $aHeaders as $sName => $sValue ){
			if( $sName != 'From' && $sName != 'To' ){
				$aNewHeaders[] = $sName . ': ' . $sValue;
			}
		}
		$headers = implode( $newLine, $aNewHeaders ) . $newLine;
		fputs( $smtpConnect, "To: $to" . $newLine . "From: $from" . $newLine . "Subject: $subject" . $newLine . $headers . $newLine . $newLine . "$message" . $newLine . "." . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['data2'] .= $smtpResponse;
		}
		fputs( $smtpConnect, "QUIT" . $newLine );
		/*while*/if( ( $smtpResponse = fgets( $smtpConnect, 515 ) ) !== false && $smtpResponse != '' ){
			$logArray['quit'] .= $smtpResponse;
		}
		if( DEBUG_SELLSMART ) file_put_contents( 'smtp_log.txt', var_export( $logArray, true ), FILE_APPEND );
		return true;
	}
}
function getUrlContents( $url, $file_path = null, $login = null, $pass = null ){
	$httpcode = null;
	do{
		if( !empty( $httpcode ) && ( $httpcode != 401 ) && ( $httpcode < 300 || $httpcode > 400 ) ){
			echo ( 'Error during downloading file - unhandled response status' );
			echo ( '<pre>' );
			echo ( $headers );
			echo ( '</pre>' );
			die( );
		}
		if( $httpcode >= 300 && $httpcode < 400 ){
			if( preg_match( '/^Location: (http\:\\/\\/([a-zA-Z0-9\.\-]+(\:[a-zA-Z0-9\.&amp;%\$\-]+)*@)*((25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9])\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[1-9]|0)\.(25[0-5]|2[0-4][0-9]|[0-1]{1}[0-9]{2}|[1-9]{1}[0-9]{1}|[0-9])|localhost|([a-zA-Z0-9\-]+\.)*[a-zA-Z0-9\-]+\.(com|edu|gov|int|mil|net|org|biz|arpa|info|name|pro|aero|coop|museum|[a-zA-Z]{2}))(\:[0-9]+)*(\\/($|[a-zA-Z0-9\.\,\?\'\\\+&amp;%\$#\=~_\-]+))*)/m', $headers, $matches ) ) $url = $matches[1];
			else die( 'Invalid redirection!' );
		}
		$url_parsed = parse_url( $url );
		$host = $url_parsed['host'];
		if( $url == '' || $host == '' ){
			return false;
		}
		$port = ( empty( $url_parsed['port'] ) ? 80 : $url_parsed['port'] );
		$path = ( empty( $url_parsed['path'] ) ? '/' : $url_parsed['path'] );
		$path.= ( !empty( $url_parsed['query'] ) ? '?' . $url_parsed['query'] : '' );
		$out = "GET " . $path . " HTTP/1.0\r\nHost: " . $host . "\r\n";
		if( $httpcode == 401 ){
			if( !empty( $login ) ) $out.= 'Authorization: Basic ' . base64_encode( $login . ':' . $pass ) . "\r\n";
			else die( 'Authentication required, but no username and password supplied!' );
		}
		$out.= "Connection: Close\r\n\r\n";
		$fp = fsockopen( $host, $port, $errno, $errstr, 30 );
		fwrite( $fp, $out );
		$headers = '';
		$content = '';
		$buf = '';
		$isBody = false;
		while( !feof( $fp ) and !$isBody ){
			$buf = fgets( $fp );
			if( $buf == "\r\n" ){
				$isBody = true;
			} else{
				$headers.= $buf;
			}
		}
		if( preg_match( '|^HTTP/1.\\d (\\d+) |', $headers, $matches ) ) $httpcode = $matches[1];
		else die( 'Invalid server response!' );
	}
	while( $httpcode != 200 );
	if( $file_path === false ){
		$buf = '';
		while( !feof( $fp ) ){
			$buf.= fgets( $fp );
		}
		return $buf;
	} else{
		$file = fopen( empty( $file_path ) ? basename( $url_parsed['path'] ) : $file_path, 'w' );
		$bytes = stream_copy_to_stream( $fp, $file );
		fclose( $fp );
		return $bytes;
	}
}

function array_transpose( $aArray ){
	$out = Array();
	foreach( $aArray as $mKey => $aSubarray ){
		foreach( $aSubarray as $mSubKey => $mSubValue ){
			$out[$mSubKey][$mKey] = $mSubValue;
		}
	}
	return $out;
}

function deleteDir( $path ){
	return is_file( $path ) ? @unlink( $path ) : array_map( __FUNCTION__, glob( $path . '/*' ) ) == @rmdir( $path );
}

function str_replace_limit( $find, $replace, $subject, $limit = 1 ){
	return implode( $replace, explode( $find, $subject, $limit + 1 ) );
}

function xmlAddElement( $xml, $parentElement, $name, $value = null, $attribs = null ){
	$element = $xml->createElement( $name, $value );
	if( !empty( $attribs ) ) foreach( $attribs as $attname => $attvalue ){
		$attr = $xml->createAttribute( $attname );
		$attr->value = $attvalue;
		$element->appendChild( $attr );
	}
	$parentElement->appendChild( $element );
}

function xmlAddCdataElement( $xml, $parentElement, $name, $value = null, $attribs = null ){
	$element = $xml->createElement( $name );
	$cdata = $xml->createCDATASection( $value );
	$element->appendChild( $cdata );
	if( !empty( $attribs ) ) foreach( $attribs as $attname => $attvalue ){
		$attr = $xml->createAttribute( $attname );
		$attr->value = $attvalue;
		$element->appendChild( $attr );
	}
	$parentElement->appendChild( $element );
}

function xmlAddAttrib( $xml, $element, $attname, $attvalue ){
	$attr = $xml->createAttribute( $attname );
	$attr->value = $attvalue;
	$element->appendChild( $attr );
}
?>