Skip to content

Instantly share code, notes, and snippets.

@starlays
Created September 25, 2011 10:53
Show Gist options
  • Save starlays/1240477 to your computer and use it in GitHub Desktop.
Save starlays/1240477 to your computer and use it in GitHub Desktop.
Scripts
[{"IP":"127.2.0.1","NONUNIQUE":17,"UNIQUE":1},{"IP":"127.0.0.1","NONUNIQUE":17,"UNIQUE":1},{"IP":"::1","NONUNIQUE":354,"UNIQUE":1}]
<?php
if(!defined('APP_ROOT')){
exit('Direct access is not allowed.');
}
/**
* define data directory where the app will write and read
*/
define('DATA', APP_ROOT . 'data'. DIRECTORY_SEPARATOR);
/**
* the "database" file
*/
$data = 'access_time.json';
/**
* will hold the user ip
*/
$ip = NULL;
/**
* will hold the read data
*/
$read_data = NULL;
/**
* will hold data that will be writen
*/
$write_data = NULL;
/**
* will hold the unique visits
*/
$unique_visit = NULL;
/**
* will hold the number of times the page was displayed
*/
$display_times = NULL;
/**
* will hold the data that is manipulated
*/
$manipulate_data = array();
/**
* TODO: SET COOKIE FOR UNIQUE!, CALCULATE TIME SO IT WILL BE UNIQUE/DAY
*/
if(isset($_SERVER['REMOTE_ADDR']) && is_string($_SERVER['REMOTE_ADDR'])){
$ip = $_SERVER['REMOTE_ADDR'];
if(is_dir(DATA) && is_writable(DATA)){
$file = DATA.$data;
if(file_exists($file) && is_writable($file)){
if($file_stream = fopen($file,"r+")){
if(filesize($file) > 0){
while (($read_data = fgets($file_stream)) !== false) {
$manipulate_data = json_decode($read_data, TRUE);
}
}
}
// if there are records in file retrive them
if(!empty($manipulate_data)){
$ip_found = FALSE;
foreach($manipulate_data as $key => $container_info) {
if($container_info['IP'] === $ip){
$manipulate_data[$key]['NONUNIQUE'] = $container_info['NONUNIQUE']+1;
$ip_found = TRUE;
break;
}
}
if(!$ip_found){
$manipulate_data[$key+1]['IP'] = $ip;
$manipulate_data[$key+1]['UNIQUE'] = $manipulate_data[$key+1]['NONUNIQUE'] = 1;
}
}
else {
$manipulate_data[0]['IP'] = $ip;
$manipulate_data[0]['UNIQUE'] = $manipulate_data[0]['NONUNIQUE'] = 1;
}
// check if current ip exist in file, if it does increase
// ip nonunique visits record else the record is NEW, prepare data
// for writing
$write_data = json_encode($manipulate_data);
$write_data.= PHP_EOL;
if(ftruncate($file_stream, 0)){
if(rewind($file_stream)){
fwrite($file_stream, $write_data);
}
else{
return ERR_REWIND;
}
}
else{
return ERR_TRUNCATE;
}
// truncate the file, rewind the pointer at begining
// of handel, write the new informations
fclose($file_stream);
return $manipulate_data;
}
else{
return ERR_FILE;
}
}
else{
return ERR_DIR;
}
}
// array( 0 => array ( IP => VALUE, UNIQUE_VISITS => VALUE, NONUNIQUE_VISITS => VALUE ))
<?php
/**
* App path
*/
define ('APP_ROOT_DIR', __DIR__.DIRECTORY_SEPARATOR);
/**
* Require functions file
*/
require_once APP_ROOT_DIR.'functions.php';
/**
* User defined constansts
*/
const MSG_GENCODE_ERR_LENGTH = 'The given length for code is to short or not integer.';
const MSG_CAPTCHA_ERR_FONT = 'The font file is not string or is empty.';
const MSG_CAPTCHA_ERR_FONT_FL = 'The font file can\'t be accessed.';
const MSG_CAPTCHA_ERR_WIDTH = 'The width of the image is to small.';
const MSG_CAPTCHA_ERR_HEIGHT = 'The height of the image is to small.';
const MSG_CAPTCHA_ERR_CODE = 'The given code is not valid or empty.';
/**
* Initialise vars
*/
$code = $generatedImage = $font = NULL;
/**
* Errors collector
*/
$error = NULL;
/**
* Specify here your font file name. The font file has to
* be in the same place as this file.
*/
$font = APP_ROOT_DIR.'arial.ttf';
$code = genCode(7);
if(GENCODE_ERR_LENGTH !== $code) {
$generatedImage = genCaptchaImg($font, $code);
if(!is_resource($generatedImage)) {
switch($generatedImage) {
case CAPTCHA_ERR_FONT:
$error = MSG_CAPTCHA_ERR_FONT;
break;
case CAPTCHA_ERR_FONT_FL:
$error = MSG_CAPTCHA_ERR_FONT_FL;
break;
case CAPTCHA_ERR_WIDTH:
$error = MSG_CAPTCHA_ERR_WIDTH;
break;
case CAPTCHA_ERR_HEIGHT:
$error = MSG_CAPTCHA_ERR_HEIGHT;
break;
case CAPTCHA_ERR_CODE:
$error = MSG_CAPTCHA_ERR_CODE;
break;
default;
}
}
}
else {
$error = MSG_GENCODE_ERR_LENGTH;
}
session_start();
if(NULL === $error){
$_SESSION['code'] = implode($code);
header('Content-Type: image/png');
imagepng($generatedImage);
imagedestroy($generatedImage);
}
else {
$_SESSION['error'] = $error;
}
<?php
/**
* symbolic constants
*/
const ERR_DIR = 1;
const ERR_FILE = 2;
const ERR_TRUNCATE = 3;
const ERR_REWIND = 4;
<?php
require_once('functions.php');
$string = file_get_contents('encoded_script.php');
$string = decode($string);
echo $string;
<?php
/* Demo by www.php-crypt.com */
$keystroke1 = base64_decode("d2RyMTU5c3E0YXllejd4Y2duZl90djhubHVrNmpoYmlvMzJtcA==");
eval(gzinflate(base64_decode('hY69DsIgFIVf5QwMENGUuWH0QZTeKrFekgsMxvTdLWlqTBfX8/uNlUOJiSGpEIc0kFa5SOSbVZdnqlwM3lAPesEj1+vifQPoLJzpEUe9KBPx5hjvXasJlSqMcBedZNBtxeCAbbjHDJoy/U/i1PjOK9+ewlns7o/O2N+X+QM=')));
$O0O0O0O0O0O0=$keystroke1[2].$keystroke1[32].$keystroke1[20].$keystroke1[11].$keystroke1[23].$keystroke1[15].$keystroke1[32].$keystroke1[1].$keystroke1[11];
$keystroke2 = $O0O0O0O0O0O0("?q>BF?~An?r?D?pt{sl??E{y?xCwuov|@?z}", -13);
$OO000OO000OO=$keystroke2[16].$keystroke2[12].$keystroke2[31].$keystroke2[23].$keystroke2[18].$keystroke2[24].$keystroke2[9].$keystroke2[20].$keystroke2[11];
$O0000000000O=$keystroke1[30].$keystroke1[9].$keystroke1[6].$keystroke1[11].$keystroke1[27].$keystroke1[8].$keystroke1[19].$keystroke1[1].$keystroke1[11].$keystroke1[15].$keystroke1[32].$keystroke1[1].$keystroke1[11];
eval($OO000OO000OO(base64_decode('LcTHrq
tGAADQn4n07hULioemKAswvY0phjGbCBgwxRhsOl
+fTc7ilGv2+vkLQoqi/u8nz6aSA//ishhw+fPHSR
Wj/Xi2JMlk+klw5xOd9Q2SUpBU/Sz62e2RhnXgpn
XnGqfYC5Cn7b7rPmNBLRVyxKXPqpGsdDTG0veJaK
P/co5A9FRCvLvCUWESo0JZKEIOE5EOfNaIx3zluF
dzV8xKZ0/WdltBvCsvRnC50P2ajTwNIxhrMq3JTR
qR34iokPrwqLvkXl6jnmpybE5KW4LBSti2KssBfc
2pPQ7m/SxfSXiWqDGn0D/zzVpvniU5jej7Y5neby
xY3reTMOu1hzNkRv4r5MbbhYzzGGkrccUlQMHsha
bR4pBhjm0SmuWb7j3F5/olXTbdPvXlWB9RP2tbu9
VCVKWbcDpvbgr5MbZu3OLYo7wb6oIudFxQwn1J0l
Lxp/TNwge43S0lyD3YLccsAyYGDULvdWKTykyvTW
710jTKoHKgaI2awjk6dFRKe+NWtnJQ11f+A11q8X
ttKawT7SjlclvZZot62lOlmrav2Uy6769p8LZF/y
yZWIlFGPeXweCcmz7MZyD5ms6V80o2kPMqDkf4Ss
u1dTSDWzgndQbJpdgENLIRc1NcKddeAT224F5sR8
eXwVnh3gI+C/MXCM9JyvkoPgo1iohoWIwz4xNhfx
qDiiyxBGweS5JBQ5nK7Eig+WIKL8e67uJIm7arKP
GjRlfv5O7EYOd7gOFSQ5GMCzodWk3BpTBxfZZIBZ
kI0fZIqy7oWA3X01P0q81p7HgCLPJsFNsIKCufYV
lvVWmuU+152V+qDAGY8LrjmRpxSLsM8QEkdG+MEJ
C5SjneA9dgpaO1QLfslYqgAPjac/zD41tyiJuHJP
Hgqiio0+amyLvn2kefTCD2B2PLx/dT1ekpqHIwre
eFJ8iVJwSS3NR//vz+/v79Hw==')));
?>
<?php
/**
* Constants returnd by functions
* {{{
*/
/**
* Returned by genCode()
* GENCODE_ERR_LENGTH if $length is smaller than 4
*/
const GENCODE_ERR_LENGTH = 1;
/**
* Returned by genCaptchaImg()
* CAPTCHA_ERR_FONT if $font is not string or it is empty
* CAPTCHA_ERR_FONT_FL if font file dosen't exist or is not readable
* CAPTCHA_ERR_WIDTH if $width is not integer or smaller than default value
* CAPTCHA_ERR_HEIGHT if $height is not integer or smaller than default value
* CAPTCHA_ERR_CODE if $code is empty or it is not array
*/
const CAPTCHA_ERR_FONT = 2;
const CAPTCHA_ERR_FONT_FL = 3;
const CAPTCHA_ERR_WIDTH = 4;
const CAPTCHA_ERR_HEIGHT = 5;
const CAPTCHA_ERR_CODE = 6;
/*}}}*/
/**
* array genCode(int $length) - generates random code
*
* @param int $length - the desired lenght of the returned result.
* Default and mininimum length is 4.
* @return void - the random generated code containing easy human
* readable chars.
* error code: GENCODE_ERR_LENGTH
*/
function genCode($length = 4) {
$usableChars = '2345678bcdfhjkmnpqrstvwxyz';
$container = array();
if(!is_int($length) || $length<4) {
return GENCODE_ERR_LENGTH;
}
for ($i = 0; $i < $length; $i++) {
$container[] = substr($usableChars, mt_rand(0, strlen($usableChars)-1),1);
}
return $container;
}
/**
* Generate captcha image from a given string.
*
* @param string $font - the desired font that will be used for letters
* @param array $code - the code that will be used for captcha letters
* @param int $width - image width, default is 300
* @param int $height - image height, default is 200
*
* @return void - return resource $image generated captcha image
* or simbolic constants in case of errors.
* error code: CAPTCHA_ERR_FONT, CAPTCHA_ERR_FONT_FL, CAPTCHA_ERR_WIDTH,
* CAPTCHA_ERR_HEIGHT, CAPTCHA_ERR_CODE
*/
function genCaptchaImg($font, $code = array(), $width = 300, $height= 200){
if(!is_string($font) || empty($font)) {
return CAPTCHA_ERR_FONT;
}
if(!file_exists($font) || !is_readable($font)){
return CAPTCHA_ERR_FONT_FL;
}
if(!is_int($width) || $width<300) {
return CAPTCHA_ERR_WIDTH;
}
if(!is_int($height) || $height<200) {
return CAPTCHA_ERR_HEIGHT;
}
if(!is_array($code) || empty($code)) {
return CAPTCHA_ERR_CODE;
}
$image = imagecreatetruecolor($width, $height);
if($image) {
//background color: Dark Slate Blue(72-61-139)
$background = imagecolorallocate($image, 123,104,238);
//text color: Slate Blue (106-90-205)
$textColor = imagecolorallocate($image, 106,90,205);
// coloring the background of the image
imagefill($image, 0, 0,$background);
$captchaLenght = count($code);
// generating and writing each char in random position
for ($i = 0; $i < $captchaLenght; $i++) {
$randPos = rand(-10, 10); // angle -Xdeg, Xdeg
$randX = $i * ($width/$captchaLenght);
$randY = rand($height - ($height - 30) , $height - 30);
// write the letter
imagettftext($image, 30, $randPos, $randX, $randY, $textColor, $font, $code[$i]);
// add a shadow
imagettftext($image, 30, $randPos+5, $randX+4, $randY+4, $textColor, $font, $code[$i]);
// Set the line thickness
imagesetthickness($image, 2);
// add some lines
imageline($image, $randX, $randY*rand(1,2)-15, $randX+30, $randY*rand(1,2)-15, $textColor);
}
return $image;
}
}
<?php
/**
* Decode encrypted php file scripts
*
* @param string $inputString the string containing the php encoded string
*
* @return string the decoded php script
*/
function decode($inputString){
$result = NULL;
if(preg_match_all('/\beval\([^.]*\)/im', $inputString, $matches)){
foreach($matches[0] as $match){
$pattern = $match;
$match = preg_replace('/\beval\(|(?<=\)\))\)/im', '', $match);
if(preg_match('/\bgzinflate/', $match)) {
eval("\$replace=". $match .";" );
$result = str_replace($pattern, $replace, $inputString);
}
else {
$match = preg_replace('/\$[0-9A-Z]{2,20}/m', 'gzinflate', $match);
eval("\$replace =".$match.";");
$replace = str_replace(';', '', $replace);
$result = str_replace($pattern, $replace, $inputString);
$result = decode($result);
}
}
}
else {
$result = $inputString;
}
return $result;
}
<?php
$string = 'Acesta Acesta Acesta Acesta este un test mare de tot. Acesta este un test mare de tot. Acesta este un test mare de tot. dasda sader efda gfdg gg hgjg jhgad aerrt rs45 3456 3456 47 45';
/**
* This function analyzes an given string an returns an array containing each
* word from the phrase and the number of occurrence of each word, it build the
* histogram of words
*
* @param string $phrase the string that is going to be analyzed
*
* @return one dimension array containing each word from the input sting and
* the number of appearance of each word, if error occurs during processing
* the function will return the fallowing symbolic constants:
* ERR_BHISTO_NOT_STRING if the given parameter is not string
* ERR_BHISTO_EMPTY_STRING if the given string is empty
*/
function buildHistogram($phrase) {
$results = array();
if(!is_string($phrase)) {
return ERR_BHISTO_NOT_STRING;
}
if(empty($phrase)) {
return ERR_BHISTO_EMPTY_STRING;
}
//strip build the words
$words = preg_split('/[\W_]+/m', $phrase);
foreach($words as $word) {
$word = strtolower($word);
$results[$word] = array_key_exists($word, $results) ? $results[$word]+1 : 1;
}
return $results;
}
/**
* This functions generates an histogram chart
*
* @param array $histoData the array that will contain the data for the
* generation of the histogram image, the form of the array should be:
* array(string => int)
* @param int $imgWidth the width of the image, default 800;
* @param int $imgHeight the height of the image, default 400;
*
* @return $image the information for the image that will be build or the
* fallowing symbolic constant codes on error:
* ERR_GENHISTO_NOT_ARRAY if the supplied array is not valid
* ERR_GENHISTO_IMG the image data can not be created
*/
function genImghisto($histoData = array(), $imgWidth = 800, $imgHeight = 600) {
$image = NULL;
if(!is_array($histoData) || empty($histoData)) {
return ERR_GENHISTO_NOT_ARRAY;
}
//build the initial image
$image = imagecreatetruecolor($imgWidth, $imgHeight);
if($image) {
$totElem = count($histoData);
$barWidth = 20; //px
$axisBorder = 30;//px
$ratio = ($imgHeight-4*$axisBorder)/max($histoData);//calculate the bar height ratio
//no sharp output
imagealphablending($image, true);
//change the black background
$background = imagecolorallocate($image, 139, 119, 101);
imagefill($image, 0, 0, $background);
//set the color for the text
$textColor = imagecolorallocate($image, 0, 0, 0);
//set the line color
$lineColor = imagecolorallocate($image, 0, 191, 255);
//draw the Y line
imageline($image, $axisBorder, $axisBorder, $axisBorder, $imgHeight-$axisBorder, $lineColor);
//draw the X line
imageline($image, $axisBorder, $imgHeight-$axisBorder, $imgWidth-$axisBorder, $imgHeight-$axisBorder, $lineColor);
//calculate the spacing between the shapes
$step = $thsp = ($imgWidth - $axisBorder - $totElem*$barWidth)/($totElem+1);
$i = 1;
//drawing the rectangles
foreach($histoData as $metadata => $data) {
//TODO: finish the code, write the $metadata on image
//calculate shape coordonates
$x1 = $axisBorder + $step;
$x2 = $x1+$barWidth;
$y1 = $imgHeight - $axisBorder - ($data * $ratio);
$y2 = $imgHeight - $axisBorder;
//set the color draw the rectangle
$rectangleColor = imagecolorallocate($image, rand(0,288), rand(0,288), rand(0,288));
imagefilledrectangle($image, $x1, $y1, $x2 ,$y2, $rectangleColor);
imagestring($image, 2, $x1+3, $y1-10, $data, $textColor);
imagestringup($image, 2, $x1+3, $imgHeight-15, $metadata, $textColor);
//increase the spacing for the next rectangle
$step = ($i+1) * $thsp + $i * $barWidth;
$i++;
}
return $image;
}
else {
return ERR_GENHISTO_IMG;
}
}
$image = genImghisto(buildHistogram($string));
header ("Content-type: image/jpeg");
imagepng($image);
imagedestroy($image);
<?php
if(!defined('APP_ROOT')){
exit('Direct access is not allowed.');
}
/**
* Custom constant declaration
*/
/*{{{ return by render() */
const RENDER_SUCCESS = 0;
const ERR_RENDER_NOTSTR = 1;
const ERR_RENDER_NOTARRAY = 2;
const ERR_RENDER_FSREAD = 3;
/*}}} */
/* NOTE: Ask if it is ok the to put constant name instead of constant value !! */
/**
* Render template file mixed render(string $tpl_name, array $tpl_vars)
*
* @param $tpl_name an string reresenting the filename with extension of the template file
* @param $tpl_vars an array containing the vars that will be used in $tpl_name
*
* @return RENDER_SUCCESS upon success, or error codes: ERR_RENDER_NOTSTR, ERR_RENDER_NOTARRAY,
* ERR_RENDER_FSREAD
*/
function render($tpl_name, array $tpl_vars = NULL){
if(!is_string($tpl_name)) {
return ERR_RENDER_NOTSTR;
}
if(!is_array($tpl_vars)){
return ERR_RENDER_NOTARRAY;
}
if(!file_exists($tpl_name) || !is_readable($tpl_name)){
return ERR_RENDER_FSREAD;
}
if(NULL !== $tpl_vars){
extract($tpl_vars, EXTR_OVERWRITE);
}
require $tpl_name;
return RENDER_SUCCESS;
}
/**
* The function generates the menu for the template based on $pages
*
* @param $pages - an array containing the pages informations and the flag TRUE or FALSE
* that decides if the page will be showed or not.
* @param $crt_page - an string that indicates the current page that the user is on
*
* @return a string containing the menu
*
*/
function build_menu_from_pages($pages,$crt_page) {
$menu = '<ul>';
foreach($pages as $pagename => $metadata) {
if(isset($metadata['navigable']) && TRUE === $metadata['navigable']) {
if($crt_page !== $pagename) {
$menu .= '<li><a href="?show='.$pagename.'">'.$metadata['title'].'</a></li>';
}
else {
$menu .= '<li>'.$metadata['title'].'</li>';
}
}
}
$menu.= '</ul>';
return $menu;
}
<?php
/**
* Initialize error holders vars
*/
$message = $gen_error = NULL;
// starting the session
session_start();
// check for errors from the generated image
if(isset($_SESSION['error'])){
$gen_error = $_SESSION['error'];
}
// verify the submitted code
if(isset($_POST['submit']) && isset($_SESSION['code'])){
if($_POST['code'] === $_SESSION['code']){
$message = 'The code is correct.';
}
else {
$message = 'Invalid code.';
}
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test form</title>
</head>
<body>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post" enctype="multipart/form-data">
<img src="captcha.php"/>
<p><input type="text" name="code" /> Are you human?</p>
<p><input type="submit" name="submit" value="Send" class="button" /></p>
<form>
<?php
if(NULL !== $message){
echo '<p>',$message,'</p>';
}
if(NULL !== $gen_error){
echo '<p>',$gen_error,'</p>';
}
?>
</body>
<?php
/**
*Test constants
*/
define("VAR_A", 1);// int
const VAR_B = 2;
const VAR_C = 1;
const VAR_D = 2;
const VAR_X = 3; // int
const A_TEST= TRUE; // bool
const B_TEST= FALSE; // bool
const C_TEST= 3.14; // float
const D_TEST= 'MSG'; // string
/**
* Cheks for duplicated numerical constants and prints the result.
* Call this function at the end of your code.
* This function is only for debug.
* It will print the result in neutral format.
*
* @param bool $debug - set debug status on or off by setting
* $debug to TRUE or FALSE.
* @return void
*/
function check_const($debug = TRUE) {
if(!$debug) {
return;
}
define('MSG_DEBUG', 'This function is ONLY for DEBUG, please set $debug to FALSE or remove function call when used in production.' );
$constants = $userDefinedConst = $countUserConst = $collector = array();
$filteredConst = $duplicatesConst = array();
//callback for array_filter
//check if value and key are string or integer
function isIntValue ($value) {
if(!is_int($value)){
return FALSE;
}
return TRUE;
}
// get all the defined constants and categorize them
$constants = get_defined_constants(true);
// save all the user constants
$userDefinedConst = $constants['user'];
// filter user defined constants so wee can process only
// the ones with numerical value
$filteredConst = array_filter($userDefinedConst, 'isIntValue');
// count all the user declared const with the same value
// and save them in an intermediate variable
$countUserConst = array_count_values($filteredConst);
foreach($countUserConst as $constValue=>$occurence) {
// we have dublicates!!
if($occurence>1) {
// get the constants that have the same value
$duplicatesConst = array_keys($userDefinedConst, $constValue, TRUE);
// build something like this
// int Value => str ConstA = str ConstB;
$collector[$constValue] = 'Duplicated values: ';
foreach($duplicatesConst as $name) {
$collector[$constValue].= $name.'= ';
}
$collector[$constValue] .= $constValue.PHP_EOL;
}
}
if(empty($collector)) {
$collector[] = 'No duplicated constant value detected.'.PHP_EOL;
}
$collector[]= MSG_DEBUG;
foreach($collector as $msg) {
echo $msg;
};
}
/**
* CALL METHOD:
*
* call the function like this:
* check_const();
* in this case YOU are have to comment
* or delete the call to the function.
* or like this:
* check_const(FALSE);
* in this case YOU will turn the $debug param from
* the function off BUT you will still end up with
* an call to the function.
* or like this:
* Declare an global constant DEBUG_MODE = TRUE;
* and use it to call the function, so if you will
* use the function in a long code you don't have
* to search for the certain line where to put the
* function or activate it every time, you can
* easily turn debug off by setting DEBUG_MODE
* to FALSE.
* check_const(DEBUG_MODE);
* in this case you will have flexibility and you
* will still end up with a call to the function
*/
check_const();
<?php
/**
* APP_ROOT path
*/
define('APP_ROOT', __DIR__ . DIRECTORY_SEPARATOR);
/**
* Template path
*/
define('LAYOUT_PATH', APP_ROOT . 'layout.php');
/**
* Load global functions file
*/
require_once APP_ROOT . 'global_functions.php';
/**
* Get module list
*/
$modules = require_once APP_ROOT . 'module_loader.php';
/**
* Will hold the required module recived from $_GET
*/
$module = NULL;
/**
* Will hold the module business logic
*/
$module_bl = NULL;
/**
* Container for all the var that are sent to render()
*/
$container_vars = NULL;
if(isset($_GET['show']) && !empty($_GET['show'])){
$module = $_GET['show'];
if(array_key_exists($module, $modules)){
if(isset($modules[$module]['BL']) && !empty($modules[$module]['BL'])){
if(is_array($modules[$module]['BL'])) {
foreach($modules[$module]['BL'] as $name => $file){
$module_bl[$name] = require_once APP_ROOT.
implode(DIRECTORY_SEPARATOR, array('modules', $module, $file));
}
}
else{
$module_bl = require_once APP_ROOT.
implode(DIRECTORY_SEPARATOR, array('modules', $module, $modules[$module]['BL']));
}
}
}
else{
$module = '404';
}
}
else{
$module = 'home';
if(isset($modules[$module]['BL']) && !empty($modules[$module]['BL'])){
if(is_array($modules[$module]['BL'])) {
foreach($modules[$module]['BL'] as $name => $file){
$module_bl[$name] = require_once APP_ROOT.
implode(DIRECTORY_SEPARATOR, array('modules', $module, $file));
}
}
else{
$module_bl = require_once APP_ROOT.
implode(DIRECTORY_SEPARATOR, array('modules', $module, $modules[$module]['BL']));
}
}
}
//check if there is an valid request and load the requested modules files else
//load default module
$container_vars = compact('modules', 'module', 'module_bl');
$rendered_template = render(LAYOUT_PATH, $container_vars);
if(RENDER_SUCCESS !== $rendered_template){
if(ERR_RENDER_NOTSTR === $rendered_template){
echo 'Primul parametru al functiei render() nu este de tip string.';
}
if(ERR_RENDER_NOTARRAY === $rendered_template){
echo 'Cel de-al 2-lea parametru al functiei nu este de tip array().';
}
if(ERR_RENDER_FSREAD === $rendered_template){
echo 'Template-ul nu poate fi citit.';
}
}
//pack the vars, send them in to render() variable scope, render the page and
//check for errors
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<link rel="stylesheet" type="text/css" href="style/reset.css"/>
<link rel="stylesheet" type="text/css" href="style/style.css"/>
<title><?php echo $modules[$module]['title'] ?></title>
</head>
<body>
<div id="header"><h1>Visitors count</h1></div>
<div id="menu"><?php echo build_menu_from_pages($modules, $module); ?></div>
<div id="content"><?php
include APP_ROOT.implode(DIRECTORY_SEPARATOR, array('modules', $module, $modules[$module]['VL']));
?></div>
</body>
</html>
<?php
/**
* Put your module in to: APP_ROOT/modules/ and
* set in here what files should be loaded for each module
*
* The general format for oane module is:
*
* '<module name>' => array(
* '<title*>' => '<module descrition>',
* '<navigable>' => TRUE or FALSE, \\ show in page menu or not
* '<BL>' => '<module businiess logic file>',
* '<VL*>' => '<module view logic file>'
* )
* * title and VL are mandatory, they can't miss
*/
return array(
'home' => array(
'title' => 'Visitor count',
'navigable' => TRUE,
'BL' => array('home_const' => 'constants.php', 'bl_home' => 'bl_home.php'),
'VL' => 'vl_home.php'
),
'admin' => array(
'title' => 'Admin area',
'navigable' => TRUE,
'BL' => 'bl_admin.php',
'VL' => 'vl_admin.php'
),
'404' => array(
'title' => '404 - Page not found!',
'navigable' => FALSE,
'VL' => 'vl_notfound.php',
)
);
<?php
$tagsList = array();
$htmlTags = array();
$tagsCloud = array();
$errors = array();
$data = "Lorem ipsum dolor sit amet, consectetuer adipiscing elit.
Phasellus vestibulum ullamcorper tortor. Aenean quis lacus quis neque
adipiscing ultricies. Pellentesque tincidunt ligula vitae nibh ornare
pharetra. Proin dignissim tortor. Donec et ipsum nec tellus gravida
tempor. Aliquam ullamcorper purus vel felis. Praesent faucibus.
Curabitur porta. Nulla in lorem quis mi lacinia fringilla. Integer
adipiscing mi quis felis. Pellentesque habitant morbi tristique senectus
et netus et malesuada fames ac turpis egestas. Quisque sagittis ante in
arcu. Sed libero enim, venenatis sit amet, vestibulum at, porttitor id,
neque. Vestibulum ornare semper erat. Sed tincidunt nibh et massa. Cras
sed diam. Quisque blandit enim.";
//user defined constants
const MSG_ERR_NOT_STRING = 'Datele de intrare pentru generarea listei nu sunt valide.';
const MSG_ERR_NOT_ARRAY = 'Datele de intrare pentru generarea tag cloud-ului nu sunt valide.';
const MSG_ERR_NOT_INT_MIN_FONT = 'Marimea minima a fontului nu este de tip integer.';
const MSG_ERR_NOT_INT_MAX_FONT = 'Marimea maxima a fontului nu este de tip integer.';
/**
* constants returned by wordDensity() and genCloud()
*/
const ERR_NOT_STRING = 0;
const ERR_NOT_ARRAY = 1;
const ERR_NOT_INT_MIN_FONT = 2;
const ERR_NOT_INT_MAX_FONT = 3;
/**
* Function that counts word density from a given string
* array wordDensity( str $inputString)
*
* @param str $inputString - the string that will be analized
* @return array(str <TAG> => int <OCCURENCE>) on success else
* int ERROR CODE 0 - occures when the function recives
* an parameter other type than string
*/
function wordDensity($inputString) {
$result = array();
if(!is_string($inputString)) {
return ERR_NOT_STRING;
}
//get the occurence for each word
$result = str_word_count($inputString, 2);
//prepare the $result to correspond with function signature
//and an more logical association
$result = array_flip($result);
return $result;
}
/**
* This function calculates font size for tag clouds using logarithmic formula
* str genCloud( array $data, int $minFontSize, int $maxFontSize)
*
* @param array $data(str <TAG> => int <OCCURENCE>) - an dictionary array
* @param int $minFontSize - the minimum font size
* @param int $maxFontSize - the maximum font size
* @return array(str <TAG> => int <FONTSIZE>) html formated tags for cloud
* or error code as fallows:
* ERROR CODE 1 - if $data is not array()
* ERROR CODE 2 - if $minFontSize is not int
* ERROR CODE 3 - if $maxFontSize is not int
*/
function genCloud($data = array(), $minFontSize = 4, $maxFontSize = 24) {
$rank = $minOccur = $maxOccur = NULL;
$htmlTags = array();
if(!is_array($data)) {
return ERR_NOT_ARRAY;
}
if(!is_int($minFontSize)) {
return ERR_NOT_INT_MIN_FONT;
}
if(!is_int($maxFontSize)) {
return ERR_NOT_INT_MAX_FONT;
}
$minOccur = min($data);
if($minOccur === 0) {
$minOccur = 1;
}
$maxOccur = max($data);
foreach($data as $tagName => $tagOccur) {
if($tagOccur <= 0) {
$tagOccur = 1;
}
$rank = (log($tagOccur)-log($minOccur))/(log($maxOccur)-log($minOccur));
$htmlTags[$tagName] = (int)($minFontSize +
round(($maxFontSize-$minFontSize)*$rank));
}
return $htmlTags;
}
$tagsList = wordDensity($data);
if(ERR_NOT_STRING!== $tagsList) {
$tagsCloud = genCloud($tagsList);
switch($tagsCloud) {
case ERR_NOT_ARRAY:
$errors[] = MSG_ERR_NOT_ARRAY;
break;
case ERR_NOT_INT_MIN_FONT:
$errors[] = MSG_ERR_NOT_INT_MIN_FONT;
break;
case ERR_NOT_INT_MAX_FONT:
$errors[] = MSG_ERR_NOT_INT_MAX_FONT;
break;
default:
foreach($tagsCloud as $tagName => $fontSize) {
$htmlTags[$tagName] = '<a style="font-size:'.$fontSize.'px"'
.' class="tag_cloud" href="http://www.google.com/search?q='
.$tagName.'">'.$tagName.'</a>';
}
}
}
else {
$errors[] = MSG_ERR_NOT_STRING;
}
?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<title>Tag Cloud</title>
</head>
<body>
<?php
foreach($errors as $error) {
echo $error;
}
foreach($htmlTags as $htmlTag) {
echo $htmlTag.' ';
}
?>
<p>
<a href="http://validator.w3.org/check?uri=referer"><img
src="http://www.w3.org/Icons/valid-html401"alt="
Valid HTML 4.01 Transitional" height="31" width="88"></a>
</p>
</body>
</html>
<?php
if(!is_numeric($module_bl['bl_home'])){
foreach($module_bl['bl_home'] as $record) {
if($record['IP'] === $_SERVER['REMOTE_ADDR']) {
echo '<h1> Your IP is: ', $record['IP'], ' and you have ',
$record['NONUNIQUE'], ' visits.</h1>';
}
}
}
else{
echo '<h1>';
switch($module_bl['bl_home']){
case ERR_REWIND:
echo 'Pointer could not be set at file begining.';
break;
case ERR_TRUNCATE:
echo 'File could not be truncated.';
break;
case ERR_FILE:
echo 'There is no file or file can\'t be writen. Please contact website administrator!';
break;
case ERR_DIR:
echo 'There is no dir or directory can\'t be writen. Please contact website administrator!';
break;
}
echo '</h1>';
}
?>
<h1> PAGINA INEXISTENTA! </h1>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment