Tag Archive for class

Php Feedback Form w/ Session and Browser Info

<? include("browser_class.php"); ?> //include class from here <a href="http://snipplr.com/view/35627/php-browser-detection-class/" >http://snipplr.com/view/35627/php-browser-detection-class/</a>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "<a href="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">" >http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"></a>
<html xmlns="<a href="http://www.w3.org/1999/xhtml">" >http://www.w3.org/1999/xhtml"></a>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<link rel="stylesheet" href="attSearch.css" type="text/css" />
<style>
body {width:400px;margin:0px auto;text-align:left!important}
h2 {color:green;}
</style>
</head>

<body style="background:none!important;">
<?php
// declare values
$loc = $_COOKIE['location'];
$contact_email = $_POST['EmailAddress'];
$contact_subject = $_POST['Subject'];
$contact_name = $_POST['FullName'];
$contact_message = $_POST['Message'];
$contact_custname = $_SESSION['businessName'];
$contact_accno = $_SESSION['accountNo'];
$mydate = date ( 'l, F d Y g:i A',time()+240 );
// where to send e-mail to
$to = '<a href="mailto:youremail@yourprovider.com">youremail@yourprovider.com</a>';

// e-mail subject
$subject = "Feedback from $contact_custname";

// e-mail message
$message = "You have received feedback:
"."----------------------------------------------
"
."Contact Name: $contact_name
"
."Business Name: $contact_accno, $contact_custname
"
."Subject: $contact_subject
"
."Submitted: $mydate
"
."From IP: {$_SERVER['REMOTE_ADDR']}
"
."URL: $loc
"
."Browser: $Browser->Name $Browser->Version
"
."Message: $contact_message";

$headers = "From: $contact_name <$contact_email>
"
."Reply-To: $contact_email
"
."X-Mailer: PHP/".phpversion();

// check for validation, then send the e-mail
if(empty($contact_name) || empty($contact_email) || empty($contact_subject) || empty($contact_message)) {
echo '<h2>Have feedback?</h2>
<form method="post" action="">
<table id="Form-Details">
<tbody>
<tr><td width="20%">Your Name:</td><td><input type="text" name="FullName" size="40" /></td></tr>
<tr><td width="20%">Subject:</td><td><select name="Subject">
		<option value="Feedback">Feedback</option>
		<option value="Suggestion">Suggestion</option>
		<option value="Bug Report">Bug Report</option>
		<option value="Question">Question</option>
		</select>
</td></tr>
<tr><td width="20%">Email:</td><td colspan="3"><input type="text" name="EmailAddress" size="40" /></td></tr>
<tr><td colspan="4">Message:</td></tr>
<tr><td colspan="4"><textarea rows="6" name="Message" cols="47" class="input"></textarea></td></tr>
<tr><td colspan="4" align="right"><input type="submit" value="Submit Feedback" /></td></tr>
</tbody>
</table>
</form>';
} elseif(!ereg("^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $contact_email)) {
echo "<h2 style='font-weight:bold;color:red;'>ERROR: Please enter a valid e-mail address.</h2>";
} else {
mail( $to, $subject, $message, $headers );
echo "<h2>Message Sent!</h2><br /><p>$contact_name,<br /><br />Thank you for your feedback, we will get back to you as soon as possible using $contact_email.";
}
?>
</body>
</html>

source

Authentication class using cookies or sessions

<?php
/*
#
#        Copyright Iulian Ciobanu (CIGraphics) 2009
#        Email: <a href="mailto:cigraphics@gmail.com">cigraphics@gmail.com</a>
#        Please leave the copyright and email intact.
#

# DATABASE TABLE:

CREATE TABLE `users` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `user` varchar(200) NOT NULL,
  `password` varchar(40) NOT NULL,
  `email` varchar(200) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 ROW_FORMAT=DYNAMIC;

# LETS INSERT SOME DATA FOR TESTING PURPOSES:
INSERT INTO `users` (`id`, `user`, `password`, `email`) VALUES (1, 'user', '20ccbe71c69cb25e4e0095483cb63bd394a12b23', '<a href="mailto:user@email.com">user@email.com</a>');

# FOR TESTING PURPOSES:
The user is: user
The password is: 123456

# USAGE:

$auth = new Auth('database', 'user', 'password', 'host'); // This must be placed at the top of your document you don't need to start the session this script will do it.
$auth->type = session or cookie; // If you want to use sessions you don't need to write it else write cookie.
$auth->emailAuth = false or true; // If you want users to login with email instead of username set it to true or don't write this because is set to false by default
$auth->minval = integer; // The minimum chars for username. Write this only if you want to change the value because it's set by default 6.
$auth->maxval = integer; // The maximum chars for username. Write this only if you want to change the value because it's set by default 22.
$auth->minpass = integer; // The minimum chars for password. Write this only if you want to change the value because it's set by default 6.
$auth->salt = 'LOTS OF CHARS OF ANY TYPE'; // Change this. This is for security hashing. I strongly recommed to change this in the script or write this with other random chars.

$auth->login($user, $password); // Place this in the part where you get the post vars from your login forms

$auth->logout(); // Place this after $auth = new Auth(..) or if you setup type and emailAuth place it below them. Like in example. If you add it without that then you will never be able to login

$auth->error(); // Place this in your document. This function will display the errors from validation and other like mysql errors.



*/
class Auth {
    
    var $type = 'cookie';
    private $connection;
    private $errors = array();
    var $minval = 6;
    var $maxval = 22;
    var $minpass = 6;
    var $salt = '#@()DIJK#)(F#&*()DS#@JKS)@(I()#@DU)*(&@#)(#U)J';
    var $emailAuth = false;
    
    function __construct($db, $user, $pass, $host) {
        if ( $this->type == 'session' ) {
            session_start();
        }
        $this->mysqlconnect($user, $pass, $host);
        $this->mysqldb($db);
        $this->check();
    }
    
    private function mysqlconnect($user, $pass, $host) {
        $conn = @mysql_connect($host, $user, $pass);
        if ( !$conn ) {
            die('There is a problem with your mysql connection');
        } else {
            $this->connection = $conn;
        }
    }
    
    private function mysqldb($db) {
        if ( !@mysql_select_db($db, $this->connection) ) {
             die('The database doesn't exist');
        }
        
    }
    
    private function query($sql) {
        $result = @mysql_query($sql, $this->connection);
        if ( !$result ) {
            $this->errors[] = 'SQL Error';
        } else {
            return $result;
        }
    }
    
    private function fobj($result) {
        return mysql_fetch_object($result);
    }
    
    private function fnum($result) {
        return mysql_num_rows($result);
    }
    
    private function fescape($value) {
        return mysql_real_escape_string($value);
    }
    
    public function login($user, $pass) {
        $email = $this->emailAuth;
        $err = false;
        $user = strtolower($user);
        $password = $this->encrypt($pass);
        if ( $email == true ) {
            if ( !$this->email($user) ) {
                $this->errors[] = 'Email invalid.';
                $err = true;
            } else {
                $col = 'email';
            }
        } else {
            if ( !$this->name($user) ) {
                $this->errors[] = 'Name invalid. Min chars: '.$this->minval.'. Max chars: '.$this->maxval;
                $err = true;
            } else {
                $col = 'user';
            }
        }
        if ( strlen($pass) < $this->minpass ) {
            $this->errors[] = 'Password min value is 6 chars.';
            $err = true;
        }
        
        if ( $err == false ) {
            
            $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($user));
            $result = $this->query($sql);
            if ( $this->fnum($result) == 0 ) {
                $this->errors[] = ucfirst($col).' doesn't exist.';
            } else {
                $row = $this->fobj($result);
                if ( $row->password == $password ) {
                    if ( $this->type == 'session' ) {
                        $this->set_session($col, $user);
                        $this->set_session('password', $password);
                    } elseif ( $this->type == 'cookie' ) {
                        $this->set_cookie($col, $user);
                        $this->set_cookie('password', $password);
                    }
                    header('Location: ./auth.php');
                } else {
                    $this->errors[] = 'Incorrect password';
                }
            }
                        
        }
    }
    
    private function encrypt($value) {
        $enc = md5($this->salt.md5($value));
        return sha1($enc);
    }
    
    // Email validation
    private function email($email) {
        $reg = "#^(((([a-zd][.-+_]?)*)[a-z0-9])+)@(((([a-zd][.-_]?){0,62})[a-zd])+).([a-zd]{2,6})$#i";
        if ( !preg_match($reg, $email) ) {
            return false;
        } else {
            return true;
        }
    }
    
    // Name validation
    private function name($name) {
        $min = $this->minval - 2;
        if ( !preg_match("#^[a-z][da-z_]{".$min.",".$this->maxval."}[a-zd]$#i", $name) ) {
            return false;
        } else {
            return true;
        }
    }
    
    private function set_session($name, $value) {
        $_SESSION[$name] = $value;
    }
    
    private function destroy_session() {
        session_unset();
        session_destroy();
    }
    
    private function set_cookie($name, $value, $time = 3600 ) {
        setcookie($name, $value, time()+$time, '/');
    }
    
    private function destroy_cookie($name) {
        setcookie($name, '', time()-1, '/');
    }
    
    public function logout() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'session' ) {
            $this->destroy_session();
        } elseif ( $this->type == 'cookie' ) {
            $this->destroy_cookie('password');
            $this->destroy_cookie($col);
        }
        header ( 'Location: ./auth.php' );
    }
    
    private function check() {
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_COOKIE[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_COOKIE[$col] || $row->password !== $_COOKIE['password'] ) {
                    $this->logout();
                }
            } 
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $sql = sprintf("SELECT * FROM users WHERE %s = '%s'", $col, $this->fescape($_SESSION[$col]) );
                $result = $this->query($sql);
                $row = $this->fobj($result);
                if ( $row->{$col} !== $_SESSION[$col] || $row->password !== $_SESSION['password'] ) {
                    $this->logout();
                }
            }
        }
    }
    
    public function error() {
        if ( is_array($this->errors) && !empty($this->errors) ) {
            echo '<div style="border:1px solid #CCC; background-color:#FAFAFA; color:#FF0000">';
            foreach ( $this->errors as $value ) {
                echo $value."<br />";
            }
            echo '</div>';
        }
    }
    
    public function isLoggedIn() {
        $ret = false;
        if ( $this->emailAuth == false ) {
            $col = 'user';
        } else {
            $col = 'email';
        }
        if ( $this->type == 'cookie' ) {
            if ( isset($_COOKIE['password']) ) {
                $ret = true;
            }
        } elseif ( $this->type == 'session' ) {
            if ( isset($_SESSION['password']) ) {
                $ret = true;
            }
        }
        return $ret;
    }
    
}
?>





Example:
login.php
<?php
include 'class_auth.php';
$auth = new Auth('database', 'user', 'password', 'host'); // This order: Database User Password Host

if ( isset($_GET['logout']) ) {
    $auth->logout();
}

if ( isset($_POST['login']) ) {
    $auth->login($_POST['user'], $_POST['pass']); // This order: User/Email Password True/False (if you want to use email as auth
}
?>

HERE HTML STUFF

<?php if ( $auth->isLoggedIn() ) : ?>
<h1>Welcome</h1>
<a href="<?=$_SERVER['PHP_SELF'];?>?logout=true">Logout</a>
<?php else : ?>
<h1>Please login</h1>
<form action="<?=$_SERVER['PHP_SELF'];?>?auth" method="post">
    <input type="text" name="user" /> User/Email<br />
  <input type="password" name="pass" /> Password<br />
  <input type="submit" name="login" value="Login" />
</form>
<?php $auth->error(); endif; ?>

source

Finding classes

File moduleFile = new File(Catalog.class.getProtectionDomain().getCodeSource().getLocation().toURI());
final ClassFinder finder = new ClassFinder();
finder.clear();
assertTrue(finder.add(moduleFile));
final ClassFilter filter = new AndClassFilter(new NotClassFilter(new InterfaceOnlyClassFilter()), new NotClassFilter(new AbstractClassFilter()), new SubclassClassFilter(UpdateTask.class));
Collection<ClassInfo> foundClasses = new ArrayList<ClassInfo>();
finder.findClasses(foundClasses, filter);

source

All in one PHP user class – uFlex

<?php
// ---------------------------------------------------------------------------
//    uFlex - An all in one authentication system PHP class
//    Copyright (C) 2010  Pablo Tejada
//
//    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 3 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, see <a href="http://www.gnu.org/licenses/gpl-3.0.html." >http://www.gnu.org/licenses/gpl-3.0.html.</a>
// --------------------------------------------------------------------------- 
// V 0.10 - Last modified 4/26/2010
//  +Registration Method
//  	-Custome and Built-in fields validation
//  	-Extendable: add as many fields and validation as required
//  	-Built-in Redundancy check for email and username
//  	-Built-in account activation by email
//  +Update Method to update anyfield on database
//  	-Built-in Redundancy check for email
//  	-Custome and Built-in fields validation
//  +Automatic user session handler
//  	-Remember user with cookies
//  	-Handles sessions on new object
//  +Class wide console
//  	-track and log Errors
//  	-Report every steps for each method
//  	-log validations, connection, SQL queries etc...
// ---------------------------------------------------------------------------

/*Thought the Class Official name is userFlex the object is simply named uFlex*/
class uFlex{
	var $salt = "sd5a4"; //IMPORTANT: Please change this value as it will make this copy unique and secured
	var $id;
	var $username;
	var $pass;
	var $signed;
	var $data;
	var $console;
	var $log;
	var $confirm;	
	var $tmp_data;	
	var $validations;

///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Register A New User
-Takes two parameter the firs been required
	@info = array object (takes an associatve array, 
				the index being the fieldname(column in database) 
				and the value its content(value)
	+optional second parameter
	@activation = boolean(true/false)
		default = false 
Returns activation hash if second parameter @activation is true
Returns true if second parameter @activation is false
Returns false on Error
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function register($info,$activation=false){
		$this->log = "registration";  //Index for Errors and Reports
		
		//Saves Registration Data in Class
		$this->tmp_data = $info;
		
		//Validate Fields Submited Fields
		$validation = array(
			"username" => array(
								"limit" => "3-15",
								"regEx" => "/^([a-zA-Z0-9_])+$/"
								),
			"password" => array(
								"limit" => "3-15",
								"regEx" => false
								),
			"email" => array(
								"limit" => "4-45",
								"regEx" => "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/",
								"optional" => true
								)
			);
		//Add Built in Validation to the Array
		$this->addValidation($validation);
		
		//Validate All Fields in the validations array
		foreach($this->validations as $field=>$opt){
			$this->validate($field,$opt['limit'],$opt['regEx']);
		}
		//Check for errors
		if($this->has_error()) return false;
		
	//Built in actions for special fields
		//Hash Password
		if(isset($info['password'])){ 
			$this->hash_pass($info['password']);
			$info['password'] = $this->pass;
		}		
		//Check for Email in database
		if(isset($info['email'])){
			if($this->check_field('email',$info['email'],"This Email is Already in Use")){
				$this->form_error('email');
			}
		}
		//Check for username in database
		if(isset($info['username'])){
			if($this->check_field('username',$info['username'],"This Username is not available")){
				$this->form_error('username');
			}
		}
		
		//Check for errors
		if($this->has_error()) return false;
		
		//Updates $Info, add defaults, and clean left overs
		$info['password'] = $this->pass;
		$info['confirmation'] = $this->confirm;
		$info['reg_date'] = time();
		
		//Generates the Confirmation Code
		$this->uConfirm();
		
		//Activates user upon registration if there is not an activation method
		if(!$activation){
			$info['activated'] = 1;
		}
		
		//Prepare Info for SQL Insertion
		foreach($info as $index => $val){
			if(!preg_match("/2$/",$index)){ //Skips double fields
				$into[] = $index;
				$values[] = "'" . mysql_real_escape_string($val) . "'";
			}
		}		
		
		$into = implode(", ",$into);
		$values = implode(",",$values);
		
		//Prepare New User	Query
		$sql = "INSERT INTO users ($into) 
					VALUES($values)";
		//exit($sql);
		
		//Enter New user to Database
		if($this->check_sql($sql,true) ){
			$this->report("New User "{$info['username']}" has been registered");
			if($activation) return "{$this->confirm}:{$this->tmp_data['username']}";
			return true;
		}else{
			$this->error("New User Registration Failed");
			return false;
		}
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Similar to the register method function in structure
This Method validates and updates any field in the database
-Takes one parameter
	@info = array object (takes an associatve array, 
				the index being the fieldname(column in database) 
				and the value its content(value)
On Success returns true
On Failure return false	
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function update($info){
		$this->log = "update";  //Index for Errors and Reports
		
		//Saves Updates Data in Class
		$this->tmp_data = $info;
		
		//Check if there have being Changes
		foreach($info as $index=>$val){
			if($this->data[$index] == $val){
				$this->error("{$index} is the same. no changes were made");
				return false;
			}elseif(isset($info[$index.(2)])){
				//Check for equal fields
				if($info[$index] != $info[$index.(2)]){
					$this->error("{$index}s did not match");
					return false;
				}else{
					$this->report("{$index}s match");
				}
			}
		}
		
		//Defaults or Built in Validations
		$validation = array(
			"username" => array(
								"limit" => "3-15",
								"regEx" => "/^([a-zA-Z0-9_])+$/"
								),
			"password" => array(
								"limit" => "3-15",
								"regEx" => false
								),
			"email" => array(
								"limit" => "4-45",
								"regEx" => "/^[_a-z0-9-]+(.[_a-z0-9-]+)*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$/",
								"optional" => true
								)
			);
		//Add Built in Validation to the quene
		$this->addValidation($validation);
		
		//Validate All Fields in the info array with the validation array
		foreach($this->validations as $field=>$opt){
			if(isset($info[$field])){
				$this->validate($field,$opt['limit'],$opt['regEx']);
			}
		}
		//Check for errors
		if($this->has_error()) return false;
		
	//Built in actions for special fields
		//Hash Password
		if(isset($info['password'])){ 
			$this->hash_pass($info['password']);
			$info['password'] = $this->pass;
		}		
		//Check for Email in database
		if(isset($info['email'])){
			if($this->check_field('email',$info['email'],"This Email is Already in Use")){
				$this->form_error('email');
			}
		}
		
		//Check for errors
		if($this->has_error()) return false;
				
		//Prepare Info for SQL Insertion
		foreach($info as $index => $val){
			if(!preg_match("/2$/",$index)){ //Skips double fields
				$value = "'".mysql_real_escape_string($val)."'";
				$set[] = "{$index}={$value}";
			}			
		}		
		
		$set = implode(", ",$set);
		
		//Prepare User Update	Query
		$sql = "UPDATE users SET $set 
					WHERE user_id='{$this->id}'";		
		//exit($sql);
		
		//Check for Changes
		if($this->check_sql_change($sql,true) ){
			$this->report("Information Updated");
			$_SESSION['updated'] = true;
			return true;
		}else{
			$this->error("The Changes Could not be made");
			return false;
		}
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Adds validation to quene list for either the Registration or Update Method
Single Entry:
	Requires the first two parameters
		@name = string (name of the field to be validated)
		@limit    = string (range in the format of "5-10")
			*to make a field optional start with 0 (Ex. "0-10")
	Optional third paramenter
		@regEx = string (Regular Expresion to test the field)
Multiple Entry:
	Takes only the first argument
		@name = Array Object (takes an object in the following format:
			array(
				"username" => array(
									"limit" => "3-15",
									"regEx" => "/^([a-zA-Z0-9_])+$/"
									),
				"password" => array(
									"limit" => "3-15",
									"regEx" => false
									)
				);
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function addValidation($name,$limit=false,$regEx=false){
		$this->log = "registration";
		if(is_array($name)){
			if(!is_array($this->validations)) $this->validations = array(); //If is not an array yet, make it one
			$new = array_merge($this->validations,$name);
			$this->validations = $new;
			$this->report("New Validation Object added");
		}else{
			$this->validations[$name]['limit'] = $limit;
			$this->validations[$name]['regEx'] = $regEx;
			$this->report("The $name field has been added for validation");
		}
	}
	
///////////////////////////////////////////////////////////////////////////////////////////////////////	
/*
Activates Account with hash
Takes Only and Only the URL c parameter of the comfirmation page
	@hash = string
Returns true on account activation and false on failure
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function activate($hash){
		$d = explode(":",$hash);
		$this->confirm = $d[0];
		$this->username = $d[1];		
		$sql = "UPDATE users SET activated=1 WHERE confirmation='{$d[0]}' AND username='{$d[1]}'";
		
		if($this->check_sql_change($sql,true)){
			$this->report("Account has been Activated");
			return true;
		}else{
			$this->error("Account could not be activated");
			return false;
		}
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Method to reset password, sents an email with a confirmation code to reset password
-Takes one parameter and is required
	@email = string(user email to reset password)
On Success it returns a hash which could then be use to construct the confimration URL
On Failure it returns false
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function pass_reset($email){
		$this->log = "pass_reset";
		$this->uConfirm();
		$sql = "SELECT username,user_id FROM users WHERE email='{$email}'";
		$this->
		$query = mysql_query($sql);
		if(!$query){
			$this->error(mysql_error()); 
			return false;
		}
		$row = mysql_fetch_assoc($query);
		if(count($row) > 1){
			//Send Email
			$code = $this->confirm.":{$row['user_id']}";
			return $code;
		}else{
			$this->error("We don't have an account with this email");
			return false;
		}
	}

///////////////////////////////////////////////////////////////////////////////////////////////////////
/*
Reset a Password with a Confirmation hash from the pass_reset method	
-Takes two parameters
	@hash = string (pass_reset method hash)
	@new  = string (New password)
					*Make sure to validate and comfirm new password in javascript for now
Returns true on a successfull password change
Returns false on error
*/
///////////////////////////////////////////////////////////////////////////////////////////////////////
	function new_pass($hash,$new){
		$d = explode(":",$hash);
		$this->confirm = $d[0];
		$this->id = $d[1];
		$pass = $this->hash_pass($new);
		$sql = "UPDATE users SET password='{$pass}' WHERE confirmation='{$d[0]}' AND user_id='{$d[1]}'";
		
		if($this->check_sql($sql,true)){
			$this->report("Your Password has been Changed");
			return true;
		}else{
			$this->error("Password could not be changed");
			return false;
		}
	}
	
////////Private and Secondary Methods below this line\\\
/*Star up function*/
	function uFlex($user=false,$pass=false,$auto=false){
		$this->log = "login";  //Index for Reports and Errors;
		session_start();	
		//$this->username = $user;
		//$this->pass = $pass;
		
		$result = $this->login($user,$pass,$auto);
		if($result == false){
			$this->id = 0;
			$this->username = "Guess";
			$this->pass = "";
			$this->signed = false;
			$_SESSION = array("username" => "Guess",
							  "user_id" => 0,
							  "signed" => false
							  );
			$this->report("User is Guess");
		}else{
			
		}
		return true;
	}
	
	private function login($user=false,$pass=false,$auto=false){
		$this->log = "login";  //Index for Reports and Errors;
		//Session Login
		if(@$_SESSION['signed']){
			$this->report("User Is signed in from session");
			$this->update_from_session();
			if(isset($this->data['updated'])){
				//Get User From database because its info has change during current session
				$update = mysql_fetch_assoc(mysql_query("SELECT * FROM users WHERE user_id='{$this->id}'"));
				$this->update_session($update);
				unset($_SESSION['updated']);
				$this->report("Session Updated From Database");
			}
			return true;
		}		
		if(isset($_COOKIE['auto'])){
		//Cookies Login	
			$c = $_COOKIE['auto'];
			$c = explode(":",$c);  //passHash:id => asd5453asf54a:52
			//if($c[1] != 1){ return false; $this->report("No auto Login"); } //No AutoLogin set return false
			$this->id = $c[1];
			$this->pass = $c[0];
			$auto = true;
			$this->report("Attemping Login with cookies");
		}else{
		//Credetials Login
			if(!$user == false && !$pass == false){
				$this->username = $user;
				$this->hash_pass($pass);
				$this->report("Creadentials recieved");
			}else{
				$this->error("No Username or Password provided");
				return false;
			}
		}

		$this->report("I got info Quering Database to autenticate user");
		//Query Database and check login
		$query = mysql_query("SELECT * FROM users WHERE user_id='{$this->id}' OR username='{$this->username}' AND password='{$this->pass}'");
		if(mysql_num_rows($query) == 1){
			$this->data = mysql_fetch_assoc($query);
			$d = $this->data;
			//If Account is not Activated
			if($d['activated'] != 1){
				if($d['last_login'] == 0){
					//Account has not been activated
					$this->error("Your Account has not been Activated. Check your Email for instructions");
				}else{
					//Account has been deactivated
					$this->error("Your account has been deactivated. Please contact Administrator");
				}
				return false;
			}
			//Account is Activated and user is logged in
			$this->update_session($d);
			
			//If auto Remember User
			if($auto){
				$this->setCookie();
			}
			//Update last_login
			$time = time();
			$sql = "UPDATE users SET last_login='{$time}' WHERE user_id='{$this->id}'";
			$this->check_sql($sql,true);
			//Done
			$this->report("User Logged in Successfully");
			return true;
		}else{
			$this->error("Wrong Username or Password");
			return false;
		}
	}
	
	function logout(){
		$this->log = "login";
		setcookie("auto", "", time()-3600,"/",".".$_SERVER['HTTP_HOST']); //Deletes the Auto Coookie
		session_unset();
		$this->report("User Logged out");
	}
	
	private function setCookie(){
		$value = $this->pass;
		$value .= ":";
		$value .= $this->id;
		setcookie("auto",$value,strtotime("+15 days"),"/",".".$_SERVER['HTTP_HOST']);
		$this->report("Cookies have been updated for auto login");
	}
	
	function update_session($d){
		$_SESSION = $d;
		$_SESSION['signed'] = true;
		
		$this->id = $d['user_id'];
		$this->username = $d['username'];
		$this->pass = $d['password'];
		$this->signed = true;
		
		$this->report("session updated");
	}
	
	function update_from_session(){
		$d = $_SESSION;
		
		$this->id = $d['user_id'];
		$this->data = $d;
		$this->username = $d['username'];
		$this->pass = $d['password'];
		$this->signed = true;
	}
	function hash_pass($pass){
		$salt = $this->salt;
		$this->pass = md5($salt.$pass.$salt);
		return $this->pass;
	}
	
	function report($str=false){
		$index = $this->log;
		if($str){
			$str = ucfirst($str);
			$this->console['reports'][$index][] = $str; //Strore Report
		}else{
			if($index){
				return $this->console['reports'][$index]; //Return the $index Reports Array
			}else{
				return $this->console['reports']; //Return the Full Reports Array
			}
		}
	}

	function error($str=false){
		$index = $this->log;
		if($str){
			$str = ucfirst($str); //Style String by making first character uppercase
			$this->console['errors'][$index][] = $str; //Strore Error
			$this->report("Error: {$str}"); //Report The error
		}else{
			if($index){
				return $this->console['errors'][$index]; //Return the $index Errors Array
			}else{
				return $this->console['errors']; //Return the Full Error Array
			}
		}
	}
	
	//Adds fields with errors to the console
	function form_error($field=false){
		$index = $this->log;
		if($field){
			$this->console['form'][$index][] = $field;	
		}else{
			if($index){
				return $this->console['form'][$index]; //Return the $index Errors Array
			}else{
				return $this->console['form']; //Return the Full form Array
			}
		}
	}
	
	//Check for errors in the console
	function has_error(){
		//Check for errors
		if($this->console['errors'][$this->log] != ""){
			$count = count($this->console['errors'][$this->log]);
			$this->report("$count Error(s) Found!");
			return true;
		}else{
			$this->report("No Error Found!");
			return false;
		}
	}
	
	//Generates a unique comfirm hash
	function uConfirm($length = false){
		$code = md5(uniqid(rand(), true));
		if($length != false){
			$this->confirm = substr($code, 0, $length);
		}else{
			$this->confirm = $code;
		}
	}
	
	//Test field in database for a value
	function check_field($field, $val, $str=false){
		$query = mysql_query("SELECT {$field} FROM users WHERE {$field}='{$val}' ");
			if(mysql_num_rows($query) >= 1){
				if($str){
					$this->error($str);
				}else{
					$this->error("There was a match for  $field = $val");
				}
				return true;
			}else{
				$this->report("No Match on Field $field=$val");
				return false;
			}
	}
	
	//Executes SQL query and checks for success
	function check_sql($sql,$debug = false){
		$this->report("SQL: {$sql}"); //Log the SQL Query first
		if (!mysql_query($sql)){
			if($debug){
				$this->error(mysql_error());
			}
			return false;
		}else{
			return true;
		}
	}
	
	//Executes SQL query and expects a change in database
	function check_sql_change($sql,$debug = false){
		$this->report("SQL: {$sql}"); //Log the SQL Query
		if (!mysql_query($sql)){
			if($debug){
				$this->error(mysql_error());
				return false; //die('Error: ' . mysql_error());
			}else{
				return false;
			}
		}else{
			$rows = mysql_affected_rows();
			if($rows > 0){
				//Good, Rows where affected
				$this->report("$rows row(s) where Affected");
				return true;
			}else{
				//Bad, No Rows where Affected
				$this->report("No row was Affected");
				return false;
			}
		}
	}
	
	//Validates field($name) in tmp_data
	private function validate($name,$limit,$regEx=false){
		$str = $this->tmp_data[$name];
		$l = explode("-",$limit);
		$min = intval($l[0]);
		$max = intval($l[1]);
		if(!$max || !$min){
			$this->report("Invalid second paramater for the private validate method on $name");
			return false;
		}
		if(!$str){
			if(!isset($this->tmp_data[$name])){
				$this->error("missing index $name from the POST array");
			}
			if(strlen($str) == $min){
				$this->report("$name is blank and optional - skipped");
				return true;
			}
			$this->error("$name is required");
			$this->form_error($name);
			return false;
		}
		if(strlen($str) > $max){
			$this->error("The $name is larger than $max character/digits");
			$this->form_error($name);
			return false;
		}
		if(strlen($str) < $min){
			$this->error("The $name is too short. it should at least be $min character/digits long");
			$this->form_error($name);
			return false;
		}
		if($regEx){
			preg_match_all($regEx,$str,$match);
			//print_r($match);echo count($match[0])."+";
			
			if(count($match[0]) != 1){
				$this->error("The $name "{$str}" is not valid");
				$this->form_error($name);
				return false;
			}
		}
		
		$this->report("The $name is Valid");
		return true;
	}
}
	


?>

source

Simple Ajax Class

// Request class
Request = function(){
	Request = window.XMLHttpRequest?new XMLHttpRequest():window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):false;
	Request.fn = function(fn){
		if(typeof fn=='string')return new Function(fn);
		if(typeof fn=='function')return fn;
		if(typeof fn=='undefined')return new Function();
	};
	Request.config = {
		'xml' : false,
		'404' : 'File not found'
	};
	
	Request.success = false;
	Request.loading = false;
	Request.error = false;
	
	Request.submit = function(obj){		
		if(Request){
			Request.onreadystatechange = function(){
				if(Request.status==200){
					if(Request.readyState==4){
						Response = Request.config['xml']?Request.responseXml:Request.responseText;
						if(Request.success){
							Request.fn(Request.success).call(this, Response, Request);
						} else {
							Request.fn(obj.success).call(this, Response, Request);
						}
					} else {
						if(Request.success){
							Request.fn(Request.loading).call(this, Request);
						} else {
							Request.fn(obj.loading).call(this, Request);
						}
					}
				} else {
					if(Request.success){
						Request.fn(Request.error).call(this, Request.config['404']);
					} else {
						Request.fn(obj.error).call(this, Request.config['404']);
					}
				};
			}
		
			Request.open("GET", obj.url, true);
			Request.send(null);
		} else obj.error.call(this, Request);
	};
	
	return Request;
};

// Eval code
var req = new Request;
req.submit({
	url : 'plik.xml',
	xml : false,
	success : function(res, req){
		document.getElementById('p2').innerHTML = res;
	},
	loading : function(){ console.log('loading...'); },
	error : function(err){ console.log(err); }
});

source

Basic usage of TNT library #1

#include <iostream>

/*
 Here we use the TNT library which contains headers for 1D,2D & 3D arrays supporting both C and FORTRAN 
 style arrays. The classes are templated allowing any array types. Moreover the classes support overloaded
 operators for common operations
*/
#include "tnt.h" //this is the only necessary header to use the entire library. However it is possible to only use the
 				 //needed headers depending on the desired functionality.

int main (int argc, char * const argv[]) {
	/* TNT::Stopwatch */
	TNT::Stopwatch timer1; //using TNT's 'Stopwatch' class to create a timer
	timer1.start();	//using the 'start' function of the timer to start counting time
	
	
	//use TNT's 'Array2D' class to create 3 30x30 arrays of which the first two are filled with the
	//value '2.0' while the 3rd is full of zeros
	TNT::Array2D<int> num(5,5,2.0); 
	TNT::Array2D<int> num2(5,5,2.0);
	TNT::Array2D<int> num3(5,5,0.0);
	
	std::cout<<num[0][0]<<"n"; //access a specific value in the matrix
	
	num3=num2*num; //element-wise multiplication of the two arrays using the overloaded '*' operator
	
	std::cout << num3 <<"n"; //using the overloaded operator '<<' to print the dimensions and contents of the array

	//using the 'matmult' function to multiply two matrices and then we print the result
	std::cout << TNT::matmult(num,num2) <<"n"; 
	
	std::cout<< num.subarray(1, 3, 1, 3); //using the 'subarray' function we print a part of the 'num' array
	
	/* TNT::Stopwatch */	
	//using the 'stop' function of the timer to stop counting. This function returns the time
	//elapsed from the call of the 'start' function in seconds.
	std::cout << timer1.stop()<<"n"; 
	
	
	
	
	return 0;
}

source

Button Template Class in AS3

/*
	
	Author: Alvin Crespo
	Date: 3/1/2010
	
	TemplateButton is a template class for buttons.

*/
package acrespo.classes.templates{
	
	//display
	import flash.display.MovieClip;
	
	//events
	import flash.events.Event;
	import flash.events.MouseEvent;
	
	public class TemplateButton extends MovieClip{
		
		private var cButtonArea:MovieClip;
		
		public function Button(){ } //Constructor
		
		protected function setClickArea(pButtonArea:MovieClip):void{ initiateClickArea(pButtonArea); }
		
		private function initiateClickArea(pButtonArea:MovieClip):void{
			cButtonArea = pButtonArea;
			cButtonArea.buttonMode = true;
			cButtonArea.addEventListener(MouseEvent.MOUSE_DOWN, buttonDown);
			cButtonArea.addEventListener(MouseEvent.MOUSE_UP, buttonUp);
			cButtonArea.addEventListener(MouseEvent.MOUSE_OVER, buttonOver);
			cButtonArea.addEventListener(MouseEvent.MOUSE_OUT, buttonOut);		
		}
		
		private function buttonDown(e:MouseEvent):void {
			stage.addEventListener(MouseEvent.MOUSE_UP, buttonUp);
			gotoAndStop('down');
		}

		private function buttonUp(e:MouseEvent):void {
			stage.removeEventListener(MouseEvent.MOUSE_UP, buttonUp);
			if (e.currentTarget != cButtonArea) {//onreleaseoutside
				gotoAndStop('normal');
			} else {//onrelease
				buttonUpAction();
			}
		}
		
		protected function buttonUpAction():void{ }
		
		private function buttonOver(e:MouseEvent):void {
			if (e.buttonDown) {//ondragover

			} else {//onrollover
			
			}			 
			gotoAndStop('over');
		}	
		
		private function buttonOut(e:MouseEvent):void {
			//The user is dragging something from the target object
			if (e.buttonDown) {//ondragout
				gotoAndStop('down');
			} else {//onrollout
				gotoAndStop('normal');
			}
		}
		
	}//end of class
}//end of package


/*
	
The Following is how you would extend that class

*/
package acrespo.classes.buttons{
	
	//classes
	import acrespo.classes.templates.TemplateButton;
	import acrespo.classes.MainDocument;
	
	public class UploadFileButton extends TemplateButton{
		
		public function UploadFileButton():void{ 
			setClickArea(buttonarea); //function of parent class TemplateButton
		}
		
		override protected function buttonUpAction():void{
			MainDocument(parent)._FileManager.uploadFiles();
		}//end of buttonUpAction
		
	}//end of class
}//end of package

source

Simple MySql class

// Author: Dealis
// Site: <a href="http://www.dealis.pl">www.dealis.pl</a>
// Email: <a href="mailto:piotrek290@gmail.com">piotrek290@gmail.com</a>


class MySql {
	public function query($sql){
		$query = @mysql_query($sql, $this->handle) or die(mysql_errno().": ".mysql_error());
		return new Result($query);
	}	
	
	public function connect($host, $root, $pass, $data){
		$connect = @mysql_connect($host, $root, $pass) or die(mysql_errno().": ".mysql_error());
		@mysql_select_db($data, $connect) or die(mysql_errno().": ".mysql_error());
		$this->handle = $connect;
		return $connect;
	}
	
	public function escape($str){
		if(get_magic_quotes_runtime()){
			$str = htmlspecialchars(stripslashes($str));
		}
		
		return @mysql_real_escape_string($str);
	}
	
	public function last(){
		return @mysql_insert_id($this->handle);
	}
	
	public function close(){
		return @mysql_close($this->handle);
	}
}

class Result extends MySql{
	public function Result($result){
		$this->query = $result;
	}
	
	public function fetch(){
		return @mysql_fetch_array($this->query);
	}
	
	public function is(){
		return ($this->query?true:false);
	}
	
	public function first_cell(){
		$row = @mysql_fetch_row($this->query);
		return $row[0];
	}
	
	public function num(){
		return @mysql_num_rows($this->query);
	}
	
	public function finish(){
		return $this->query;
	}
}

source

Tag class html + comment1

<${1:tag} class="${2:${3:enumerate}}">
	${0:$TM_SELECTED_TEXT}
</$1> <!-- Fermeture de CLASS : ${2} -->

source

MySQL Interface Class

<?php

// manages mysql connection
class SQL {

	private $conn, $lastq;
	public $query_count = 0;

	// constructor. connects upon class formation.
	function SQL ($server, $user, $pw, $db, $persist) {

		// connect
		$this->conn = (
			$persist ? @mysql_pconnect($server, $user, $pw) :
						@mysql_connect($server, $user, $pw))
			or exit ("Error Connecting to MySQL: ".mysql_error()."
");

		// select db
		@mysql_select_db($db, $this->conn) or
			exit ("Error Selecting MySQL DB: ".mysql_error() . "
");

		return true;

	}

	// run a query
	function query($q) {
		// run it
		$this->lastq = @mysql_query($q, $this->conn) or
			$this->error_message ("Query Error: ".mysql_error()."
");

		// increment query count
		$this->query_count++;

		// return result
		return $this->lastq;
	}

	// run an unbuffered query. (used only a few times)
	function query_unbuff($q)
	{
		// run it
		$this->lastq = @mysql_unbuffered_query($q, $this->conn) or
			$this->error_message ("Query Error: ".mysql_error()."
");

		// increment query count
		$this->query_count++;

		// return result
		return $this->lastq;

	}

	// free a result
	function free($r) {
		@mysql_free_result($r);
	}

	// free last query result
	function freelast() {
		if (is_resource($this->conn) && is_resource($this->lastq))
			@mysql_free_result($this->lastq);
	}

	// get result as a numerical array
	function fetch_row($r = null) {
		$r = @$r ? $r : $this->lastq;
		return @mysql_fetch_row($r);
	}

	// get result as a associative array
	function fetch_assoc($r = null) {
		$r = @$r ? $r : $this->lastq;
		return @mysql_fetch_assoc($r);
	}

	// close mysql connection
	function close() {
		if (is_resource($this->conn))
			mysql_close($this->conn);
	}

	// escape
	function prot($s) {
		return ctype_digit($s) ? $s : mysql_real_escape_string($s, $this->conn);
	}

	// last id
	function lastid() {
		return mysql_insert_id($this->conn);
	}

	// rows affected by last update/replace/delete/insert
	function affected_rows() {
		return mysql_affected_rows($this->conn);
	}

	// show error message
	function error_message() {

		// halt whilst showing the message
		exit ("MySQL Error: 
".mysql_error($this->conn)."
");

	}

	// are we connected?
	function is_connected() {
		return is_resource($this->conn);
	}

	// return number of results
	function num($r) {
		return mysql_num_rows($r);
	}
}

source