Category Archives: Packages

PHP AdminPanel –Script for Packages

PHP AdminPanel – Control Panel Script 1.0.5 Full Download Development Tools Apps Description. PHP Admin Panel (PHP AP) provides you access to the control features of your site as creating static or dynamical pages and allows your easily manage database tables with embedded PHP DataGrid. It includes Creating, Reading, Updating and Deleting (CRUD) records in database tables on your existing site.

 

 

<?php
################################################################################
##              -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =-                 #
## --------------------------------------------------------------------------- #
##  PHP AdminPanel Free                                                        #
##  Developed by:  ApPhp <info@apphp.com>                                      #
##  License:       GNU GPL v.2                                                 #
##  Site:          http://www.apphp.com/php-adminpanel/                        #
##  Copyright:     PHP AdminPanel (c) 2006-2009. All rights reserved.          #
##                                                                             #
##  Additional modules (embedded):                                             #
##  -- PHP DataGrid 4.2.8                   http://www.apphp.com/php-datagrid/ #
##  -- JS AFV 1.0.5                 http://www.apphp.com/js-autoformvalidator/ #
##  -- jQuery 1.1.2                                         http://jquery.com/ #
##                                                                             #
################################################################################

 // check if previouse name was saved
 $admin_username = (isset($_COOKIE['remember_name']) &amp;&amp; ($_COOKIE['remember_name'] != "")) ? $_COOKIE['remember_name'] : "";
 $remember_me    = (isset($_COOKIE['remember_name']) &amp;&amp; ($_COOKIE['remember_name'] != "")) ? "checked" : "";

 session_start();
 include_once("inc/config.inc.php");
 include_once("inc/functions.inc.php");
 require_once("inc/settings.inc.php");

 $log = (isset($_REQUEST['log'])) ? "out" : "";
 $msg = (isset($_REQUEST['msg'])) ? $_REQUEST['msg'] : "";

 $adm_logged = (isset($_SESSION['adm_logged'])) ? $_SESSION['adm_logged'] : false;

 if($adm_logged == true){
 header("Location: index.php");
 exit;
 }


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3c.org/TR/1999/REC-html401-19991224/loose.dtd">
<html>
<head>
 <title><?php echo $SETTINGS['site_name']; ?> :: Admin Panel</title>

 <meta http-equiv=Content-Type content="text/html; charset=utf-8">
 <link href="css/style_<?php echo $SETTINGS['css_style'];?>.css" type=text/css rel=stylesheet>
 <script type='text/javascript' src='modules/jsafv/lang/jsafv-en.js'></script>
 <script type='text/javascript' src='modules/jsafv/chars/diactric_chars_utf8.js'></script>
 <script type="text/javaScript" src="modules/jsafv/form.scripts.js"></script>
 <script type="text/javaScript" src="js/functions.js"></script>
 <script>
 function rememberMe(val){
 if(document.getElementById("st_remember").checked == true){
 setCookie("remember_name",document.getElementById("rt_admin_username").value,14);
 }else{
 setCookie("remember_name","",-2);
 }
 }
 </script>
</head>
<body>

<table cellspacing="1" cellpadding="6" width="85%" align="left" border="0">
<tbody>
<tr>
 <td valign="top" nowrap height="350px">
 <br><br>
 <form name="frmLogin" action="check_login.php" method="post">
 <input type="hidden" value="login" name="do">

 <table cellspacing="1" cellpadding="6" width="400px" align="center" border="0">
 <tbody>
 <tr>
 <td colspan="2" align="center"><strong>Please enter your username and password to log in</strong></td></tr>
 <tr>
 <td>
 <div align="center">
 <?php
 if($msg == "1"){
 echo "<label class='msg_error'>Wrong username or password!</label>";
 }
 ?>
 <div align="left">
 <fieldset><legend>Log In</legend>
 <div style="PADDING-RIGHT: 6px; PADDING-LEFT: 6px; PADDING-BOTTOM: 6px; PADDING-TOP: 6px">
 <table cellSpacing="0" width="100%" cellPadding="6" border="0">
 <tbody>
 <tr vAlign="top">
 <td colSpan="2">Username<br><input type="text" size="50" maxsize="100" id="rt_admin_username" name="rt_admin_username" value="<?php echo $admin_username; ?>" title="Username"></td>
 </tr>
 <tr vAlign=top>
 <td colSpan="2">Password<br><input type="password" size="50" maxsize="100" id="rt_admin_password" name="rt_admin_password" title="Password"></td>
 </tr>
 <tr>
 <td vAlign="top" width="9%"><input id="st_remember" type="checkbox" value="1" name="st_remember" <?php echo $remember_me; ?> title="Remember Me"></td>
 <td align="left" width="91%"><small><label>Remember me</label></small></td>
 </tr>
 </tbody>
 </table>
 </div>
 </fieldset>
 </div>
 </div>
 <div style="MARGIN-TOP: 6px" align=center>
 <input accessKey="s" type="submit" value="Login" onClick="rememberMe(); return onSubmitCheck(document.forms['frmLogin'], false,false);">
 </div>
 </td>
 </tr>
 </tbody>
 </table>
 </form>

 </td>
</tr>
</tbody>
</table>
</body>
</html>

<script>
document.getElementById("rt_admin_username").focus();
</script>

PHP Scripts for File Joiner Packages

This PHP script is designed to join files retrieve via HTTP into a single file. File Joiner first takes a list of HTTP URLs and then retrieves the data from the specified locations. Finally retrieved data will be brought together and saved to a single file in the desired location.

 

 

<?php

class FileJoiner {
 var $fileList;
 var $timeout;
 var $fileContents;
 var $compression;

 function __construct($fileList=array()) {
 try {
 if(empty($fileList)) throw new Exception("File list is empty.");
 if(!is_array($fileList)) throw new Exception("File list is expected to be array.");

 $this->fileList = $fileList;
 $this->fileContents = '';
 $this->timeout = 30;
 $this->compression = false;
 }
 catch (Exception $e) {
 echo 'Error: ' .$e->getMessage();
 }
 }

 function join($fileName='') {
 if (empty($fileName)) throw new Exception("File name cannot be empty.");
 foreach ($this->fileList as $url) {
 $this->getFile($url, $this->timeout);
 }
 try {
 // Save file
 if (!$fp = fopen($fileName, 'w')) throw new Exception("Cannot open file ($fileName).");
 if (false === fwrite($fp, $this->fileContents)) throw new Exception("Cannot write to file ($fileName).");
 fclose($fp);
 }
 catch (Exception $e) {
 echo 'File IO error: ' .$e->getMessage();
 }
 }

 function getFile($url, $timeout=0) {
 try {
 $fileContents = '';
 # use CURL library to fetch remote file
$ch = curl_init();
 $this->url = $url;
 $this->timeout = $timeout;
 curl_setopt ($ch, CURLOPT_URL, $url);
 curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $this->timeout);
 $fileContents = curl_exec($ch);
 if ( curl_getinfo($ch, CURLINFO_HTTP_CODE) !== 200 ) {
 throw new Exception('Bad data file '.$url);
 }
 if($this->compression) $fileContents = preg_replace('/\s+/', ' ', $fileContents);
 $this->fileContents .= "/* ".basename($url)." */\n\n".$fileContents."\n\n";
 }
 catch (Exception $e) {
 echo 'Network error: ' .$e->getMessage();
 }
 }
}

// Get CSS files
$fileList = array();
$fileList[] = 'http://www.ackrentals.net/css/reset.css';
$fileList[] = 'http://www.ackrentals.net/css/960_24_col.css';
$fileList[] = 'http://www.ackrentals.net/css/syles.css';
$fileList[] = 'http://www.ackrentals.net/css/calendar_styles.css';
$fileList[] = 'http://www.ackrentals.net/css/styles_prop_details.css';
$fileList[] = 'http://www.ackrentals.net/css/textstyles.css';
$fileList[] = 'http://www.ackrentals.net/css/print.css';
$fileList[] = 'http://www.ackrentals.net/css/menus.css';
$fileList[] = 'http://www.ackrentals.net/css/tabs.css';
$fileList[] = 'http://www.ackrentals.net/css/formStyles.css';
$fileList[] = 'http://www.ackrentals.net/css/image_gallery_plugin.css';
$fileList[] = 'http://www.ackrentals.net/css/text.css';
$fileList[] = 'http://www.ackrentals.net/css/textstyles.css';
$fileList[] = 'http://www.ackrentals.net/js/fancybox/jquery.fancybox-1.3.1.css';

$joiner = new FileJoiner($fileList);
$joiner->compression = true;
$joiner->join('css/allstyles.css');
unset($joiner);

////

$fileList = array();
$fileList[] = 'http://www.ackrentals.net/js/DD_belatedPNG.js';
$fileList[] = 'http://www.ackrentals.net/js/swfobject_new.js';
$fileList[] = 'http://www.ackrentals.net/js/RegExpValidate.js';
$fileList[] = 'http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js';
$fileList[] = 'http://cdn.jquerytools.org/1.1.2/tiny/jquery.tools.min.js';
$fileList[] = 'http://www.ackrentals.net/js/fancybox/jquery.mousewheel-3.0.2.pack.js';
$fileList[] = 'http://www.ackrentals.net/js/fancybox/jquery.fancybox-1.3.1.js';

$joiner = new FileJoiner($fileList);
$joiner->compression = false;
$joiner->join('js/allscripts.js');
unset($joiner);


?>

&amp;nbsp;

PHP Scripts for HTTP Viewer Packages

This PHP script is designed to emulate a browser to show you what browser is used to read from the server. HTTP Viewer is able to show you the full server response of a web resource with any one of the Apache request methods. It features for finding server redirect’s, viewing source code or examing questionable websites.

 

 

<?php

# COPYRIGHT
# HTTP Viewer (c) 2010 Scott Connell
# Redistribution without permission is forbidden.
# Source http://www.scottconnell.com
# Last Updated 12/26/2010
#
# SET VARIABLES ########################

# Change the header path, and footer path,
# to your full directory path if neccessary.

$header_path = "header.php";
$footer_path = "footer.php";

# END SETTING VARIABLES #################

if(!function_exists("fsockopen"))
{
$title = "Whoops! - Function Disabled";
include_once($header_path);

print <<<ENDHTM
<p>Your server has the PHP function (fsockopen) disabled! You will not be able to run this program.</p>
ENDHTM
;

exit(include_once($footer_path));
}

function printForm()
{
global $www,$options;

$action = $_SERVER["PHP_SELF"];
$action = str_replace("index.php","", $action);

print <<<ENDHTM

<form method="post" action="$action">

<p>http:// <input type="text" name="www" value="$www"/></p>

<p>Method <select name="methods">
ENDHTM
;

foreach($options as $o)
{
print "<option value=\"$o\">$o</option>\n";
}

print <<<ENDHTM
</select></p>
<p><input type="submit" value="Submit"/></p>
</form>

ENDHTM
;
}

function fetchURL($m)
{
global $domain;

$theArray = parse_url($domain);

$theProtocol = $theArray["scheme"];
$theHost   = $theArray["host"];
$thePort   = $theArray["port"];
$theUser   = $theArray["user"];
$thePass   = $theArray["pass"];
$thePath   = $theArray["path"];
$theQuery  = $theArray["query"];
$theFragment = $theArray["fragment"];

if(!$thePort)
{
$thePort  = "80";
}
if(!$thePath)
{
$thePath    = "/";
}

$thePage = $thePath . ($theQuery?"?":"") . $theQuery;

$open_socket = @fsockopen($theHost, $thePort, $errno, $errstr, 30);

 if($open_socket)
 {
 $message .= $m ." ". $thePage . " HTTP/1.1\r\n";
 $message .= "Host: $theHost\r\n";
 $message .= "Connection: close\r\n\r\n";

 fputs($open_socket, "$message\n");

 while ($read_text = fgets($open_socket, 4096))
 {
 $response .= htmlspecialchars($read_text, ENT_QUOTES);
 }

 return $response;
 }
}

$options = array('HEAD','GET','POST','OPTIONS','TRACE','BASELINE_CONTROL','CHECKIN','CHECKOUT','CONNECT','COPY','DELETE','INVALID','LABEL','LOCK','MERGE','MKACTIVITY','MKCOL','MKWORKSPACE','MOVE','PATCH','PROPFIND','PROPPATCH','PUT','REPORT','UNCHECKOUT','UNLOCK','UPDATE','VERSION_CONTROL');

if($_REQUEST['www'])
{
$domain = strtolower($_REQUEST['www']);
$xArray = @parse_url($domain);

 if(!$xArray["scheme"])
 {
 $domain = "http://" . $domain;
 $xArray = @parse_url($domain);
 }

 $xProtocol = $xArray["scheme"];
 $xHost   = $xArray["host"];
 $xPort   = $xArray["port"];
 $xUser   = $xArray["user"];
 $xPass   = $xArray["pass"];
 $xPath   = $xArray["path"];
 $xQuery  = $xArray["query"];
 $xFragment = $xArray["fragment"];

 $domain = $xProtocol ."://". $xHost . $xPath . ($xQuery?"?":"") . $xQuery;
 $www = $xHost . $xPath . ($xQuery?"?":"") . $xQuery;

 setcookie("URL", strtolower($www), time()+(60*60*24*30), "/"); // 30 days

 $title = "HTTP Viewer - Emulate a browser with this page sniffer.";
 include_once($header_path);

 if(!$fp = @fsockopen($xHost, 80, $errno, $errstr, 30))
 {
 $host = $xArray["host"];
 printForm();
 print "<p><span class=\"bold\">ERROR</span> Could not connect to $host</p>\n";
 exit(include_once($footer_path));
 }
 else
 {
 $result = fetchURL($_REQUEST['methods']);
 printForm();
 print "<h4>". $_REQUEST['methods'] ." Request</h4>\n";
 print "<pre>$result</pre>\n\n";
 }
}
else
{
$title = "HTTP Viewer - Emulate a browser with this page sniffer.";
include_once($header_path);

 if(isset($_COOKIE['URL']))
 {
 $www = $_COOKIE['URL'];
 }

printForm();
}

?>

<?php

include_once($footer_path);

?>

&amp;nbsp;

&amp;nbsp;

Scripts for Simple PHP Upload Packages

This PHP script is created to validate and process uploaded files. It is used to validate a given uploaded file to check whether there was not an upload error, the file size is under a given limit, the file name extension is one of the allowed.
Simple PHP Upload script can also move the uploaded file to a given directory if the upload is valid.

 

 

<?php

//****************************
//  Simple PhpUpload Class   |
//     Writed 14.12.2010     |
//     Slavomir Mikolaj      |
//***************************|

 class PhpUpload {

 public $Var_ReturnOutput = false;
 public $Var_ext = array();
 public $Var_FullDisplay = false;
 public $Var_InstanceName = 'Upload1';
 public $Var_MsgError = 'Error occured';
 public $Var_MsgDone = 'Completed!';
 public $Var_UploadDir = '/';
 public $Var_ErrorTypes = array();
 public $Var_ReturnBool = false;
 public $Var_Ext = array();
 public $Var_MaxSize = 0;
 public $Ext = '';
 public $Var_NewName = '';

 public function SetExts($array) {
 $node_array = explode('|', $array);

 foreach($node_array as $item) {
 array_push($this->Var_Ext, $item);
 }
 }

 public function SetMaxSize($int) {
 $this->Var_MaxSize = $int * 1000;
 }

 public function NewName($str) {
 $this->Var_NewName = $str;
 }

 public function SetErrorTypes($type1, $type2, $type3, $type4) {

 $type4 = str_replace(array('$'), array($this->Var_MaxSize / 1000), $type4);
 $this->Var_ErrorTypes = array(1=>$type1, 6=>$type2, 19=>$type3, 20=>$type4);

 }

 public function ReturnBool($bool) {
 $this->Var_ReturnBool = $bool;
 }

 public function ReturnOutput($bool) {
 $this->Var_ReturnOutput = $bool;
 }

 public function FullDIsplay($bool) {
 $this->Var_FullDisplay = $bool;
 }

 public function SetUploadDir($dir) {
 $this->Var_UploadDir = $dir;
 }


 function ShowUpload($instance, $uploadfile = '', $formid = 'uploadform', $submitvalue = 'Upload') {
 global $Var_FullDisplay;
 global $Var_ReturnOutput;
 global $Var_InstanceName;
 global $Var_UploadDir;

 $Var_InstanceName = $instance;
 $a='';

 if($this->Var_FullDisplay == true) {
 $a .= '<form method="post" id="'.$formid.'" action="'.$uploadfile.'" enctype="multipart/form-data">';
 $a .= '<input type="file" name="'.$instance.'"/>';
 $a .= '<input type="submit" value="'.$submitvalue.'" name="upload" />';
 $a .= '</form>';
 }else {
 $a .= '<input type="file" name="'.$instance.'"/>';
 }

 if($Var_ReturnOutput != true) {
 echo $a;
 }else {
 return $a;
 }
 }

 function TryUpload() {
 global $Var_InstanceName;
 global $Var_UploadDir;

 $FalseUpload = false;


 if(strlen($this->Var_UploadDir) <= 0) {
 if(!$this->Var_ReturnOutput) {

 if($this->Var_ReturnBool) {return false; exit;}

 echo 'System error: nothing upload folder';
 exit;

 }else {

 return 'System error: nothing upload folder';
 exit;
 }
 }

 if(isset($_FILES[$Var_InstanceName]) &amp;&amp; strlen($_FILES[$Var_InstanceName]['name'])>0) {

 if($_FILES[$Var_InstanceName]['error'] > 0) {

 if($this->Var_ReturnBool) {return false; exit;}

 if(!$this->Var_ReturnOutput) {
 echo $this->Var_ErrorTypes[$_FILES[$Var_InstanceName]['error']];
 exit;
 }else {
 return $this->Var_ErrorTypes[$_FILES[$Var_InstanceName]['error']];
 exit;
 }

 }
 //
 if($_FILES[$Var_InstanceName]['size'] > $this->Var_MaxSize) {

 if($this->Var_ReturnBool) {return false; exit;}

 if(!$this->Var_ReturnOutput) {
 echo $this->Var_ErrorTypes[20];
 }else {
 return $this->Var_ErrorTypes[20];
 }
 exit;
 }
 //
 $node_array = explode('.', $_FILES[$Var_InstanceName]['name']);
 $fExt = strtolower(end($node_array));
 $this->Ext = $fExt;

 if(!in_array($fExt, $this->Var_Ext)) {

 if($this->Var_ReturnBool) {return false; exit;}

 if(!$this->Var_ReturnOutput) {
 echo $this->Var_ErrorTypes[19];
 }else {
 return $this->Var_ErrorTypes[19];
 }
 exit;
 }

 try {

 if(strlen($this->Var_NewName)>0) {
 $process = move_uploaded_file($_FILES[$Var_InstanceName]['tmp_name'], $this->Var_UploadDir.$this->Var_NewName);
 }else {
 $process = move_uploaded_file($_FILES[$Var_InstanceName]['tmp_name'], $this->Var_UploadDir.basename($_FILES[$Var_InstanceName]['name']));
 }

 if($process) {

 if($this->Var_ReturnBool) {return true; exit;}

 if(!$this->Var_ReturnOutput) {
 echo $this->Var_MsgDone;
 }else {

 return $this->Var_MsgDone;

 }
 }

 } catch (Exception $e) {

 if($this->Var_ReturnBool) {return false; exit;}

 if(!$this->Var_ReturnOutput) {
 echo $this->Var_MsgError.': '.$e;
 }else {
 return $this->Var_MsgError.': '.$e;
 }
 }
 }
 }
 }

?>

&amp;nbsp;

PHP Scripts for Proxy Connector Packages

PHP5 script for interfacing PHP with the Tor network to retrieve remote web pages. It can connect to an HTTP proxy server that accesses the TOR network to communicate with any remote web server. While the proxy host is fully configurable by the user, so this script is not limited to only the Tor network. Proxy Connector can also switch the TOR user identity and use a random browser identity on each request to further obfuscate the web accesses done by the script.

 

 

<?php

/**
 * Description of proxyConnector
 *
 * PHP5 class for interfacing php with the Tor network,
 * the proxy host is fully configurable by the user,
 * so the class is not limited to only the Tor
 * network.
 *
 * by Marco Baldini <info@marcobaldini.com>
 *
 * Licensed: GNU General Public License, version 2 (GPLv2)
 *
 * The default setting however is to run
 * through the Tor/Polipo network.
 *
 * New identity are changed using hashed password,
 * remember to configure your Tor Proxy to allow this.
 *
 * @author Marco Baldini
 *
 * @copyright 2010 Marco Baldini
 *
 * @license GNU General Public License, version 2 (GPLv2)
 *
 * @version proxyConnector 1.0 TorVersion (12/10/2010)
 *
 * @example index.php
 *
 * Based on TOR Class by Josh Sandlin <josh@thenullbyte.org>
 */


class proxyConnector {


 private static $instance;

 private $destinationUrl;
 private $userAgent;
 private $timeout;
 private $vector;
 private $payload;
 private $returnData;
 private $ip;
 private $port;
 private $controlPort;
 private $controlPassword;
 private $switchIdentityAfterRequest = true;


 ##PUBLIC
public static function getIstance()
 {
 if (!isset(self::$instance)) {
 $c = __CLASS__;
 self::$instance = new $c;
 }

 return self::$instance;
 }


 /**
 *
 * SetUp the proxy configuration
 *
 * @param string $extIp Proxy Ip
 * @param number $extPort  Proxy Port
 */

 public function setProxy($extIp="127.0.0.1", $extPort="8118")
 {
 $this->ip = $extIp;
 $this->port =$extPort;

 }

 /**
 *
 * SetUp the control information
 * used by a Tor proxy to renew identity
 *
 * @param string $extPort Proxy Ip
 * @param number $extPassword Proxy Control Port
 */

 public function setControlParameters($extPort, $extPassword)
 {
 $this->controlPassword = '"'.$extPassword.'"';
 $this->controlPort = $extPort;

 }

 /**
 *
 * Request a remote url using Curl
 *
 * @param string $extUrl
 * @param string $extVector
 * @param number $extTimeout
 */

 public function launch($extUrl, $extVector, $extTimeout = null)
 {
 //set parameters
 $this->destinationUrl = $extUrl;
 $this->vector =$extVector;

 $this->setUserAgent();

 //set payload
 $this->setPayload();

 //if a timeout is set in the args, use it
 if(isset($timeout))
 {
 $this->timeout = $extTimeout;
 }

 //run cURL action against url
 $this->setCurl();

 //renew identity
 if ($this->switchIdentityAfterRequest) {
 $this->newIdentity();
 $this->setUserAgent();
 }
 }

 /**
 *
 * Return downloaded data from the proxy
 *
 * @return array
 *          url: requested url
 *          userAgent: used userAgent
 *          timeout: used timeout
 *          proxy: proxy address
 *          payload: payload
 *          return: url content
 */

 public function getProxyData()
 {
 return array(
 'url' => $this->destinationUrl,
 'userAgent' => $this->userAgent,
 'timeout' => $this->timeout,
 'proxy' => $this->ip .":". $this->port,
 'payload' => $this->payload,
 'return' => $this->returnData
 );
 }


 /**
 *
 * Change identity in the Tor Network
 * (change public IP Address)
 *
 * @return bool
 *          true is new identity is created
 *          false is fail creating a new identity
 */

 public function newIdentity(){
 $fp = fsockopen($this->ip, $this->controlPort, $errno, $errstr, 30);
 if (!$fp) return false; //can't connect to the control port

 fputs($fp, "AUTHENTICATE ".$this->controlPassword."\r\n");
 $response = fread($fp, 1024);
 list($code, $text) = explode(' ', $response, 2);
 if ($code != '250') return false; //authentication failed

 //send the request to for new identity
 fputs($fp, "signal NEWNYM\r\n");
 $response = fread($fp, 1024);
 list($code, $text) = explode(' ', $response, 2);
 if ($code != '250') return false; //signal failed

 fclose($fp);
 return true;
 }


 /**
 * Load the default configuration for the proxy connection
 * located in "proxyConfiguration.ini"
 */

 public function loadDefaultSetUp() {

 $loaded_ini_array = parse_ini_file("./proxyConfiguration.ini",TRUE);

 $this->destinationUrl = null;
 $this->userAgent = null;
 $this->vector = null;
 $this->payload = null;
 $this->returnData = null;

 $this->timeout = $loaded_ini_array["general"]["timeout"];
 $this->ip = $loaded_ini_array["general"]["ip"];
 $this->port = $loaded_ini_array["general"]["port"];
 $this->controlPort = $loaded_ini_array["TOR"]["controlPort"];
 $this->controlPassword = '"'.$loaded_ini_array["TOR"]["controlPassword"].'"';
 $this->switchIdentityAfterRequest = $loaded_ini_array["TOR"]["switchIdentityAfterRequest"];
 }


 ##PRIVATE
private function  __construct() {
 $this->loadDefaultSetUp();
 }

 private function setUserAgent()
 {
 //list of browsers
 $agentBrowser = array(
 'Firefox',
 'Safari',
 'Opera',
 'Flock',
 'Internet Explorer',
 'Seamonkey',
 'Konqueror',
 'GoogleBot'
 );
 //list of operating systems
 $agentOS = array(
 'Windows 3.1',
 'Windows 95',
 'Windows 98',
 'Windows 2000',
 'Windows NT',
 'Windows XP',
 'Windows Vista',
 'Redhat Linux',
 'Ubuntu',
 'Fedora',
 'AmigaOS',
 'OS 10.5'
 );
 //randomly generate UserAgent
 $this->userAgent = $agentBrowser[rand(0,7)].'/'.rand(1,8).'.'.rand(0,9).' (' .$agentOS[rand(0,11)].' '.rand(1,7).'.'.rand(0,9).'; en-US;)';
 }


 private function setCurl()
 {
 $action = curl_init();
 curl_setopt($action, CURLOPT_PROXY, $this->ip .":". $this->port);
 curl_setopt($action, CURLOPT_URL, $this->payload);
 curl_setopt($action, CURLOPT_HEADER, 1);
 curl_setopt($action, CURLOPT_USERAGENT, $this->userAgent);
 curl_setopt($action, CURLOPT_RETURNTRANSFER, 1);
 curl_setopt($action, CURLOPT_FOLLOWLOCATION, 1);
 curl_setopt($action, CURLOPT_TIMEOUT, $this->timeout);
 $this->returnData = curl_exec($action);
 curl_close($action);
 }

 private function setPayload()
 {
 $this->payload = $this->destinationUrl . $this->vector;
 }

 private function  __clone() {
 trigger_error("Clonig not allowed");
 }


}

&amp;nbsp;

rss2php Scripts for Packages

rss2php is a library of php scripts to parse and interpret rss feeds from websites. The data that the scripts process can then be used to create one page, showing news from many different sites for example. Internet, Browsers & Tools.

 

 

<?php

// this is the file that does most of the data processing (xml parsing) for
// aggregating a rss feed
// each rss feed needs a seperate config file (look at default.php for an
// example)
// this file only needs to be modified to include any extra tags that you
// may need to take advantage of other features of rss feeds
// this file is used globally for every feed you use, so needs the tag
// definitions for every file

class RSSParser {
 var $insideitem = false;
 var $tag = "";

 // add more here for any extra types of tags needed
 // remember to update endElement and characterData
 // functions as well
 var $title = "";
 var $description = "";
 var $link = "";
 var $subject = "";
 var $section = "";

 function startElement($parser, $tagName, $attrs) {
 if ($this->insideitem) {
 $this->tag = $tagName;
 } elseif ($tagName == "ITEM") {
 $this->startElement_extra();
 }
 }

 function endElement($parser, $tagName) {
 if ($tagName == "ITEM") {
 if ($this->title) {
 $this->endElement_extra($this);
 }
 // add more here for any extra types of tags needed
 // remember to update characterData function and class
 // variables as well
 $this->title = "";
 $this->description = "";
 $this->link = "";
 $this->subject = "";
 $this->section = "";
 $this->insideitem = false;
 }
 }

 function characterData($parser, $data) {
 if ($this->insideitem) {
 switch ($this->tag) {
 // add more here for any extra types of tags needed
 // remember to update endElement function and class
 // variables as well
 case "TITLE":
 $this->title .= $data;
 break;
 case "DESCRIPTION":
 $this->description .= $data;
 break;
 case "LINK":
 $this->link .= $data;
 break;
 case "DC:SUBJECT":
 $this->subject .= $data;
 break;
 case "SLASH:SECTION":
 $this->section .= $data;
 break;
 }
 }
 }
}

function feed($rss_parser, $cachefilename) {
 $input = fopen($cachefilename,"r")
 or die("Error reading RSS data.");
 $xml_parser = xml_parser_create();
 xml_set_object($xml_parser,&amp;$rss_parser);
 xml_set_element_handler($xml_parser, "startElement", "endElement");
 xml_set_character_data_handler($xml_parser, "characterData");
 while ($data = fread($input, 4096))
 xml_parse($xml_parser, $data, feof($input))
 or die(sprintf("XML error: %s at line %d",
 xml_error_string(xml_get_error_code($xml_parser)),
 xml_get_current_line_number($xml_parser)));
 fclose($input);
 xml_parser_free($xml_parser);
}

?>

&amp;nbsp;

PHP SUS Reports Scripts for Packages

SUS Reports is a collection of PHP scripts which contain a logfile parser for MicroSoft Software Update Services (SUS) and a couple of reports. For example one report contains patches downloaded/installed by which pc and when. Data will be stored in a MySql Database.

 

<?php
#    This program is free software; you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation; either version 2 of the License, or
#    (at your option) any later version.

#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.

#    You should have received a copy of the GNU General Public License
#    along with this program; if not, write to the Free Software
#    Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA

set_time_limit(0);

$startTotalTimer = mktime();
$startTimer = $startTotalTimer;

if (isset($HTTP_SERVER_VARS["REMOTE_ADDR"])) {
 if ($HTTP_SERVER_VARS["REMOTE_ADDR"] || $_SERVER["REMOTE_ADDR"] || $REMOTE_ADDR) { die ("This file can only be executed locally.<br />\n"); }
}

# read config file
if (!$cfg = @file("config.php")) { die ("Config file missing.\n"); }

$n = 0;
$lines = count($cfg);
while($n < $lines) {
#  list($ln, $junk) = preg_split("/##/", $cfg[$n], 2);
$parts = preg_split("/##/", $cfg[$n], 2);
 $ln = $parts[0];
 if (preg_match("/=/", $ln)) {
 list($name, $value) = preg_split("/=/", $ln, 2);
 $conf[trim($name)] = trim($value);
 }
 $n++;
}

include_once("library.inc");

# default connect
ConnectDB($conf["SQL_Server"],
 $conf["SQL_User"],
 $conf["SQL_Password"],
 $conf["SQL_Database"],
 $conf["SQL_Type"]);

# version 0.30
# change column name from File into Filename
if ($conf["SQL_Type"] == "mysql") {
 # only for mysql installations needed.
# mssql script alrady has this
$result = SqlSelectQuery("DESC Last_log_file", __FILE__, __LINE__);
 $number = SqlNumRows($result);
 $n = 0;
 while ($n < $number) {
 if (SqlGetRow($result, $n, "Field") == "File") {
 print "  Altering table Last_log_file\n";
 SqlQuery("alter table Last_log_file change File Filename Varchar(30)", __FILE__, __LINE__);
 $n = $number;
 }
 $n++;
 }
}

# version 0.31
# Add new table SUS_Error
$result = SqlSelectQuery("SHOW TABLES like 'SUS_Errors'", __FILE__, __LINE__);
$number = SqlNumRows($result);
if ($number == 0) {
 print "  Creating SUS Error table.\n";
 SqlQuery("CREATE TABLE SUS_Errors (
 Error varchar(10) NOT NULL default '',
 Description text,
 Details text,
 INDEX (Error))"
, __FILE__, __LINE__);

 print "  Inserting error codes into table.\n";
 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('0x0', 'Success', ''),
 ('0x3', 'iuctl.dll and iuengine.dll are not the correct version', 'iuctl.dll.dll and iuengine.dll are not the correct version and are unable to be updated.'),
 ('0x1', 'iuctl.dll is not the correct version', 'iuctl.dll is not the correct version and is unable to be updated.'),

 ('80000007', 'Operation aborted', ''),

 ('80004004', 'E_ABORT', 'Operation aborted error'),
 ('80004005', 'E_Fail', 'General error or Unknown Error')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('80070001', 'An error occurred during transmission:  A network connection with the remote server could not be established.', ''),
 ('80070002', 'INSTALL_FAILURE', 'Error_File_Not_Found: The system cannot find the file Specified.'),
 ('80070003', 'The system cannot find the path specified. ', 'Windows Update folder does not exist or the V4 folder within Windows Update is missing. (The correct code path is something like this: %Program Files%WindowsUpdateV4)'),
 ('80070004', 'The set of folders could not be opened. You do not have sufficient privileges to access the file. Personal Folders', ''),
 ('80070005', 'ERROR_ACCESS_DENIED', 'Access is denied. The authentication method is not supported.'),
 ('80070006', 'E_Handle', 'Handle not valid error'),
 ('80070008', 'ERROR_NOT_ENOUGH_MEMORY', 'The system is out of memory.'),
 ('8007000b', 'FALSE_ERROR', 'attempts to make a request to the SUS Servers website for the default webpage, please ignore'),
 ('8007000d', 'The Data is invalid. Cannot open', ''),
 ('80070015', 'Cannot open please verify the path and file are correct or The_device_is_not_ready', ''),
 ('80070017', 'Data error (cyclic redundancy check).', 'Data error (cyclic redundancy check).'),
 ('8007001e', 'AN ERROR OCCURED CALLING DLLREGISTER SERVER', ''),
 ('80070020', 'The process cannot access the file because it is being used by another process', ''),
 ('80070052', 'Unpack Error', 'Unpack error due to: Low Disk Space, Access Permissions or an Exchange 2000 IFS Drive'),
 ('80070057', 'E_INVALIDARG', 'One or more arguments are not valid error.'),
 ('80070070', 'Method \'~\' of object \'~\' failed Not enough Hard Drive Space', ''),
 ('8007007e', 'The specified module could not be found', ''),
 ('80070080', 'ERROR_WAIT_NO_CHILDREN', 'There are no child processes to wait for.'),
 ('800700c1', 'is not a valid Win32 application', 'not a valid Win32 application.'),
 ('800700e7', 'ERROR_PIPE_BUSY', '')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('800700ff', 'ERROR_EA_LIST_INCONSISTENT', 'The extended attributes are inconsistent.'),
 ('80070103', 'Error_No_More_Items:', 'Windows has determined that the selected driver is not the best driver for your machine.'),
 ('80070190', 'HTTP_STATUS_BAD_REQUEST (400)', '400 invalid syntax. The request could not be processed by the server due to invalid syntax.'),
 ('80070193', 'HTTP_STATUS_FORBIDDEN (403)', '403 Server is too busy to process request. The server understood the request, but is refusing to fulfill it.'),
 ('80070194', 'HTTP_STATUS_NOT_FOUND (404)', '404 Cabs or page is not found. The server has not found anything matching the requested URI (Uniform Resource Identifier).'),
 ('80070197', 'HTTP_STATUS_PROXY_AUTH_REQ (407)', '407 error (proxy authentication required) - need specific password/user to access. Proxy authentication required.'),
 ('80070198', 'HTTP_STATUS_REQUEST_TIMEOUT (408)', 'The server timed out waiting for the request.'),
 ('8007019b', 'HTTP_STATUS_LENGTH_REQUIRED (411)', 'This is a known issue. Possibly relating to proxy servers that don\'t support http1.1. The server refuses to accept the request without a defined content length.'),
 ('800701a9', 'ERROR_INVALID_FUNCTION', ''),
 ('800701f4', 'HTTP_STATUS_SERVER_ERROR (500)', 'The server encountered an unexpected condition that prevented it from fulfilling the request.'),
 ('800701f6', 'Proxy was unable to forward the request to the    destination server', ''),
 ('800701f7', 'HTTP_STATUS_SERVICE_UNAVAIL (503)', '503 Server is to busy to process request. The service is temporarily overloaded.'),
 ('800701f8', 'HTTP_STATUS_GATEWAY_TIMEOUT (504)', ' 504 timed out waiting for gateway. The request was timed out waiting for a gateway.'),
 ('800703e3', 'ERROR_OPERATION_ABORTED', 'The I/O operation has been aborted because of either a thread exit or an application request.'),
 ('800703e5', 'ERROR_IO_PENDING', ''),
 ('800703e6', 'Invalid access to memory location', ''),
 ('800703f5', 'ERROR_CANTWIRTE', 'The configuration registry key could not be written.'),
 ('800703fb', 'ERROR_NO_LOG_SPACE', 'System could not allocate the required space in a registry log.'),
 ('800703fd', 'Cannot create a stable subkey under a volatile parent key.', 'Cannot create a stable subkey under a volatile parent key.')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('8007041f', 'The service database is locked', ''),
 ('80070426', 'The service has not been started', ''),
 ('8007042b', 'ERROR_PROCESS_ABORTED', 'The process terminated unexpectedly.'),
 ('80070430', 'The specified service has been marked for deletion', ''),
 ('8007045a', 'ERROR_DLL_INIT_FAILED', ''),
 ('8007045d', 'ERROR_IO_DEVICE', 'The request could not be performed because of an I/O device error.'),
 ('8007048f', 'The device is not connected.', ''),
 ('80070490', 'Permission denied / [Problem initializing or using session variables] or Element not found', ''),
 ('800704c7', 'Cancelled by user', ''),
 ('8007051b', 'ERROR_INVALID_OWNER', 'This security ID may not be assigned as the owner of this object.'),
 ('80070570', 'Cannot open file', ''),
 ('800705aa', 'Error loading resources', ''),
 ('800705af', 'The paging file is too small for this operation to complete', ''),
 ('80070643', 'Fatal error during installation', ''),
 ('80070714', 'Version unavailable or Invalid', 'The specified image file did not contain a resource section.'),
 ('80070715', 'ERROR_RESOURCE_TYPE_NOT_FOUND', 'The specified resource type cannot be found in the image file.')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('80072733', 'DLOAD_FAILURE', 'A non-blocking socket operation could not be completed immediately.'),
 ('800727E7', 'DLOAD_FAILURE', 'The requested lookup key was not found in any active activation context.'),

 ('80072ee2', 'ERROR_INTERNET_TIMEOUT', 'The request has timed out. The connection to this Internet site took longer than the allotted time.'),
 ('80072ee4', 'ERROR_INTERNET_INTERNAL_ERROR', 'An internal error has occurred.'),
 ('80072ee7', 'ERROR_INTERNET_NAME_NOT_RESOLVED', 'The server name could not be resolved. DNS Error.  Please try a different root DNS (Like UUNET)'),
 ('80072efd', 'ERROR_INTERNET_CANNOT_CONNECT ', 'Cannot connect to the Internet server'),
 ('80072efe', 'ERROR_INTERNET_CONNECTION_ABORTED', 'The connection with the server has been terminated.'),
 ('80072eff', 'ERROR_INTERNET_CONNECTION_RESET', 'The connection with the server has been reset.'),
 ('80072f76', 'ERROR_HTTP_HEADER_NOT_FOUND', 'The requested http header could not be located'),
 ('80072f78', 'ERROR_HTTP_INVALID_SERVER_RESPONSE', 'The server response could not be parsed.'),
 ('80072f7c', 'ERROR_HTTP_REDIRECT_FAILED', '')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('800a0005', 'Microsoft VBScript runtime error Invalid procedure call or argument: \'fs.OpenTextFile\'', ''),
 ('800a01b6', 'Microsoft VBScript runtime error Object doesn\'t support this property or method:', ''),
 ('800a1391', 'Microsoft Jscript runtime \'Recordset1\' is undefined', 'Jscript error undefined identifier'),

 ('800b0003', 'TRUST_E_SUBJECT_FORM_UNKNOWN', ''),
 ('800b0004', 'Trust_E_Subject_Not_Trusted', ' The subject is not trusted for the specified action.'),
 ('800b0100', 'TRUST_E_NOSIGNATURE', ''),

 ('800c0002', 'http can not find the file specified', 'http can not find the file specified'),
 ('800c0008', 'Cannot download the information you requested.', ''),

 ('80190191', 'HTTP 401', 'Translates in a HTTP 401 error'),
 ('80190192', 'HTTP 402', 'Translates in a HTTP 402 error'),
 ('80190193', 'HTTP 403', 'is produced when the SUS Servers IIS website has no default webpage'),
 ('80190194', 'HTTP 404', 'Translates in a HTTP 404 error'),

 ('801901F4', 'Invalid interface string', 'Invalid interface string')"
, __FILE__, __LINE__);

 SqlQuery("INSERT INTO SUS_Errors (`Error`, `Description`, `Details`) VALUES
 ('c0000005', 'STATUS_ACCESS_VIOLATION', ''),
 ('c0000006', 'STATUS_IN_PAGE_ERROR', ''),
 ('c000001d', 'STATUS_ILLEGAL_INSTRUCTION', ''),
 ('c000013a', 'STATUS_CONTROL_C_EXIT', ''),
 ('c0000142', 'STATUS_DLL_INIT_FAILED', ''),

 ('e0000101', 'ERROR_SECTION_NOT_FOUND', ''),
 ('e000020b', 'ERROR_NO_SUCH_DEVINST', ''),
 ('e000020d', 'ERROR_INVALID_CLASS_INSTALLER', ''),
 ('e0000219', 'ERROR_NO_ASSOCIATED_SERVICE', ''),
 ('e000022b', 'ERROR_DI_DONT_INSTALL', ''),
 ('e0000234', 'ERROR_DRIVER_NONNATIVE', ''),

 ('fffffb4a', 'JET_errDatabaseCorrupted', ''),
 ('fffffbf8', 'JET_errFileAccessDenied', ''),
 ('fffffc0d', 'JET_errOutOfMemory', ''),
 ('ffffff99', 'JET_errOutOfThreads', ''),
 ('ffffffff', 'Cancel', 'The user canceled the transaction')"
, __FILE__, __LINE__);
}

$endTotalTimer = mktime();
$runTime = date("i:s", ($endTotalTimer - $startTotalTimer));
print "\n\nScript runtime: " . $runTime . ".\n\n";

?>

&amp;nbsp;

google php calendar Scripts for Packages

This is a short PHP script to display your Google Calendar on your website.This code currently requires Simplepie, a free PHP XML parser. Requirements: Simplepie Calendar Systems.

 

 

<?
//v0.52: Bugfix for the correct time.
//v0.51: Small change with Google's date (the 'GMT' appears to have gone); debug mode
//v0.5: Fix for new Google date. Also means this now copes with... times. Yay!
//v0.41: moving location of simplepie to the configuration section: thanks Greg
//v0.4: rewrite, to use simplepie

// Your Gmail address
$gmail = "joe@gmail.com";

// Date format you want your details to appear
$dateformat="j F, Y: g.ia"; // Thursday, 10 March - see http://www.php.net/date for details

// Cache location for your XML file
$cache_location='./cache';

// Here is where your copy of Simplepie lives
include ($_SERVER['DOCUMENT_ROOT']."/simplepie.inc");

// Change this to 'true' to see some debug code
$debug_mode=false;


if ($debug_mode) {echo "<P>Debug mode is on.</p>";}

$calendar_xml_address = "http://www.google.com/calendar/feeds/".$gmail."/public/basic?start-min=".date("Y-m-d");

if ($debug_mode) {echo "<P>Getting <a href='$calendar_xml_address'>XML feed</a></p>";}

$feed = new SimplePie();
$feed->feed_url($calendar_xml_address);
$feed->cache_location($cache_location);
$feed->init();

foreach($feed->get_items() as $item) {
 if ($debug_mode) { echo "<P>Item found</p>"; }

 // Extract the 'when' information from the item summary, and ignore everything else
 $from = $item->get_description();
 $from = trim(substr($from,strpos($from,"When: ")+6));
 if ($debug_mode) { echo "<P>Basing time on ".substr($from,0,20)."</p>"; }
 $time = strtotime(trim(substr($from,0,20)));

 // Extract the 'where' information from the item summary, and ignore everything else
 $where = $item->get_description();
 $where = substr($where,strpos($where,"Where: ")+6);
 $where = trim(substr($where,0,strpos($where,"&amp;lt;")));

 if (substr($where,0,2)=="20") {$where = "";} // If there's no location, just ignore it

 // Extract the link for Google Calendar
 $url=$item->get_links();


 // Stick into a nice array
 $bookings[]=array('time'=>$time,'where'=>$where,'title'=>$item->get_title(),'url'=>$url[0]);
}

// Sort the bookings into time order
sort($bookings);

foreach($bookings as $booking) {
 if ($booking['time']>0) { // If the time is valid
 echo "<p><a href='".$booking['url']."'>".$booking['title']."</a><BR>".date($dateformat,$booking['time']);
 if ($booking['where']) {echo "<BR>".$booking['where'];}
 }
}

?>

&amp;nbsp;

Simple PHP Apache log parser Packages

This is a simple PHP Apache log parser. It makes a list of IP, Usee Agent, Status code, ect. and puts it in an array for you to use.The script is very easy to install, use and customize to suit your needs.

 

 

<?php
/*
+----------------------------------------------+
|                                              |
|         PHP apache log parser class          |
|                                              |
+----------------------------------------------+
| Filename   : apache-log-parser.php           |
| Created    : 21-Sep-05 23:28 GMT             |
| Created By : Sam Clarke                      |
| Email      : admin@free-webmaster-help.com   |
| Version    : 1.0                             |
|                                              |
+----------------------------------------------+


LICENSE

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License (GPL)
as published by the Free Software Foundation; either version 2
of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

To read the license please visit http://www.gnu.org/copyleft/gpl.html

*/


class apache_log_parser
{

 var $bad_rows; // Number of bad rows
 var $fp; // File pointer

 function format_log_line($line)
 {
 preg_match("/^(\S+) (\S+) (\S+) \[([^:]+):(\d+:\d+:\d+) ([^\]]+)\] \"(\S+) (.*?) (\S+)\" (\S+) (\S+) (\".*?\") (\".*?\")$/", $line, $matches); // pattern to format the line
 return $matches;
 }

 function format_line($line)
 {
 $logs = $this->format_log_line($line); // format the line

 if (isset($logs[0])) // check that it formated OK
 {
 $formated_log = array(); // make an array to store the lin info in
 $formated_log['ip'] = $logs[1];
 $formated_log['identity'] = $logs[2];
 $formated_log['user'] = $logs[2];
 $formated_log['date'] = $logs[4];
 $formated_log['time'] = $logs[5];
 $formated_log['timezone'] = $logs[6];
 $formated_log['method'] = $logs[7];
 $formated_log['path'] = $logs[8];
 $formated_log['protocal'] = $logs[9];
 $formated_log['status'] = $logs[10];
 $formated_log['bytes'] = $logs[11];
 $formated_log['referer'] = $logs[12];
 $formated_log['agent'] = $logs[13];
 return $formated_log; // return the array of info
 }
 else
 {
 $this->badRows++; // if the row is not in the right format add it to the bad rows
 return false;
 }
 }

 function open_log_file($file_name)
 {
 $this->fp = fopen($file_name, 'r'); // open the file
 if (!$this->fp)
 {
 return false; // return false on fail
 }
 return true; // return true on sucsess
 }

 function close_log_file()
 {
 return fclose($this->fp); // close the file
 }

 function get_line($line_length=300)
 {
 return fgets($this->fp, $line_length); // true and get a line and return the result
 }

}
?>

&amp;nbsp;

PHP CXS Script for Packages

CXS Script is the Flash & PHP implementation of CXS offering a CXS parser for each programming environment enabling complex data exchange between Flash & PHP. CXS stands for Compact XML Serialization and is an XML application aimed to enable complex data exchange between programming languages. Parsers are offered for Flash and PHP.It is aimed to show:- how the serialization / unserialization works, – what the results look like, – how many signs are used for serialization (traffic) and.

 

 

<?php
/*
 * THIS PROGRAM IS LICENSED FREE OF CHARGE. THERE IS NO WARRANTY FOR THE PROGRAM,
 * TO THE EXTENT PERMITTED BY APPLICABLE LAW. THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES PROVIDE
 * THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING,
 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 * THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU.
 * SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
 * REPAIR OR CORRECTION.
 * IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO
 * MAY MODIFY AND/OR REDISTRIBUTE THE PROGRAM AS PERMITTED BY THE LGP-LICENSE, BE LIABLE TO
 * YOU FOR DAMAGES, INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT
 * OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF DATA OR DATA BEING
 * RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO
 * OPERATE WITH ANY OTHER PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
 * POSSIBILITY OF SUCH DAMAGES.
 *
 * @license LESSER GENERAL PUBLIC LICENSE (LGPL)
 * @copyright (c) 2005 download.zehnet.de
 *
 * CXS (Compact Xml Serialization) adapts php's serialize format to xml structure.
 * It is aimed to serve as an effective way for server-client data exchange
 * between flash and php (or any other server-side language).
 *
 * @project : CXS
 * @file : CXS parser [php.xml]
 * @author : Nicolas Zeh - cxs@download.zehnet.de
 * @date : 02/10/2005 - 03/01/2005
 * @version $Id: class.cxs.php,v 0.2.20 2005/03/01 15:00:00 $
 *
*/


// FLAGS
define('NO_XML_DECL',1);
define('PARSE_STRICT',2);
define('URI_ENCODE',4);
define('NO_UTF8',8);
define('OBJECT_AS_HASH',16);
define('RECORDSET_AS_HASH',32);


class CXS
{

 var $FLAGS = 0;
 var $mysql_trans = array(
 'int'                 => 'i',
 'real'                 => 'd',
 'string'             => 's',
 'blob'                 => 's',
 'date'                 => 's',
 'datetime'             => 's',
 'timestamp'             => 's',
 'time'                 => 's',
 'year'                 => 's'
 );
 var $xml_entities_enc = array(
 '&amp;' => '&amp;amp;',
 '<' => '&amp;lt;',
 '>' => '&amp;gt;',
 '\''=> '&amp;apos;',
 '"' => '&amp;quot;'
 );

/*
 function: initialize
*/

 function CXS(){
 $this->_parseFlags(func_get_args(),0);
 $this->xml_entities_dec = array_flip(array_reverse($this->xml_entities_enc));
 } // end initialize

/*
 function: _parseFlags
*/

 function _parseFlags( $a,$i ){
 for($i; $i<count($a); $i++){
 $this->FLAGS |= $a[$i];
 }
 } // end _parseFlags

/*
 function: _xmlEntities
 comment first line out if you want to skip if string is matching a CDATA section
*/

 function _xmlEntities( $str,$t=false ){
 #if(!$t &amp;&amp; preg_match('#^<!\[CDATA\[.*\]\]>$#', trim($str)) ) return $str;
return strtr( $str, $t ? $this->xml_entities_dec : $this->xml_entities_enc );
 } // end _xmlEntities

/*
 function: serialize
*/

 function serialize( $obj ){
 $f = $this->FLAGS|0;
 $this->_parseFlags(func_get_args(),1);
 if( $x = $this->_parse($obj) ){
 if($this->FLAGS &amp; PARSE_STRICT)        $x = '<cxs version="1.0">'. $x .'</cxs>';
 if(($this->FLAGS &amp; NO_XML_DECL) ==0)$x = '<?xml version="1.0" encoding="UTF-8"?>'."\n" . $x;
 if($this->FLAGS &amp; URI_ENCODE)        $x = '&amp;CXS_data='. urlencode($x);
 }
 $this->FLAGS = $f;
 return $x;
 } // end serialize


/*
 function: serializeAsObject
*/

 function serializeAsObject( $obj, $classname ){
 $f = $this->FLAGS|0;
 $this->_parseFlags(func_get_args(),2);
 $obj = (method_exists($obj, 'onSerialize')) ? $obj->onSerialize() : (array)$obj;
 if( $x = $this->_createObject('o',$obj,$classname) ){
 if($this->FLAGS &amp; PARSE_STRICT)        $x = '<cxs version="1.0">'. $x .'</cxs>';
 if(($this->FLAGS &amp; NO_XML_DECL) ==0)$x = '<?xml version="1.0" encoding="UTF-8"?>'."\n" . $x;
 if($this->FLAGS &amp; URI_ENCODE)        $x = '&amp;CXS_data='. urlencode($x);
 }
 $this->FLAGS = $f;
 return $x;
 } // end serializeAsObject

/*
 function: _createRessource
*/

 function _createRessource( $o ){

 switch( get_resource_type($o) ){

 case('mysql result'):

 $numFields = mysql_num_fields($o);

 for($i=0; $i<$numFields; $i++){

 $col = mysql_field_name($o, $i);
 $type = mysql_field_type($o, $i);
 $flag = mysql_field_flags($o, $i);

 $types[$i] = $this->mysql_trans[$type] ? $this->mysql_trans[$type] : 's';
 if( preg_match('#binary#i', $flag) ) $types[$i] = 'c';
 $cols[] = $col;
 $field[$i] = '<f n="' . utf8_encode($this->_xmlEntities($col)) . '">';
 }

 while($row = mysql_fetch_row($o)){
 for($i=0; $i<$numFields; $i++){
 $field[$i] .= $this->_createElement($row[$i], $types[$i]);
 }
 }

 mysql_free_result($o);
 return '<r n="' . utf8_encode($this->_xmlEntities(implode(',', $cols))) . '">' . implode('</f>', $field) . '</f></r>';

 case('file'): // from php documentation
 case('stream'): // but on a test it returned stream
 $r = ini_get('auto_detect_line_endings');
 if(!$r) @ini_set('auto_detect_line_endings',1);
 while(!feof($o)) {
 $file .= fgets($o, 4096);
 }
 if(!$r) @ini_set('auto_detect_line_endings',0);
 return $this->_createElement('c', base64_encode($file));

 default:
 return;

 }
 } // end _createRessource

/*
 function: _createElement
*/

 function _createElement( $t,$o='' ){
 $x = '<'.$t;
 $x .= (is_null($o) || $o==='') ? '/>' : '>'.$o.'</'.$t.'>';
 return $x;
 } // end _createElement

/*
 function: _createObject
*/

 function _createObject( $t,$o,$a=false ){
 $x = '<'.$t;
 if($a) $x .= ' n="'.utf8_encode($this->_xmlEntities($a)).'"';
 $x .= '>';
 while(list($k,$v) = each($o)){
 $x .= $this->_parse($k);
 $x .= $this->_parse($v);
 }
 return $x .'</'.$t.'>';
 } // end _createObject

/*
 function: _createArray
*/

 function _createArray($o){
 $x = '<a>';
 while(list($k,$v) = each($o)){
 $x .= $this->_parse($v);
 }
 return $x .'</a>';
 } // end _createArray

/*
 function: _parse
*/

 function _parse( $o ){

 switch( gettype($o) ){
 case('object'):
 $n    = get_class($o);
 $o    = (method_exists($o, 'onSerialize')) ? $o->onSerialize() : (array)$o; // or use get_object_vars -> don't know what's better
 return ($this->FLAGS &amp; OBJECT_AS_HASH) ? $this->_createObject('h',$o) : $this->_createObject('o',$o,$n);
 case('array'):
 return (array_values($o) == $o) ? $this->_createArray($o) : $this->_createObject('h',$o);
 case('string'):
 $o = $this->_xmlEntities($o);
 if(($this->FLAGS &amp; NO_UTF8) ==0) $o = utf8_encode($o);
 return $this->_createElement('s',$o);
 case('integer'):
 return $this->_createElement('i',$o);
 case('double'):
 return $this->_createElement('d',$o);
 case('boolean'):
 return $this->_createElement('b',$o ?1:0);
 case('NULL'):
 return $this->_createElement('n');
 case('resource'):
 return $this->_createRessource($o);
 }
 return;
 } // end _parse


/*
 function: unserialize
*/

 function unserialize( $str ){
 if($this->_parse_xml($str)){
 $f = $this->FLAGS|0;
 $this->_parseFlags(func_get_args(),1);
 $this->x = $this->_unparse( $this->x );
 $this->FLAGS = $f;
 return $this->x;
 }
 return NULL;
 } // end unserialize

/*
 function: unserializeInto
*/

 function unserializeInto( $str, &amp;$obj ){
 $intObj = &amp;$obj ;
 if(!$this->_parse_xml($str)) return false;
 $f = $this->FLAGS|0;
 $this->_parseFlags(func_get_args(),2);
 $re=false; $t = gettype($intObj);
 if($this->x &amp;&amp; ($this->x['nodeName']=='O' || $this->x['nodeName']=='A')){
 if($t=='object'){
 $len=count($this->x['childNodes']);
 for($i=0; $i<$len; $i=$i+2){
 $k            = $this->_unparse($this->x['childNodes'][$i]);
 $intObj->$k = $this->_unparse($this->x['childNodes'][($i+1)]);
 }
 $re=true;
 } else if($t=='array'){
 $len=count($this->x['childNodes']);
 for($i=0; $i<$len; $i=$i+2){
 $k            = $this->_unparse($this->x['childNodes'][$i]);
 $intObj[$k] = $this->_unparse($this->x['childNodes'][($i+1)]);
 }
 $re=true;
 }
 }
 $this->FLAGS = $f;
 return $re;
 } // end unserializeInto

/*
 function: _parseRecordSetAsHash
*/

 function _parseRecordSetAsHash( $c,$a ){
 $o=array(); $item=array();
 $a = explode(',',$a);
 $len=count($a);
 $flen = count( $c['childNodes'][0]['childNodes'] );
 for($i=0; $i<$flen; $i++){
 for($j=0; $j<$len; $j++){
 $item[$a[$j]] = $this->_uparse($c['childNodes'][$j]['childNodes'][$i]);
 }
 $o[$i]=$item;
 }
 return array('columns'=>$a, 'rows'=>$o);
 } // end _parseRecordSetAsHash

/*
 function: _parseRecordSet
*/

 function _parseRecordSet( $c,$a ){
 if(!class_exists('CXS_RecordSet')) return NULL;
 $a = explode(',',$a); $len=count($a); $item=array();
 $o = new CXS_RecordSet($a);
 $flen = count( $c['childNodes'][0]['childNodes'] );
 for($i=0; $i<$flen; $i++){
 for($j=0; $j<$len; $j++){
 $item[$a[$j]] = $this->_uparse($c['childNodes'][$j]['childNodes'][$i]);
 }
 $o.addItem($item);
 }
 return $o;
 } // end _parseRecordSet

/*
 function: _parseObject
*/

 function _parseObject( $c,$a=false ){
 $o = ($a &amp;&amp; class_exists($a)) ? new $a : new stdClass; $len=count($c['childNodes']);
 for($i=0; $i<$len; $i=$i+2){
 $k        = $this->_unparse($c['childNodes'][$i]);
 $o->$k    = $this->_unparse($c['childNodes'][($i+1)]);
 }
 if(method_exists($o, 'onUnserialize')) $o->onUnserialize();
 return $o;
 } // end _parseObject

/*
 function: _parseHash
*/

 function _parseHash( $c ){
 $o = array(); $len=count($c['childNodes']);
 for($i=0; $i<$len; $i=$i+2){
 $k        = $this->_unparse($c['childNodes'][$i]);
 $o[$k]    = $this->_unparse($c['childNodes'][($i+1)]);
 }
 return $o;
 } // end _parseHash

/*
 function: _parseArray
*/

 function _parseArray( $c ){
 $o = array(); $len=count($c['childNodes']);
 for($i=0; $i<$len; $i++){
 $o[$i]    = $this->_unparse($c['childNodes'][$i]);
 }
 return $o;
 } // end _parseArray

/*
 function: _unparse
*/

 function _unparse( $c ){

 switch( $c['nodeName'] ){
 case('O'): // object
 return ($this->FLAGS &amp; OBJECT_AS_HASH) ? $this->_parseHash($c) : $this->_parseObject($c,$c['attributes']['N']);
 case('H'): // associative array
 return $this->_parseHash($c);
 case('A'): // associative array
 return $this->_parseArray($c);
 case('S'): // string
 return (string) ($this->FLAGS &amp; NO_UTF8) ? $c['content'] : utf8_decode($c['content']);
 case('B'): // boolean
 return (bool) $c['content'];
 case('I'): // integer
 return (int) $c['content'];
 case('D'): // double, float
 return (double) $c['content'];
 case('N'): // null
 return;
 case('C'): // binary
 return base64_decode($c['content']);
 case('R'): // recordset
 return ($this->FLAGS &amp; RECORDSET_AS_HASH) ? $this->_parseRecordSetAsHash($c,$c['attributes']['N']) : $this->_parseRecordSet($c,$c['attributes']['N']);
 }
 return;
 } // end _unparse

/*
 function: _parse_xml
*/

 function _parse_xml( $str ){

 $str = trim($str);
 $this->x=array(); $this->_cur=array(-1);
 $this->_cxs = ($this->FLAGS &amp; PARSE_STRICT) ? 0 : 1;

 $this->_xml_parser = xml_parser_create();
 xml_set_object($this->_xml_parser, &amp;$this);
 xml_parser_set_option($this->_xml_parser,XML_OPTION_CASE_FOLDING,1);
 xml_set_element_handler($this->_xml_parser, "_xml_se", "_xml_ee");
 xml_set_character_data_handler($this->_xml_parser, "_xml_cd");

 if(xml_parse($this->_xml_parser, $str))
 $this->x = $this->x[0];
 else
 $this->x = NULL;

 xml_parser_free($this->_xml_parser);
 return $this->x ? true : false;

 } // end _parse_xml

/*
 function: xml start_element_handler
*/

 function _xml_se($parser, $name, $attribs){

 if($this->_cxs){
 $this->_cur[count($this->_cur)-1]++;
 $add = array('nodeName' => $name, 'attributes' => $attribs, 'content' => '', 'childNodes' => array() );
 eval('$this->x['. implode('][\'childNodes\'][',$this->_cur) .'] = $add;');
 $this->_cur[] = -1;
 }
 if($name == 'CXS' &amp;&amp; $attribs['VERSION']=='1.0')
 $this->_cxs=1;

 } // end _xml_se

/*
 function: xml character_data_handler
*/

 function _xml_cd($parser, $data){
 if($this->_cxs){
 $temp = $this->_cur;
 array_pop($temp);
 eval('$this->x['. implode('][\'childNodes\'][',$temp) .'][\'content\'] .= $data;');
 }
 } // end _xml_cd

/*
 function: xml end_element_handler
*/

 function _xml_ee($parser, $name){

 if($this->_cxs)
 array_pop($this->_cur);

 } // end _xml_ee

} // end class
?>

&amp;nbsp;