Category Archives: Polls and Voting

PHP Scripts for GentleSource Poll & Voting allows

GentleSource Poll & Voting allows you to put votes and polls on your website. Your visitors select one option and click the submit button to vote.The options can be displayed as radio buttons with text or images as options to be slected. The results will be displayed as graphical bars.To prevent manipulations the script uses the IP address of the user and/or Cookies. That is to make sure, every visitor votes only once. Please note that these two features can only try to prevent fraudulent votes.

 

<?php

/*****************************************************
** Title........: Configuration File
** Filename.....: config.php
** Author.......: Ralf Stadtaus
** Homepage.....: http://www.stadtaus.com/
** Contact......: http://www.stadtaus.com/forum/
** Notes........: This file contains the configuration
*****************************************************/


/*****************************************************
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
** OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
** LIMITED   TO  THE WARRANTIES  OF  MERCHANTABILITY,
** FITNESS    FOR    A    PARTICULAR    PURPOSE   AND
** NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR
** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
** OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
** CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF
** OR  IN  CONNECTION WITH THE SOFTWARE OR THE USE OR
** OTHER DEALINGS IN THE SOFTWARE.
**
*****************************************************/






/*****************************************************
** Script configuration - for the documentation of
** following variables please take a look at the
** documentation file in folder 'docu'.
*****************************************************/



$vote_title             = 'asdfasdf';
$vote_text              = 'q453253242345';

$vote_option[]          = '123';
$vote_option[]          = '345';
$vote_option[]          = 'uuu';
$vote_option[]          = 'mmm';


$intern_vote_name       = 'asdfasdf';
$form_field_type        = 'radio';             // (radio, select, radio_image)
$bar_image_name         = 'silver.gif';
$max_bar_width          = '800';               // (pixel)

$check_ip_address       = 'no';                // (yes/no)
$check_cookie           = 'no';


$language               = 'de';                // See folder "languages"

$script_root            = './';
$path['templates']      = $script_root . 'templates/';
$path['logfiles']       = $script_root . 'logfiles/';

$tmpl['layout']         = 'voting.tpl.html';

$log['logfile']         = 'log.txt';

$show_error_messages    = 'yes';





/*****************************************************
** Add here further words, text, variables and stuff
** that you want to appear in the template.
*****************************************************/

$add_text = array(

'txt_additional'  => 'Additional',  //  {txt_additional}
'txt_more'        => 'More',        //  {txt_more}

'txt_script_name' => 'Voting Script'

);








/*****************************************************
** Send safety signal to included files
*****************************************************/

define('IN_SCRIPT', 'true');




/*****************************************************
** Include script code
*****************************************************/

include $script_root . 'inc/core.inc.php';

echo $voutput;

?>

&amp;nbsp;

Ajax Poll Script With PHP MySQL & jQuery

An Ajax Poll Script that displays the results with colored and animated lines using PHP, MySQL and jQuery.The script has a pretty easy logic and can be implemented into any website quickly by simply calling a php function like getPoll(2) which brings the second poll.

<?php
require("inc/db.php");
require("inc/functions.php");
?>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Ajax Poll Script - Demo</title>
<script src="inc/js/jquery-1.4.2.min.js" type="text/javascript"></script>
<script src="inc/js/poll.js" type="text/javascript"></script>
<style>
body {
font-family: Arial, Helvetica, sans-serif;
font-size: 1em;
}
#pollWrap{
width: 250px;
}
#pollWrap h3 {
font-size: 1em;
margin-bottom: 5px;
}
#pollWrap ul {
margin: 0;
padding: 0 0 0 5px;
list-style:none;
}
#pollWrap li {
padding: 0;
overflow:hidden; /*for our lovely friend IE6 to behave nicely*/
font-size: 0.8em;
}
#pollWrap li span {
font-size: 0.7em;
}
.pollChart {
margin-left: 25px;
height: 5px;
width:1px;
/*Adding rounded corners to the graphs - Optional - START*/
-moz-border-radius-topright: 4px;
-moz-border-radius-bottomright: 4px;
-webkit-border-top-right-radius: 4px;
-webkit-border-bottom-right-radius: 4px;
/*Adding rounded corners to the graphs - Optional - END*/
}
#pollSubmit {
margin-top: 5px;
}
#pollMessage {
color:#C00;
font-size: 0.8em;
font-weight: bold;
}
</style>
</head>

<body>
<?php getPoll(1);?>
</body>
</html>

PHP poll module and provides multiple Scripts

Advanced Poll is a replacement to Drupal’s poll module and provides multiple voting systems, decision-making tools, and management options. Voting systems: Basic polls, Approval Voting, Borda Count, and Instant-Runoff Voting. Vote management: view each user’s vote, delete all votes, or restrict the poll to a list of users. Time management: schedule when to open or close the poll, and choose when to show results. Choice management: write-in choices, and support for HTML (or other input filter).

 

 

<?php
/* vim: set expandtab tabstop=4 shiftwidth=4: */
// +----------------------------------------------------------------------+
// | PHP version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2003 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.0 of the PHP license,       |
// | that is bundled with this package in the file LICENSE, and is        |
// | available through the world-wide-web at                              |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Authors: Paul M. Jones <pmjones@ciaweb.net>                          |
// |          Marshall Roch <mroch@php.net>                               |
// +----------------------------------------------------------------------+
//
// $Id$

define('FILE_IMC_ERROR',                        100);
define('FILE_IMC_ERROR_INVALID_DRIVER',         101);
define('FILE_IMC_ERROR_INVALID_PARAM',          102);
define('FILE_IMC_ERROR_INVALID_VCARD_VERSION',  103);
define('FILE_IMC_ERROR_PARAM_NOT_SET',          104);
define('FILE_IMC_ERROR_INVALID_ITERATION',      105);

/**
* This class handles vCard and vCalendar files, formats designed by the
* Internet Mail Consortium (IMC).
*
* vCard automates the exchange of personal information typically found
* on a traditional business card. vCard is used in applications such as
* Internet mail, voice mail, Web browsers, telephony applications, call
* centers, video conferencing, PIMs (Personal Information Managers),
* PDAs (Personal Data Assistants), pagers, fax, office equipment, and
* smart cards.
*
* vCalendar defines a transport and platform-independent format for
* exchanging calendaring and scheduling information in an easy, automated,
* and consistent manner. It captures information about event and "to-do"
* items that are normally used by applications such as a personal
* information managers (PIMs) and group schedulers. Programs that use
* vCalendar can exchange important data about events so that you can
* schedule meetings with anyone who has a vCalendar-aware program.
*
* This class is capable of building and parsing vCard 2.1, vCard 3.0, and
* vCalendar files.  The vCard code was moved from Contact_Vcard_Build
* and Contact_Vcard_Parse, and the API remains basically the same.
* The only difference is that this package uses a factory pattern:
*
* <code>
*     $parse = File_IMC::parse('vCard');
*     $build = File_IMC::build('vCard', '3.0');
* </code>
* instead of
* <code>
*     $parse = new Contact_Vcard_Parse();
*     $build = new Contact_Vcard_Build('3.0');
* </code>
*
* @link http://www.imc.org/pdi/ IMC's vCard and vCalendar info page
* @package File_IMC
* @author Paul M. Jones <pmjones@ciaweb.net>
* @author Marshall Roch <mroch@php.net>
*/

class File_IMC {

/**
* Builder factory
*
* Creates an instance of the correct parser class, based on the
* parameter passed. For example, File_IMC::parse('vCard') creates
* a new object to parse a vCard file.
*
* @param string Type of file to parse, vCard or vCalendar
* @return object
*/

function build($format, $version = null)
{
$filename = 'File/IMC/Build/'. $format . '.php';
$classname = 'File_IMC_Build_'. $format;

if (!file_exists($filename)) {
return File_IMC::raiseError(
'No builder driver exists for format: ' . $format,
FILE_IMC_ERROR_INVALID_DRIVER);
}

include_once $filename;

if (!class_exists($classname)) {
return File_IMC::raiseError(
'No builder driver exists for format: ' . $format,
FILE_IMC_ERROR_INVALID_DRIVER);
}

if ($version !== null) {
$class = new $classname($version);
} else {
$class = new $classname;
}

return $class;
}

/**
* Parser factory
*
* Creates an instance of the correct parser class, based on the
* parameter passed. For example, File_IMC::parse('vCard') creates
* a new object to parse a vCard file.
*
* @param string Type of file to parse, vCard or vCalendar
* @return object
*/

function parse($format)
{
$filename = 'File/IMC/Parse/'. $format . '.php';
$classname = 'File_IMC_Parse_'. $format;

if (!file_exists($filename)) {
return File_IMC::raiseError(
'No builder driver exists for format: ' . $format,
FILE_IMC_ERROR_INVALID_DRIVER);
}

include_once $filename;

if (!class_exists($classname)) {
return File_IMC::raiseError(
'No parser driver exists for format: ' . $format,
FILE_IMC_ERROR_INVALID_DRIVER);
}

$class = new $classname;

return $class;
}

/**
* Raises a PEAR error message
*
* Returns a PEAR_Error.  Doing it this way instead of extending
* the PEAR class means that the extra overhead of the PEAR class
* is only included when needed to throw an error.
*
* @param string Error message to display
* @param int    Error code
* @return object PEAR_Error
*/

function raiseError($msg, $code)
{
include_once 'PEAR.php';

return PEAR::raiseError($msg, $code, PEAR_ERROR_PRINT);
}

}

?>

&amp;nbsp;

PHP Scripts Advanced Poll Builder allows polls & voting

Advanced Poll Builder allows you to create your own polls as many as you like and place them to your site easily. It produces 2 types of code to insert into your pages. Just copy and paste this code to any place on your page and your poll starts its work. Each poll is customizable on-the-fly. You can see the result right upon poll creation process. Users can see the statistics using “view results” link (link is customizable as well). In admin panel you can preview your polls, view the top 20 polls and see the number of votes for each poll.

 

 

<?php
//
// +----------------------------------------------------------------------+
// | PHP Version 4                                                        |
// +----------------------------------------------------------------------+
// | Copyright (c) 1997-2005 The PHP Group                                |
// +----------------------------------------------------------------------+
// | This source file is subject to version 2.02 of the PHP license,      |
// | that is bundled with this package in the file LICENSE, and is        |
// | available at through the world-wide-web at                           |
// | http://www.php.net/license/2_02.txt.                                 |
// | If you did not receive a copy of the PHP license and are unable to   |
// | obtain it through the world-wide-web, please send a note to          |
// | license@php.net so we can mail you a copy immediately.               |
// +----------------------------------------------------------------------+
// | Author: Sterling Hughes <sterling@php.net>                           |
// +----------------------------------------------------------------------+
//
// $Id: Find.php,v 1.21 2005/09/20 11:33:15 techtonik Exp $
//

require_once 'PEAR.php';

define('FILE_FIND_VERSION', '@package_version@');


/**
*  Commonly needed functions searching directory trees
*
* @access public
* @version $Id: Find.php,v 1.21 2005/09/20 11:33:15 techtonik Exp $
* @package File
* @author Sterling Hughes <sterling@php.net>
*/

class File_Find
{
/**
* internal dir-list
* @var array
*/

var $_dirs = array();

/**
* found files
* @var array
*/

var $files = array();

/**
* found dirs
* @var array
*/

var $directories = array();

/**
* Search the current directory to find matches for the
* the specified pattern.
*
* @param string $pattern a string containing the pattern to search
* the directory for.
*
* @param string $dirpath a string containing the directory path
* to search.
*
* @param string $pattern_type a string containing the type of
* pattern matching functions to use (can either be 'php' or
* 'perl').
*
* @return array containing all of the files and directories
* matching the pattern or null if no matches
*
* @author Sterling Hughes <sterling@php.net>
* @access public
* @static
*/

function &amp;glob($pattern, $dirpath, $pattern_type = 'php')
{
$dh = @opendir($dirpath);

if (!$dh) {
$pe = PEAR::raiseError("Cannot open directory");
return $pe;
}

$match_function = File_Find::_determineRegex($pattern, $pattern_type);
$matches = array();
while (false !== ($entry = @readdir($dh))) {
if ($match_function($pattern, $entry) &amp;&amp;
$entry != '.' &amp;&amp; $entry != '..') {
$matches[] = $entry;
}
}

@closedir($dh);

$result = (count($matches) > 0) ? $matches : null;
return $result;
}

/**
* Map the directory tree given by the directory_path parameter.
*
* @param string $directory contains the directory path that you
* want to map.
*
* @return array a two element array, the first element containing a list
* of all the directories, the second element containing a list of all the
* files.
*
* @author Sterling Hughes <sterling@php.net>
* @access public
*/

function &amp;maptree($directory)
{

/* if called statically */
if (!isset($this)  || !is_a($this, "File_Find")) {
$obj = &amp;new File_Find();
return $obj->maptree($directory);
}

/* clear the results just in case */
$this->files       = array();
$this->directories = array();

/* consistency rules - strip out trailing slashes */
$directory = preg_replace('![\\\\/]+$!', '', $directory);
/* use only native system directory delimiters */
$directory = preg_replace("![\\\\/]+!", DIRECTORY_SEPARATOR, $directory);

$this->_dirs = array($directory);

while (count($this->_dirs)) {
$dir = array_pop($this->_dirs);
File_Find::_build($dir);
array_push($this->directories, $dir);
}

return array($this->directories, $this->files);
}

/**
* Map the directory tree given by the directory parameter.
*
* @param string $directory contains the directory path that you
* want to map.
* @param integer $maxrecursion maximun number of folders to recursive
* map
*
* @return array a multidimensional array containing all subdirectories
* and their files. For example:
*
* Array
* (
*    [0] => file_1.php
*    [1] => file_2.php
*    [subdirname] => Array
*       (
*          [0] => file_1.php
*       )
* )
*
* @author Mika Tuupola <tuupola@appelsiini.net>
* @access public
* @static
*/

function &amp;mapTreeMultiple($directory, $maxrecursion = 0, $count = 0)
{
$retval = array();

$count++;

$directory .= DIRECTORY_SEPARATOR;
$dh = opendir($directory);
while (false !== ($entry = @readdir($dh))) {
if ($entry != '.' &amp;&amp; $entry != '..') {
array_push($retval, $entry);
}
}

closedir($dh);

while (list($key, $val) = each($retval)) {
$path = $directory . $val;
$path = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR, $path);

if (!is_array($val) &amp;&amp; is_dir($path)) {
unset($retval[$key]);
if ($maxrecursion == 0 || $count < $maxrecursion) {
$retval[$val] = &amp;File_Find::mapTreeMultiple($path,
$maxrecursion, $count);
}
}
}

return $retval;
}

/**
* Search the specified directory tree with the specified pattern.  Return
* an array containing all matching files (no directories included).
*
* @param string $pattern the pattern to match every file with.
*
* @param string $directory the directory tree to search in.
*
* @param string $type the type of regular expression support to use, either
* 'php' or 'perl'.
*
* @param bool $fullpath whether the regex should be matched against the
* full path or only against the filename
*
* @param string $match can be either 'files', 'dirs' or 'both' to specify
* the kind of list to return
*
* @return array a list of files matching the pattern parameter in the the
* directory path specified by the directory parameter
*
* @author Sterling Hughes <sterling@php.net>
* @access public
* @static
*/

function &amp;search($pattern, $directory, $type = 'php', $fullpath = true, $match = 'files')
{

$matches = array();
list ($directories,$files)  = File_Find::maptree($directory);
switch($match) {
case 'directories': $data = $directories; break;
case 'both': $data = array_merge($directories, $files); break;
case 'files':
default:
$data = $files;
}
unset($files, $directories);

$match_function = File_Find::_determineRegex($pattern, $type);

reset($data);
while (list(,$entry) = each($data)) {
if ($match_function($pattern,
$fullpath ? $entry : basename($entry))) {
$matches[] = $entry;
}
}

return ($matches);
}

/**
* Determine whether or not a variable is a PEAR error
*
* @param object PEAR_Error $var the variable to test.
*
* @return boolean returns true if the variable is a PEAR error, otherwise
* it returns false.
* @access public
*/

function isError(&amp;$var)
{
return PEAR::isError($var);
}

/**
* internal function to build singular directory trees, used by
* File_Find::maptree()
*
* @param string $directory name of the directory to read
* @return void
*/

function _build($directory)
{

$dh = @opendir($directory);

if (!$dh) {
$pe = PEAR::raiseError("Cannot open directory");
return $pe;
}

while (false !== ($entry = @readdir($dh))) {
if ($entry != '.' &amp;&amp; $entry != '..') {

$entry = $directory.DIRECTORY_SEPARATOR.$entry;
$entry = str_replace(DIRECTORY_SEPARATOR.DIRECTORY_SEPARATOR,
DIRECTORY_SEPARATOR, $entry);

if (is_dir($entry)) {
array_push($this->_dirs, $entry);
} else {
array_push($this->files, $entry);
}
}
}

@closedir($dh);
}

/**
* internal function to determine the type of regular expression to
* use, implemented by File_Find::glob() and File_Find::search()
*
* @param string $type given RegExp type
* @return string kind of function ( "eregi", "ereg" or "preg_match") ;
*
*/

function _determineRegex($pattern, $type)
{
if (!strcasecmp($type, 'shell')) {
$match_function = 'File_Find_match_shell';
} else if (!strcasecmp($type, 'perl')) {
$match_function = 'preg_match';
} else if (!strcasecmp(substr($pattern, -2), '/i')) {
$match_function = 'eregi';
} else {
$match_function = 'ereg';
}
return $match_function;
}

}

/**
* Package method to match via 'shell' pattern. Provided in global
* scope, because they should be called like 'preg_match' and 'eregi'
* and can be easily copied into other packages
*
* @author techtonik <techtonik@php.net>
* @return mixed bool on success and PEAR_Error on failure
*/

function File_Find_match_shell($pattern, $filename)
{
// {{{ convert pattern to positive and negative regexps
$positive = $pattern;
$negation = substr_count($pattern, "|");

if ($negation > 1) {
return PEAR::raiseError("Mask string contains errors!");
} elseif ($negation) {
list($positive, $negative) = explode("|", $pattern);
if (strlen($negation) == 0) {
return PEAR::raiseError("Mask string contains errors!");
}
}

$positive = _File_Find_match_shell_get_pattern($positive);
if ($negation) {
$negative = _File_Find_match_shell_get_pattern($negative);
}
// }}} convert end


if (defined("FILE_FIND_DEBUG")) {
print("Method: $type\nPattern: $pattern\n Converted pattern:");
print_r($positive);
if (isset($negative)) print_r($negative);
}

if (!preg_match($positive, $filename)) {
return FALSE;
} else {
if (isset($negative)
&amp;&amp; preg_match($negative, $filename)) {
return FALSE;
} else {
return TRUE;
}
}
}

/**
* function used by File_Find_match_shell to convert 'shell' mask
* into pcre regexp. Some of the rules (see testcases for more):
*  escaping all special chars and replacing
*    . with \.
*    * with .*
*    ? with .{1}
*    also adding ^ and $ as the pattern matches whole filename
*
* @author techtonik <techtonik@php.net>
* @return string pcre regexp for preg_match
*/

function _File_Find_match_shell_get_pattern($mask) {
// get array of several masks (if any) delimited by comma
// do not touch commas in char class
$premasks = preg_split("|(\[[^\]]+\])|", $mask, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY );
if (defined("FILE_FIND_DEBUG")) {
print("\nPremask: ");
print_r($premasks);
}
$pi = 0;
foreach($premasks as $pm) {
if (!isset($masks[$pi])) $masks[$pi] = "";
if ($pm{0} == '[' &amp;&amp; $pm{strlen($pm)-1} == ']') {
// strip commas from character class
$masks[$pi] .= str_replace(",", "", $pm);
} else {
$tarr = explode(",", $pm);
if (sizeof($tarr) == 1) {
$masks[$pi] .= $pm;
} else {
foreach ($tarr as $te) {
$masks[$pi++] .= $te;
$masks[$pi] = "";
}
unset($masks[$pi--]);
}
}
}

// convert to preg regexp
$regexmask = implode("|", $masks);
if (defined("FILE_FIND_DEBUG")) {
print("regexMask step one(implode): $regexmask");
}
$regexmask = addcslashes($regexmask, '^$}{)(\/.+');
if (defined("FILE_FIND_DEBUG")) {
print("\nregexMask step two(addcslashes): $regexmask");
}
$regexmask = preg_replace("!(\*|\?)!", ".$1", $regexmask);
if (defined("FILE_FIND_DEBUG")) {
print("\nregexMask step three(*,? -> .*,.?): $regexmask");
}
// if no extension supplied - add .* to match partially from filename start
if (strpos($regexmask, "\\.") === FALSE) $regexmask .= ".*";
// file mask match whole name - adding restrictions
$regexmask = preg_replace("!(\|)!", '^'."$1".'$', $regexmask);
$regexmask = '^'.$regexmask.'$';
if (defined("FILE_FIND_DEBUG")) {
print("\nregexMask step three(^ and $ to match whole name): $regexmask");
}
// wrap regex into + since all + are already escaped
$regexmask = "+$regexmask+i";
if (defined("FILE_FIND_DEBUG")) {
print("\nWrapped regex: $regexmask\n");
}
return $regexmask;
}

/*
* Local variables:
* tab-width: 4
* c-basic-offset: 4
* End:
*/


?>


&amp;nbsp;

PHP Comprehensive web-based survey poll & voting

A comprehensive web-based survey builder with one-click install on any server using PHP4 and MySQL. Run unlimited multi-page surveys with unlimited questions and answers. You have complete control over the layout using CSS and templates. Avoid duplicates using IP Addresses, Cookies or even Verified Email Addresses. View survey results online or download them in CSV or XML format for use in your favorite programs. Multi-language support allows you to run separate surveys in different languages.

 

 

<?php

/**
* Garbage Collector -   garbage_collector.class.inc.php
*
* (C) Ralf Stadtaus http://www.stadtaus.com/
*/


include 'Find.php';



/**
*
*/

class garbage_collector
{


/**
* Number of files to be deleted at once
*/

var $number = 20;

/**
* Time in minutes until a file gets deleted
*/

var $time = 120;

/**
* Directory that contains the garbage
*/

var $directory = '';

// -----------------------------------------------------------------------------




/**
* Constructor
*/

function garbage_collector($config)
{

// Extract configuration array
if (is_array($config)) {
$valid = array_keys(get_class_vars(get_class($this)));
while (list($key, $val) = each($config))
{
if (in_array($key, $valid)) {
$this->$key = $val;
}
}
}
}

// -----------------------------------------------------------------------------




/**
* Get file list
*/

function file_list()
{
if (!is_dir($this->directory)) {
return false;
}
$items = &amp;File_Find::glob(  '#([a-zA-Z0-9])\.png#',
$this->directory,
'perl');
if (!is_array($items) or sizeof($items) <= 0) {
return false;
}
$list = array();
while (list($key, $val) = each($items))
{
if (sizeof($list) >= ($this->number - 1)) {
return $list;
}
$diff = (time() - filectime($this->directory . $val))/60;

if ($diff > $this->time) {
$list[] = $val;
}
}
return $list;
}

// -----------------------------------------------------------------------------




/**
* Display file list
*/

function display()
{
if ($list = $this->file_list()) {
$list = join('<br />', $list);
echo $list;
}
}

// -----------------------------------------------------------------------------




/**
* Delete files
*/

function delete()
{
if ($list = $this->file_list()) {
if (!is_array($list)) {
return false;
}
reset($list);
while (list($key, $val) = each($list))
{
if (!is_file($this->directory . $val)) {
continue;
}
unlink($this->directory . $val);
}
}
}

// -----------------------------------------------------------------------------




} // Scool's out








?>


&amp;nbsp;

PHP pool tool neither it provides evaluation scripts

This is not a simple pool tool neither it provides evaluation scripts for colected data. For scientific/marketing research professionals with no (or very basic) programming knownledge. Features: random sequence of questions, rotation of items, branching/skip logic with unlimited number of conditions, matrix questions, supported all types of questions (multiple options – one answer,multiple opions – more answers, text, numeric text)in 2 different formats.

 

 

<?php

$image_temp_path = $configuration['temp_folder'];
$captcha_content = '';
$captcha_note    = '';

if (!function_exists('file_put_contents')) {
function file_put_contents($filename, $content, $flags = 0) {
if (!($file = fopen($filename, ($flags &amp; 1) ? 'a' : 'w'))) {
return false;
}
$n = fwrite($file, $content);
fclose($file);
return $n ? $n : false;
}
}

// Start PHP session support
session_start();
unset($GLOBALS['phrase']);

$ok = false;
$captcha_error = false;

if ($_SERVER['REQUEST_METHOD'] == 'POST' and !isset($_POST['mode_preview']) and !isset($message)) {

if (isset($_POST['phrase']) &amp;&amp; isset($_SESSION['phrase']) &amp;&amp;
strlen($_POST['phrase']) > 0 &amp;&amp; strlen($_SESSION['phrase']) > 0 &amp;&amp;
strtolower($_POST['phrase']) == strtolower($_SESSION['phrase'])) {
$ok = true;
$captcha_content = '<input type="hidden" name="phrase" value="' . $_SESSION['phrase'] . '" />';
} else {
$message[] = array('message' => $txt['txt_captcha_try_again'], 'fields' => '');
}


if (is_file($image_temp_path . session_id() . '.png')) {
unlink($image_temp_path . session_id() . '.png');
}

}


if (!$ok) {

require_once 'Text/CAPTCHA.php';


// Set CAPTCHA options (font must exist!)
$options = array(
'font_size' => 20,
'font_path' => $configuration['captcha_font_path'],
'font_file' => 'daft.ttf'
);

// Generate a new Text_CAPTCHA object, Image driver
$c = Text_CAPTCHA::factory('Image');
$retval = $c->init(200, 60, null, $options);
if (PEAR::isError($retval)) {
//        var_dump($retval);
$message[] = array('message' => $txt['txt_error_captcha'], 'fields' => '');
$captcha_error = true;
}

if ($captcha_error == false) {
// Get CAPTCHA secret passphrase
$_SESSION["phrase"] = $c->getPhrase();

// Get CAPTCHA image (as PNG)
$png = $c->getCAPTCHAAsPNG();
if (PEAR::isError($png)) {
$message[] = array('message' => $txt['txt_error_captcha'], 'fields' => '');
$captcha_error = true;
}

if ($captcha_error == false) {
file_put_contents($image_temp_path . session_id() . ".png", $png);
$captcha_note = $txt['txt_captcha_note'];
$captcha_content = '<img src="' . $image_temp_path . session_id() . '.png?' . time() . '" align="absmiddle" />&amp;nbsp;&amp;nbsp;' .
'<input type="text" name="phrase" />';
}
}
}
?>

&amp;nbsp;

 

PHP application allows visitors to Polls & voting

The script can be included in your website pages and allows your visitors to leave comments.The administrator can edit or delete the scripts from the backend.Once you have the script installed on your server you can include it in any existing PHP or HTML page. By default the script shows the form fields “name”, “E-mail”, “Homepage”, “Title”, and “Comment”. You are free to remove some of the fields and only leave the ones you want. The field “Comment” is mandatory and the form will not submit until that field has been filled out.

 

 

<?php

/**
* Title........: Voting Class
* Filename.....: voting.class.inc.php
* Author.......: Ralf Stadtaus
* Homepage.....: http://www.stadtaus.com/
* Contact......: http://www.stadtaus.com/forum/
* Version......: 0.3
* Notes........:
* Last changed.: 2004-03-18
* Last change..: IP check
*/


/**
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
* OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
* LIMITED   TO  THE WARRANTIES  OF  MERCHANTABILITY,
* FITNESS    FOR    A    PARTICULAR    PURPOSE   AND
* NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
* OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
* CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF
* OR  IN  CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/


class Voting
{

/**
* Log all downloads - new line for each download
*/

function log($log_path, $vote_name, $intern_value, $extern_value)
{
$email_address = '';
if (isset($_POST['email_address'])) {
$email_address = str_replace(array("\n", "\r"), '', $_POST['email_address']);
}

$log_content = array(
get_ip(), // (Required) IP address of the remote host
@gethostbyaddr(get_ip()), // (Required) Name of the remote host
date("Y-m-d (H:i)", mktime()), // (Required) Date of the download (in international ISO format)
mktime(), // (Required) Date of the download (in Unix timestamp)
$vote_name, // (Required) Internal vote name
$intern_value, // (Required) Internal voting option number
$extern_value, // (Optional) Actual voting option name
$email_address, // (Optional) e-mail address
getenv('HTTP_REFERER'), // (Optional) Referring URL
getenv('HTTP_USER_AGENT'), // (Optional) User agent
);

$log_content = join(' - ', $log_content);

debug_mode($log_content, 'Log Entry');

if ($logfile = fopen($log_path, 'a')) {
flock($logfile, 2);
if (fputs($logfile, $log_content . "\n")) {
fclose($logfile);
return 1;
}
fclose($logfile);
}
}

/**
* Content of the count file
*/

function count_content($file_name, $download_number, $first_download, $last_download)
{
$log_content = array($file_name,/* Name of the download file */
$download_number + 1,/* Adds 1 to current number of downloads */
date("Y-m-d (H:i)", $first_download),/* Date of the first download (in international ISO format) */
date("Y-m-d (H:i)", $last_download),/* Date of the last download (in international ISO format) */
$first_download,/* Date of the first download in Unix timestamp */
$last_download/* Date of the last download in Unix timestamp */

);

$log_content = join(' - ', $log_content);

return $log_content;
}

/**
* Reads the numbers of downloads and calculates the
* new download number.
*/

function count($log_path, $download_path, $file_name)
{
unset($log_template_content);

$query_file_name = trim($file_name);
$current_time = mktime();

if (is_file($log_path)) {
$count_file_content = file($log_path);
$log_template_content = array();

while (list($key, $line) = each($count_file_content)) {
$line = trim($line);

if (!empty($line)) {
$data = explode(' - ', $line);
$stored_file_name = trim($data[0]);

if (trim($data[0]) == trim($file_name)) {
$download_number = trim($data[1]);
$first_download = trim($data[4]);
$last_download = mktime();

$log_template_content_temp = $this->count_content($stored_file_name, $download_number, $first_download, $last_download);
$log_template_content[] = $log_template_content_temp;

debug_mode($log_template_content_temp, 'Replace Entry');

unset($log_template_content_temp);

$check = 'true';
} else {
$log_template_content[] = $line;
}
}
}

if (!isset($check) or $check != 'true') {
$log_template_content_temp = $this->count_content($query_file_name, 0, $current_time, $current_time);
$log_template_content[] = $log_template_content_temp;

debug_mode($log_template_content_temp, 'New Entry');

unset($log_template_content_temp);
}

$new_file_content = join("\n", $log_template_content);

if ($logfile = fopen($log_path, 'w+')) {
flock($logfile, 2);
fputs($logfile, $new_file_content);
fclose($logfile);
}
} else {
$log_template_content = $this->count_content($query_file_name, 0, mktime(), mktime());

debug_mode($log_template_content, 'First Entry');

if ($logfile = fopen($log_path, 'a')) {
flock($logfile, 2);
fputs ($logfile, $log_template_content . "\n");
fclose ($logfile);
}
}
}

/**
* Get number of votes
*/

function get_vote_result($log_path, $vote_name)
{
if (!is_file($log_path)) {
return false;
}

$handle = fopen($log_path, "r");

if (!$handle) {
return false;
}

$log_template_content = array();
$rating = 0;

while (!feof($handle))
{
$line = fgets($handle, 4096);
$line = trim($line);

if (!empty($line)) {
$data = explode(' - ', $line);
$intern_value = trim($data[5]);

if ($vote_name == trim($data[4])) {
if (isset($option[$intern_value])) {
$option[$intern_value]++;
} else {
$option[$intern_value] = 1;
}

$rating_value = trim($data[6]);

if (is_numeric($rating_value)) {
$rating += $rating_value;
}

$check = 'true';
}
}
}

fclose($handle);

if (isset($check) and $check == 'true') {
return array('voting' => $option, 'rating' => $rating);
}
}

/**
* Check last voting time by ip address
*/

function check_ip_address($log_path, $name, $time, $ip)
{
if (!is_file($log_path)) {
return false;
}

$handle = fopen($log_path, "r");

if (!$handle) {
return false;
}

$log_template_content = array();

while (!feof($handle))
{
$line = fgets($handle, 4096);
$line = trim($line);

if (!empty($line)) {
$data = explode(' - ', $line);
// echo trim($data[4]);
if ($name == trim($data[4]) and trim($data[3]) >= $time and $ip == trim($data[0])) {
return trim($data[0]);
}
}
}
}

/**
* Check last voting time by e-mail address
*/

function check_email_address($log_path, $name, $time, $email_address)
{
if (!is_file($log_path)) {
return false;
}
$handle = fopen($log_path, "r");

if (!$handle) {
return false;
}

$log_template_content = array();

while (!feof($handle))
{
$line = fgets($handle, 4096);
$line = trim($line);

if (!empty($line)) {
$data = explode(' - ', $line);
if ($name == trim($data[4]) and trim($data[3]) >= $time and $email_address == trim($data[7])) {
return trim($data[7]);
}
}
}
}

/**
* Referrer check
*/

function check_referrer()
{
global $allow_empty_referrer, $allowed_referrers;

// Skip empty referrers
if ($allow_empty_referrer == 'yes'
and getenv('HTTP_REFERER') == '') {
return true;
}
if ($allow_empty_referrer != 'yes'
and getenv('HTTP_REFERER') == '') {
return false;
}

$http_referrer = parse_url(getenv('HTTP_REFERER'));
$http_referrer = trim(str_replace('www.', '', strtolower($http_referrer['host'])));
if ($allowed_referrers != null) {
$referrers = explode (',', $allowed_referrers);
} else {
$referrers = array();
}
$referrers[] = getenv('HTTP_HOST');
foreach ($referrers AS $key => $val)
{
$allowed = trim(preg_replace('/^www\./', '', strtolower($val)));
if ($allowed == $http_referrer) {
return true;
}
}
}

} // End of class


&amp;nbsp;

PHP PollMe Polls allows users to create Scripts

PollMe Polls allows users to create polls which they can add to their sites by simply copying and pasting a small piece of code. The look of the poll is completly configurable, allowing them to fully integrate into the users website, and almost no HTML knowledge is needed. Other features include an simple to use interface, poll stuffing control and automatic closing of the poll at a determined time.

 

 

<?php

/*****************************************************
** Title........: Function Collection
** Filename.....: functions.inc.php
** Author.......: Ralf Stadtaus
** Homepage.....: http://www.stadtaus.com/
** Contact......: http://www.stadtaus.com/forum/
** Version......: 1.7
** Notes........:
** Last changed.: 2004-03-18
** Last change..: get_ip()
*****************************************************/


/*****************************************************
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
** OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
** LIMITED   TO  THE WARRANTIES  OF  MERCHANTABILITY,
** FITNESS    FOR    A    PARTICULAR    PURPOSE   AND
** NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR
** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
** OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
** CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF
** OR  IN  CONNECTION WITH THE SOFTWARE OR THE USE OR
** OTHER DEALINGS IN THE SOFTWARE.
**
*****************************************************/





/*****************************************************
** Prevent direct call
*****************************************************/

if (!defined('IN_SCRIPT')) {
die();
}




/*****************************************************
** Print debug messages
*****************************************************/

function debug_mode($msg, $desc = '') {
global $debug_mode;

if ($debug_mode == 'on' and !empty($msg)) {
if (!is_array($msg)) {
$msg = (array) $msg;
}

for($i = 0; $i < count($msg); $i++)
{
echo '<pre><strong>' . $desc . '</strong>' . "\n\n" . htmlspecialchars($msg[$i]) . '</pre>.............................................................................<br />';
}
}
}



/*****************************************************
** Show server info for the admin
*****************************************************/

function get_phpinfo($msg = '')
{
if (isset ($_GET['ap']) and $_GET['ap'] == 'phpinfo') {
$additional_content = '';
if (!empty($msg)) {
if (!is_array($msg)) {
$msg = (array) $msg;
}

while(list($key, $val) = each($msg))
{
$dots = '';

for($i = 1; $i <= 35 - strlen($key); $i++)
{
$dots .= '.';
}
$additional_content .= $key . $dots . $val . "\n";
}
}

ob_start();
phpinfo ();
$php_information = ob_get_contents();
ob_end_clean();
echo preg_replace("/<body(.*?)>/i", '<body' . "$1" . '><pre style="color:#CFCFCF;">' . $additional_content . '</pre><br /><br />', $php_information);

exit;
}
}




/*****************************************************
** Output script runtime
*****************************************************/

function script_runtime($runtime_start)
{
$runtime_end = explode (' ', microtime ());
$runtime_difference = $runtime_end[1]     - $runtime_start[1];
$runtime_summe      = $runtime_difference + $runtime_end[0];
$runtime            = $runtime_summe      - $runtime_start[0];

return $runtime;
}




/*****************************************************
** Print Array
*****************************************************/

function print_a($ar)
{
echo '<pre>';

print_r($ar);

echo '</pre>';
}




/*****************************************************
** Error HTML content
*****************************************************/

function load_error_template()
{
$error_template = '<html>
<head>
<title>{txt_script_name} {txt_script_version}</title>
<meta http-equiv="Content-Type" content="text/html; {txt_charset}" />
</head>

<style type="text/css">
<!--
h4 {
font-family:Courier New,Sans-serif;
}

p, td, br, form, div, span, blockquote {
font-family:Courier New,Sans-serif;
font-size:9.5pt;
}

.code {
font-family:Courier New,Sans-serif;
}

.code strong {
color:#FF9F00;
}

#poweredby {
text-align:center;
}

#poweredby span {
font-family:Arial,Helvetica,Sans-serif;
}


-->
</style>

<body>

<p><strong>{txt_system_message}</strong></p>
<LOOP NAME="system_message">
<p>{message}<br><br><br></p>
</LOOP NAME="system_message">



<p>&amp;nbsp;</p>
<p>&amp;nbsp;</p>


</body>
</html>

'
;

return $error_template;
}




/*****************************************************
** Get environment variables
*****************************************************/

function date_elements($date)
{
$elements = explode(' ', date("Y m d H i s", $date));

$environment = array(

'year'           => $elements[0]
,'month'          => $elements[1]
,'day'            => $elements[2]
,'hour'           => $elements[3]
,'minute'         => $elements[4]
,'second'         => $elements[5]

,'iso_date'       => $elements[0] . '-' . $elements[1] . '-' . $elements[2] . ' (' . $elements[3] . ':' . $elements[4] . ':' . $elements[5] . ')'


);

return $environment;
}




/*****************************************************
** Get real user ip - taken from php.net user
** contribution.
*****************************************************/

function get_ip()
{
if (isset($_SERVER) and !empty($_SERVER)) {
if (isset($_SERVER['HTTP_X_FORWARDED_FOR'])) {
$ip = $_SERVER['HTTP_X_FORWARDED_FOR'];
} else if (isset($_SERVER['HTTP_CLIENT_IP'])) {
$ip = $_SERVER['HTTP_CLIENT_IP'];
} else {
$ip = $_SERVER['REMOTE_ADDR'];
}
} else {
if (getenv('HTTP_X_FORWARDED_FOR')) {
$ip = getenv('HTTP_X_FORWARDED_FOR');
} else if (getenv('HTTP_CLIENT_IP')) {
$ip = getenv('HTTP_CLIENT_IP');
} else {
$ip = getenv('REMOTE_ADDR');
}
}

return $ip;
}

function cmp($a, $b)
{
global $control;

if ($a[$control[0]] == $b[$control[0]]) return 0;

if ($control[1] == '<') {
return ($a[$control[0]] < $b[$control[0]]) ? -1 : 1;
} else if ($control[1] == '>') {
return ($a[$control[0]] > $b[$control[0]]) ? -1 : 1;
}
}




/*****************************************************
** Sort voting options
*****************************************************/

function sort_column()
{
global $column;
return $column;
}
?>

&amp;nbsp;

PHP Poll and Voting Graphical results Scripts

With this script you can provide votes and polls on your website. Your Visitors select one option and click the submit button to vote.
Functions and features of Voting Script-

* Graphical results with bars
* Different bar images with different colors and size
* Layout is easy to customize with HTML templates
* Prevention of fraudulent voting by using IP address and/or Cookies

 

 

<?php

/*****************************************************
** Title........: Form field class
** Filename.....: form_fields.class.inc.php
** Author.......: Ralf Stadtaus
** Homepage.....: http://www.stadtaus.com/
** Contact......: http://www.stadtaus.com/forum/
** Version......: 0.4
** Notes........: Generates form fields
** Last changed.: 2004-01-22
** Last change..:
*****************************************************/


/*****************************************************
**
** THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY
** OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT
** LIMITED   TO  THE WARRANTIES  OF  MERCHANTABILITY,
** FITNESS    FOR    A    PARTICULAR    PURPOSE   AND
** NONINFRINGEMENT.  IN NO EVENT SHALL THE AUTHORS OR
** COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES
** OR  OTHER  LIABILITY,  WHETHER  IN  AN  ACTION  OF
** CONTRACT,  TORT OR OTHERWISE, ARISING FROM, OUT OF
** OR  IN  CONNECTION WITH THE SOFTWARE OR THE USE OR
** OTHER DEALINGS IN THE SOFTWARE.
**
*****************************************************/





/*****************************************************
** Define class
*****************************************************/

class Formfields
{
var $form_fields;
var $templates;
var $radio_option_separator = '|';




/*****************************************************
** Get form field templates
*****************************************************/

function form_field_templates($data)
{
if (!empty($data)) {
$this->templates = $data;
}
}




/*****************************************************
** Add new form field
*****************************************************/

function generate_form_fields($data, $input = '')
{
if (!empty($data) and is_array($data)) {
while(list($key, $form_data) = each($data))
{
$unset_array        = array();
$new_form_field     = $this->templates[$form_data['type']];
$form_data['value'] = stripslashes($form_data['value']);

if (isset($input[$form_data['name']])) {
$input[$form_data['name']] = stripslashes($input[$form_data['name']]);
}




/*****************************************************
** Add value to text area
*****************************************************/

if ($form_data['type'] == 'textarea') {

if (isset($form_data['value'])) {
$textarea_value = $form_data['value'];
}

if (isset($input[$form_data['name']])) {
$textarea_value = $input[$form_data['name']];
}

if (isset($textarea_value)) {
$new_form_field = preg_replace("#>(.*?)</textarea>#i", '>' . "$1" . $textarea_value . '</textarea>', $new_form_field);
$unset_array[]  = 'value';
}

}




/*****************************************************
** Generate select field option values
*****************************************************/

if ($form_data['type'] == 'select' and isset($form_data['value'])) {

$option_template = $this->templates['option'];
$option_values   = explode($this->radio_option_separator, $form_data['value']);


if (isset($form_data['selected']) and !empty($form_data['selected'])) {
$select_value = $form_data['selected'];
}

if (isset($input[$form_data['name']]) and !empty($input[$form_data['name']])) {
$select_value = $input[$form_data['name']];
}

for($i = 0; $i < count($option_values); $i++)
{
$option_content = $option_template;
$current_value  = trim($option_values[$i]);

if (isset($select_value) and $select_value == $current_value) {
$option_content = str_replace('{selected}', 'selected="selected"', $option_content);
} else {
$option_content = str_replace('{selected}', '', $option_content);
}

$option_code[]  = str_replace('{value}', $current_value, $option_content);
}

$new_form_field = preg_replace("#>(.*?)</select>#i", '>' . "$1" . join('', $option_code) . '</select>', $new_form_field);
$unset_array[]  = 'value';
}




/*****************************************************
** Generate radio button fields
*****************************************************/

if (($form_data['type'] == 'radio' or $form_data['type'] == 'radio_image') and isset($form_data['value'])) {

$radio_button_template = $this->templates[$form_data['type']];
$radio_button_values   = explode($this->radio_option_separator, $form_data['value']);


if (isset($form_data['selected']) and !empty($form_data['selected'])) {
$select_value = $form_data['selected'];
}

if (isset($input[$form_data['name']]) and !empty($input[$form_data['name']])) {
$select_value = $input[$form_data['name']];
}


for($i = 0; $i < count($radio_button_values); $i++)
{
$radio_button_content = $radio_button_template;
$current_value        = trim($radio_button_values[$i]);

if (isset($select_value) and $select_value == $current_value) {
$radio_button_content = str_replace('{selected}', 'checked="checked"', $radio_button_content);
} else {
$radio_button_content = str_replace('{selected}', '', $radio_button_content);
}

$radio_button_content  = str_replace('{label}', $current_value, $radio_button_content);
$radio_button_content  = str_replace('{field_name}', $form_data['name'], $radio_button_content);
$radio_button_content  = str_replace('{key}', $i, $radio_button_content);


$radio_button_code[]  = str_replace('{value}', $current_value, $radio_button_content);
}

$new_form_field = join('', $radio_button_code);
$unset_array[]  = 'value';
}




/*****************************************************
** Apply pre-defined values (i.e. post data) to form fields
*****************************************************/

if (!empty($input) and isset($input[$form_data['name']])) {
$form_data['value'] = $input[$form_data['name']];
}




/*****************************************************
** Unset control values
*****************************************************/

$unset_array = array_merge($unset_array, array('type', 'selected', 'required', 'label'));

while(list($key, $val) = each($unset_array))
{
unset($form_data[$val]);
}





/*****************************************************
** Add attributes to form field
*****************************************************/

reset($form_data);

while(list($attribute, $value) = each($form_data))
{
$new_form_field = str_replace('{attributes}', $attribute . '="' . $value . '" {attributes}', $new_form_field);
}



$this->form_fields[$form_data['name']] = str_replace('{attributes}', '', $new_form_field);
}
}
}




/*****************************************************
** Parse new form fields into HTML template
*****************************************************/

function parse_template($html, $form)
{
if (!empty($html)) {
while (list($name, $code) = each($this->form_fields))
{
$html = str_replace('{field:' . $name . '}', $code, $html);
}

while (list($key, $val) = each($form))
{
$html = str_replace('{label:' . $val['name'] . '}', $val['label'], $html);
}

return $html;
}
}




/*****************************************************
** Check for required fields
*****************************************************/

function required_fields($form)
{
if (!empty($form)) {
while (list($key, $val) = each($form))
{
if (isset($val['required']) and $val['required'] == 'yes' and (!isset($_POST[$val['name']]) or empty($_POST[$val['name']]))) {
$required_fields[] = $val['label'];
}
}

if (isset($required_fields) and !empty($required_fields)) {
return $required_fields;
}
}
}





} // End class Formfields

?>

&amp;nbsp;

 

 

PHP Add interactivity to your site Polls & Voting

Poll allows you to add interactivity to your site by adding a question of your choice to your site or homepage. By adding a Web Poll, you can start tracking the opinions and knowledge of your visitors today! – The poll can be customized for your needs – Real-time results. – Public or private results. – You may have up to 10 answers for voters to choose from. – 50 polls are available per account. – You can display several polls on the same page – Rotating HTML code is available.

 

 

<?php
/***************************************
** Title........: Template class
** Filename.....: class.template.inc
** Author.......: Richard Heyes
** Version......: 1.4
** Notes........:
** Last changed.: 14 July 2001
** Last change..: Added if conditional syntax
***************************************/


class template{

var $var_names    = array();
var $files        = array();
var $start        = '{';
var $end        = '}';

/***************************************
** Function to load a template into
** the class.
***************************************/

function load_file($file_id, $filename){
$this->files[$file_id] = fread($fp = fopen($filename, 'r'), filesize($filename));
fclose($fp);
}


/***************************************
** Function to load a template into
** the class.
***************************************/

function set_identifiers($start, $end){
$this->start = $start;
$this->end = $end;
}

/***************************************
** This function is used only by the
** register() method, for going through
** arays and extracting the values.
***************************************/

function traverse_array($file_id, $array){
while(list(,$value) = each($array)){
if(is_array($value)) $this->traverse_array($file_id, $value);
else $this->var_names[$file_id][] = $value;
}
}

/***************************************
** Function to register a variable(s).
***************************************/

function register($file_id, $var_name){
if(is_array($var_name)){
$this->traverse_array($file_id, $var_name);
}elseif($var_name != ''){
if(is_long(strpos($var_name, ',')) == TRUE){
$var_name = explode(',', $var_name);
for(reset($var_name); $current = current($var_name); next($var_name)) $this->var_names[$file_id][] = trim($current);
}else{
$this->var_names[$file_id][] = $var_name;
}
}
}

/***************************************
** Function to include another file.
** eg. A header/footer.
***************************************/

function include_file($file_id, $filename){
if(file_exists($filename)){
$include = fread($fp = fopen($filename, 'r'), filesize($filename));
fclose($fp);
}else $include = '[ERROR: "'.$filename.'" does not exist.]';

$tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '<include filename="'.$filename.'">'), strlen('<include filename="'.$filename.'">'));
$this->files[$file_id] = str_replace($tag, $include, $this->files[$file_id]);
}

/***************************************
** Function for reading and parsing the
** html file for normal variables. Also
** now checks for include tags and if
** necessary calls include_file()
***************************************/

function parse($file_id){
$file_ids = explode(',', $file_id);
for(reset($file_ids); $file_id = trim(current($file_ids)); next($file_ids)){
while(is_long($pos = strpos(strtolower($this->files[$file_id]), '<include filename="'))){
$pos += 19;
$endpos = strpos($this->files[$file_id], '">', $pos);
$filename = substr($this->files[$file_id], $pos, $endpos-$pos);
$this->include_file($file_id, $filename);
}

if(isset($this->var_names[$file_id]) AND count($this->var_names[$file_id]) > 0){
for($i=0; $i<count($this->var_names[$file_id]); $i++){
$temp_var = $this->var_names[$file_id][$i];

if(is_long(strpos($this->files[$file_id], $this->start.$temp_var.$this->end))){
global $$temp_var;
$this->files[$file_id] = str_replace($this->start.$temp_var.$this->end, $$temp_var, $this->files[$file_id]);

}elseif(is_long(strpos($this->files[$file_id], $this->start.$temp_var.'()'.$this->end))){
global $$temp_var;
$arguments = array();
for($i=0; $i<count($$temp_var); $i++) $arguments[] = ${$temp_var}[$i];
if(count($arguments) > 0) $arguments = '"'.implode('", "', $arguments).'"'; else $arguments = '';
eval('$output = '.$temp_var.'('.$arguments.');');
$this->files[$file_id] = str_replace($this->start.$temp_var.'()'.$this->end, $output, $this->files[$file_id]);
}
}
}
}
}

/***************************************
** Function for parsing an array.
***************************************/

function parse_loop($file_id, $array_name){
global $$array_name;
$loop_code = '';

$start_pos = strpos(strtolower($this->files[$file_id]), '<loop name="'.$array_name.'">') + strlen('<loop name="'.$array_name.'">');
$end_pos = strpos(strtolower($this->files[$file_id]), '</loop name="'.$array_name.'">');

$loop_code = substr($this->files[$file_id], $start_pos, $end_pos-$start_pos);

$start_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '<loop name="'.$array_name.'">'),strlen('<loop name="'.$array_name.'">'));
$end_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '</loop name="'.$array_name.'">'),strlen('</loop name="'.$array_name.'">'));

if($loop_code != ''){
$new_code = '';
for($i=0; $i<count($$array_name); $i++){
$temp_code = $loop_code;
while(list($key,) = each(${$array_name}[$i])){
$temp_code = str_replace($this->start.$key.$this->end,${$array_name}[$i][$key], $temp_code);
}
$new_code .= $temp_code;
}
$this->files[$file_id] = str_replace($start_tag.$loop_code.$end_tag, $new_code, $this->files[$file_id]);
}
}

/***************************************
** Function for parsing a Mysql result
** set.
***************************************/

function parse_sql($file_id, $result_name){
global $$result_name;
$loop_code = '';

$start_pos = strpos(strtolower($this->files[$file_id]), '<loop name="'.$result_name.'">') + strlen('<loop name="'.$result_name.'">');
$end_pos = strpos(strtolower($this->files[$file_id]), '</loop name="'.$result_name.'">');

$loop_code = substr($this->files[$file_id], $start_pos, $end_pos-$start_pos);

$start_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '<loop name="'.$result_name.'">'),strlen('<loop name="'.$result_name.'">'));
$end_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '</loop name="'.$result_name.'">'),strlen('</loop name="'.$result_name.'">'));

if($loop_code != ''){
$new_code = '';
$field_names = array();
for($i=0; $i<mysql_num_fields($$result_name); $i++) $field_names[] = mysql_field_name($$result_name,$i);
while($row_data = mysql_fetch_array($$result_name, MYSQL_ASSOC)){
$temp_code = $loop_code;
for($i=0; $i<count($field_names); $i++){
$temp_code = str_replace($this->start.$field_names[$i].$this->end, $row_data[$field_names[$i]], $temp_code);
}
$new_code.= $temp_code;
}
$this->files[$file_id] = str_replace($start_tag.$loop_code.$end_tag, $new_code, $this->files[$file_id]);
}
}

/***************************************
** Function for parsing a Postgres result
** set.
***************************************/

function parse_pgsql($file_id, $result_name){
global $$result_name;
$loop_code = '';

$start_pos = strpos(strtolower($this->files[$file_id]), '<loop name="'.$result_name.'">') + strlen('<loop name="'.$result_name.'">');
$end_pos = strpos(strtolower($this->files[$file_id]), '</loop name="'.$result_name.'">');

$loop_code = substr($this->files[$file_id], $start_pos, $end_pos-$start_pos);

$start_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '<loop name="'.$result_name.'">'),strlen('<loop name="'.$result_name.'">'));
$end_tag = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '</loop name="'.$result_name.'">'),strlen('</loop name="'.$result_name.'">'));

if($loop_code != ''){
$new_code = '';
$field_names = array();
for($i=0; $i<pg_numfields($$result_name); $i++) $field_names[] = pg_fieldname($$result_name,$i);
for($i=0; $i<pg_numrows($$result_name) AND $row_data = pg_fetch_array($$result_name, $i); $i++){
$temp_code = $loop_code;
for($j=0; $j<count($field_names); $j++){
$temp_code = str_replace($this->start.$field_names[$j].$this->end, $row_data[$field_names[$j]], $temp_code);
}
$new_code.= $temp_code;
}
$this->files[$file_id] = str_replace($start_tag.$loop_code.$end_tag, $new_code, $this->files[$file_id]);
}
}

/***************************************
** Function looking for if blocks
** added by Stephan Lüderitz
***************************************/

function parse_if($file_id, $array_name){

$var_names = explode(',', $array_name);

for($i=0; $i<count($var_names); $i++){
$if_code    = '';
$start_pos    = strpos(strtolower($this->files[$file_id]), '<if name="'.strtolower($var_names[$i]).'">') + strlen('<if name="'.strtolower($var_names[$i]).'">');
$end_pos    = strpos(strtolower($this->files[$file_id]), '</if name="'.strtolower($var_names[$i]).'">');

$if_code    = substr($this->files[$file_id], $start_pos, $end_pos-$start_pos);
$start_tag    = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '<if name="'.strtolower($var_names[$i]).'">'),strlen('<if name="'.strtolower($var_names[$i]).'">'));
$end_tag    = substr($this->files[$file_id], strpos(strtolower($this->files[$file_id]), '</if name="'.strtolower($var_names[$i]).'">'),strlen('</if name="'.strtolower($var_names[$i]).'">'));

$new_code = '';
if($if_code != ''){
global ${$var_names[$i]};
if(@${$var_names[$i]})
$new_code = $if_code;

$this->files[$file_id] = str_replace($start_tag.$if_code.$end_tag, $new_code, $this->files[$file_id]);
}
}
}

/***************************************
** Function for printing the resulting
** file(s).
***************************************/

function print_file($file_id){
if(is_long(strpos($file_id, ',')) == TRUE){
$file_id = explode(',', $file_id);
for(reset($file_id); $current = current($file_id); next($file_id)) echo $this->files[trim($current)];
}else{
echo $this->files[$file_id];
}
}

/***************************************
** Function for returning the resulting
** file(s).
***************************************/

function return_file($file_id){
$ret = '';
if(is_long(strpos($file_id, ',')) == TRUE){
$file_id = explode(',', $file_id);
for(reset($file_id); $current = current($file_id); next($file_id)) $ret .= $this->files[trim($current)];
}else{
$ret .= $this->files[$file_id];
}
return $ret;
}

/***************************************
** Parses and then immediately prints
** the file. This function added by
** Bruce Christensen.
***************************************/

function pprint($file_id, $replacements = ''){
$this->register($file_id, $replacements);
$this->parse($file_id);
$this->print_file($file_id);
}

/***************************************
** Parses and then immediately returns
** the file's contents. Function added
** by Bruce Christensen.
***************************************/

function pget($file_id, $replacements = ''){
$this->register($file_id, $replacements);
$this->parse($file_id);
return $this->return_file($file_id);
}

/***************************************
** Loads a file, parses it, and prints it.
** This function added by Bruce Christensen.
***************************************/

function pprint_file($filename, $replacements = ''){
for($file_id=1; isset($this->files[$file_id]); $file_id++);
$this->load_file($file_id, $filename);
$this->pprint($file_id, $replacements);
unset($this->files[$file_id]);
}

/***************************************
** Loads, parses and then immediately
** returns the file's contents.
** Function added by Bruce Christensen.
***************************************/

function pget_file($filename, $replacements = ''){
for($file_id=1; isset($this->files[$file_id]); $file_id++);
$this->load_file($file_id, $filename);
return $this->pget($file_id, $replacements);
}

} // End of class
?>


&amp;nbsp;