Category Archives: User Authentication

PHP Scripts for CookieAuth User Authentication

CookieAuth is a simple PHP class, compatible with any version of PHP, that permits to add “User-ID and Password” authentication in other projects, using cookies and additional table-field. This class is suitable for any existing MySQL database.

<?php
/**
* A simple class that can authenticate users using an
* (eventually already existing) MySQL data-base.
*
* This software and all associated files are released
* under the GNU Lesser Public License (LGPL), see
* license.txt for details.
*
* @version    1.0.2
* @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
*        Luca Marchetti <l.marchetti@d-sign.it>
*/

class CookieAuth
{
 /**
 * @var        dbcon        string - opened database connection
 * @access    private
 */

 var    $dbconn;

 /**
 * @var        dbtable        string - database table name
 * @access    private
 */

 var    $dbtable;

 /**
 * @var        dbuser        string - name of the user-ID field
 * @access    private
 */

 var    $dbuser;

 /**
 * @var        dbpass        string - name of the password field
 * @access    private
 */

 var    $dbpass;

 /**
 * @var        dbpacket    string - name of the packet (new) field
 * @access    private
 */

 var    $dbpacket;

 /**
 * @var        cookiename    string - name of cookie to be sent
 * @access    private
 */

 var    $cookiename;

 /**
 * @var        timeout        int - maximum time (<= 0 meens no limit)
 * @access    private
 */

 var    $timeout;

 /**
 * @var        separator    string - string used to split packet parts
 * @access    private
 */

 var    $separator;

 /**
 * The constructor preserves data passed by the user for
 * class purposes.
 *
 * @param    dbcon        string - opened database connection
 * @param    dbtable        string - database table name
 * @param    dbuser        string - name of the user-ID field
 * @param    dbpass        string - name of the password field
 * @param    dbpacket    string - name of the packet (new) field
 * @param    dbcookiename    string - name of cookie to be sent
 * @param    timeout        int - maximum time (<= 0 meens no limit)
 * @param    separator    string - string used to split packet parts
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>
 */

 function CookieAuth($dbconn, $dbtable, $dbuser, $dbpass, $dbpacket, $cookiename, $timeout, $separator)
 {
 $this->dbconn = $dbconn;
 $this->dbtable = $dbtable;
 $this->dbuser = $dbuser;
 $this->dbpass = $dbpass;
 $this->dbpacket = $dbpacket;
 $this->cookiename = $cookiename;
 $this->timeout = $timeout;
 $this->separator = $separator;
 }

 /**
 * auth_login starts a new session for user $user updating,
 * values in the data-base and setting a new cookie.
 *
 * @param    user        string - user-ID
 * @param    pass        string - password
 * @param    other        string - other data to save
 * @return    correctly compiled packet
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
 *        Luca Marchetti <l.marchetti@d-sign.it>
 */

 function auth_login($user, $pass, $other)
 {
 // check username and password in the db
 $dbquery =    "SELECT ".$this->dbuser." ".
 "FROM ".$this->dbtable." ".
 "WHERE ".$this->dbuser." = '$user' ".
 "AND ".$this->dbpass." = '$pass'";
 if($dbri = mysql_query($dbquery, $this->dbconn)) {
 if(mysql_num_rows($dbri) > 0) {
 // Ok, user authenticated
 $unique = md5(uniqid(rand()));
 $packet = ereg_replace("'", "\'", $this->packetget($unique, $other));
 // set the new cookie
 setcookie($this->cookiename, $unique);
 // update packet in the data-base
 $dbquery =     "UPDATE ".$this->dbtable." ".
 "SET ".$this->dbpacket." = '$packet' ".
 "WHERE ".$this->dbuser." = '$user'";
 if($dbri = mysql_query($dbquery, $this->dbconn))
 return($packet);
 else return(FALSE);
 }
 else return(FALSE);
 }
 else return(FALSE);
 }

 /**
 * auth_logout checks for a valid, existing session for
 * user $user.
 *
 * @param    user    string - user-ID
 * @return    string - correctly compiled packet
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
 *        Luca Marchetti <l.marchetti@d-sign.it>
 */

 function auth_check($user)
 {
 $dbquery =    "SELECT ".$this->dbpacket." ".
 "FROM ".$this->dbtable." ".
 "WHERE ".$this->dbuser." = '$user' ";
 if($dbri = mysql_query($dbquery, $this->dbconn)) {
 if($dbrow = mysql_fetch_row($dbri)) {
 $packet = $dbrow[0];
 if($this->packetcheck($packet))
 return($packet);
 else {
 return(FALSE);
 }
 }
 else return(FALSE);
 }
 else return(FALSE);
 }

 /**
 * auth_touch updates time and client informations
 * into the data-base, using the same unique-id.
 *
 * @param    user    string - user-ID
 * @return    string - correctly compiled packet
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
 *        Luca Marchetti <l.marchetti@d-sign.it>
 */

 function auth_touch($user)
 {
 if($packet = $this->auth_check($user)) {
 // Ok, user authenticated
 $unique = strtok($packet, $this->separator);
 $addr = strtok($this->separator);
 $time = strtok($this->separator);
 $other = strtok($this->separator);
 $packet = ereg_replace("'", "\'", $this->packetget($unique, $other));
 // update packet in the data-base
 $dbquery =     "UPDATE ".$this->dbtable." ".
 "SET ".$this->dbpacket." = '$packet' ".
 "WHERE ".$this->dbuser." = '$user'";
 if($dbri = mysql_query($dbquery, $this->dbconn))
 return($packet);
 else return(FALSE);
 }
 else return(FALSE);
 }

 /**
 * auth_update is similar to auth_touch, but it will also
 * replace the supplemental data supplied by the user.
 *
 * @param    user    string - user-ID
 * @param    other    string - other data to save
 * @return    string - correctly compiled packet
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
 *        Luca Marchetti <l.marchetti@d-sign.it>
 */

 function auth_update($user, $other)
 {
 if($packet = $this->auth_check($user)) {
 // Ok, user authenticated
 $unique = strtok($packet, $this->separator);
 $packet = ereg_replace("'", "\'", $this->packetget($unique, $other));
 // update packet in the data-base
 $dbquery =     "UPDATE ".$this->dbtable." ".
 "SET ".$this->dbpacket." = '$packet' ".
 "WHERE ".$this->dbuser." = '$user'";
 if($dbri = mysql_query($dbquery, $this->dbconn))
 return($packet);
 else return(FALSE);
 }
 else return(FALSE);
 }

 /**
 * auth_logout stops an existing session for user $user
 * removing the cookie sent with auth_login().
 *
 * @param    user    string - user-ID
 * @return    string - correctly compiled packet
 *
 * @access    public
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>,
 *        Luca Marchetti <l.marchetti@d-sign.it>
 */

 function auth_logout($user)
 {
 if($this->auth_check($user)) {
 // authenticated, can remove the cookie
 setcookie($this->cookiename);
 // update packet in the data-base
 $unique = md5(uniqid(rand()));
 $packet = ereg_replace("'", "\'", $this->packetget($unique, ""));
 $dbquery =     "UPDATE ".$this->dbtable." ".
 "SET ".$this->dbpacket." = '$packet' ".
 "WHERE ".$this->dbuser." = '$user'";
 if($dbri = mysql_query($dbquery, $this->dbconn))
 return($packet);
 else return(FALSE);
 }
 else return(FALSE);
 }

 /**
 * packetget formats a authorization packet using
 * passed unique-id $unique.
 *
 * @param    unique    string - unique-ID for the session
 * @param    other    string - other data to save
 * @return    string - correctly compiled packet
 *
 * @access    private
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>
 */

 function packetget($unique, $other)
 {
 global    $REMOTE_ADDR;

 $packet =    $unique.$this->separator.
 $REMOTE_ADDR.$this->separator.
 time();
 if($other) $packet = $packet.$this->separator.$other;
 return($packet);
 }

 /**
 * packetcheck scans the packet $packet to
 * examine its validity.
 *
 * @param    packet    string - packet (supposed correctly filled)
 * @return    string - session time left
 *
 * @access    private
 * @author    Davide Lucchesi <d.lucchesi@d-sign.it>
 */

 function packetcheck($packet)
 {
 global    $REMOTE_ADDR;

 $parts = explode($this->separator, trim($packet));
 $cookie = $GLOBALS[$this->cookiename];
 if($this->timeout > 0)
 $timeleft = -(time()-$parts[2]-$this->timeout);
 else $timeleft = 1;
 if(strcmp($parts[0], $cookie) == 0) {
 if(strcmp($parts[1], $REMOTE_ADDR) == 0) {
 if($timeleft > 0)
 return($timeleft);
 else return(FALSE);
 }
 else return(FALSE);
 }
 else return(FALSE);
 }
}
?>

&amp;nbsp;

&amp;nbsp;

PHP script for creating HTML Forms

PHP Dataform (PHP DF) script is a simple tool for creating HTML Forms with ease. It was especially designed for web developers, who do not want to spend excessive time on creating Forms in HTML or through PHP, but want to use a first-class OOP backend. Expandable structure, wise usage of common PHP-Patterns and continuous support make this a must for your PHP-swissarmy-knife.

 

 

<?
 include_once("include/functions.php");
?>
<html>
<html>
 <head>
 <title>PHP MicroCMS</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <LINK href="css/style.css" type=text/css rel=stylesheet />
 </head>
<body>
<?
if (file_exists("include/base.inc.php")) {
 echo "<script>document.location.href='index.php'</script>";
} else {
?>
<center>
<br/>
Welcome to PHP MicroCMS installation!
<br/><br/>
<?php
 $completed=false;
 if ($_POST['submit']=="Install!") {
 define('DB_ENCRYPT_KEY', '964j4ghr85fp');
 define('DB_PREFIX', 'MicroCMS_');
 $admin_mail = "";
 $username=isset($_POST['username'])?$_POST['username']:"";
 $password=isset($_POST['password'])?$_POST['password']:"";
 $database_name=isset($_POST['database_name'])?$_POST['database_name']:"";
 $database_host=isset($_POST['database_host'])?$_POST['database_host']:"";
 $database_username=isset($_POST['database_username'])?$_POST['database_username']:"";
 $database_password=isset($_POST['database_password'])?$_POST['database_password']:"";
 if (empty($username) || empty($password) || empty($database_host) || empty($database_username) || empty($database_password) || empty($database_name)) {
 draw_important_message("All fields are required! Please re-enter."); echo "<br />";
 } else {
 $f=fopen("include/base.inc.php","w+");
 $database_inf="<?php
 // DATABASE CONNECTION INFORMATION
 define('DATABASE_HOST', '"
.$database_host."');            // Database host
 define('DATABASE_NAME', '"
.$database_name."');            // Name of the database to be used
 define('DATABASE_USER_NAME', '"
.$database_username."');    // User name for access to database
 define('DATABASE_PASSWORD', '"
.$database_password."');    // Password for access to database
 define('DB_ENCRYPT_KEY', '964j4ghr85fp');        // Database encryption key
 define('DB_PREFIX', 'MicroCMS_');                // Unique prefix of all table names in the database

 define('ADMIN_EMAIL', '"
.$admin_mail."');        // Admin email for site users to contact
 ?>"
;

 if (fwrite($f,$database_inf)>0) {
 fclose($f);
 if (@mysql_connect($database_host, $database_username, $database_password)) {
 if (@mysql_select_db($database_name)) {
 if (@mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."accounts")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."accounts (
 id smallint(6) NOT NULL PRIMARY KEY auto_increment,
 user_name varchar(15) NOT NULL default '',
 password tinytext,
 account_type varchar(12) NOT NULL default '')"
)!=0 &amp;&amp;
 @mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."menus")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."menus (
 id int(11) NOT NULL PRIMARY KEY auto_increment,
 menu_name varchar(20) default NULL,
 menu_order tinyint(3) default '1')"
)!=0 &amp;&amp;
 @mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."static_pages")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."static_pages (
 id int(11) NOT NULL PRIMARY KEY auto_increment,
 page_key varchar(20) default NULL,
 page_title varchar(255) default NULL,
 page_text text,
 menu_id int(11) default '0',
 menu_link varchar(20) default NULL) "
)!=0 &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."accounts SET
 user_name='"
.$username."',
 password = AES_ENCRYPT('"
. $password . "', '" . DB_ENCRYPT_KEY . "'),
 account_type='mainadmin'"
)!=0 &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."menus (id, menu_name, menu_order) VALUES (NULL,'Categories',1)") &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."static_pages (id, page_key, page_title, page_text, menu_id, menu_link) VALUES (1, 'au', 'Page1', 'Integer sit amet lectus ut neque aliquam laoreet. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Integer tincidunt vestibulum velit. Etiam pulvinar leo non ipsum. Maecenas non elit vitae tortor pretium euismod. Vivamus consectetuer nisl ut odio. Etiam eget leo. Integer tellus nisl, mollis quis, tincidunt in, rhoncus sed, quam. Aliquam nulla dui, ullamcorper eget, rutrum in, convallis eu, mi. Pellentesque adipiscing nunc vitae dui. Morbi massa. Pellentesque diam velit, porttitor non, ultricies vehicula, viverra at, lorem. ', 1, 'Page 1'), (2, 'ssss_ssss', 'Page 2', '<P>Quisque sem lectus, vehicula vitae, blandit non, rutrum sed, pede. Integer neque ante, molestie sed, scelerisque rhoncus, suscipit vitae, orci. Quisque sapien. Praesent pretium orci ut nisl. Etiam magna nisi, fringilla dictum, dapibus vitae, bibendum id, nunc. Donec nibh odio, condimentum placerat, ullamcorper sit amet, fringilla at, felis. Proin feugiat urna at nibh. Morbi aliquet fermentum est. Nulla aliquam mi id enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed gravida tincidunt nibh. Phasellus condimentum hendrerit pede. Aliquam a velit quis ante dignissim elementum. Curabitur ornare velit et libero. Praesent vitae libero. </P>', 1, 'Page 2'), (3, 'home', 'Welcome to PHP MicroCMS Home', \"<span style='font-weight: bold;'>Welcome to PHP Micro CMS!</span> <br><br>You have just installed a FREE version of PHP MicroCMS. <br>There is a new version ADVANCED available for purchasing and downloading. <br>To get more info about this version, please <a name='' target='' classname='' class='' href='/php-microcms/index.php?page=downloads'>visit our site</a> .<br><br>This is comparison table of main features for both versions.<br><br><div style='text-align: justify;'><img alt='' src='images/uploads/Mong_Jai.jpg' vspace='' border='0' hspace=''><img alt='compare' src='images/compare_versions.png' vspace='' border='0' hspace=''></div><br><br>\", 0, ''); ")) {
 draw_success_message("PHP MicroCMS installation completed successfully!"); echo "<br /><br />";
 echo "<a href='index.php'>Home</a>&amp;nbsp;&amp;nbsp|&amp;nbsp;";
 echo "&amp;nbsp;<a href='index.php?admin=login'>Admin Login</a>&amp;nbsp;";
 $completed=true;
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("Cannot open file include/base.inc.php"); echo "<br />";
 }
 }
 }

?>
<? if (!$completed) { ?>
<form method="post" action="<? $_SERVER['SCRIPT_NAME'] ?>">
<table width="50%" border="0" cellspacing="0" cellpadding="2">
<tr>
 <tr>
 <td>&amp;nbsp;Database Host</td>
 <td>
 <input type="text" name="database_host" value='localhost' size="30">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Name</td>
 <td>
 <input type="text" name="database_name" size="30" value="<?= $database_name ?>">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Username</td>
 <td>
 <input type="text" name="database_username" size="30" value="<?= $database_username ?>">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Password</td>
 <td>
 <input type="text" name="database_password" size="30" value="<?= $database_password ?>">
 </td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Admin Login</td>
 <td><input type="text" name="username" size="30" value="<?= $username ?>"></td>
 </tr>
 <tr>
 <td>&amp;nbsp;Admin Password</td>
 <td><input name="password" type="text" size="15" maxlength="15" value="<?= $password ?>"></td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td colspan=2 align='center'>
 <input type="submit" name="submit" value="Install!">
 </td>
 </tr>

</table>
</form>
<? } ?>
</center>
<? } ?>
</body>
</html>

&amp;nbsp;

&amp;nbsp;

 


Welcome to PHP MicroCMS PHP MicroCMS (PHP MCMS) is a simple, but very powerful Content Management System that everyone can use. The PHP MCMS can be installed easily by web developers, webmasters, graphic designers, etc. PHP MCMS was developed in OOP and allows users to build websites in a few minutes. PHP MicroCMS allows users with very little technical knowledge to build websites, as done by millions of bloggers on the web.

 

 

<?
 include_once("include/functions.php");
?>
<html>
<html>
 <head>
 <title>PHP MicroCMS</title>
 <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
 <LINK href="css/style.css" type=text/css rel=stylesheet />
 </head>
<body>
<?
if (file_exists("include/base.inc.php")) {
 echo "<script>document.location.href='index.php'</script>";
} else {
?>
<center>
<br/>
Welcome to PHP MicroCMS installation!
<br/><br/>
<?php
 $completed=false;
 if ($_POST['submit']=="Install!") {
 define('DB_ENCRYPT_KEY', '964j4ghr85fp');
 define('DB_PREFIX', 'MicroCMS_');
 $admin_mail = "";
 $username=isset($_POST['username'])?$_POST['username']:"";
 $password=isset($_POST['password'])?$_POST['password']:"";
 $database_name=isset($_POST['database_name'])?$_POST['database_name']:"";
 $database_host=isset($_POST['database_host'])?$_POST['database_host']:"";
 $database_username=isset($_POST['database_username'])?$_POST['database_username']:"";
 $database_password=isset($_POST['database_password'])?$_POST['database_password']:"";
 if (empty($username) || empty($password) || empty($database_host) || empty($database_username) || empty($database_password) || empty($database_name)) {
 draw_important_message("All fields are required! Please re-enter."); echo "<br />";
 } else {
 $f=fopen("include/base.inc.php","w+");
 $database_inf="<?php
 // DATABASE CONNECTION INFORMATION
 define('DATABASE_HOST', '"
.$database_host."');            // Database host
 define('DATABASE_NAME', '"
.$database_name."');            // Name of the database to be used
 define('DATABASE_USER_NAME', '"
.$database_username."');    // User name for access to database
 define('DATABASE_PASSWORD', '"
.$database_password."');    // Password for access to database
 define('DB_ENCRYPT_KEY', '964j4ghr85fp');        // Database encryption key
 define('DB_PREFIX', 'MicroCMS_');                // Unique prefix of all table names in the database

 define('ADMIN_EMAIL', '"
.$admin_mail."');        // Admin email for site users to contact
 ?>"
;

 if (fwrite($f,$database_inf)>0) {
 fclose($f);
 if (@mysql_connect($database_host, $database_username, $database_password)) {
 if (@mysql_select_db($database_name)) {
 if (@mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."accounts")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."accounts (
 id smallint(6) NOT NULL PRIMARY KEY auto_increment,
 user_name varchar(15) NOT NULL default '',
 password tinytext,
 account_type varchar(12) NOT NULL default '')"
)!=0 &amp;&amp;
 @mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."menus")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."menus (
 id int(11) NOT NULL PRIMARY KEY auto_increment,
 menu_name varchar(20) default NULL,
 menu_order tinyint(3) default '1')"
)!=0 &amp;&amp;
 @mysql_query("DROP TABLE IF EXISTS ".DB_PREFIX."static_pages")!=0 &amp;&amp;
 @mysql_query("CREATE TABLE IF NOT EXISTS ".DB_PREFIX."static_pages (
 id int(11) NOT NULL PRIMARY KEY auto_increment,
 page_key varchar(20) default NULL,
 page_title varchar(255) default NULL,
 page_text text,
 menu_id int(11) default '0',
 menu_link varchar(20) default NULL) "
)!=0 &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."accounts SET
 user_name='"
.$username."',
 password = AES_ENCRYPT('"
. $password . "', '" . DB_ENCRYPT_KEY . "'),
 account_type='mainadmin'"
)!=0 &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."menus (id, menu_name, menu_order) VALUES (NULL,'Categories',1)") &amp;&amp;
 @mysql_query("INSERT INTO ".DB_PREFIX."static_pages (id, page_key, page_title, page_text, menu_id, menu_link) VALUES (1, 'au', 'Page1', 'Integer sit amet lectus ut neque aliquam laoreet. Vestibulum ante ipsum primis in faucibus orci luctus et ultrices posuere cubilia Curae; Nulla facilisi. Integer tincidunt vestibulum velit. Etiam pulvinar leo non ipsum. Maecenas non elit vitae tortor pretium euismod. Vivamus consectetuer nisl ut odio. Etiam eget leo. Integer tellus nisl, mollis quis, tincidunt in, rhoncus sed, quam. Aliquam nulla dui, ullamcorper eget, rutrum in, convallis eu, mi. Pellentesque adipiscing nunc vitae dui. Morbi massa. Pellentesque diam velit, porttitor non, ultricies vehicula, viverra at, lorem. ', 1, 'Page 1'), (2, 'ssss_ssss', 'Page 2', '<P>Quisque sem lectus, vehicula vitae, blandit non, rutrum sed, pede. Integer neque ante, molestie sed, scelerisque rhoncus, suscipit vitae, orci. Quisque sapien. Praesent pretium orci ut nisl. Etiam magna nisi, fringilla dictum, dapibus vitae, bibendum id, nunc. Donec nibh odio, condimentum placerat, ullamcorper sit amet, fringilla at, felis. Proin feugiat urna at nibh. Morbi aliquet fermentum est. Nulla aliquam mi id enim. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Sed gravida tincidunt nibh. Phasellus condimentum hendrerit pede. Aliquam a velit quis ante dignissim elementum. Curabitur ornare velit et libero. Praesent vitae libero. </P>', 1, 'Page 2'), (3, 'home', 'Welcome to PHP MicroCMS Home', \"<span style='font-weight: bold;'>Welcome to PHP Micro CMS!</span> <br><br>You have just installed a FREE version of PHP MicroCMS. <br>There is a new version ADVANCED available for purchasing and downloading. <br>To get more info about this version, please <a name='' target='' classname='' class='' href='/php-microcms/index.php?page=downloads'>visit our site</a> .<br><br>This is comparison table of main features for both versions.<br><br><div style='text-align: justify;'><img alt='' src='images/uploads/Mong_Jai.jpg' vspace='' border='0' hspace=''><img alt='compare' src='images/compare_versions.png' vspace='' border='0' hspace=''></div><br><br>\", 0, ''); ")) {
 draw_success_message("PHP MicroCMS installation completed successfully!"); echo "<br /><br />";
 echo "<a href='index.php'>Home</a>&amp;nbsp;&amp;nbsp|&amp;nbsp;";
 echo "&amp;nbsp;<a href='index.php?admin=login'>Admin Login</a>&amp;nbsp;";
 $completed=true;
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("An error occured while connecting to database! Check your connection parameters."); echo "<br />";
 @unlink("include/base.inc.php");
 }
 } else {
 draw_important_message("Cannot open file include/base.inc.php"); echo "<br />";
 }
 }
 }

?>
<? if (!$completed) { ?>
<form method="post" action="<? $_SERVER['SCRIPT_NAME'] ?>">
<table width="50%" border="0" cellspacing="0" cellpadding="2">
<tr>
 <tr>
 <td>&amp;nbsp;Database Host</td>
 <td>
 <input type="text" name="database_host" value='localhost' size="30">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Name</td>
 <td>
 <input type="text" name="database_name" size="30" value="<?= $database_name ?>">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Username</td>
 <td>
 <input type="text" name="database_username" size="30" value="<?= $database_username ?>">
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Database Password</td>
 <td>
 <input type="text" name="database_password" size="30" value="<?= $database_password ?>">
 </td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td>&amp;nbsp;Admin Login</td>
 <td><input type="text" name="username" size="30" value="<?= $username ?>"></td>
 </tr>
 <tr>
 <td>&amp;nbsp;Admin Password</td>
 <td><input name="password" type="text" size="15" maxlength="15" value="<?= $password ?>"></td>
 </tr>
 <tr>
 <td colspan=2 >
 &amp;nbsp;
 </td>
 </tr>
 <tr>
 <td colspan=2 align='center'>
 <input type="submit" name="submit" value="Install!">
 </td>
 </tr>

</table>
</form>
<? } ?>
</center>
<? } ?>
</body>
</html>

PHP DataGrid (AJAX Enabled) User Authentication

PHP DataGrid (AJAX Enabled) script is a simple, innovative and powerful tool for generating data-bound grid control. It was specially designed for web developers. The PHP DataGrid is excellent for all PHP database-driven web sites and online-based data administration; it is also useful for dynamic content management and PHP-based hosting providers. The goal of this script is to simplify the generation and editing of DataGrid for web developers. The PHP DG is an excellent tool for: – PHP database-driven web sites – Adding Back-End for existing sites; – Creating online-based data administration; – Creating dynamic content management or your own CMS.

 

 

<?php
################################################################################
##              -= YOU MAY NOT REMOVE OR CHANGE THIS NOTICE =-                 #
## --------------------------------------------------------------------------- #
##  PHP DataGrid version 4.2.8 (01.10.2008)                                    #
##  Author &amp; developer:     Leumas Naypoka <leumas.a@gmail.com>                #
##  Developers:             Zewa           <http://www.softic.at>              #
##                          Fcallez        <http://www.innovavirtual.org>      #
##  Lisence:    GNU GPL                                                        #
##  Site:       http://phpbuilder.blogspot.com                                 #
##  Copyright:  Leumas Naypoka (c) 2006-2008. All rights reserved.             #
################################################################################
## +---------------------------------------------------------------------------+
## | 1. Creating &amp; Calling:                                                    |
## +---------------------------------------------------------------------------+
##  *** define a relative (virtual) path to datagrid.class.php file and "pear"
##  *** directory (relatively to the current file)
##  *** RELATIVE PATH ONLY ***
//
//  define ("DATAGRID_DIR", "");                     /* Ex.: "datagrid/" */
//  define ("PEAR_DIR", "pear/");                    /* Ex.: "datagrid/pear/" */
//
//  require_once(DATAGRID_DIR.'datagrid.class.php');
//  require_once(PEAR_DIR.'PEAR.php');
//  require_once(PEAR_DIR.'DB.php');
##
##  *** creating variables that we need for database connection
//  $DB_USER='name';            /* usually like this: prefix_name             */
//  $DB_PASS='';                /* must be already enscrypted (recommended)   */
//  $DB_HOST='localhost';       /* usually localhost                          */
//  $DB_NAME='dbName';          /* usually like this: prefix_dbName           */
//
//  ob_start();
##  *** (example of ODBC connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('odbc://root:12345@test_db'));
##  *** (example of Oracle connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('oci8://root:12345@localhost:1521/mydatabase));
##  *** (example of PostgreSQL connection string)
##  *** $result_conn = $db_conn->connect(DB::parseDSN('pgsql://root:12345@localhost/mydatabase));
##  === (Examples of connections to other db types see in "docs/pear/" folder)
//  $db_conn = DB::factory('mysql');  /* don't forget to change on appropriate db type */
//  $result_conn = $db_conn->connect(DB::parseDSN('mysql://'.$DB_USER.':'.$DB_PASS.'@'.$DB_HOST.'/'.$DB_NAME));
//  if(DB::isError($result_conn)){ die($result_conn->getDebugInfo()); }
##  *** put a primary key on the first place
//  $sql = "SELECT primary_key, field_1, field_2 ... FROM tableName ;";
##  *** set needed options and create a new class instance
//  $debug_mode = false;        /* display SQL statements while processing */
//  $messaging = true;          /* display system messages on a screen */
//  $unique_prefix = "abc_";    /* prevent overlays - must be started with a letter */
//  $dgrid = new DataGrid($debug_mode, $messaging, $unique_prefix, DATAGRID_DIR);
##  *** set encoding and collation (default: utf8/utf8_unicode_ci)
/// $dg_encoding = "utf8";
/// $dg_collation = "utf8_unicode_ci";
/// $dgrid->SetEncoding($dg_encoding, $dg_collation);
##  *** set data source with needed options
//  $default_order_field = "field_name_1 [, field_name_2...]";
//  $default_order_type = "ASC|DESC [, ASC|DESC...]";
//  $dgrid->DataSource($db_conn, $sql, $default_order_field, $default_order_type);
##
##
## +---------------------------------------------------------------------------+
## | 2. General Settings:                                                      |
## +---------------------------------------------------------------------------+
##  *** set interface language (default - English)
##  *** (en) - English     (de) - German     (se) - Swedish   (hr) - Bosnian/Croatian
##  *** (hu) - Hungarian   (es) - Espanol    (ca) - Catala    (fr) - Francais
##  *** (nl) - Netherlands/"Vlaams"(Flemish) (it) - Italiano  (pl) - Polish
##  *** (ch) - Chinese     (sr) - Serbian    (bg) - Bulgarian (pb) - Brazilian Portuguese
##  *** (ar) - Arabic      (tr) - Turkish    (cz) - Czech     (ro/ro_utf8) - Romanian
##  *** (gk) - Greek       (he) - Hebrew     (ru_utf8) - Russian
/// $dg_language = "en";
/// $dgrid->SetInterfaceLang($dg_language);
##  *** set direction: "ltr" or "rtr" (default - "ltr")
/// $direction = "ltr";
/// $dgrid->SetDirection($direction);
##  *** set layouts: "0" - tabular(horizontal) - default, "1" - columnar(vertical), "2" - customized
/// $layouts = array("view"=>"0", "edit"=>"1", "details"=>"1", "filter"=>"1");
/// $dgrid->SetLayouts($layouts);
/// $details_template = "<table><tr><td>{field_name_1}</td><td>{field_name_2}</td></tr>...</table>";
/// $dgrid->SetTemplates("","",$details_template);
##  *** set modes for operations ("type" => "link|button|image")
##  *** "byFieldValue"=>"fieldName" - make the field to be a link to edit mode page
/// $modes = array(
///     "add"      =>array("view"=>true, "edit"=>false, "type"=>"link", "show_add_button"=>"inside|outside"),
///     "edit"      =>array("view"=>true, "edit"=>true,  "type"=>"link", "byFieldValue"=>""),
///     "cancel"  =>array("view"=>true, "edit"=>true,  "type"=>"link"),
///     "details" =>array("view"=>true, "edit"=>false, "type"=>"link"),
///     "delete"  =>array("view"=>true, "edit"=>true,  "type"=>"image")
/// );
/// $dgrid->SetModes($modes);
##  *** allow scrolling on datagrid
/// $scrolling_option = false;
/// $dgrid->AllowScrollingSettings($scrolling_option);
##  *** set scrolling settings (optional)
/// $scrolling_width = "90%";
/// $scrolling_height = "100%";
/// $dgrid->setScrollingSettings($scrolling_width, $scrolling_height);
##  *** allow multirow operations
//  $multirow_option = true;
//  $dgrid->AllowMultirowOperations($multirow_option);
/// $multirow_operations = array(
///     "delete"  => array("view"=>true),
///     "details" => array("view"=>true),
///     "my_operation_name" => array("view"=>true, "flag_name"=>"my_flag_name", "flag_value"=>"my_flag_value", "tooltip"=>"Do something with selected", "image"=>"image.gif")
/// );
/// $dgrid->SetMultirowOperations($multirow_operations);
##  *** set CSS class for datagrid
##  *** "default" or "blue" or "gray" or "green" or "pink" or your own css file
/// $css_class = "default";
/// $dgrid->SetCssClass($css_class);
##  *** set variables that used to get access to the page (like: my_page.php?act=34&amp;id=56 etc.)
/// $http_get_vars = array("act", "id");
/// $dgrid->SetHttpGetVars($http_get_vars);
##  *** set other datagrid/s unique prefixes (if you use few datagrids on one page)
##  *** format (in which mode to allow processing of another datagrids)
##  *** array("unique_prefix"=>array("view"=>true|false, "edit"=>true|false, "details"=>true|false));
/// $anotherDatagrids = array("abcd_"=>array("view"=>true, "edit"=>true, "details"=>true));
/// $dgrid->SetAnotherDatagrids($anotherDatagrids);
##  *** set DataGrid caption
/// $dg_caption = "My Favorite Lovely PHP DataGrid";
/// $dgrid->SetCaption($dg_caption);
##
##
## +---------------------------------------------------------------------------+
## | 3. Printing &amp; Exporting Settings:                                         |
## +---------------------------------------------------------------------------+
##  *** set printing option: true(default) or false
/// $printing_option = true;
/// $dgrid->AllowPrinting($printing_option);
##  *** set exporting option: true(default) or false and relative (virtual) path
##  *** to export directory (relatively to datagrid.class.php file).
##  *** Ex.: "" - if we use current datagrid folder
/// $exporting_option = true;
/// $exporting_directory = "";
/// $dgrid->AllowExporting($exporting_option, $exporting_directory);
/// $exporting_types = array("excel"=>"true", "pdf"=>"true", "xml"=>"true");
/// $dgrid->AllowExportingTypes($exporting_types);
##
##
## +---------------------------------------------------------------------------+
## | 4. Sorting &amp; Paging Settings:                                             |
## +---------------------------------------------------------------------------+
##  *** set sorting option: true(default) or false
/// $sorting_option = true;
/// $dgrid->AllowSorting($sorting_option);
##  *** set paging option: true(default) or false
/// $paging_option = true;
/// $rows_numeration = false;
/// $numeration_sign = "N #";
/// $dgrid->AllowPaging($paging_option, $rows_numeration, $numeration_sign);
##  *** set paging settings
/// $bottom_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
/// $top_paging = array("results"=>true, "results_align"=>"left", "pages"=>true, "pages_align"=>"center", "page_size"=>true, "page_size_align"=>"right");
//  $pages_array = array("10"=>"10", "25"=>"25", "50"=>"50", "100"=>"100", "250"=>"250", "500"=>"500", "1000"=>"1000");
/// $default_page_size = 10;
/// $paging_arrows = array("first"=>"|&amp;lt;&amp;lt;", "previous"=>"&amp;lt;&amp;lt;", "next"=>"&amp;gt;&amp;gt;", "last"=>"&amp;gt;&amp;gt;|");
/// $dgrid->SetPagingSettings($bottom_paging, $top_paging, $pages_array, $default_page_size, $paging_arrows);
##
##
## +---------------------------------------------------------------------------+
## | 5. Filter Settings:                                                       |
## +---------------------------------------------------------------------------+
##  *** set filtering option: true or false(default)
/// $filtering_option = true;
/// $show_search_type = true;
/// $dgrid->AllowFiltering($filtering_option, $show_search_type);
##  *** set aditional filtering settings
##  *** tips: use "," (comma) if you want to make search by some words, for ex.: hello, bye, hi
/// $fill_from_array = array("0"=>"No", "1"=>"Yes");  /* as "value"=>"option" */
/// $filtering_fields = array(
///     "Caption_1"=>array("type"=>"textbox", "table"=>"tableName_1", "field"=>"fieldName_1|,fieldName_2", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_2"=>array("type"=>"textbox", "autocomplete"=>"false", "handler"=>"modules/autosuggest/test.php", "maxresults"=>"12", "shownoresults"=>"false", "table"=>"tableName_1", "field"=>"fieldName_1|,fieldName_2", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_3"=>array("type"=>"dropdownlist", "order"=>"ASC|DESC", "table"=>"tableName_2", "field"=>"fieldName_2", "source"=>"self"|$fill_from_array, "show"=>"", "condition"=>"", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
///     "Caption_4"=>array("type"=>"calendar", "table"=>"tableName_3", "field"=>"fieldName_3", "show_operator"=>"false", "default_operator"=>"=|<|>|like|%like|like%|%like%|not like", "case_sensitive"=>"false", "comparison_type"=>"string|numeric|binary", "width"=>"", "on_js_event"=>""),
/// );
/// $dgrid->SetFieldsFiltering($filtering_fields);
##
##
## +---------------------------------------------------------------------------+
## | 6. View Mode Settings:                                                    |
## +---------------------------------------------------------------------------+
##  *** set view mode table properties
/// $vm_table_properties = array("width"=>"90%");
/// $dgrid->SetViewModeTableProperties($vm_table_properties);
##  *** set columns in view mode
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
##  ***      "barchart" : number format in SELECT SQL must be equal with number format in max_value
/// $fill_from_array = array("0"=>"Banned", "1"=>"Active", "2"=>"Closed", "3"=>"Removed"); /* as "value"=>"option" */
/// $vm_colimns = array(
///     "FieldName_1"=>array("header"=>"Name_A", "type"=>"label",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_2"=>array("header"=>"Name_B", "type"=>"linktoview", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_3"=>array("header"=>"Name_C", "type"=>"linktoedit", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_4"=>array("header"=>"Name_D", "type"=>"linktodelete", "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_5"=>array("header"=>"Name_E", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"{0}"),
///     "FieldName_6"=>array("header"=>"Name_F", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"mailto:{0}"),
///     "FieldName_7"=>array("header"=>"Name_G", "type"=>"link",       "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "rel"=>"", "title"=>"", "target"=>"_new", "href"=>"http://mydomain.com?act={0}&amp;act={1}&amp;code=ABC"),
///     "FieldName_8"=>array("header"=>"Name_H", "type"=>"money",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "sign"=>"$", "decimal_places"=>"2", "dec_separator"=>".", "thousands_separator"=>","),
///     "FieldName_9"=>array("header"=>"Name_I", "type"=>"password",   "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_10"=>array("header"=>"Name_J", "type"=>"barchart",   "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "field"=>"field_name", "maximum_value"=>"value"),
///     "FieldName_11"=>array("header"=>"Name_K", "type"=>"enum",      "align"=>"left", "width"=>"X%|Xpx", "wrap"=>"wrap|nowrap", "text_length"=>"-1", "tooltip"=>"false", "tooltip_type"=>"floating|simple", "case"=>"normal|upper|lower|camel", "summarize"=>"false", "sort_type"=>"string|numeric", "sort_by"=>"", "visible"=>"true", "on_js_event"=>"", "source"=>$fill_from_array),
/// );
/// $dgrid->SetColumnsInViewMode($vm_colimns);
##  *** set auto-genereted columns in view mode
//  $auto_column_in_view_mode = false;
//  $dgrid->SetAutoColumnsInViewMode($auto_column_in_view_mode);
##
##
## +---------------------------------------------------------------------------+
## | 7. Add/Edit/Details Mode Settings:                                        |
## +---------------------------------------------------------------------------+
##  *** set add/edit mode table properties
/// $em_table_properties = array("width"=>"70%");
/// $dgrid->SetEditModeTableProperties($em_table_properties);
##  *** set details mode table properties
/// $dm_table_properties = array("width"=>"70%");
/// $dgrid->SetDetailsModeTableProperties($dm_table_properties);
##  ***  set settings for add/edit/details modes
//  $table_name  = "table_name";
//  $primary_key = "primary_key";
//  $condition   = "table_name.field = ".$_REQUEST['abc_rid'];
//  $dgrid->SetTableEdit($table_name, $primary_key, $condition);
##  *** set columns in edit mode
##  *** first letter:  r - required, s - simple (not required)
##  *** second letter: t - text(including datetime), n - numeric, a - alphanumeric,
##                     e - email, f - float, y - any, l - login name, z - zipcode,
##                     p - password, i - integer, v - verified, c - checkbox, u - URL
##  *** third letter (optional):
##          for numbers: s - signed, u - unsigned, p - positive, n - negative
##          for strings: u - upper,  l - lower,    n - normal,   y - any
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
##  *** Ex.: type = textbox|textarea|label|date(yyyy-mm-dd)|datedmy(dd-mm-yyyy)|datetime(yyyy-mm-dd hh:mm:ss)|datetimedmy(dd-mm-yyyy hh:mm:ss)|time(hh:mm:ss)|image|password|enum|print|checkbox
##  *** make sure your WYSIWYG dir has 777 permissions
/// $fill_from_array = array("0"=>"No", "1"=>"Yes", "2"=>"Don't know", "3"=>"My be"); /* as "value"=>"option" */
/// $em_columns = array(
///     "FieldName_1"  =>array("header"=>"Name_A", "type"=>"textbox",    "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_2"  =>array("header"=>"Name_B", "type"=>"textarea",   "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "edit_type"=>"simple|wysiwyg", "resizable"=>"false", "rows"=>"7", "cols"=>"50"),
///     "FieldName_3"  =>array("header"=>"Name_C", "type"=>"label",      "req_type"=>"rt", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_4"  =>array("header"=>"Name_D", "type"=>"date",       "req_type"=>"rt", "width"=>"187px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "calendar_type"=>"popup|floating"),
///     "FieldName_5"  =>array("header"=>"Name_E", "type"=>"datetime",   "req_type"=>"st", "width"=>"187px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "calendar_type"=>"popup|floating"),
///     "FieldName_6"  =>array("header"=>"Name_F", "type"=>"time",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_7"  =>array("header"=>"Name_J", "type"=>"password",   "req_type"=>"rp", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_8"  =>array("header"=>"Name_H", "type"=>"enum",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "source"=>"self"|$fill_from_array, "view_type"=>"dropdownlist(default)|radiobutton", "radiobuttons_alignment"=>"horizontal|vertical", "multiple"=>"false", "multiple_size"=>"4"),
///     "FieldName_9"  =>array("header"=>"Name_I", "type"=>"print",      "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>""),
///     "FieldName_10" =>array("header"=>"Name_J", "type"=>"checkbox",   "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "true_value"=>1, "false_value"=>0),
///     "FieldName_11" =>array("header"=>"Name_K", "type"=>"link",       "req_type"=>"st", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true", "on_js_event"=>"", "field_key"=>"field_name_0"|"field_key_1"=>"field_name_1"|..., "field_data"=>"field_name_2", "target"=>"_new", "href"=>"http://mydomain.com?act={0}&amp;act={1}&amp;code=ABC"),
///     "FieldName_12" =>array("header"=>"Name_L", "type"=>"foreign_key","req_type"=>"ri", "width"=>"210px", "title"=>"", "readonly"=>"false", "default"=>"", "unique"=>"false", "unique_condition"=>"", "visible"=>"true"),
///     "FieldName_13" =>array("header"=>"",       "type"=>"hidden",     "req_type"=>"st", "default"=>"default_value", "visible"=>"true", "unique"=>"false"),
///     "validator"    =>array("header"=>"Name_O", "type"=>"validator",  "req_type"=>"rv", "width"=>"210px", "title"=>"", "readonly"=>"false", "maxlength"=>"-1", "default"=>"", "visible"=>"true", "on_js_event"=>"", "for_field"=>"", "validation_type"=>"password|email"),
///     "delimiter"    =>array("inner_html"=>"<br>"),
/// );
/// $dgrid->SetColumnsInEditMode($em_columns);
##  *** set auto-genereted columns in edit mode
//  $auto_column_in_edit_mode = false;
//  $dgrid->SetAutoColumnsInEditMode($auto_column_in_edit_mode);
##  *** set foreign keys for add/edit/details modes (if there are linked tables)
##  *** Ex.: "field_name"=>"CONCAT(field1,','field2) as field3"
##  *** Ex.: "condition"=>"TableName_1.FieldName > 'a' AND TableName_1.FieldName < 'c'"
##  *** Ex.: "on_js_event"=>"onclick='alert(\"Yes!!!\");'"
/// $foreign_keys = array(
///     "ForeignKey_1"=>array("table"=>"TableName_1", "field_key"=>"FieldKey_1", "field_name"=>"FieldName_1", "view_type"=>"dropdownlist(default)|radiobutton|textbox", "radiobuttons_alignment"=>"horizontal|vertical", "condition"=>"", "order_by_field"=>"", "order_type"=>"ASC|DESC", "on_js_event"=>""),
///     "ForeignKey_2"=>array("table"=>"TableName_2", "field_key"=>"FieldKey_2", "field_name"=>"FieldName_2", "view_type"=>"dropdownlist(default)|radiobutton|textbox", "radiobuttons_alignment"=>"horizontal|vertical", "condition"=>"", "order_by_field"=>"", "order_type"=>"ASC|DESC", "on_js_event"=>"")
/// );
/// $dgrid->SetForeignKeysEdit($foreign_keys);
##
##
################################################################################


?>

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
 <title>:: Home</title>
 <meta http-equiv=Content-Type content="text/html; charset=utf-8">
 <?php
 ## call of this method between HTML <HEAD> elements
// $dgrid->WriteCssClass();
 ?>
</head>

<body>
<?php
 ################################################################################
## +---------------------------------------------------------------------------+
## | 8. Bind the DataGrid:                                                     |
## +---------------------------------------------------------------------------+
##  *** bind the DataGrid and draw it on the screen
//  $dgrid->Bind();
 //  ob_end_flush();
 ################################################################################
?>
</body>
</html>

&amp;nbsp;

 

PHP Scripts for Rad User Manager

Password protect sections of your website or create a members only area with the help of the Rad User Manager. The User Manager is a complete authentication system that is secure and customizable. All user information is saved in a database and can be easily integrated with existing web applications that use the same technology. Visitors to your site can sign up online or the administrator can add new members with the admin section. The admin se.

 

<?
# Rad User Manager Version 2.90
# Copyright (C) Rad Inks (Pvt) Ltd. 2003-2005
# http://www.radinks.net/

# Licence:
# The contents of this file are subject to the Mozilla Public
# License Version 1.1 (the "License"); you may not use this file
# except in compliance with the License. You may obtain a copy of
# the License at http://www.mozilla.org/MPL/
#
# Software distributed under the License is distributed on an "AS
# IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
# implied. See the License for the specific language governing
# rights and limitations under the License.
#
# The Initial Developer of the Original Code is Rad Inks (Pvt) Ltd.
# Portions created by Rad Inks are Copyright (C) 2003-2005
# Rad Inks (Pvt) Ltd. All Rights Reserved.
#


require_once(dirname(__FILE__)."/../inc/config.php");


define("iMANAGER",4);
define("iUSER",1);


class UserProfile
{
 var $id;
 var $userName;

 var $title;
 var $firstName;
 var $lastName;
 var $company;

 var $email;
 var $addr1;
 var $addr2;
 var $city;
 var $state;
 var $country;
 var $tel;
 var $fax;
 var $mobiTel;
 var $homeTel;
 var $web;
 var $key;
 var $IP;
 var $signUp;
 var $validated;
 var $newsLetter;
 var $zip;
}


function db_query($query)
{
 global $db_type;


 if($db_type == 'mysql')
 {
 $res = @mysql_query($query);
 }
 else
 {
 $res = @pg_query($query);
 }
 return $res;
}

function db_num_rows($res)
{
 global $db_type;
 if($db_type == 'mysql')
 {

 return @mysql_num_rows($res);
 }
 else
 {
 return @pg_num_rows($res);
 }
}


function db_fetch_row($res)
{
 global $db_type;
 if($db_type == 'mysql')
 {
 return mysql_fetch_row($res);
 }
 else
 {
 return pg_fetch_row($res);
 }
}


function db_fetch_array($res)
{
 global $db_type;
 if($db_type == 'mysql')
 {
 return mysql_fetch_array($res);
 }
 else
 {
 $row=pg_fetch_assoc($res);
 return $row;
 }
}

function db_error_log($line='')
{
 global $db_type;


 if($db_type == 'mysql')
 {
 if(mysql_errno() != 0)
 {
 $errMessage = mysql_error();
 error_log("$line $errMessage");
 return $errMessage;
 }
 }
 else
 {
 $errMessage = pg_last_error();
 error_log("$line $errMessage");
 return $errMessage;
 }
}

function db_insert_id($sequence)
{
 global $db_type;
 if($db_type == 'mysql')
 {
 return mysql_insert_id();
 }
 else
 {
 $result = pg_query("SELECT currval('$sequence')");
 if($result)
 {
 $row = pg_fetch_row($result);
 return $row[0];
 }
 }
}

/**
 * shows a formatted error message
 */

function err_message($str)
{
 echo sprintf('<table border=0 width="350" align="center">
 <tr><td>%s</td></tr>
 </table><br>'
,$str);
}

/**
 * this function returns the currently logged in user's username
 */

function get_name()
{
 global $con;
 $sid = session_id();
 $query = "SELECT a.userFirstName FROM userProfile a, loggedUsers b
 WHERE b.sessionId = '$sid' and b.userId = a.userId"
;

 $result = db_query($query);

 if($result)
 {
 $row = db_fetch_row($result);

 return $row[0];
 }
 else
 {
 return "";
 }

}

/**
 * Creates an entry in the logged users table. Call this method
 * directly if you want to automatically log in a new user who
 * has just signed up.
 */


function set_session($userId,$sessionId, $con)
{
 $query = "INSERT INTO loggedUsers(userId,sessionId, loginTime,lastAccess )
 VALUES($userId,'$sessionId', now(),now())"
;

 $result = db_query($query,$con);

 if(db_error_log() != '')
 {
 /*
 * it could be that you are already logged in
 */

 $u2 = is_logged($sessionId);

 return ($u2 == $userId);
 }

 return 1;
}

/**
 * this should not be a function, it should be a cron. It has however
 * been made available so that you have a means of cleaning up unwanted
 * sessions, even if you do not have access to the cron daemon or other
 * scheduling mechanism.
 */

function clean_sessions()
{
 global $db_type;
 if($db_type=='mysql')
 {
 $query = "delete from loggedUsers where
 unix_timestamp(date_add(lastAccess, interval 1 hour)) < unix_timestamp(now())"
;
 }
 else
 {
 $query = "delete from loggedUsers where
 round(date_part('epoch',lastAccess + interval '1 hour')) < round(date_part('epoch',now()))"
;
 }

 $result = db_query($query);
}

/**
 * returns 0 if you are not logged in. else returns your userid
 * also updates the 'lastAccess' field in the logged users table.
 */

function is_logged($sid="")
{
 global $con,$db_type;


 if(!isset($sid) || $sid == '')
 {
 $sid = session_id();
 }

 /*
 * if you set up a cron to clean up unwanted sessions, please comment
 * the next line.
 */

 clean_sessions();
 if($db_type=='mysql')
 {
 $query = "SELECT userId from loggedUsers where sessionId = '$sid' and
 unix_timestamp(date_add(lastAccess, interval 1 hour)) > unix_timestamp(now())"
;
 }
 else
 {
 $query = "SELECT userId from loggedUsers where sessionId = '$sid' and
 round(date_part('epoch',lastAccess + interval '1 hour')) >
 round(date_part('epoch',now()))"
;
 }

 $result = db_query($query);

 if($result)
 {
 $row = db_fetch_row($result);
 if($row)
 {

 $query = "UPDATE loggedUsers set lastAccess=now() where userId = $row[0]";
 db_query($query);
 db_error_log();
 }
 return $row[0];
 }
 else
 {
 return 0;
 }
}

/**
 * Are you logged in as the administrator?
 * also updates the 'lastAccess' field in the logged users table.
 */

function is_admin($sid="")
{
 global $con, $db_type;

 if(!isset($sid) || $sid == '')
 {
 $sid = session_id();
 }
 clean_sessions();

 if($db_type == 'mysql')
 {
 $query = "SELECT a.userId,b.userStatus FROM loggedUsers a, users b
 WHERE a.sessionId = '$sid' AND b.userStatus >= 2 AND
 a.userId = b.userId AND
 unix_timestamp(date_add(lastAccess, interval 1 hour)) > unix_timestamp(now())"
;
 }
 else
 {
 $query = "SELECT a.userId,b.userStatus FROM loggedUsers a, users b
 WHERE a.sessionId = '$sid' AND b.userStatus >= 2 AND
 a.userId = b.userId AND
 round(date_part('epoch',lastAccess + interval '1 hour')) >
 round(date_part('epoch',now()))"
;
 }


 $result = db_query($query);

 if($result)
 {
 $row = db_fetch_row($result);
 if($row[1]>1)
 {
 $query = "UPDATE loggedUsers set lastAccess=now() where userId = $row[0]";
 db_query($query);
 return $row[1];
 }
 }
 return 0;
}


/**
 * retrieves the uers's status. Currently supported values are
 * 0 - disabled.
 * 1 - enable.
 * 2 - admin.
 */


function get_user_status($userId)
{
 $query = "SELECT userStatus from users where userId = $userId";
 $result = db_query($query);
 if($result)
 {
 $row = db_fetch_row($result);
 return $row[0];
 }
 return 0;
}

/**
 * retrieves the email address given the username, used mainly by the
 * password reminder service.
 */

function get_email($username, $userId=0)
{
 if($userId==0)
 {
 $query = "SELECT a.userEmail from userProfile a, users b
 where b.username='$username' and b.userId = a.userId"
;
 }
 else
 {
 $query = "SELECT userEmail from userProfile    where
 userId = $userId"
;
 }
 error_log($query);
 $result = db_query($query);


 if(db_error_log == 0)
 {
 if($result)
 {
 $row=db_fetch_row($result);
 return $row[0];
 }
 else
 {

 return 0;

 }
 }
 else
 {

 return 0;
 }
}

/**
 * returns an instance of UserProfile for the member whose userId
 * is passed in as a parameter.
 */

function get_profile($userId)
{

 $query = "SELECT * from userProfile where userId = $userId";
 $result = db_query($query);

 if($result)
 {

 $row = array_change_key_case(db_fetch_array($result));

 $profile = new UserProfile;
 $profile->id = $row['userid'];
 $profile->firstName = $row['userfirstname'];
 $profile->lastName = $row['userlastname'];
 $profile->email = $row['useremail'];
 $profile->addr1 = $row['useraddr1'];
 $profile->addr2 = $row['useraddr2'];
 $profile->city = $row['usercity'];
 $profile->state = $row['userstate'];
 $profile->country = $row['usercountry'];
 $profile->tel = $row['usertel']    ;
 $profile->mobiTel = $row['usermobitel']    ;
 $profile->homeTel = $row['userhometel']    ;
 $profile->web = $row['userweb']    ;

 $profile->fax = $row['userfax'];
 $profile->key = $row['uservalidationkey'];
 $profile->IP = $row['userip'];
 $profile->signUp = $row['usersignup'];
 $profile->validated = $row['uservalidated'];
 $profile->newsLetter = $row['usernewsletter'];
 $porfile->zip = $row['userzip'];

 /*
 * this can be optimized so kill me
 */

 $query = "SELECT userName FROM users WHERE userId = $userId";
 $result = db_query($query);
 $row = db_fetch_row($result);

 $profile->userName=$row[0];


 return $profile;
 }
}


/**
 * displays the box that allows the user to view/change his
 * profile
 */

function show_profile($userId)
{

 $profile = get_profile($userId);

 require_once('profile.txt');
}

/**
 * called in when the user submits the change profile form
 */

function change_profile($profile)
{
 $query = sprintf("UPDATE userProfile SET userFirstName='%s',
 userLastName='%s', userAddr1 = '%s', userAddr2 = '%s',
 userEmail = '%s', userTel = '%s', userFax = '%s',
 userWeb = '%s', userMobiTel = '%s', userHomeTel = '%s',
 userZip = '%s',    userCountry = '%s', userState = '%s',
 userCity= '%s'    WHERE userId = %s"
,

 $profile->firstName, $profile->lastName,
 $profile->addr1, $profile->addr2, $profile->email,
 $profile->tel, $profile->fax, $profile->web,
 $profile->mobiTel, $profile->homeTel,
 $profile->zip,$profile->country,
 $profile->state,$profile->city,$profile->id);

 $result = db_query($query);

 return db_error_log();
}

/**
 * subscribe/unsubscribe from newsletters
 */

function change_newsletter($userId,$setting)
{
 global $con;
 $val = 0;
 if($setting == 'yes')
 {
 $val=1;
 }

 $query = "UPDATE userProfile set userNewsLetter=$val where userId=$userId";

 db_query($query);
 return db_error_log();
}

/**
 * changes the password for the given user
 */


function change_password($userId,$password)
{
 global $con,$user_password_function;
 $password = addslashes($password);
 if($user_password_function == 1)
 {
 $query = "UPDATE users set userPassword= password('$password') WHERE userId=$userId";
 }
 else
 {
 $query = "UPDATE users set userPassword= md5('$password') WHERE userId=$userId";
 }
 $result = db_query($query);

 return db_error_log();
}

/**
 * returns true if the username and password, and password confirm fields
 * are set. And the username field does not contain the '/' or '\' chars.
 */

function is_valid_username()
{
 $pass = sanitize_variable($_REQUEST['password']);
 $pass1 = sanitize_variable($_REQUEST['password1']);
 $user = sanitize_variable($_REQUEST['username']);

 return (isset($pass) &amp;&amp; $pass != '' &amp;&amp;
 isset($pass1) &amp;&amp; $pass1 != '' &amp;&amp;
 isset($user) &amp;&amp; $user != '' &amp;&amp;
 strpos($user,'/') ===false &amp;&amp;
 strpos($user,"\\") ===false);
}


/**
 * finds the userId when the userName is known.
 */

function get_user_id($user)
{
 $user = addslashes($user);
 $query = "SELECT userId from users WHERE userName='$user'";
 $result = db_query($query);
 if($result &amp;&amp; db_num_rows($result) != 0)
 {
 $row = db_fetch_row($result);
 return $row[0];
 }
 else
 {
 return -1;
 }
}


/**
 * this method changes the user status. The acceptable values are
 * 0 - disable account
 * 1 - enable account
 * 2 - mark as admin
 */


function set_user_status($userId, $status)
{
 $query = "UPDATE users set userStatus = $status WHERE userId = $userId";
 return db_query($query);
}


function sanitize_variable($var)
{
 return addslashes(trim(strip_tags($var)));
}

/**
 * hotmail, msn, bigfoot and other free addresses are not allowed.
 */

function is_valid_addr()
{
 $disallow = "/hotmail\.com|msn\.com|yahoo\.com|bigoot\.com|lycos\.com/";
 $email = sanitize_variable($_REQUEST['email']);
 if($email == '' || preg_match($disallow,$email))
 {
 return 0;
 }
 else
 {
 return 1;
 }

}


/**
 * returns userId on success. 0 on failure.
 * This method should be called when someone enters his username and pwd.
 */

function is_valid($user,$password)
{
 global $user_password_function;


 if($user_password_function == 1)
 {
 $query = "SELECT userId FROM users WHERE
 userName = '$user' and userPassword = password('$password') and userStatus > 0"
;
 }
 else
 {
 $query = "SELECT userId FROM users WHERE
 userName = '$user' and userPassword = md5('$password') and userStatus > 0"
;
 }
 $result = db_query($query);
 db_error_log();

 if($result &amp;&amp; db_num_rows($result) ==1)
 {

 $row = db_fetch_row($result);

 return $row[0];
 }
 return 0;
}



/**
 * check the referer to minimize abuse..
 * todo: a more vigourous check.
 */

function is_valid_referer()
{
 global $site_url;
 return (strstr($_SERVER['HTTP_REFERER'],$site_url));
}



function on_session_start($save_path, $session_name) {
 error_log($session_name . " ". session_id());
}

function on_session_end() {
 // Nothing needs to be done in this function
 // since we used persistent connection.
}

function on_session_read($key) {
 global $db_type;


 $stmt = "select session_data from sessions ";
 $stmt .= "where session_id ='$key' ";

 if($db_type == 'mysql')
 {
 $stmt .= "and unix_timestamp(session_expiration) >
 unix_timestamp(date_add(now(),interval 1 hour))"
;
 }
 else
 {
 $stmt .= "and round(date_part('epoch',session_expiration)) >
 round(date_part('epoch',lastAccess + interval '1 hour'))"
;
 }

 $result = db_query($stmt);

 if($result)
 {
 $row = array_change_key_case(db_fetch_array($result));
 return($row['session_data']);
 }
 else
 {
 return $result;
 }
}

/**
 * The heart of the session manager.
 *
 * If you are load balancing your web site across several servers you cannot
 * store session information in files. You will either need to store the
 * information in a database or use cookies. Since many people are reluctant
 * to trust cookies your choices narrow down to exactly one. YOu need to use
 * database.
 *
 * Storing session information in a database makes sense if you are on a
 * shared hosting enviorenment and have concerns about security.
 *
 * To enabale this feature set the variable $session_in_db to 'db';
 */

function on_session_write($key, $val) {
 global $db_type;

 $val = addslashes($val);

 $insert_stmt  = "insert into sessions values('$key', ";
 if($db_type == 'mysql')
 {
 $insert_stmt .= "'$val',unix_timestamp(date_add(now(), interval 1 hour)))";
 }
 else
 {
 $insert_stmt .= "'$val',round(date_part('epoch',lastAccess + interval '1 hour')))";
 }

 $update_stmt  = "update sessions set session_data ='$val', ";
 if($db_type == 'mysql')
 {
 $update_stmt .= "session_expiration = unix_timestamp(date_add(now(), interval 1 hour))";
 }
 else
 {
 $update_stmt .= "session_expiration = round(date_part('epoch',lastAccess + interval '1 hour'))";
 }

 $update_stmt .= "where session_id ='$key '";

 // First we try to insert, if that doesn't succeed, it means
 // session is already in the table and we try to update


 db_query($insert_stmt);

 $err = db_error_log();

 if ($err != '')
 {
 db_query($update_stmt);
 }
}

function on_session_destroy($key) {
 db_query("delete from sessions where session_id = '$key'");
}

function on_session_gc($max_lifetime)
{
 global $db_query;
 if($db_query == 'mysql')
 {
 db_query("delete from sessions where unix_timestamp(session_expiration)
 < unix_timestamp(now())"
);
 }
 else
 {
 db_query("delete from sessions where round(date_part('epoch',session_expiration))
 < round(date_part('epoch',now()))"
);
 }
}

if(isset($session_save) &amp;&amp; $session_save == 'db')
{
 error_log('setting save handler');
 // Set the save handlers
 session_set_save_handler("on_session_start",   "on_session_end",
 "on_session_read",    "on_session_write",
 "on_session_destroy", "on_session_gc");
}

session_start();
?>

&amp;nbsp;

Scripts for LDAP Account Manager Authentication

LDAP Account Manager is a webfrontend for managing accounts stored in an LDAP directory.Features: – management of Unix user and group accounts (posixAccount/posixGroup) – management of Samba 2.x/3 user and host accounts (sambaAccount/sambaSamAccount) – management of Kolab 2 accounts (kolabInetorgPerson) – profiles for account creation – account creation via file upload – automatic creation/deletion of home directories – setting quotas – PDF outp.

 

<?php
/**
* This file includes the FPDF implementation which is used to generate PDF files.
*
* @author Olivier Plathey
* @package PDF
*/


/*******************************************************************************
* Software: FPDF                                                               *
* Version:  1.53                                                               *
* Date:     2004-12-31                                                         *
* Author:   Olivier PLATHEY                                                    *
* License:  Freeware                                                           *
*                                                                              *
* You may use, modify and redistribute this software as you wish.              *
*******************************************************************************/


if(!class_exists('FPDF'))
{
define('FPDF_VERSION','1.53');

/**
 * Main FPDF class for creating PDF documents
 *
 * @package PDF
 */

class FPDF
{
//Private properties
var $page;               //current page number
var $n;                  //current object number
var $offsets;            //array of object offsets
var $buffer;             //buffer holding in-memory PDF
var $pages;              //array containing pages
var $state;              //current document state
var $compress;           //compression flag
var $DefOrientation;     //default orientation
var $CurOrientation;     //current orientation
var $OrientationChanges; //array indicating orientation changes
var $k;                  //scale factor (number of points in user unit)
var $fwPt,$fhPt;         //dimensions of page format in points
var $fw,$fh;             //dimensions of page format in user unit
var $wPt,$hPt;           //current dimensions of page in points
var $w,$h;               //current dimensions of page in user unit
var $lMargin;            //left margin
var $tMargin;            //top margin
var $rMargin;            //right margin
var $bMargin;            //page break margin
var $cMargin;            //cell margin
var $x,$y;               //current position in user unit for cell positioning
var $lasth;              //height of last cell printed
var $LineWidth;          //line width in user unit
var $CoreFonts;          //array of standard font names
var $fonts;              //array of used fonts
var $FontFiles;          //array of font files
var $diffs;              //array of encoding differences
var $images;             //array of used images
var $PageLinks;          //array of links in pages
var $links;              //array of internal links
var $FontFamily;         //current font family
var $FontStyle;          //current font style
var $underline;          //underlining flag
var $CurrentFont;        //current font info
var $FontSizePt;         //current font size in points
var $FontSize;           //current font size in user unit
var $DrawColor;          //commands for drawing color
var $FillColor;          //commands for filling color
var $TextColor;          //commands for text color
var $ColorFlag;          //indicates whether fill and text colors are different
var $ws;                 //word spacing
var $AutoPageBreak;      //automatic page breaking
var $PageBreakTrigger;   //threshold used to trigger page breaks
var $InFooter;           //flag set when processing footer
var $ZoomMode;           //zoom display mode
var $LayoutMode;         //layout display mode
var $title;              //title
var $subject;            //subject
var $author;             //author
var $keywords;           //keywords
var $creator;            //creator
var $AliasNbPages;       //alias for total number of pages
var $PDFVersion;         //PDF version number

/*******************************************************************************
*                                                                              *
*                               Public methods                                 *
*                                                                              *
*******************************************************************************/

function FPDF($orientation='P',$unit='mm',$format='A4')
{
 //Some checks
 $this->_dochecks();
 //Initialization of properties
 $this->page=0;
 $this->n=2;
 $this->buffer='';
 $this->pages=array();
 $this->OrientationChanges=array();
 $this->state=0;
 $this->fonts=array();
 $this->FontFiles=array();
 $this->diffs=array();
 $this->images=array();
 $this->links=array();
 $this->InFooter=false;
 $this->lasth=0;
 $this->FontFamily='';
 $this->FontStyle='';
 $this->FontSizePt=12;
 $this->underline=false;
 $this->DrawColor='0 G';
 $this->FillColor='0 g';
 $this->TextColor='0 g';
 $this->ColorFlag=false;
 $this->ws=0;
 //Standard fonts
 $this->CoreFonts=array('courier'=>'Courier','courierB'=>'Courier-Bold','courierI'=>'Courier-Oblique','courierBI'=>'Courier-BoldOblique',
 'helvetica'=>'Helvetica','helveticaB'=>'Helvetica-Bold','helveticaI'=>'Helvetica-Oblique','helveticaBI'=>'Helvetica-BoldOblique',
 'times'=>'Times-Roman','timesB'=>'Times-Bold','timesI'=>'Times-Italic','timesBI'=>'Times-BoldItalic',
 'symbol'=>'Symbol','zapfdingbats'=>'ZapfDingbats');
 //Scale factor
 if($unit=='pt')
 $this->k=1;
 elseif($unit=='mm')
 $this->k=72/25.4;
 elseif($unit=='cm')
 $this->k=72/2.54;
 elseif($unit=='in')
 $this->k=72;
 else
 $this->Error('Incorrect unit: '.$unit);
 //Page format
 if(is_string($format))
 {
 $format=strtolower($format);
 if($format=='a3')
 $format=array(841.89,1190.55);
 elseif($format=='a4')
 $format=array(595.28,841.89);
 elseif($format=='a5')
 $format=array(420.94,595.28);
 elseif($format=='letter')
 $format=array(612,792);
 elseif($format=='legal')
 $format=array(612,1008);
 else
 $this->Error('Unknown page format: '.$format);
 $this->fwPt=$format[0];
 $this->fhPt=$format[1];
 }
 else
 {
 $this->fwPt=$format[0]*$this->k;
 $this->fhPt=$format[1]*$this->k;
 }
 $this->fw=$this->fwPt/$this->k;
 $this->fh=$this->fhPt/$this->k;
 //Page orientation
 $orientation=strtolower($orientation);
 if($orientation=='p' || $orientation=='portrait')
 {
 $this->DefOrientation='P';
 $this->wPt=$this->fwPt;
 $this->hPt=$this->fhPt;
 }
 elseif($orientation=='l' || $orientation=='landscape')
 {
 $this->DefOrientation='L';
 $this->wPt=$this->fhPt;
 $this->hPt=$this->fwPt;
 }
 else
 $this->Error('Incorrect orientation: '.$orientation);
 $this->CurOrientation=$this->DefOrientation;
 $this->w=$this->wPt/$this->k;
 $this->h=$this->hPt/$this->k;
 //Page margins (1 cm)
 $margin=28.35/$this->k;
 $this->SetMargins($margin,$margin);
 //Interior cell margin (1 mm)
 $this->cMargin=$margin/10;
 //Line width (0.2 mm)
 $this->LineWidth=.567/$this->k;
 //Automatic page break
 $this->SetAutoPageBreak(true,2*$margin);
 //Full width display mode
 $this->SetDisplayMode('fullwidth');
 //Enable compression
 $this->SetCompression(true);
 //Set default PDF version number
 $this->PDFVersion='1.3';
}

function SetMargins($left,$top,$right=-1)
{
 //Set left, top and right margins
 $this->lMargin=$left;
 $this->tMargin=$top;
 if($right==-1)
 $right=$left;
 $this->rMargin=$right;
}

function SetLeftMargin($margin)
{
 //Set left margin
 $this->lMargin=$margin;
 if($this->page>0 &amp;&amp; $this->x<$margin)
 $this->x=$margin;
}

function SetTopMargin($margin)
{
 //Set top margin
 $this->tMargin=$margin;
}

function SetRightMargin($margin)
{
 //Set right margin
 $this->rMargin=$margin;
}

function SetAutoPageBreak($auto,$margin=0)
{
 //Set auto page break mode and triggering margin
 $this->AutoPageBreak=$auto;
 $this->bMargin=$margin;
 $this->PageBreakTrigger=$this->h-$margin;
}

function SetDisplayMode($zoom,$layout='continuous')
{
 //Set display mode in viewer
 if($zoom=='fullpage' || $zoom=='fullwidth' || $zoom=='real' || $zoom=='default' || !is_string($zoom))
 $this->ZoomMode=$zoom;
 else
 $this->Error('Incorrect zoom display mode: '.$zoom);
 if($layout=='single' || $layout=='continuous' || $layout=='two' || $layout=='default')
 $this->LayoutMode=$layout;
 else
 $this->Error('Incorrect layout display mode: '.$layout);
}

function SetCompression($compress)
{
 //Set page compression
 if(function_exists('gzcompress'))
 $this->compress=$compress;
 else
 $this->compress=false;
}

function SetTitle($title)
{
 //Title of document
 $this->title=$title;
}

function SetSubject($subject)
{
 //Subject of document
 $this->subject=$subject;
}

function SetAuthor($author)
{
 //Author of document
 $this->author=$author;
}

function SetKeywords($keywords)
{
 //Keywords of document
 $this->keywords=$keywords;
}

function SetCreator($creator)
{
 //Creator of document
 $this->creator=$creator;
}

function AliasNbPages($alias='{nb}')
{
 //Define an alias for total number of pages
 $this->AliasNbPages=$alias;
}

function Error($msg)
{
 //Fatal error
 die('<B>FPDF error: </B>'.$msg);
}

function Open()
{
 //Begin document
 $this->state=1;
}

function Close()
{
 //Terminate document
 if($this->state==3)
 return;
 if($this->page==0)
 $this->AddPage();
 //Page footer
 $this->InFooter=true;
 $this->Footer();
 $this->InFooter=false;
 //Close page
 $this->_endpage();
 //Close document
 $this->_enddoc();
}

function AddPage($orientation='')
{
 //Start a new page
 if($this->state==0)
 $this->Open();
 $family=$this->FontFamily;
 $style=$this->FontStyle.($this->underline ? 'U' : '');
 $size=$this->FontSizePt;
 $lw=$this->LineWidth;
 $dc=$this->DrawColor;
 $fc=$this->FillColor;
 $tc=$this->TextColor;
 $cf=$this->ColorFlag;
 if($this->page>0)
 {
 //Page footer
 $this->InFooter=true;
 $this->Footer();
 $this->InFooter=false;
 //Close page
 $this->_endpage();
 }
 //Start new page
 $this->_beginpage($orientation);
 //Set line cap style to square
 $this->_out('2 J');
 //Set line width
 $this->LineWidth=$lw;
 $this->_out(sprintf('%.2f w',$lw*$this->k));
 //Set font
 if($family)
 $this->SetFont($family,$style,$size);
 //Set colors
 $this->DrawColor=$dc;
 if($dc!='0 G')
 $this->_out($dc);
 $this->FillColor=$fc;
 if($fc!='0 g')
 $this->_out($fc);
 $this->TextColor=$tc;
 $this->ColorFlag=$cf;
 //Page header
 $this->Header();
 //Restore line width
 if($this->LineWidth!=$lw)
 {
 $this->LineWidth=$lw;
 $this->_out(sprintf('%.2f w',$lw*$this->k));
 }
 //Restore font
 if($family)
 $this->SetFont($family,$style,$size);
 //Restore colors
 if($this->DrawColor!=$dc)
 {
 $this->DrawColor=$dc;
 $this->_out($dc);
 }
 if($this->FillColor!=$fc)
 {
 $this->FillColor=$fc;
 $this->_out($fc);
 }
 $this->TextColor=$tc;
 $this->ColorFlag=$cf;
}

function Header()
{
 //To be implemented in your own inherited class
}

function Footer()
{
 //To be implemented in your own inherited class
}

function PageNo()
{
 //Get current page number
 return $this->page;
}

function SetDrawColor($r,$g=-1,$b=-1)
{
 //Set color for all stroking operations
 if(($r==0 &amp;&amp; $g==0 &amp;&amp; $b==0) || $g==-1)
 $this->DrawColor=sprintf('%.3f G',$r/255);
 else
 $this->DrawColor=sprintf('%.3f %.3f %.3f RG',$r/255,$g/255,$b/255);
 if($this->page>0)
 $this->_out($this->DrawColor);
}

function SetFillColor($r,$g=-1,$b=-1)
{
 //Set color for all filling operations
 if(($r==0 &amp;&amp; $g==0 &amp;&amp; $b==0) || $g==-1)
 $this->FillColor=sprintf('%.3f g',$r/255);
 else
 $this->FillColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
 $this->ColorFlag=($this->FillColor!=$this->TextColor);
 if($this->page>0)
 $this->_out($this->FillColor);
}

function SetTextColor($r,$g=-1,$b=-1)
{
 //Set color for text
 if(($r==0 &amp;&amp; $g==0 &amp;&amp; $b==0) || $g==-1)
 $this->TextColor=sprintf('%.3f g',$r/255);
 else
 $this->TextColor=sprintf('%.3f %.3f %.3f rg',$r/255,$g/255,$b/255);
 $this->ColorFlag=($this->FillColor!=$this->TextColor);
}

function GetStringWidth($s)
{
 //Get width of a string in the current font
 $s=(string)$s;
 $cw=&amp;$this->CurrentFont['cw'];
 $w=0;
 $l=strlen($s);
 for($i=0;$i<$l;$i++)
 $w+=$cw[$s{$i}];
 return $w*$this->FontSize/1000;
}

function SetLineWidth($width)
{
 //Set line width
 $this->LineWidth=$width;
 if($this->page>0)
 $this->_out(sprintf('%.2f w',$width*$this->k));
}

function Line($x1,$y1,$x2,$y2)
{
 //Draw a line
 $this->_out(sprintf('%.2f %.2f m %.2f %.2f l S',$x1*$this->k,($this->h-$y1)*$this->k,$x2*$this->k,($this->h-$y2)*$this->k));
}

function Rect($x,$y,$w,$h,$style='')
{
 //Draw a rectangle
 if($style=='F')
 $op='f';
 elseif($style=='FD' || $style=='DF')
 $op='B';
 else
 $op='S';
 $this->_out(sprintf('%.2f %.2f %.2f %.2f re %s',$x*$this->k,($this->h-$y)*$this->k,$w*$this->k,-$h*$this->k,$op));
}

function AddFont($family,$style='',$file='')
{
 //Add a TrueType or Type1 font
 $family=strtolower($family);
 if($file=='')
 $file=str_replace(' ','',$family).strtolower($style).'.php';
 if($family=='arial')
 $family='helvetica';
 $style=strtoupper($style);
 if($style=='IB')
 $style='BI';
 $fontkey=$family.$style;
 if(isset($this->fonts[$fontkey]))
 $this->Error('Font already added: '.$family.' '.$style);
 include($this->_getfontpath().$file);
 if(!isset($name))
 $this->Error('Could not include font definition file');
 $i=count($this->fonts)+1;
 $this->fonts[$fontkey]=array('i'=>$i,'type'=>$type,'name'=>$name,'desc'=>$desc,'up'=>$up,'ut'=>$ut,'cw'=>$cw,'enc'=>$enc,'file'=>$file);
 if($diff)
 {
 //Search existing encodings
 $d=0;
 $nb=count($this->diffs);
 for($i=1;$i<=$nb;$i++)
 {
 if($this->diffs[$i]==$diff)
 {
 $d=$i;
 break;
 }
 }
 if($d==0)
 {
 $d=$nb+1;
 $this->diffs[$d]=$diff;
 }
 $this->fonts[$fontkey]['diff']=$d;
 }
 if($file)
 {
 if($type=='TrueType')
 $this->FontFiles[$file]=array('length1'=>$originalsize);
 else
 $this->FontFiles[$file]=array('length1'=>$size1,'length2'=>$size2);
 }
}

function SetFont($family,$style='',$size=0)
{
 //Select a font; size given in points
 global $fpdf_charwidths;

 $family=strtolower($family);
 if($family=='')
 $family=$this->FontFamily;
 if($family=='arial')
 $family='helvetica';
 elseif($family=='symbol' || $family=='zapfdingbats')
 $style='';
 $style=strtoupper($style);
 if(strpos($style,'U')!==false)
 {
 $this->underline=true;
 $style=str_replace('U','',$style);
 }
 else
 $this->underline=false;
 if($style=='IB')
 $style='BI';
 if($size==0)
 $size=$this->FontSizePt;
 //Test if font is already selected
 if($this->FontFamily==$family &amp;&amp; $this->FontStyle==$style &amp;&amp; $this->FontSizePt==$size)
 return;
 //Test if used for the first time
 $fontkey=$family.$style;
 if(!isset($this->fonts[$fontkey]))
 {
 //Check if one of the standard fonts
 if(isset($this->CoreFonts[$fontkey]))
 {
 if(!isset($fpdf_charwidths[$fontkey]))
 {
 //Load metric file
 $file=$family;
 if($family=='times' || $family=='helvetica')
 $file.=strtolower($style);
 include($this->_getfontpath().$file.'.php');
 if(!isset($fpdf_charwidths[$fontkey]))
 $this->Error('Could not include font metric file');
 }
 $i=count($this->fonts)+1;
 $this->fonts[$fontkey]=array('i'=>$i,'type'=>'core','name'=>$this->CoreFonts[$fontkey],'up'=>-100,'ut'=>50,'cw'=>$fpdf_charwidths[$fontkey]);
 }
 else
 $this->Error('Undefined font: '.$family.' '.$style);
 }
 //Select it
 $this->FontFamily=$family;
 $this->FontStyle=$style;
 $this->FontSizePt=$size;
 $this->FontSize=$size/$this->k;
 $this->CurrentFont=&amp;$this->fonts[$fontkey];
 if($this->page>0)
 $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt));
}

function SetFontSize($size)
{
 //Set font size in points
 if($this->FontSizePt==$size)
 return;
 $this->FontSizePt=$size;
 $this->FontSize=$size/$this->k;
 if($this->page>0)
 $this->_out(sprintf('BT /F%d %.2f Tf ET',$this->CurrentFont['i'],$this->FontSizePt));
}

function AddLink()
{
 //Create a new internal link
 $n=count($this->links)+1;
 $this->links[$n]=array(0,0);
 return $n;
}

function SetLink($link,$y=0,$page=-1)
{
 //Set destination of internal link
 if($y==-1)
 $y=$this->y;
 if($page==-1)
 $page=$this->page;
 $this->links[$link]=array($page,$y);
}

function Link($x,$y,$w,$h,$link)
{
 //Put a link on the page
 $this->PageLinks[$this->page][]=array($x*$this->k,$this->hPt-$y*$this->k,$w*$this->k,$h*$this->k,$link);
}

function Text($x,$y,$txt)
{
 //Output a string
 $s=sprintf('BT %.2f %.2f Td (%s) Tj ET',$x*$this->k,($this->h-$y)*$this->k,$this->_escape($txt));
 if($this->underline &amp;&amp; $txt!='')
 $s.=' '.$this->_dounderline($x,$y,$txt);
 if($this->ColorFlag)
 $s='q '.$this->TextColor.' '.$s.' Q';
 $this->_out($s);
}

function AcceptPageBreak()
{
 //Accept automatic page break or not
 return $this->AutoPageBreak;
}

function Cell($w,$h=0,$txt='',$border=0,$ln=0,$align='',$fill=0,$link='')
{
 //Output a cell
 $k=$this->k;
 if($this->y+$h>$this->PageBreakTrigger &amp;&amp; !$this->InFooter &amp;&amp; $this->AcceptPageBreak())
 {
 //Automatic page break
 $x=$this->x;
 $ws=$this->ws;
 if($ws>0)
 {
 $this->ws=0;
 $this->_out('0 Tw');
 }
 $this->AddPage($this->CurOrientation);
 $this->x=$x;
 if($ws>0)
 {
 $this->ws=$ws;
 $this->_out(sprintf('%.3f Tw',$ws*$k));
 }
 }
 if($w==0)
 $w=$this->w-$this->rMargin-$this->x;
 $s='';
 if($fill==1 || $border==1)
 {
 if($fill==1)
 $op=($border==1) ? 'B' : 'f';
 else
 $op='S';
 $s=sprintf('%.2f %.2f %.2f %.2f re %s ',$this->x*$k,($this->h-$this->y)*$k,$w*$k,-$h*$k,$op);
 }
 if(is_string($border))
 {
 $x=$this->x;
 $y=$this->y;
 if(strpos($border,'L')!==false)
 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-$y)*$k,$x*$k,($this->h-($y+$h))*$k);
 if(strpos($border,'T')!==false)
 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-$y)*$k);
 if(strpos($border,'R')!==false)
 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',($x+$w)*$k,($this->h-$y)*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
 if(strpos($border,'B')!==false)
 $s.=sprintf('%.2f %.2f m %.2f %.2f l S ',$x*$k,($this->h-($y+$h))*$k,($x+$w)*$k,($this->h-($y+$h))*$k);
 }
 if($txt!=='')
 {
 if($align=='R')
 $dx=$w-$this->cMargin-$this->GetStringWidth($txt);
 elseif($align=='C')
 $dx=($w-$this->GetStringWidth($txt))/2;
 else
 $dx=$this->cMargin;
 if($this->ColorFlag)
 $s.='q '.$this->TextColor.' ';
 $txt2=str_replace(')','\\)',str_replace('(','\\(',str_replace('\','\\\',$txt)));
 $s.=sprintf('
BT %.2f %.2f Td (%s) Tj ET',($this->x+$dx)*$k,($this->h-($this->y+.5*$h+.3*$this->FontSize))*$k,$txt2);
 if($this->underline)
 $s.='
'.$this->_dounderline($this->x+$dx,$this->y+.5*$h+.3*$this->FontSize,$txt);
 if($this->ColorFlag)
 $s.='
Q';
 if($link)
 $this->Link($this->x+$dx,$this->y+.5*$h-.5*$this->FontSize,$this->GetStringWidth($txt),$this->FontSize,$link);
 }
 if($s)
 $this->_out($s);
 $this->lasth=$h;
 if($ln>0)
 {
 //Go to next line
 $this->y+=$h;
 if($ln==1)
 $this->x=$this->lMargin;
 }
 else
 $this->x+=$w;
}

function MultiCell($w,$h,$txt,$border=0,$align='
J',$fill=0)
{
 //Output text with automatic or explicit line breaks
 $cw=&amp;$this->CurrentFont['
cw'];
 if($w==0)
 $w=$this->w-$this->rMargin-$this->x;
 $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
 $s=str_replace("\r",'
',$txt);
 $nb=strlen($s);
 if($nb>0 &amp;&amp; $s[$nb-1]=="\n")
 $nb--;
 $b=0;
 if($border)
 {
 if($border==1)
 {
 $border='
LTRB';
 $b='
LRT';
 $b2='
LR';
 }
 else
 {
 $b2='
';
 if(strpos($border,'
L')!==false)
 $b2.='
L';
 if(strpos($border,'
R')!==false)
 $b2.='
R';
 $b=(strpos($border,'
T')!==false) ? $b2.'T' : $b2;
 }
 }
 $sep=-1;
 $i=0;
 $j=0;
 $l=0;
 $ns=0;
 $nl=1;
 while($i<$nb)
 {
 //Get next character
 $c=$s{$i};
 if($c=="\n")
 {
 //Explicit line break
 if($this->ws>0)
 {
 $this->ws=0;
 $this->_out('
0 Tw');
 }
 $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
 $i++;
 $sep=-1;
 $j=$i;
 $l=0;
 $ns=0;
 $nl++;
 if($border &amp;&amp; $nl==2)
 $b=$b2;
 continue;
 }
 if($c=='
')
 {
 $sep=$i;
 $ls=$l;
 $ns++;
 }
 $l+=$cw[$c];
 if($l>$wmax)
 {
 //Automatic line break
 if($sep==-1)
 {
 if($i==$j)
 $i++;
 if($this->ws>0)
 {
 $this->ws=0;
 $this->_out('
0 Tw');
 }
 $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
 }
 else
 {
 if($align=='
J')
 {
 $this->ws=($ns>1) ? ($wmax-$ls)/1000*$this->FontSize/($ns-1) : 0;
 $this->_out(sprintf('
%.3f Tw',$this->ws*$this->k));
 }
 $this->Cell($w,$h,substr($s,$j,$sep-$j),$b,2,$align,$fill);
 $i=$sep+1;
 }
 $sep=-1;
 $j=$i;
 $l=0;
 $ns=0;
 $nl++;
 if($border &amp;&amp; $nl==2)
 $b=$b2;
 }
 else
 $i++;
 }
 //Last chunk
 if($this->ws>0)
 {
 $this->ws=0;
 $this->_out('
0 Tw');
 }
 if($border &amp;&amp; strpos($border,'
B')!==false)
 $b.='
B';
 $this->Cell($w,$h,substr($s,$j,$i-$j),$b,2,$align,$fill);
 $this->x=$this->lMargin;
}

function Write($h,$txt,$link='
')
{
 //Output text in flowing mode
 $cw=&amp;$this->CurrentFont['
cw'];
 $w=$this->w-$this->rMargin-$this->x;
 $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
 $s=str_replace("\r",'
',$txt);
 $nb=strlen($s);
 $sep=-1;
 $i=0;
 $j=0;
 $l=0;
 $nl=1;
 while($i<$nb)
 {
 //Get next character
 $c=$s{$i};
 if($c=="\n")
 {
 //Explicit line break
 $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'
',0,$link);
 $i++;
 $sep=-1;
 $j=$i;
 $l=0;
 if($nl==1)
 {
 $this->x=$this->lMargin;
 $w=$this->w-$this->rMargin-$this->x;
 $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
 }
 $nl++;
 continue;
 }
 if($c=='
')
 $sep=$i;
 $l+=$cw[$c];
 if($l>$wmax)
 {
 //Automatic line break
 if($sep==-1)
 {
 if($this->x>$this->lMargin)
 {
 //Move to next line
 $this->x=$this->lMargin;
 $this->y+=$h;
 $w=$this->w-$this->rMargin-$this->x;
 $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
 $i++;
 $nl++;
 continue;
 }
 if($i==$j)
 $i++;
 $this->Cell($w,$h,substr($s,$j,$i-$j),0,2,'
',0,$link);
 }
 else
 {
 $this->Cell($w,$h,substr($s,$j,$sep-$j),0,2,'
',0,$link);
 $i=$sep+1;
 }
 $sep=-1;
 $j=$i;
 $l=0;
 if($nl==1)
 {
 $this->x=$this->lMargin;
 $w=$this->w-$this->rMargin-$this->x;
 $wmax=($w-2*$this->cMargin)*1000/$this->FontSize;
 }
 $nl++;
 }
 else
 $i++;
 }
 //Last chunk
 if($i!=$j)
 $this->Cell($l/1000*$this->FontSize,$h,substr($s,$j),0,0,'
',0,$link);
}

function Image($file,$x,$y,$w=0,$h=0,$type='
',$link='')
{
 //Put an image on the page
 if(!isset($this->images[$file]))
 {
 //First use of image, get info
 if($type=='
')
 {
 $pos=strrpos($file,'
.');
 if(!$pos)
 $this->Error('
Image file has no extension and no type was specified: '.$file);
 $type=substr($file,$pos+1);
 }
 $type=strtolower($type);
 $mqr=get_magic_quotes_runtime();
 set_magic_quotes_runtime(0);
 if($type=='
jpg' || $type=='jpeg')
 $info=$this->_parsejpg($file);
 elseif($type=='
png')
 $info=$this->_parsepng($file);
 else
 {
 //Allow for additional formats
 $mtd='
_parse'.$type;
 if(!method_exists($this,$mtd))
 $this->Error('
Unsupported image type: '.$type);
 $info=$this->$mtd($file);
 }
 set_magic_quotes_runtime($mqr);
 $info['
i']=count($this->images)+1;
 $this->images[$file]=$info;
 }
 else
 $info=$this->images[$file];
 //Automatic width and height calculation if needed
 if($w==0 &amp;&amp; $h==0)
 {
 //Put image at 72 dpi
 $w=$info['
w']/$this->k;
 $h=$info['
h']/$this->k;
 }
 if($w==0)
 $w=$h*$info['
w']/$info['h'];
 if($h==0)
 $h=$w*$info['
h']/$info['w'];
 $this->_out(sprintf('
q %.2f 0 0 %.2f %.2f %.2f cm /I%d Do Q',$w*$this->k,$h*$this->k,$x*$this->k,($this->h-($y+$h))*$this->k,$info['i']));
 if($link)
 $this->Link($x,$y,$w,$h,$link);
}

function Ln($h='
')
{
 //Line feed; default value is last cell height
 $this->x=$this->lMargin;
 if(is_string($h))
 $this->y+=$this->lasth;
 else
 $this->y+=$h;
}

function GetX()
{
 //Get x position
 return $this->x;
}

function SetX($x)
{
 //Set x position
 if($x>=0)
 $this->x=$x;
 else
 $this->x=$this->w+$x;
}

function GetY()
{
 //Get y position
 return $this->y;
}

function SetY($y)
{
 //Set y position and reset x
 $this->x=$this->lMargin;
 if($y>=0)
 $this->y=$y;
 else
 $this->y=$this->h+$y;
}

function SetXY($x,$y)
{
 //Set x and y positions
 $this->SetY($y);
 $this->SetX($x);
}

function Output($name='
',$dest='')
{
 //Output PDF to some destination
 //Finish document if necessary
 if($this->state<3)
 $this->Close();
 //Normalize parameters
 if(is_bool($dest))
 $dest=$dest ? '
D' : 'F';
 $dest=strtoupper($dest);
 if($dest=='
')
 {
 if($name=='
')
 {
 $name='
doc.pdf';
 $dest='
I';
 }
 else
 $dest='
F';
 }
 switch($dest)
 {
 case '
I':
 //Send to standard output
 if(ob_get_contents())
 $this->Error('
Some data has already been output, can\'t send PDF file');
 if(php_sapi_name()!='cli')
 {
 //We send to a browser
 header('Content-Type: application/pdf');
 if(headers_sent())
 $this->Error('Some data has already been output to browser, can\'t send PDF file');
 header('Content-Length: '.strlen($this->buffer));
 header('Content-disposition: inline; filename="'.$name.'"');
 }
 echo $this->buffer;
 break;
 case 'D':
 //Download file
 if(ob_get_contents())
 $this->Error('Some data has already been output, can\'t send PDF file');
 if(isset($_SERVER['HTTP_USER_AGENT']) &amp;&amp; strpos($_SERVER['HTTP_USER_AGENT'],'MSIE'))
 header('Content-Type: application/force-download');
 else
 header('Content-Type: application/octet-stream');
 if(headers_sent())
 $this->Error('Some data has already been output to browser, can\'t send PDF file');
 header('Content-Length: '.strlen($this->buffer));
 header('Content-disposition: attachment; filename="'.$name.'"');
 echo $this->buffer;
 break;
 case 'F':
 //Save to local file
 $f=fopen($name,'wb');
 if(!$f)
 $this->Error('Unable to create output file: '.$name);
 fwrite($f,$this->buffer,strlen($this->buffer));
 fclose($f);
 break;
 case 'S':
 //Return as a string
 return $this->buffer;
 default:
 $this->Error('Incorrect output destination: '.$dest);
 }
 return '';
}

/*******************************************************************************
*                                                                              *
*                              Protected methods                               *
*                                                                              *
*******************************************************************************/

function _dochecks()
{
 //Check for locale-related bug
 if(1.1==1)
 $this->Error('Don\'t alter the locale before including class file');
 //Check for decimal separator
 if(sprintf('%.1f',1.0)!='1.0')
 setlocale(LC_NUMERIC,'C');
}

function _getfontpath()
{
 if(!defined('FPDF_FONTPATH') &amp;&amp; is_dir(dirname(__FILE__).'/font'))
 define('FPDF_FONTPATH',dirname(__FILE__).'/font/');
 return defined('FPDF_FONTPATH') ? FPDF_FONTPATH : '';
}

function _putpages()
{
 $nb=$this->page;
 if(!empty($this->AliasNbPages))
 {
 //Replace number of pages
 for($n=1;$n<=$nb;$n++)
 $this->pages[$n]=str_replace($this->AliasNbPages,$nb,$this->pages[$n]);
 }
 if($this->DefOrientation=='P')
 {
 $wPt=$this->fwPt;
 $hPt=$this->fhPt;
 }
 else
 {
 $wPt=$this->fhPt;
 $hPt=$this->fwPt;
 }
 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
 for($n=1;$n<=$nb;$n++)
 {
 //Page
 $this->_newobj();
 $this->_out('<</Type /Page');
 $this->_out('/Parent 1 0 R');
 if(isset($this->OrientationChanges[$n]))
 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$hPt,$wPt));
 $this->_out('/Resources 2 0 R');
 if(isset($this->PageLinks[$n]))
 {
 //Links
 $annots='/Annots [';
 foreach($this->PageLinks[$n] as $pl)
 {
 $rect=sprintf('%.2f %.2f %.2f %.2f',$pl[0],$pl[1],$pl[0]+$pl[2],$pl[1]-$pl[3]);
 $annots.='<</Type /Annot /Subtype /Link /Rect ['.$rect.'] /Border [0 0 0] ';
 if(is_string($pl[4]))
 $annots.='/A <</S /URI /URI '.$this->_textstring($pl[4]).'>>>>';
 else
 {
 $l=$this->links[$pl[4]];
 $h=isset($this->OrientationChanges[$l[0]]) ? $wPt : $hPt;
 $annots.=sprintf('/Dest [%d 0 R /XYZ 0 %.2f null]>>',1+2*$l[0],$h-$l[1]*$this->k);
 }
 }
 $this->_out($annots.']');
 }
 $this->_out('/Contents '.($this->n+1).' 0 R>>');
 $this->_out('endobj');
 //Page content
 $p=($this->compress) ? gzcompress($this->pages[$n]) : $this->pages[$n];
 $this->_newobj();
 $this->_out('<<'.$filter.'/Length '.strlen($p).'>>');
 $this->_putstream($p);
 $this->_out('endobj');
 }
 //Pages root
 $this->offsets[1]=strlen($this->buffer);
 $this->_out('1 0 obj');
 $this->_out('<</Type /Pages');
 $kids='/Kids [';
 for($i=0;$i<$nb;$i++)
 $kids.=(3+2*$i).' 0 R ';
 $this->_out($kids.']');
 $this->_out('/Count '.$nb);
 $this->_out(sprintf('/MediaBox [0 0 %.2f %.2f]',$wPt,$hPt));
 $this->_out('>>');
 $this->_out('endobj');
}

function _putfonts()
{
 $nf=$this->n;
 foreach($this->diffs as $diff)
 {
 //Encodings
 $this->_newobj();
 $this->_out('<</Type /Encoding /BaseEncoding /WinAnsiEncoding /Differences ['.$diff.']>>');
 $this->_out('endobj');
 }
 $mqr=get_magic_quotes_runtime();
 set_magic_quotes_runtime(0);
 foreach($this->FontFiles as $file=>$info)
 {
 //Font file embedding
 $this->_newobj();
 $this->FontFiles[$file]['n']=$this->n;
 $font='';
 $f=fopen($this->_getfontpath().$file,'rb',1);
 if(!$f)
 $this->Error('Font file not found');
 while(!feof($f))
 $font.=fread($f,8192);
 fclose($f);
 $compressed=(substr($file,-2)=='.z');
 if(!$compressed &amp;&amp; isset($info['length2']))
 {
 $header=(ord($font{0})==128);
 if($header)
 {
 //Strip first binary header
 $font=substr($font,6);
 }
 if($header &amp;&amp; ord($font{$info['length1']})==128)
 {
 //Strip second binary header
 $font=substr($font,0,$info['length1']).substr($font,$info['length1']+6);
 }
 }
 $this->_out('<</Length '.strlen($font));
 if($compressed)
 $this->_out('/Filter /FlateDecode');
 $this->_out('/Length1 '.$info['length1']);
 if(isset($info['length2']))
 $this->_out('/Length2 '.$info['length2'].' /Length3 0');
 $this->_out('>>');
 $this->_putstream($font);
 $this->_out('endobj');
 }
 set_magic_quotes_runtime($mqr);
 foreach($this->fonts as $k=>$font)
 {
 //Font objects
 $this->fonts[$k]['n']=$this->n+1;
 $type=$font['type'];
 $name=$font['name'];
 if($type=='core')
 {
 //Standard font
 $this->_newobj();
 $this->_out('<</Type /Font');
 $this->_out('/BaseFont /'.$name);
 $this->_out('/Subtype /Type1');
 if($name!='Symbol' &amp;&amp; $name!='ZapfDingbats')
 $this->_out('/Encoding /WinAnsiEncoding');
 $this->_out('>>');
 $this->_out('endobj');
 }
 elseif($type=='Type1' || $type=='TrueType')
 {
 //Additional Type1 or TrueType font
 $this->_newobj();
 $this->_out('<</Type /Font');
 $this->_out('/BaseFont /'.$name);
 $this->_out('/Subtype /'.$type);
 $this->_out('/FirstChar 32 /LastChar 255');
 $this->_out('/Widths '.($this->n+1).' 0 R');
 $this->_out('/FontDescriptor '.($this->n+2).' 0 R');
 if($font['enc'])
 {
 if(isset($font['diff']))
 $this->_out('/Encoding '.($nf+$font['diff']).' 0 R');
 else
 $this->_out('/Encoding /WinAnsiEncoding');
 }
 $this->_out('>>');
 $this->_out('endobj');
 //Widths
 $this->_newobj();
 $cw=&amp;$font['cw'];
 $s='[';
 for($i=32;$i<=255;$i++)
 $s.=$cw[chr($i)].' ';
 $this->_out($s.']');
 $this->_out('endobj');
 //Descriptor
 $this->_newobj();
 $s='<</Type /FontDescriptor /FontName /'.$name;
 foreach($font['desc'] as $k=>$v)
 $s.=' /'.$k.' '.$v;
 $file=$font['file'];
 if($file)
 $s.=' /FontFile'.($type=='Type1' ? '' : '2').' '.$this->FontFiles[$file]['n'].' 0 R';
 $this->_out($s.'>>');
 $this->_out('endobj');
 }
 else
 {
 //Allow for additional types
 $mtd='_put'.strtolower($type);
 if(!method_exists($this,$mtd))
 $this->Error('Unsupported font type: '.$type);
 $this->$mtd($font);
 }
 }
}

function _putimages()
{
 $filter=($this->compress) ? '/Filter /FlateDecode ' : '';
 reset($this->images);
 while(list($file,$info)=each($this->images))
 {
 $this->_newobj();
 $this->images[$file]['n']=$this->n;
 $this->_out('<</Type /XObject');
 $this->_out('/Subtype /Image');
 $this->_out('/Width '.$info['w']);
 $this->_out('/Height '.$info['h']);
 if($info['cs']=='Indexed')
 $this->_out('/ColorSpace [/Indexed /DeviceRGB '.(strlen($info['pal'])/3-1).' '.($this->n+1).' 0 R]');
 else
 {
 $this->_out('/ColorSpace /'.$info['cs']);
 if($info['cs']=='DeviceCMYK')
 $this->_out('/Decode [1 0 1 0 1 0 1 0]');
 }
 $this->_out('/BitsPerComponent '.$info['bpc']);
 if(isset($info['f']))
 $this->_out('/Filter /'.$info['f']);
 if(isset($info['parms']))
 $this->_out($info['parms']);
 if(isset($info['trns']) &amp;&amp; is_array($info['trns']))
 {
 $trns='';
 for($i=0;$i<count($info['trns']);$i++)
 $trns.=$info['trns'][$i].' '.$info['trns'][$i].' ';
 $this->_out('/Mask ['.$trns.']');
 }
 $this->_out('/Length '.strlen($info['data']).'>>');
 $this->_putstream($info['data']);
 unset($this->images[$file]['data']);
 $this->_out('endobj');
 //Palette
 if($info['cs']=='Indexed')
 {
 $this->_newobj();
 $pal=($this->compress) ? gzcompress($info['pal']) : $info['pal'];
 $this->_out('<<'.$filter.'/Length '.strlen($pal).'>>');
 $this->_putstream($pal);
 $this->_out('endobj');
 }
 }
}

function _putxobjectdict()
{
 foreach($this->images as $image)
 $this->_out('/I'.$image['i'].' '.$image['n'].' 0 R');
}

function _putresourcedict()
{
 $this->_out('/ProcSet [/PDF /Text /ImageB /ImageC /ImageI]');
 $this->_out('/Font <<');
 foreach($this->fonts as $font)
 $this->_out('/F'.$font['i'].' '.$font['n'].' 0 R');
 $this->_out('>>');
 $this->_out('/XObject <<');
 $this->_putxobjectdict();
 $this->_out('>>');
}

function _putresources()
{
 $this->_putfonts();
 $this->_putimages();
 //Resource dictionary
 $this->offsets[2]=strlen($this->buffer);
 $this->_out('2 0 obj');
 $this->_out('<<');
 $this->_putresourcedict();
 $this->_out('>>');
 $this->_out('endobj');
}

function _putinfo()
{
 $this->_out('/Producer '.$this->_textstring('FPDF '.FPDF_VERSION));
 if(!empty($this->title))
 $this->_out('/Title '.$this->_textstring($this->title));
 if(!empty($this->subject))
 $this->_out('/Subject '.$this->_textstring($this->subject));
 if(!empty($this->author))
 $this->_out('/Author '.$this->_textstring($this->author));
 if(!empty($this->keywords))
 $this->_out('/Keywords '.$this->_textstring($this->keywords));
 if(!empty($this->creator))
 $this->_out('/Creator '.$this->_textstring($this->creator));
 $this->_out('/CreationDate '.$this->_textstring('D:'.date('YmdHis')));
}

function _putcatalog()
{
 $this->_out('/Type /Catalog');
 $this->_out('/Pages 1 0 R');
 if($this->ZoomMode=='fullpage')
 $this->_out('/OpenAction [3 0 R /Fit]');
 elseif($this->ZoomMode=='fullwidth')
 $this->_out('/OpenAction [3 0 R /FitH null]');
 elseif($this->ZoomMode=='real')
 $this->_out('/OpenAction [3 0 R /XYZ null null 1]');
 elseif(!is_string($this->ZoomMode))
 $this->_out('/OpenAction [3 0 R /XYZ null null '.($this->ZoomMode/100).']');
 if($this->LayoutMode=='single')
 $this->_out('/PageLayout /SinglePage');
 elseif($this->LayoutMode=='continuous')
 $this->_out('/PageLayout /OneColumn');
 elseif($this->LayoutMode=='two')
 $this->_out('/PageLayout /TwoColumnLeft');
}

function _putheader()
{
 $this->_out('%PDF-'.$this->PDFVersion);
}

function _puttrailer()
{
 $this->_out('/Size '.($this->n+1));
 $this->_out('/Root '.$this->n.' 0 R');
 $this->_out('/Info '.($this->n-1).' 0 R');
}

function _enddoc()
{
 $this->_putheader();
 $this->_putpages();
 $this->_putresources();
 //Info
 $this->_newobj();
 $this->_out('<<');
 $this->_putinfo();
 $this->_out('>>');
 $this->_out('endobj');
 //Catalog
 $this->_newobj();
 $this->_out('<<');
 $this->_putcatalog();
 $this->_out('>>');
 $this->_out('endobj');
 //Cross-ref
 $o=strlen($this->buffer);
 $this->_out('xref');
 $this->_out('0 '.($this->n+1));
 $this->_out('0000000000 65535 f ');
 for($i=1;$i<=$this->n;$i++)
 $this->_out(sprintf('%010d 00000 n ',$this->offsets[$i]));
 //Trailer
 $this->_out('trailer');
 $this->_out('<<');
 $this->_puttrailer();
 $this->_out('>>');
 $this->_out('startxref');
 $this->_out($o);
 $this->_out('%%EOF');
 $this->state=3;
}

function _beginpage($orientation)
{
 $this->page++;
 $this->pages[$this->page]='';
 $this->state=2;
 $this->x=$this->lMargin;
 $this->y=$this->tMargin;
 $this->FontFamily='';
 //Page orientation
 if(!$orientation)
 $orientation=$this->DefOrientation;
 else
 {
 $orientation=strtoupper($orientation{0});
 if($orientation!=$this->DefOrientation)
 $this->OrientationChanges[$this->page]=true;
 }
 if($orientation!=$this->CurOrientation)
 {
 //Change orientation
 if($orientation=='P')
 {
 $this->wPt=$this->fwPt;
 $this->hPt=$this->fhPt;
 $this->w=$this->fw;
 $this->h=$this->fh;
 }
 else
 {
 $this->wPt=$this->fhPt;
 $this->hPt=$this->fwPt;
 $this->w=$this->fh;
 $this->h=$this->fw;
 }
 $this->PageBreakTrigger=$this->h-$this->bMargin;
 $this->CurOrientation=$orientation;
 }
}

function _endpage()
{
 //End of page contents
 $this->state=1;
}

function _newobj()
{
 //Begin a new object
 $this->n++;
 $this->offsets[$this->n]=strlen($this->buffer);
 $this->_out($this->n.' 0 obj');
}

function _dounderline($x,$y,$txt)
{
 //Underline text
 $up=$this->CurrentFont['up'];
 $ut=$this->CurrentFont['ut'];
 $w=$this->GetStringWidth($txt)+$this->ws*substr_count($txt,' ');
 return sprintf('%.2f %.2f %.2f %.2f re f',$x*$this->k,($this->h-($y-$up/1000*$this->FontSize))*$this->k,$w*$this->k,-$ut/1000*$this->FontSizePt);
}

function _parsejpg($file)
{
 //Extract info from a JPEG file
 $a=GetImageSize($file);
 if(!$a)
 $this->Error('Missing or incorrect image file: '.$file);
 if($a[2]!=2)
 $this->Error('Not a JPEG file: '.$file);
 if(!isset($a['channels']) || $a['channels']==3)
 $colspace='DeviceRGB';
 elseif($a['channels']==4)
 $colspace='DeviceCMYK';
 else
 $colspace='DeviceGray';
 $bpc=isset($a['bits']) ? $a['bits'] : 8;
 //Read whole file
 $f=fopen($file,'rb');
 $data='';
 while(!feof($f))
 $data.=fread($f,4096);
 fclose($f);
 return array('w'=>$a[0],'h'=>$a[1],'cs'=>$colspace,'bpc'=>$bpc,'f'=>'DCTDecode','data'=>$data);
}

function _parsepng($file)
{
 //Extract info from a PNG file
 $f=fopen($file,'rb');
 if(!$f)
 $this->Error('Can\'t open image file: '.$file);
 //Check signature
 if(fread($f,8)!=chr(137).'PNG'.chr(13).chr(10).chr(26).chr(10))
 $this->Error('Not a PNG file: '.$file);
 //Read header chunk
 fread($f,4);
 if(fread($f,4)!='IHDR')
 $this->Error('Incorrect PNG file: '.$file);
 $w=$this->_freadint($f);
 $h=$this->_freadint($f);
 $bpc=ord(fread($f,1));
 if($bpc>8)
 $this->Error('16-bit depth not supported: '.$file);
 $ct=ord(fread($f,1));
 if($ct==0)
 $colspace='DeviceGray';
 elseif($ct==2)
 $colspace='DeviceRGB';
 elseif($ct==3)
 $colspace='Indexed';
 else
 $this->Error('Alpha channel not supported: '.$file);
 if(ord(fread($f,1))!=0)
 $this->Error('Unknown compression method: '.$file);
 if(ord(fread($f,1))!=0)
 $this->Error('Unknown filter method: '.$file);
 if(ord(fread($f,1))!=0)
 $this->Error('Interlacing not supported: '.$file);
 fread($f,4);
 $parms='/DecodeParms <</Predictor 15 /Colors '.($ct==2 ? 3 : 1).' /BitsPerComponent '.$bpc.' /Columns '.$w.'>>';
 //Scan chunks looking for palette, transparency and image data
 $pal='';
 $trns='';
 $data='';
 do
 {
 $n=$this->_freadint($f);
 $type=fread($f,4);
 if($type=='PLTE')
 {
 //Read palette
 $pal=fread($f,$n);
 fread($f,4);
 }
 elseif($type=='tRNS')
 {
 //Read transparency info
 $t=fread($f,$n);
 if($ct==0)
 $trns=array(ord(substr($t,1,1)));
 elseif($ct==2)
 $trns=array(ord(substr($t,1,1)),ord(substr($t,3,1)),ord(substr($t,5,1)));
 else
 {
 $pos=strpos($t,chr(0));
 if($pos!==false)
 $trns=array($pos);
 }
 fread($f,4);
 }
 elseif($type=='IDAT')
 {
 //Read image data block
 $data.=fread($f,$n);
 fread($f,4);
 }
 elseif($type=='IEND')
 break;
 else
 fread($f,$n+4);
 }
 while($n);
 if($colspace=='Indexed' &amp;&amp; empty($pal))
 $this->Error('Missing palette in '.$file);
 fclose($f);
 return array('w'=>$w,'h'=>$h,'cs'=>$colspace,'bpc'=>$bpc,'f'=>'FlateDecode','parms'=>$parms,'pal'=>$pal,'trns'=>$trns,'data'=>$data);
}

function _freadint($f)
{
 //Read a 4-byte integer from file
 $a=unpack('Ni',fread($f,4));
 return $a['i'];
}

function _textstring($s)
{
 //Format a text string
 return '('.$this->_escape($s).')';
}

function _escape($s)
{
 //Add \ before \, ( and )
 return str_replace(')','\\)',str_replace('(','\\(',str_replace('\','\\\',$s)));
}

function _putstream($s)
{
 $this->_out('
stream');
 $this->_out($s);
 $this->_out('
endstream');
}

function _out($s)
{
 //Add a line to the document
 if($this->state==2)
 $this->pages[$this->page].=$s."\n";
 else
 $this->buffer.=$s."\n";
}
//End of class
}

//Handle special IE contype request
if(isset($_SERVER['
HTTP_USER_AGENT']) &amp;&amp; $_SERVER['HTTP_USER_AGENT']=='contype')
{
 header('
Content-Type: application/pdf');
 exit;
}

}
?>


&amp;nbsp;

PHP Scripts for AuthMan Free Authentication

AuthMan Free is an authentication/password protection and membership management system written in PHP and licensed under the GNU GPL. It uses .htpasswd and .htaccess files to protect web directory. Installation is easy and programming knowledge does not required. Features: – Easy to install and use – Optionally, script can send an email notification to the administrator when a new user registers – Allows users to modify their account deta.

 

<?php
/*~ class.pop3.php
.---------------------------------------------------------------------------.
|  Software: PHPMailer - PHP email class                                    |
|   Version: 2.0.0 rc2                                                      |
|   Contact: via sourceforge.net support pages (also www.codeworxtech.com)  |
|      Info: http://phpmailer.sourceforge.net                               |
|   Support: http://sourceforge.net/projects/phpmailer/                     |
| ------------------------------------------------------------------------- |
|    Author: Andy Prevost (project admininistrator)                         |
|    Author: Brent R. Matzelle (original founder)                           |
| Copyright (c) 2004-2007, Andy Prevost. All Rights Reserved.               |
| Copyright (c) 2001-2003, Brent R. Matzelle                                |
| ------------------------------------------------------------------------- |
|   License: Distributed under the Lesser General Public License (LGPL)     |
|            http://www.gnu.org/copyleft/lesser.html                        |
| This program is distributed in the hope that it will be useful - WITHOUT  |
| ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or     |
| FITNESS FOR A PARTICULAR PURPOSE.                                         |
| ------------------------------------------------------------------------- |
| We offer a number of paid services (www.codeworxtech.com):                |
| - Web Hosting on highly optimized fast and secure servers                 |
| - Technology Consulting                                                   |
| - Oursourcing (highly qualified programmers and graphic designers)        |
'---------------------------------------------------------------------------'

/**
 * POP Before SMTP Authentication Class
 * Version 1.0
 *
 * Author: Richard Davey (rich@corephp.co.uk)
 * License: LGPL, see PHPMailer License
 *
 * Specifically for PHPMailer to allow POP before SMTP authentication.
 * Does not yet work with APOP - if you have an APOP account, contact me
 * and we can test changes to this script.
 *
 * This class is based on the structure of the SMTP class by Chris Ryan
 *
 * This class is rfc 1939 compliant and implements all the commands
 * required for POP3 connection, authentication and disconnection.
 *
 * @package PHPMailer
 * @author Richard Davey
 */


class POP3
{
 /**
 * Default POP3 port
 * @var int
 */

 var $POP3_PORT = 110;

 /**
 * Default Timeout
 * @var int
 */

 var $POP3_TIMEOUT = 30;

 /**
 * POP3 Carriage Return + Line Feed
 * @var string
 */

 var $CRLF = "\r\n";

 /**
 * Displaying Debug warnings? (0 = now, 1+ = yes)
 * @var int
 */

 var $do_debug = 2;

 /**
 * POP3 Mail Server
 * @var string
 */

 var $host;

 /**
 * POP3 Port
 * @var int
 */

 var $port;

 /**
 * POP3 Timeout Value
 * @var int
 */

 var $tval;

 /**
 * POP3 Username
 * @var string
 */

 var $username;

 /**
 * POP3 Password
 * @var string
 */

 var $password;

 /**#@+
 * @access private
 */

 var $pop_conn;
 var $connected;
 var $error;     //  Error log array
 /**#@-*/

 /**
 * Constructor, sets the initial values
 *
 * @return POP3
 */

 function POP3 ()
 {
 $this->pop_conn = 0;
 $this->connected = false;
 $this->error = null;
 }

 /**
 * Combination of public events - connect, login, disconnect
 *
 * @param string $host
 * @param integer $port
 * @param integer $tval
 * @param string $username
 * @param string $password
 */

 function Authorise ($host, $port = false, $tval = false, $username, $password, $debug_level = 0)
 {
 $this->host = $host;

 //  If no port value is passed, retrieve it
 if ($port == false)
 {
 $this->port = $this->POP3_PORT;
 }
 else
 {
 $this->port = $port;
 }

 //  If no port value is passed, retrieve it
 if ($tval == false)
 {
 $this->tval = $this->POP3_TIMEOUT;
 }
 else
 {
 $this->tval = $tval;
 }

 $this->do_debug = $debug_level;
 $this->username = $username;
 $this->password = $password;

 //  Refresh the error log
 $this->error = null;

 //  Connect
 $result = $this->Connect($this->host, $this->port, $this->tval);

 if ($result)
 {
 $login_result = $this->Login($this->username, $this->password);

 if ($login_result)
 {
 $this->Disconnect();

 return true;
 }

 }

 //  We need to disconnect regardless if the login succeeded
 $this->Disconnect();

 return false;
 }

 /**
 * Connect to the POP3 server
 *
 * @param string $host
 * @param integer $port
 * @param integer $tval
 * @return boolean
 */

 function Connect ($host, $port = false, $tval = 30)
 {
 //  Are we already connected?
 if ($this->connected)
 {
 return true;
 }

 /*
 On Windows this will raise a PHP Warning error if the hostname doesn't exist.
 Rather than supress it with @fsockopen, let's capture it cleanly instead
 */


 set_error_handler(array(&amp;$this, 'catchWarning'));

 //  Connect to the POP3 server
 $this->pop_conn = fsockopen($host,    //  POP3 Host
 $port,    //  Port #
 $errno,   //  Error Number
 $errstr,  //  Error Message
 $tval);   //  Timeout (seconds)

 //  Restore the error handler
 restore_error_handler();

 //  Does the Error Log now contain anything?
 if ($this->error &amp;&amp; $this->do_debug >= 1)
 {
 $this->displayErrors();
 }

 //  Did we connect?
 if ($this->pop_conn == false)
 {
 //  It would appear not...
 $this->error = array(
 'error' => "Failed to connect to server $host on port $port",
 'errno' => $errno,
 'errstr' => $errstr
 );

 if ($this->do_debug >= 1)
 {
 $this->displayErrors();
 }

 return false;
 }

 //  Increase the stream time-out

 //  Check for PHP 4.3.0 or later
 if (version_compare(phpversion(), '4.3.0', 'ge'))
 {
 stream_set_timeout($this->pop_conn, $tval, 0);
 }
 else
 {
 //  Does not work on Windows
 if (substr(PHP_OS, 0, 3) !== 'WIN')
 {
 socket_set_timeout($this->pop_conn, $tval, 0);
 }
 }

 //  Get the POP3 server response
 $pop3_response = $this->getResponse();

 //  Check for the +OK
 if ($this->checkResponse($pop3_response))
 {
 //  The connection is established and the POP3 server is talking
 $this->connected = true;
 return true;
 }

 }

 /**
 * Login to the POP3 server (does not support APOP yet)
 *
 * @param string $username
 * @param string $password
 * @return boolean
 */

 function Login ($username = '', $password = '')
 {
 if ($this->connected == false)
 {
 $this->error = 'Not connected to POP3 server';

 if ($this->do_debug >= 1)
 {
 $this->displayErrors();
 }
 }

 if (empty($username))
 {
 $username = $this->username;
 }

 if (empty($password))
 {
 $password = $this->password;
 }

 $pop_username = "USER $username" . $this->CRLF;
 $pop_password = "PASS $password" . $this->CRLF;

 //  Send the Username
 $this->sendString($pop_username);
 $pop3_response = $this->getResponse();

 if ($this->checkResponse($pop3_response))
 {
 //  Send the Password
 $this->sendString($pop_password);
 $pop3_response = $this->getResponse();

 if ($this->checkResponse($pop3_response))
 {
 return true;
 }
 else
 {
 return false;
 }
 }
 else
 {
 return false;
 }
 }

 /**
 * Disconnect from the POP3 server
 */

 function Disconnect ()
 {
 $this->sendString('QUIT');

 fclose($this->pop_conn);
 }

 /*
 ---------------
 Private Methods
 ---------------
 */


 /**
 * Get the socket response back.
 * $size is the maximum number of bytes to retrieve
 *
 * @param integer $size
 * @return string
 */

 function getResponse ($size = 128)
 {
 $pop3_response = fgets($this->pop_conn, $size);

 return $pop3_response;
 }

 /**
 * Send a string down the open socket connection to the POP3 server
 *
 * @param string $string
 * @return integer
 */

 function sendString ($string)
 {
 $bytes_sent = fwrite($this->pop_conn, $string, strlen($string));

 return $bytes_sent;

 }

 /**
 * Checks the POP3 server response for +OK or -ERR
 *
 * @param string $string
 * @return boolean
 */

 function checkResponse ($string)
 {
 if (substr($string, 0, 3) !== '+OK')
 {
 $this->error = array(
 'error' => "Server reported an error: $string",
 'errno' => 0,
 'errstr' => ''
 );

 if ($this->do_debug >= 1)
 {
 $this->displayErrors();
 }

 return false;
 }
 else
 {
 return true;
 }

 }

 /**
 * If debug is enabled, display the error message array
 *
 */

 function displayErrors ()
 {
 echo '<pre>';

 foreach ($this->error as $single_error)
 {
 print_r($single_error);
 }

 echo '</pre>';
 }

 /**
 * Takes over from PHP for the socket warning handler
 *
 * @param integer $errno
 * @param string $errstr
 * @param string $errfile
 * @param integer $errline
 */

 function catchWarning ($errno, $errstr, $errfile, $errline)
 {
 $this->error[] = array(
 'error' => "Connecting to the POP3 server raised a PHP warning: ",
 'errno' => $errno,
 'errstr' => $errstr
 );
 }

 //  End of class
}
?>

&amp;nbsp;

mod_auth_scripts for User Authentication

You should have dreamed to do some complex, tricky or user friendly authentication when using Apache web server. You can do this by some CGI or PHP script to send out the requested content only when some condition is met. However, this approach is not perfect because some features of Apache web server cannot be used under such mechanism. Such features include HTTP/1.1 partial file retrieving, content negotiation and output stream compression.

 

 

/*
 * Copyright (c) 2001 Accense Technology, Inc. All rights reserved.
 *
 * (the Apache like license)
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 *
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 *
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in
 *    the documentation and/or other materials provided with the
 *    distribution.
 *
 * 3. The end-user documentation included with the redistribution,
 *    if any, must include the following acknowledgment:
 *       "This product includes software developed by
 *        Accense Technology, Inc. (http://accense.com/)."
 *    Alternately, this acknowledgment may appear in the software itself,
 *    if and wherever such third-party acknowledgments normally appear.
 *
 * 4. The names "Accense Technology" must not be used to endorse or promote
 *    products derived from this software without prior written
 *    permission.
 *
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
 * WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
 * DISCLAIMED.  IN NO EVENT SHALL ACCENSE BE LIABLE FOR ANY DIRECT,
 * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
 * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
 * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
 * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
 * OF THE POSSIBILITY OF SUCH DAMAGE.
 *
 */

/*
 * mod_auth_script
 *
 * This module makes it possible authentication/authorization to be done
 * by an external program. The external program can be provided as a CGI,
 * PHP or any other schemes which allow dynamic content to Apache. The program
 * SHOULD print some headers, and MUST NOT print any content body. Recognized
 * headers are as follows.
 *
 *   auth-script
 *       Authentication/authorization result (required)
 *           allow       access allowed
 *           deny        access denied
 *           prompt      access denied and cause browser to prompt the
 *                       browser built-in userid/password dialog
 *
 *   auth-script-user
 *       Set the "REMOTE_USER" CGI variable (optional, at most 1)
 *       The value of this header will be a value of "REMOTE_USER".
 *
 *   auth-script-custom-response
 *       Specify an error document for access denial (optional, at most 1)
 *           /...        internal URI
 *           http://...  external URL
 *           text...     simple text message to display
 *           "text...    simple text message to display
 *
 *   auth-script-debug
 *       Just print a debug message in the apache error_log (optional)
 *       Any number of debug message can be printed by repeating this
 *       header line. However, mod_cgi or other modules may merge them
 *       or ignore them except the last header line.
 *
 *
 * This module provides following configuration directives:
 *
 *   AuthScriptFile  "OS path to the program"
 *       Specify the program to provide authentication/authorization.
 *       This path should be absolute path or relative to the ServerRoot.
 *
 *   AuthScriptURI   "virtual path"
 *       Specify the program to provide authentication/authorization.
 *       The script should be inside the web content tree.
 *
 *
 * Configuration should be like as follows. AuthType should be "Basic".
 * AuthName should be provided to prompt a browser dialog. Please note that
 * the "require" directive is required, but the actual content of the
 * directive is meaningless in this version of implementation.
 *
 *   AuthType        Basic
 *   AuthName        "authentication realm"
 *   AuthScriptFile  "OS path to the program"
 *   Require         valid-user
 *
 *
 * This software was written by Shigeru Kanemoto <sgk@ppona.com>.
 *
 */


#include "httpd.h"
#include "http_config.h"
#include "http_core.h"
#include "http_protocol.h"
#include "http_request.h"
#include "http_log.h"
#include <string.h>            /* strcmp() */

static const char* myname = "mod_auth_script";
#define MY_MARK myname,0

typedef struct {
 enum { type_file, type_uri } type_;
 char* path_;
} config_rec;

static void*
dir_config(pool* p, char* d)
{
 config_rec* conf = (config_rec*)ap_pcalloc(p, sizeof(config_rec));
 conf->type_ = type_file;
 conf->path_ = 0;            /* null pointer */
 return conf;
}

static const char*
config_file(cmd_parms* cmd, void* mconfig, char* arg)
{
 if (((config_rec*)mconfig)->path_)
 return "Path to the script already set.";

 ((config_rec*)mconfig)->type_ = type_file;
 ((config_rec*)mconfig)->path_ = ap_server_root_relative(cmd->pool, arg);
 return 0;
}

static const char*
config_uri(cmd_parms* cmd, void* mconfig, char* arg)
{
 if (((config_rec*)mconfig)->path_)
 return "Path to the script already set.";
 if (arg[0] != '/')
 return "URI should start with '/'.";

 ((config_rec*)mconfig)->type_ = type_uri;
 ((config_rec*)mconfig)->path_ = ap_pstrdup(cmd->pool, arg);
 return 0;
}

static const command_rec command_table[] = {
 { "AuthScriptFile",
 config_file, 0,
 OR_AUTHCFG, TAKE1,
 "Set an OS path to a CGI or PHP program to provide authentication/authorization function. The path can be absolute or relative to the ServerRoot." },
 { "AuthScriptURI",
 config_uri, 0,
 OR_AUTHCFG, TAKE1,
 "Set virtual path to a CGI or PHP program to provide authentication/authorization function." },
 { 0 }
};

module MODULE_VAR_EXPORT auth_script_module;

static int
callback_print_debug(void* rec, const char* key, const char* value)
{
 ap_log_rerror(MY_MARK, APLOG_DEBUG, (request_rec*)rec, "debug %s", value);
 return 1;                /* not zero */
}

static int
check_user_id(request_rec *r)
{
 config_rec* conf;
 request_rec* subreq;
 const char* s;
 int st;

 /* check if there is a request loop. */
 for (subreq = r->main; subreq != 0; subreq = subreq->main) {
 if (strcmp(subreq->uri, r->uri) == 0) {
 ap_log_rerror(MY_MARK, APLOG_ERR, r, "request loop getting '%s'; the script cannot be inside the protected directory itself.", subreq->uri);
 return DECLINED;
 }
 }

 /* get config */
 conf = (config_rec*)ap_get_module_config(
 r->per_dir_config, &amp;auth_script_module);
 if (conf->path_ == 0) {
 ap_log_rerror(MY_MARK, APLOG_ERR, r, "not configured properly");
 return DECLINED;        /* not configured properly */
 }

 /* run the script as a sub request */
 subreq = (conf->type_ == type_file ?
 ap_sub_req_lookup_file(conf->path_, r) :
 ap_sub_req_lookup_uri(conf->path_, r));
 if ((st = ap_run_sub_req(subreq)) != OK) {
 ap_destroy_sub_req(subreq);
 ap_log_rerror(MY_MARK, APLOG_ERR, r, "error on script execution");
 return st;            /* script claims an error */
 }

 /* debug message from the script */
 ap_table_do(callback_print_debug, (void*)r,
 subreq->headers_out, "auth-script-debug", 0);
 ap_table_do(callback_print_debug, (void*)r,
 subreq->err_headers_out, "auth-script-debug", 0);

 /* custom response  */
 s = ap_table_get(subreq->headers_out, "auth-script-custom-response");
 if (s == 0)
 ap_table_get(subreq->err_headers_out, "auth-script-custom-response");
 if (s != 0) {
 char* ss;
 ss = ap_pstrdup(r->pool, s);
 ap_custom_response(r, HTTP_UNAUTHORIZED, ss);
 ap_custom_response(r, HTTP_PROXY_AUTHENTICATION_REQUIRED, ss);
 }

 /* user id */
 s = ap_table_get(subreq->headers_out, "auth-script-user");
 if (s == 0)
 ap_table_get(subreq->err_headers_out, "auth-script-user");
 if (s != 0)
 r->connection->user = ap_pstrdup(r->connection->pool, s);

 /* check the result from the script */
 s = ap_table_get(subreq->headers_out, "auth-script");
 if (s == 0)
 s = ap_table_get(subreq->err_headers_out, "auth-script");
 if (s == 0) {
 ap_destroy_sub_req(subreq);
 ap_log_rerror(MY_MARK, APLOG_ERR, r, "no result from script");
 return DECLINED;        /* script do not provide the header */
 }

 /* authentication is ok if "auth-script:allow". */
 if (strcasecmp(s, "allow") == 0) {
 if (r->connection->user == 0) {
 /* retrieve userid from header and set it to r->connection->user */
 /* returned value and 's' will be ignored */
 (void)ap_get_basic_auth_pw(r, &amp;s);
 }
 ap_destroy_sub_req(subreq);
 return OK;
 }

 /* just return deny if "auth-script:deny". */
 if (strcasecmp(s, "deny") == 0) {
 ap_destroy_sub_req(subreq);
 return AUTH_REQUIRED;
 }

 /* prompt the authentication dialog if "auth-script:prompt". */
 if (strcasecmp(s, "prompt") == 0) {
 ap_note_basic_auth_failure(r);
 ap_destroy_sub_req(subreq);
 return AUTH_REQUIRED;
 }

 /* other response is not allowed. */
 ap_log_rerror(MY_MARK, APLOG_ERR, r,
 "unrecognized response '%s' from script", s);
 ap_destroy_sub_req(subreq);
 return DECLINED;
}

static int
check_auth(request_rec *r)
{
 /* This version ignores the content of "require" directive. */
 return OK;
}

module MODULE_VAR_EXPORT auth_script_module =
{
 STANDARD_MODULE_STUFF,
 0,                /* initializer */
 dir_config,            /* dir config creater */
 0,                /* dir merger --- default is to override */
 0,                /* server config */
 0,                /* merge server config */
 command_table,        /* command table */
 0,                /* handlers */
 0,                /* filename translation */
 check_user_id,        /* check_user_id */
 check_auth,            /* check auth */
 0,                /* check access */
 0,                /* type_checker */
 0,                /* fixups */
 0,                /* logger */
 0,                /* header parser */
 0,                /* child_init */
 0,                /* child_exit */
 0                /* post read-request */
};

&amp;nbsp;

Scripts for w3pw PHP User Authentication

W3pw is a web based password wallet manager written in PHP. The encrypted information is stored in a MySql Database. Features: – Platform independent. Webserver, PHP and MySql are available for a wide range of Operating Systems – Information is encrypted – Available Fields per entry: Info, host, login, password and description – Upload function for semicolon separated text-files – Timout for automatic logout Requirements: · A Webserv

 

<?php
 session_start();
 include("include/config.php");
?>
<html>
<head>
<title>w3pw Main</title>
<?php
 include("include/css.php");
 include("include/headerstuff.php");
 include("include/crypt.php");
?>
</head>
<body>

<?php

 // session active?
 if (!isset($_SESSION['logged_in']))
 {
 // no session active - check pw
 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 $cleartext_pw = "";
 // encrypt the pw given at logon
 if (isset($_POST['password']))
 {
 $cleartext_pw = $_POST['password'];
 }
 $crypt_pw = sha1($cleartext_pw);

 // check pw
 $list = mysql_query ("SELECT version, pw FROM main");
 $entries = mysql_fetch_object($list);
 $db_pw=$entries->pw;
 if ($crypt_pw == $db_pw)
 {
 // password match - proceed
 $_SESSION['logged_in'] = 1;
 $_SESSION['key'] = md5("%dJ9&amp;".strtolower($cleartext_pw)."(/&amp;k.=".strtoupper($cleartext_pw)."1x&amp;%");
 // delete cleartext pw in memory
 unset($cleartext_pw);
 $_SESSION['version']=$entries->version;
 }
 else
 {
 session_unset();
 session_destroy();
 echo "<body><b>Wrong Password</b>....<br />try <a href=\"index.php\">again</a>\n";
 }
 }
 else
 {
 // cant connect to database
 session_unset();
 session_destroy();
 echo "<br />Ooops - <b>Can't connect to the database</b>....<br />Please try <a href=\"index.php\">again</a>\n";
 }
 mysql_close($conn);
 }
 else
 {
 // cant connect to the server
 session_unset();
 session_destroy();
 echo "<br />Ooops - <b>Can't connect to the database-server</b>...<br />Please try <a href=\"index.php\">again</a>\n";
 }
 }

 if ((isset($_SESSION['logged_in'])) &amp;&amp; ($_SESSION['logged_in'] == 1))
 {
 // session is active

 // any actions to perform?
 if (isset($_POST['action']))
 {
 // save new entry
 if ($_POST['action'] == "save")
 {
 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 $list = mysql_query ("INSERT INTO wallet VALUES('','".
 mysql_escape_string (en_crypt($_POST['itemname'],$_SESSION['key']))."','".
 mysql_escape_string (en_crypt($_POST['host'],$_SESSION['key']))."','".
 mysql_escape_string (en_crypt($_POST['login'],$_SESSION['key']))."','".
 mysql_escape_string (en_crypt($_POST['password'],$_SESSION['key']))."','".
 mysql_escape_string (en_crypt($_POST['comment'],$_SESSION['key']))."')");

 unset($_POST['itemname'], $_POST['host'], $_POST['login'], $_POST['password'], $_POST['comment']);
 }
 else
 {
 echo "<br />Ooops - <b>can't find the database</b>....\n";
 }
 mysql_close($conn);
 }
 else
 {
 echo "<br />Ooops - <b>can't connect to the database-server</b>...\n";
 }

 }

 // save edited entry
 if ($_POST['action'] == "editsave")
 {
 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 $list = mysql_query ("UPDATE wallet SET itemname='".mysql_escape_string(en_crypt($_POST['itemname'],$_SESSION['key'])).
 "', host='".mysql_escape_string(en_crypt($_POST['host'],$_SESSION['key'])).
 "', login='".mysql_escape_string(en_crypt($_POST['login'],$_SESSION['key'])).
 "', pw='".mysql_escape_string(en_crypt($_POST['password'],$_SESSION['key'])).
 "', comment='".mysql_escape_string(en_crypt($_POST['comment'],$_SESSION['key'])).
 "' WHERE ID=".$_POST['ID']);

 unset($_POST['itemname'], $_POST['host'], $_POST['login'], $_POST['password'], $_POST['comment']);
 }
 else
 {
 echo "<br />Ooops - <b>Can't find the database</b>....\n";
 }
 mysql_close($conn);
 }
 else
 {
 echo "<br />Ooops - <b>Can't connect to the database-server</b>...\n";
 }
 }

 // delete entry
 if ($_POST['action'] == "reallydelete")
 {
 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 $list = mysql_query ("DELETE FROM wallet WHERE ID=".$_POST['ID']);
 }
 else
 {
 echo "<br />Ooops - <b>Can't find the database</b>....\n";
 }
 mysql_close($conn);
 }
 else
 {
 echo "<br />Ooops - <b>Can't connect to the database-server</b>...\n";
 }
 }

 // import uploaded file
 if ($_POST['action'] == "import")
 {

 $row = $_POST['row'];

 // check that each header field is used only once in import2.php

 // sort header_fields by occurence
 asort($row);

 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 // finally import the data

 $fd = fopen ($tmppath."w3pw.csv", "r");
 while ($data = fgetcsv ($fd, 4096, ";"))
 {
 if (count($data)>1)
 {
 $mysql_string="INSERT INTO wallet VALUES(''";

 reset($_POST['row']);
 while (list ($index, $val) = each ($_POST['row']))
 {
 $mysql_string.=",'".mysql_escape_string(en_crypt($data[$val],$_SESSION['key']))."'";
 }
 $mysql_string.=")";
 mysql_query ($mysql_string);
 unset($mysql_string);
 }
 }
 fclose ($fd);

 unset($row);
 unset($data);
 }
 else
 {
 echo "<br />Ooops - <b>Can't find the database</b>....\n";
 }
 mysql_close($conn);
 }
 else
 {
 echo "<br />Ooops - <b>Can't connect to the database-server</b>...\n";
 }

 }
 }

 // check if there is an uploaded file still in the tmp directory -> delete
 if (is_file($tmppath."w3pw.csv"))
 {
 unlink ($tmppath."w3pw.csv");
 }

 // menu header
 echo "<center><table width=\"100%\" style=\"table-layout:fixed\">\n<tr>\n";
 echo "<td><a href=\"main.php\" class=\"menu\">list</a></td><td><a href=\"insert.php\" class=\"menu\">new entry</a></td><td><a href=\"import.php\" class=\"menu\">import</a></td><td><a href=\"logout.php\" class=\"menu\">logout</a></td>\n";
 echo "</tr></table></center><p>\n";

 if ($conn = mysql_connect($hostname, $dbuser, $dbpasswd))
 {
 if (mysql_select_db($database,$conn))
 {
 $list = mysql_query ("SELECT ID, itemname FROM wallet");
 $header_array = array();
 while ($entries = mysql_fetch_object($list))
 {
 $header_array[$entries->ID]=de_crypt($entries->itemname,$_SESSION['key']);
 }

 natcasesort($header_array);
 reset($header_array);

 $counter=0;
 while (list ($ID, $itemname) = each ($header_array))
 {
 $counter++;
 $list = mysql_query ("SELECT host FROM wallet WHERE ID=".$ID);
 $entries = mysql_fetch_object($list);

 // table header
 if ($counter == 1)
 {
 echo "<center><table width=\"100%\" style=\"table-layout:fixed\"><tr><th style=\"width:140px\">Entryname</th><th>Host/URL</th><th style=\"width:32px\">&amp;nbsp;</th><th style=\"width:32px\">&amp;nbsp;</th><th style=\"width:45px\">&amp;nbsp;</th></tr>\n";
 }

 // show entries
 if ($counter % 2 == 0)
 {
 echo "<tr class=\"even\">";
 }
 else
 {
 echo "<tr class=\"odd\">";
 }
 echo "<td>".$itemname."</td><td>".de_crypt($entries->host,$_SESSION['key'])."</td><td>&amp;nbsp;<a href=\"view.php?ID=".$ID."\">view</a>&amp;nbsp;</td><td>&amp;nbsp;<a href=\"edit.php?ID=".$ID."\">edit</a>&amp;nbsp;</td><td>&amp;nbsp;<a href=\"delete.php?ID=".$ID."\">delete</a>&amp;nbsp;</td></tr>\n";

 }

 // table footer
 if ($counter >= 1)
 {
 echo "</table></center>";
 }

 unset($header_array,$itemname);
 echo "<p>w3pw v".$_SESSION['version']."</p>";
 }
 else
 {
 echo "<br />Ooops - <b>Can't find the database</b>....\n";
 }
 mysql_close($conn);
 }
 else
 {
 echo "<br />Ooops - <b>Can't connect to the database-server</b>...\n";
 }
 }
?>
</body>
</html>

&amp;nbsp;