1
0
Fork 0

initial commit

This commit is contained in:
fanir 2015-11-13 23:51:46 +01:00
commit 1cc4bf3572
254 changed files with 63622 additions and 0 deletions

BIN
database.dia Normal file

Binary file not shown.

101
database.sql Normal file
View file

@ -0,0 +1,101 @@
START TRANSACTION;
LOCK feed, feedhistory, feeditem, announcement;
CREATE TEMPORARY TABLE backup_feed AS SELECT * FROM feed;
CREATE TEMPORARY TABLE backup_feedhistory AS SELECT * FROM feedhistory;
CREATE TEMPORARY TABLE backup_feeditem AS SELECT * FROM feeditem;
CREATE TEMPORARY TABLE backup_announcement AS SELECT * FROM announcement;
-- Parse::SQL::Dia version 0.27
-- Documentation http://search.cpan.org/dist/Parse-Dia-SQL/
-- Environment Perl 5.018004, /usr/bin/perl
-- Architecture i386-linux-thread-multi
-- Target Database postgres
-- Input file database.dia
-- Generated at Wed Jan 14 02:25:25 2015
-- Typemap for postgres not found in input file
-- get_constraints_drop
-- get_permissions_drop
-- get_view_drop
-- get_schema_drop
drop table announcement;
drop table feedhistory;
drop table feeditem;
drop table feed;
-- get_smallpackage_pre_sql
-- get_schema_create
create table feed (
id serial PRIMARY KEY ,
slug varchar(255) NOT NULL UNIQUE ,
uri varchar(255) NOT NULL ,
auto_refresh boolean NOT NULL ,
refresh_interval integer ,
next_refresh timestamp NOT NULL ,
expire boolean NOT NULL ,
expire_date timestamp ,
password varchar(255) ,
creation_ip inet NOT NULL ,
creation_date timestamp NOT NULL DEFAULT now()
) ;
create table feeditem (
feed integer NOT NULL REFERENCES feed ON DELETE CASCADE ON UPDATE CASCADE ,
timestamp timestamp NOT NULL DEFAULT now() ,
html text NOT NULL ,
diff text ,
PRIMARY KEY (feed, timestamp)
) ;
create table announcement (
id serial PRIMARY KEY ,
title varchar(255) NOT NULL ,
content text NOT NULL ,
abstract text ,
publication_date timestamp NOT NULL DEFAULT now(),
show_until timestamp ,
is_important boolean NOT NULL
) ;
create table feedhistory (
feed integer NOT NULL REFERENCES feed ON DELETE CASCADE ON UPDATE CASCADE ,
timestamp timestamp NOT NULL DEFAULT now() ,
ip inet NOT NULL ,
slug varchar(255) ,
uri varchar(255) ,
auto_refresh boolean ,
refresh_interval integer ,
next_refresh timestamp ,
expire boolean NOT NULL ,
expire_date timestamp ,
password varchar(255) ,
PRIMARY KEY (feed, timestamp)
) ;
-- get_view_create
-- get_permissions_create
-- get_inserts
-- get_smallpackage_post_sql
-- get_associations_create
LOCK feed, feedhistory, feeditem, announcement;
ALTER TABLE feed OWNER TO feedizer;
ALTER TABLE feeditem OWNER TO feedizer;
ALTER TABLE feedhistory OWNER TO feedizer;
ALTER TABLE announcement OWNER TO feedizer;
INSERT INTO feed SELECT * FROM backup_feed;
INSERT INTO feeditem SELECT * FROM backup_feeditem;
INSERT INTO feedhistory SELECT * FROM backup_feedhistory;
INSERT INTO announcement SELECT * FROM backup_announcement;
COMMIT;

73
database.sql- Normal file
View file

@ -0,0 +1,73 @@
-- Parse::SQL::Dia version 0.27
-- Documentation http://search.cpan.org/dist/Parse-Dia-SQL/
-- Environment Perl 5.018004, /usr/bin/perl
-- Architecture i386-linux-thread-multi
-- Target Database postgres
-- Input file database.dia
-- Generated at Wed Jan 21 00:43:48 2015
-- Typemap for postgres not found in input file
-- get_constraints_drop
-- get_permissions_drop
-- get_view_drop
-- get_schema_drop
drop table feed;
drop table feeditem;
drop table announcement;
drop table feedhistory;
-- get_smallpackage_pre_sql
-- get_schema_create
create table feed (
id serial PRIMARY KEY ,
slug varchar(255) NOT NULL UNIQUE ,
uri varchar(255) NOT NULL ,
auto_refresh boolean NOT NULL ,
refresh_interval integer ,
next_refresh timestamp NOT NULL ,
password varchar(255) ,
creation_ip inet NOT NULL ,
creation_date timestamp NOT NULL DEFAULT now
) ;
create table feeditem (
feed varchar(255) NOT NULL REFERENCES feed ON DELETE CASCADE ON UPDATE CASCADE ,
timestamp timestamp NOT NULL DEFAULT now ,
content text NOT NULL ,
diff text NOT NULL ,
PRIMARY KEY (feed, timestamp)
) ;
create table announcement (
id serial PRIMARY KEY ,
title varchar(255) NOT NULL ,
content text NOT NULL ,
abstract text ,
publication_date timestamp NOT NULL DEFAULT now ,
show_until timestamp ,
is_important boolean NOT NULL
) ;
create table feedhistory (
feed integer NOT NULL REFERENCES feed ON DELETE CASCADE ON UPDATE CASCADE ,
timestamp timestamp NOT NULL DEFAULT 'now' ,
ip inet NOT NULL ,
slug varchar(255) ,
uri varchar(255) ,
auto_refresh boolean ,
refresh_interval integer ,
next_refresh timestamp ,
password varchar(255) ,
PRIMARY KEY (feed, timestamp)
) ;
-- get_view_create
-- get_permissions_create
-- get_inserts
-- get_smallpackage_post_sql
-- get_associations_create

23
htdocs/.htaccess Normal file
View file

@ -0,0 +1,23 @@
RewriteEngine On
# Don't rewrite the following URIs
RewriteRule ^static/.*$ - [L]
RewriteRule ^libraries/.*$ - [L]
RewriteRule ^favicon\.ico$ - [L]
RewriteRule ^robots\.txt$ - [L]
# Everything else goes to index.php
RewriteRule ^(.*)$ index.php [QSA,L]
# Absolutely no access to PHP include files
#<Files "*.inc.php">
# Require all denied
#</Files>
AddDefaultCharset utf-8
# Thou shall not pass!
AuthType Basic
AuthName "construction site"
AuthUserFile /var/www/vhosts/feedizer.tigris.fanir.de/htpasswd
Require user fanir guest

2
htdocs/cache/.gitignore vendored Normal file
View file

@ -0,0 +1,2 @@
*
!.gitignore

BIN
htdocs/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.1 KiB

View file

@ -0,0 +1,3 @@
Order Allow,Deny
Deny from All

View file

@ -0,0 +1,36 @@
<?php
/* Database-Connection */
// Data Source Name.
define('DB_DSN', 'pgsql:host=localhost dbname=feedizer');
// Username for DB connection
define('DB_USER', 'feedizer');
// Password for DB connection
define('DB_PASS', '');
define('DB_OPTIONS', array(
// Make a persistent connection
PDO::ATTR_PERSISTENT => true,
));
/* Logging */
// Send errors to stdout?
ini_set('display_errors', 0);
// What to report?
error_reporting(E_ALL);
/* Admin user */
#define('ADMIN_NAME', 'fanir');
#define('ADMIN_PASS', '');
/* Crawler */
define('CRAWLER_LOG_FILE', BASE_PATH . 'logs/crawl.log');

View file

@ -0,0 +1,144 @@
<?php
/* Classes and functions for database abstraction */
class announcements {
public static function getList() {
global $db;
return $db->query('SELECT * FROM announcement')->fetchAll();
}
public static function getById($id) {
global $db;
$stmt = $db->prepare('SELECT * FROM announcement WHERE id = :id');
if ($stmt->execute(array(':id' => $id)))
return $stmt->fetch(PDO::FETCH_ASSOC);
else
return false;
}
public static function getLatest() {
global $db;
return $db->query('SELECT * FROM announcement ORDER BY publication_date DESC LIMIT 1')->fetch(PDO::FETCH_ASSOC);
}
}
class feeds {
public static function getList() {
global $db;
return $db->query('SELECT * FROM feed')->fetchAll(PDO::FETCH_ASSOC);
}
public static function getRefreshList() {
global $db;
return $db->query('SELECT * FROM feed WHERE auto_refresh = TRUE AND next_refresh <= now()')->fetchAll(PDO::FETCH_ASSOC);
}
public static function getBySlug($slug) {
global $db;
$stmt = $db->prepare('SELECT * FROM feed WHERE slug = :slug');
if ($stmt->execute(array(':slug' => $slug)))
return $stmt->fetch(PDO::FETCH_ASSOC);
else
return false;
}
public static function updateNextRefresh($id) {
global $db;
$stmt = $db->prepare('
UPDATE feed
SET next_refresh = next_refresh + (
SELECT concat(refresh_interval, \' seconds\')
FROM feed
WHERE id = :id
)::interval
WHERE id = :id'
);
$stmt->bindValue(':id', $id);
$stmt->execute();
}
public static function create($slug, $uri,
$auto_refresh, $refresh_interval, $next_refresh,
$expire, $expire_date,
$password, $creation_ip, $creation_date
) {
global $db;
$stmt = $db->prepare('
INSERT INTO feed(
slug, uri,
auto_refresh, refresh_interval, next_refresh,
expire, expire_date,
password, creation_ip, creation_date
) VALUES (
:slug, :uri,
:auto_refresh, :refresh_interval, :next_refresh,
:expire, :expire_date,
:password, :creation_ip, :creation_date
)'
);
$stmt->bindValue(':slug', $slug);
$stmt->bindValue(':uri', $uri);
$stmt->bindValue(':auto_refresh', $auto_refresh);
$stmt->bindValue(':refresh_interval', $refresh_interval ? $refresh_interval : null);
$stmt->bindValue(':next_refresh', $next_refresh);
$stmt->bindValue(':expire', $expire);
$stmt->bindValue(':expire_date', $expire_date ? $expire_date: null);
$stmt->bindValue(':password', $password ? $password : null);
$stmt->bindValue(':creation_ip', $creation_ip);
$stmt->bindValue(':creation_date', $creation_date);
return $stmt->execute();
}
}
class feedItems {
public static function getLatest($feedId) {
global $db;
$stmt = $db->prepare('SELECT * FROM feeditem WHERE feed = :feedid ORDER BY timestamp DESC LIMIT 1');
if ($stmt->execute(array(':feedid' => $feedId)))
return $stmt->fetch(PDO::FETCH_ASSOC);
else
return false;
}
public static function getAll($feedId) {
global $db;
$stmt = $db->prepare('SELECT * FROM feeditem WHERE feed = :feedid ORDER BY timestamp DESC');
if ($stmt->execute(array(':feedid' => $feedId)))
return $stmt->fetchAll(PDO::FETCH_ASSOC);
else
return false;
}
public static function newItem($feedId, $html) {
$html = mb_convert_encoding($html, 'UTF-8', 'UTF-8,ISO-8859-1,Windows-1251,GB2312,SJIS,Windows-1251');
$latest = feedItems::getLatest($feedId);
if ($latest)
$diff = xdiff_string_diff($latest['html'], $html);
else
$diff = xdiff_string_diff('', $html);
if (empty($diff))
return 1;
global $db;
$stmt = $db->prepare('INSERT INTO feeditem VALUES (:feedid, \'now\', :html, :diff)');
$stmt->bindValue(':feedid', $feedId);
$stmt->bindValue(':html', $html);
$stmt->bindValue(':diff', $diff);
$stmt->execute();
return 0;
}
public static function deleteOldItems($keepCount) {
global $db;
return 1;
}
}

View file

@ -0,0 +1,41 @@
<?php
function sec2hms($seconds) {
if ($seconds == 0)
return '0 seconds';
$hours = floor($seconds / 3600);
$seconds = $seconds % 3600;
if ($hours > 0)
$hstr = $hours . ($hours > 1 ? ' hours' : ' hour');
else
$hstr = false;
if ($seconds > 0) {
$minutes = floor($seconds / 60);
$seconds = $seconds % 60;
if ($minutes > 0)
$mstr .= $minutes . ($minutes > 1 ? ' minutes' : ' minute');
else
$mstr = false;
if ($seconds > 0)
$sstr .= $seconds . ($seconds > 1 ? ' seconds' : ' second');
else
$sstr = false;
} else {
$mstr = false;
$sstr = false;
}
if ($hstr and $mstr and $sstr)
return $hstr . ', ' . $mstr . ' and ' . $sstr;
elseif ($hstr and $mstr)
return $hstr . ' and ' . $mstr;
elseif ($hstr and $sstr)
return $hstr . ' and ' . $sstr;
elseif ($mstr and $sstr)
return $mstr . ' and ' . $sstr;
else
return $hstr . $mstr . $sstr;
}

View file

@ -0,0 +1,52 @@
<?php
define('BASE_PATH', realpath(dirname(__FILE__) . '/..') . '/');
set_include_path(get_include_path()
. PATH_SEPARATOR . BASE_PATH . 'includes'
. PATH_SEPARATOR . BASE_PATH . 'libraries'
);
require('config.inc.php');
// Versioning
define('VERSION', '0.0');
define('CRAWLER_VERSION', '0.2');
define('CRAWLER_LAST_UPDATED', filemtime(BASE_PATH . 'scripts/crawler.php'));
// For a better death!
function handle_exception($e) {
error_log('An exception occurred: ' . $e);
echo "An error occured: " . $e->getMessage() . "<br>\n<br>\n"
."Please notify the site administrator (webmaster at tigris dot fanir dot de) and include the information in the box below:<br>\n"
."<textarea style='width: 100%; max-width: 80em; height: 20em;' readonly>"
."Timestamp: " . strftime('%c') . "\n"
."\n"
."Code: " . $e->getCode() . "\n"
."Message: " . $e->getMessage() . "\n";
if ($e->getPrevious()) {
echo "\n"
."Previous exception:\n"
."Code: " . $e->getPrevious()->getCode() . "\n"
."Message: " . $e->getPrevious()->getMessage() . "\n";
}
echo "</textarea>";
exit($e->getCode());
}
set_exception_handler('handle_exception');
// Connect to DB
try {
$db = new PDO(DB_DSN, DB_USER, DB_PASS);
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
throw new Exception('Cannot connect to database', 16, $e);
}
// Load database abstraction
require('database.inc.php');
// Load helper functions
require('helpers.inc.php');

View file

@ -0,0 +1,24 @@
<?php
// Initialize templating engine
require('smarty3/Smarty.class.php');
$tpl = new Smarty;
$tpl->setCacheDir(BASE_PATH . 'cache');
$tpl->setCompileDir(BASE_PATH . 'cache');
$tpl->setTemplateDir(BASE_PATH . 'templates');
$tpl->left_delimiter = '{{';
$tpl->right_delimiter = '}}';
require('routes.inc.php');
/*
// Markdown
require('Michelf/Markdown.inc.php');
#require('Michelf/MarkdownInterface.php');
#require('Michelf/Markdown.php');
$md = new \Michelf\Markdown;
$md->empty_element_suffix = '>';
*/

View file

@ -0,0 +1,11 @@
<?php
// Define the routes
$routes = array(
'feed' => "/feed/(?'slug'[[:alnum:]\._-]+)/(?'contentType'page|diff)/(?'feedType'atom|rss)",
'feedInfo' => "/feed/(?'slug'[[:alnum:]\._-]+)(/info)?",
'home' => "/",
'create' => "/create",
'flatpage' => "/page/(?'slug'[[:alnum:]-\._]+)",
'announcement' => "/announcement/(?'id'[0-9]+)(/.*)?",
);

View file

@ -0,0 +1,196 @@
<?php
#require_once(BASE_PATH . 'classes/Nibble-Forms/Nibble/NibbleForms/NibbleForm.php');
require(BASE_PATH . 'libraries/password_compat/lib/password.php');
require(BASE_PATH . 'libraries/FeedWriter/FeedTypes.php');
class views {
public static function home($params) {
global $tpl;
/* #FIXME
$tpl->assign('announcement', array(
'id' => 1234,
'date' => time(),
'title' => 'Foo Bar',
'abstract' => 'baz',
'content' => 'It\'s the text!',
'is_important' => false
));
*/
$tpl->display('home.html');
}
public static function create($params) {
global $tpl;
$formdata = array(
'name' => array('value' => $_REQUEST['slug']),
'uri' => array('value' => $_REQUEST['uri']),
'refresh_on_request' => array('checked' => $_REQUEST['refresh'] == 'interval' ? false : true),
'interval' => array('value' => $_REQUEST['interval']),
'expire' => array('checked' => isset($_REQUEST['expire']) ? true : false,
'value' => $_REQUEST['expire_value'],
'unit' => $_REQUEST['expire_unit']),
'description' => array('value' => $_REQUEST['description']),
);
// Check name (slug)
if (isset($_REQUEST['slug'])
and preg_match('#^[a-zA-Z0-9_\.+-]+$#', $_REQUEST['slug'])
) {
// Check URI
if (isset($_REQUEST['uri'])
and preg_match('#^https?://[a-zA-Z0-9_\.-]+\.[a-zA-Z0-9]{2,}(/.*)?$#', $_REQUEST['uri'])
) {
// Check refresh
if ($_REQUEST['refresh'] == 'request'
or ($_REQUEST['refresh'] == 'interval'
and $_REQUEST['interval'] >= 900
)) {
// Check expire
if ($_REQUEST['expire'] == false
or ($_REQUEST['expire'] == true
and intval($_REQUEST['expire_value']) > 0
and in_array($_REQUEST['expire_unit'], ['h', 'd', 'w', 'm'])
)) {
// Check description
if (strlen($_REQUEST['description']) < 1000) {
// Calculate expiration date, if needed
if ($_REQUEST['expire'] == true) {
$expireDate = new DateTime();
switch ($_REQUEST['expire_unit']) {
case 'h':
#$expireDate = strtotime('+' . $_REQUEST['expire_value'] . ' hours');
$expireString = $expireDate->add(new DateInterval("PT$_REQUEST[expire_value]H"))->format('Y-m-d H:i:s');
break;
case 'd':
#$expireDate = strtotime('+' . $_REQUEST['expire_value'] . ' days');
$expireString = $expireDate->add(new DateInterval("P$_REQUEST[expire_value]D"))->format('Y-m-d H:i:s');
break;
case 'w':
#$expireDate = strtotime('+' . $_REQUEST['expire_value'] . ' weeks');
$expireString = $expireDate->add(new DateInterval("P$_REQUEST[expire_value]W"))->format('Y-m-d H:i:s');
break;
case 'm':
#$expireDate = strtotime('+' . $_REQUEST['expire_value'] . ' months');
$expireString = $expireDate->add(new DateInterval("P$_REQUEST[expire_value]M"))->format('Y-m-d H:i:s');
break;
}
} else $expireString = null;
if (feeds::create($_REQUEST['slug'],
$_REQUEST['uri'],
$_REQUEST['refresh'] == 'interval' ? 'true' : 'false',
$_REQUEST['interval'],
'now',
isset($_REQUEST['expire']) ? 'true' : 'false',
$expireString,
$_REQUEST['password'],
$_SERVER['REMOTE_ADDR'],
'now'
)) {
$tpl->assign('title', 'Feedized!');
$tpl->assign('feed', $_REQUEST);
$tpl->assign('interval_hms', sec2hms($_REQUEST['interval']));
if ($_REQUEST['expire'])
$tpl->assign('expire_hms', sec2hms($_REQUEST['expire_value']));
$tpl->display('created.html');
exit();
}
} else { // erroneous description?
$formdata['description']['has_error'] = true;
$formdata['description']['error_message'] = 'You description is too long.';
}
} else { // erroneous expire?
$formdata['expire']['has_error'] = true;
$formdata['expire']['error_message'] = 'Please enter a valid timespan.';
}
} else { // erroneous interval?
$formdata['interval']['has_error'] = true;
$formdata['interval']['error_message'] = 'The request interval must be at least 15 minutes (900 seconds). Why did you even try?';
}
} else { // erroneous uri?
$formdata['uri']['has_error'] = true;
$formdata['uri']['error_message'] = 'Please enter a valid URI, like "http://duckduckgo.com/"';
}
} else { // erroneous name?
$formdata['name']['has_error'] = true;
$formdata['name']['error_message'] = 'Please enter a valid name for your feed. Allowed characters are: a-z A-Z 0-9 _ . -';
}
$tpl->assign('form', $formdata);
views::home($params);
}
public static function feed($params) {
$feedData = feeds::getBySlug($params['slug']);
if (!$feedData)
return [404, 'feed'];
$itemData = feedItems::getAll($feedData['id']);
$feed = new ATOMFeedWriter();
$feed->setTitle($feedData['slug']);
$feed->setLink('https://feedizer.tigris.fanir.de/feed/' . $feedData['slug']);
$feed->setChannelElement('updated', (new DateTime($itemData[0]['timestamp']))->format(DATE_ATOM));
foreach ($itemData as $item) {
$feedItem = $feed->createNewItem();
$feedItem->setTitle($feedData['slug']);
$feedItem->setLink($feedData['uri']);
$feedItem->setDate($item['timestamp']);
switch ($params['contentType']) {
case 'page':
$feedItem->setDescription($item['html']);
break;
case 'diff':
$feedItem->setDescription(nl2br(htmlspecialchars($item['diff'], ENT_XML1 | ENT_SUBSTITUTE | ENT_COMPAT)));
break;
default: return [404];
}
$feed->addItem($feedItem);
}
$feed->generateFeed();
return 0;
}
public static function feedInfo($params) {
global $tpl, $md;
$feed = feeds::getBySlug($params['slug']);
if (!$feed)
return [404, 'feed'];
#$feed['description'] = $md->transform(htmlspecialchars($feed['description']));
$tpl->assign('feed', $feed);
$tpl->assign('interval_hms', sec2hms($feed['refresh_interval']));
$tpl->display('feedInfo.html');
}
public static function flatpage($params) {
$file = $params['slug'] . '.html';
if (in_array($file, scandir(BASE_PATH . 'templates/flatpages'))) {
global $tpl;
$tpl->display('flatpages/' . $file);
} else {
return [404];
}
}
public static function announcement($params) {
$ann = announcements::getById($params['id']);
if ($ann != false) {
global $tpl;
$tpl->assign('announcement', $ann);
$tpl->display('announcement.html');
} else {
return [404, 'announcement'];
}
}
}

31
htdocs/index.php Normal file
View file

@ -0,0 +1,31 @@
<?php
require(dirname(__FILE__) . '/includes/init.inc.php');
require(dirname(__FILE__) . '/includes/init.web.inc.php');
// Prepare the request URI
$uri = rtrim(dirname($_SERVER['SCRIPT_NAME']), '/');
$uri = '/' . trim(str_replace($uri, '', $_SERVER['REQUEST_URI']), '/');
$uri = urldecode($uri);
// Which route is it?
foreach ($routes as $action => $rule) {
if (preg_match('~^'.$rule.'$~i', $uri, $params)) {
include('includes/views.inc.php');
$r = eval('return views::' . $action . '($params);');
switch ($r[0]) {
case 0:
exit;
case 404:
break;
default:
if ($r > 9000) die('<h1>It\'s over 9000!</h1>');
header("HTTP/1.1 500 Internal Server Error", true, 500);
exit('<h1>500 Internal Server Error</h1>');
}
}
}
// No match? Send 404!
header($_SERVER['SERVER_PROTOCOL'] . " 404 Not Found");
if (isset($r[1])) $tpl->assign('type', $r[1]);
$tpl->display('error404.html');

View file

@ -0,0 +1,674 @@
GNU GENERAL PUBLIC LICENSE
Version 3, 29 June 2007
Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The GNU General Public License is a free, copyleft license for
software and other kinds of works.
The licenses for most software and other practical works are designed
to take away your freedom to share and change the works. By contrast,
the GNU General Public License is intended to guarantee your freedom to
share and change all versions of a program--to make sure it remains free
software for all its users. We, the Free Software Foundation, use the
GNU General Public License for most of our software; it applies also to
any other work released this way by its authors. You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
them if you wish), that you receive source code or can get it if you
want it, that you can change the software or use pieces of it in new
free programs, and that you know you can do these things.
To protect your rights, we need to prevent others from denying you
these rights or asking you to surrender the rights. Therefore, you have
certain responsibilities if you distribute copies of the software, or if
you modify it: responsibilities to respect the freedom of others.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must pass on to the recipients the same
freedoms that you received. You must make sure that they, too, receive
or can get the source code. And you must show them these terms so they
know their rights.
Developers that use the GNU GPL protect your rights with two steps:
(1) assert copyright on the software, and (2) offer you this License
giving you legal permission to copy, distribute and/or modify it.
For the developers' and authors' protection, the GPL clearly explains
that there is no warranty for this free software. For both users' and
authors' sake, the GPL requires that modified versions be marked as
changed, so that their problems will not be attributed erroneously to
authors of previous versions.
Some devices are designed to deny users access to install or run
modified versions of the software inside them, although the manufacturer
can do so. This is fundamentally incompatible with the aim of
protecting users' freedom to change the software. The systematic
pattern of such abuse occurs in the area of products for individuals to
use, which is precisely where it is most unacceptable. Therefore, we
have designed this version of the GPL to prohibit the practice for those
products. If such problems arise substantially in other domains, we
stand ready to extend this provision to those domains in future versions
of the GPL, as needed to protect the freedom of users.
Finally, every program is threatened constantly by software patents.
States should not allow patents to restrict development and use of
software on general-purpose computers, but in those that do, we wish to
avoid the special danger that patents applied to a free program could
make it effectively proprietary. To prevent this, the GPL assures that
patents cannot be used to render the program non-free.
The precise terms and conditions for copying, distribution and
modification follow.
TERMS AND CONDITIONS
0. Definitions.
"This License" refers to version 3 of the GNU General Public License.
"Copyright" also means copyright-like laws that apply to other kinds of
works, such as semiconductor masks.
"The Program" refers to any copyrightable work licensed under this
License. Each licensee is addressed as "you". "Licensees" and
"recipients" may be individuals or organizations.
To "modify" a work means to copy from or adapt all or part of the work
in a fashion requiring copyright permission, other than the making of an
exact copy. The resulting work is called a "modified version" of the
earlier work or a work "based on" the earlier work.
A "covered work" means either the unmodified Program or a work based
on the Program.
To "propagate" a work means to do anything with it that, without
permission, would make you directly or secondarily liable for
infringement under applicable copyright law, except executing it on a
computer or modifying a private copy. Propagation includes copying,
distribution (with or without modification), making available to the
public, and in some countries other activities as well.
To "convey" a work means any kind of propagation that enables other
parties to make or receive copies. Mere interaction with a user through
a computer network, with no transfer of a copy, is not conveying.
An interactive user interface displays "Appropriate Legal Notices"
to the extent that it includes a convenient and prominently visible
feature that (1) displays an appropriate copyright notice, and (2)
tells the user that there is no warranty for the work (except to the
extent that warranties are provided), that licensees may convey the
work under this License, and how to view a copy of this License. If
the interface presents a list of user commands or options, such as a
menu, a prominent item in the list meets this criterion.
1. Source Code.
The "source code" for a work means the preferred form of the work
for making modifications to it. "Object code" means any non-source
form of a work.
A "Standard Interface" means an interface that either is an official
standard defined by a recognized standards body, or, in the case of
interfaces specified for a particular programming language, one that
is widely used among developers working in that language.
The "System Libraries" of an executable work include anything, other
than the work as a whole, that (a) is included in the normal form of
packaging a Major Component, but which is not part of that Major
Component, and (b) serves only to enable use of the work with that
Major Component, or to implement a Standard Interface for which an
implementation is available to the public in source code form. A
"Major Component", in this context, means a major essential component
(kernel, window system, and so on) of the specific operating system
(if any) on which the executable work runs, or a compiler used to
produce the work, or an object code interpreter used to run it.
The "Corresponding Source" for a work in object code form means all
the source code needed to generate, install, and (for an executable
work) run the object code and to modify the work, including scripts to
control those activities. However, it does not include the work's
System Libraries, or general-purpose tools or generally available free
programs which are used unmodified in performing those activities but
which are not part of the work. For example, Corresponding Source
includes interface definition files associated with source files for
the work, and the source code for shared libraries and dynamically
linked subprograms that the work is specifically designed to require,
such as by intimate data communication or control flow between those
subprograms and other parts of the work.
The Corresponding Source need not include anything that users
can regenerate automatically from other parts of the Corresponding
Source.
The Corresponding Source for a work in source code form is that
same work.
2. Basic Permissions.
All rights granted under this License are granted for the term of
copyright on the Program, and are irrevocable provided the stated
conditions are met. This License explicitly affirms your unlimited
permission to run the unmodified Program. The output from running a
covered work is covered by this License only if the output, given its
content, constitutes a covered work. This License acknowledges your
rights of fair use or other equivalent, as provided by copyright law.
You may make, run and propagate covered works that you do not
convey, without conditions so long as your license otherwise remains
in force. You may convey covered works to others for the sole purpose
of having them make modifications exclusively for you, or provide you
with facilities for running those works, provided that you comply with
the terms of this License in conveying all material for which you do
not control copyright. Those thus making or running the covered works
for you must do so exclusively on your behalf, under your direction
and control, on terms that prohibit them from making any copies of
your copyrighted material outside their relationship with you.
Conveying under any other circumstances is permitted solely under
the conditions stated below. Sublicensing is not allowed; section 10
makes it unnecessary.
3. Protecting Users' Legal Rights From Anti-Circumvention Law.
No covered work shall be deemed part of an effective technological
measure under any applicable law fulfilling obligations under article
11 of the WIPO copyright treaty adopted on 20 December 1996, or
similar laws prohibiting or restricting circumvention of such
measures.
When you convey a covered work, you waive any legal power to forbid
circumvention of technological measures to the extent such circumvention
is effected by exercising rights under this License with respect to
the covered work, and you disclaim any intention to limit operation or
modification of the work as a means of enforcing, against the work's
users, your or third parties' legal rights to forbid circumvention of
technological measures.
4. Conveying Verbatim Copies.
You may convey verbatim copies of the Program's source code as you
receive it, in any medium, provided that you conspicuously and
appropriately publish on each copy an appropriate copyright notice;
keep intact all notices stating that this License and any
non-permissive terms added in accord with section 7 apply to the code;
keep intact all notices of the absence of any warranty; and give all
recipients a copy of this License along with the Program.
You may charge any price or no price for each copy that you convey,
and you may offer support or warranty protection for a fee.
5. Conveying Modified Source Versions.
You may convey a work based on the Program, or the modifications to
produce it from the Program, in the form of source code under the
terms of section 4, provided that you also meet all of these conditions:
a) The work must carry prominent notices stating that you modified
it, and giving a relevant date.
b) The work must carry prominent notices stating that it is
released under this License and any conditions added under section
7. This requirement modifies the requirement in section 4 to
"keep intact all notices".
c) You must license the entire work, as a whole, under this
License to anyone who comes into possession of a copy. This
License will therefore apply, along with any applicable section 7
additional terms, to the whole of the work, and all its parts,
regardless of how they are packaged. This License gives no
permission to license the work in any other way, but it does not
invalidate such permission if you have separately received it.
d) If the work has interactive user interfaces, each must display
Appropriate Legal Notices; however, if the Program has interactive
interfaces that do not display Appropriate Legal Notices, your
work need not make them do so.
A compilation of a covered work with other separate and independent
works, which are not by their nature extensions of the covered work,
and which are not combined with it such as to form a larger program,
in or on a volume of a storage or distribution medium, is called an
"aggregate" if the compilation and its resulting copyright are not
used to limit the access or legal rights of the compilation's users
beyond what the individual works permit. Inclusion of a covered work
in an aggregate does not cause this License to apply to the other
parts of the aggregate.
6. Conveying Non-Source Forms.
You may convey a covered work in object code form under the terms
of sections 4 and 5, provided that you also convey the
machine-readable Corresponding Source under the terms of this License,
in one of these ways:
a) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by the
Corresponding Source fixed on a durable physical medium
customarily used for software interchange.
b) Convey the object code in, or embodied in, a physical product
(including a physical distribution medium), accompanied by a
written offer, valid for at least three years and valid for as
long as you offer spare parts or customer support for that product
model, to give anyone who possesses the object code either (1) a
copy of the Corresponding Source for all the software in the
product that is covered by this License, on a durable physical
medium customarily used for software interchange, for a price no
more than your reasonable cost of physically performing this
conveying of source, or (2) access to copy the
Corresponding Source from a network server at no charge.
c) Convey individual copies of the object code with a copy of the
written offer to provide the Corresponding Source. This
alternative is allowed only occasionally and noncommercially, and
only if you received the object code with such an offer, in accord
with subsection 6b.
d) Convey the object code by offering access from a designated
place (gratis or for a charge), and offer equivalent access to the
Corresponding Source in the same way through the same place at no
further charge. You need not require recipients to copy the
Corresponding Source along with the object code. If the place to
copy the object code is a network server, the Corresponding Source
may be on a different server (operated by you or a third party)
that supports equivalent copying facilities, provided you maintain
clear directions next to the object code saying where to find the
Corresponding Source. Regardless of what server hosts the
Corresponding Source, you remain obligated to ensure that it is
available for as long as needed to satisfy these requirements.
e) Convey the object code using peer-to-peer transmission, provided
you inform other peers where the object code and Corresponding
Source of the work are being offered to the general public at no
charge under subsection 6d.
A separable portion of the object code, whose source code is excluded
from the Corresponding Source as a System Library, need not be
included in conveying the object code work.
A "User Product" is either (1) a "consumer product", which means any
tangible personal property which is normally used for personal, family,
or household purposes, or (2) anything designed or sold for incorporation
into a dwelling. In determining whether a product is a consumer product,
doubtful cases shall be resolved in favor of coverage. For a particular
product received by a particular user, "normally used" refers to a
typical or common use of that class of product, regardless of the status
of the particular user or of the way in which the particular user
actually uses, or expects or is expected to use, the product. A product
is a consumer product regardless of whether the product has substantial
commercial, industrial or non-consumer uses, unless such uses represent
the only significant mode of use of the product.
"Installation Information" for a User Product means any methods,
procedures, authorization keys, or other information required to install
and execute modified versions of a covered work in that User Product from
a modified version of its Corresponding Source. The information must
suffice to ensure that the continued functioning of the modified object
code is in no case prevented or interfered with solely because
modification has been made.
If you convey an object code work under this section in, or with, or
specifically for use in, a User Product, and the conveying occurs as
part of a transaction in which the right of possession and use of the
User Product is transferred to the recipient in perpetuity or for a
fixed term (regardless of how the transaction is characterized), the
Corresponding Source conveyed under this section must be accompanied
by the Installation Information. But this requirement does not apply
if neither you nor any third party retains the ability to install
modified object code on the User Product (for example, the work has
been installed in ROM).
The requirement to provide Installation Information does not include a
requirement to continue to provide support service, warranty, or updates
for a work that has been modified or installed by the recipient, or for
the User Product in which it has been modified or installed. Access to a
network may be denied when the modification itself materially and
adversely affects the operation of the network or violates the rules and
protocols for communication across the network.
Corresponding Source conveyed, and Installation Information provided,
in accord with this section must be in a format that is publicly
documented (and with an implementation available to the public in
source code form), and must require no special password or key for
unpacking, reading or copying.
7. Additional Terms.
"Additional permissions" are terms that supplement the terms of this
License by making exceptions from one or more of its conditions.
Additional permissions that are applicable to the entire Program shall
be treated as though they were included in this License, to the extent
that they are valid under applicable law. If additional permissions
apply only to part of the Program, that part may be used separately
under those permissions, but the entire Program remains governed by
this License without regard to the additional permissions.
When you convey a copy of a covered work, you may at your option
remove any additional permissions from that copy, or from any part of
it. (Additional permissions may be written to require their own
removal in certain cases when you modify the work.) You may place
additional permissions on material, added by you to a covered work,
for which you have or can give appropriate copyright permission.
Notwithstanding any other provision of this License, for material you
add to a covered work, you may (if authorized by the copyright holders of
that material) supplement the terms of this License with terms:
a) Disclaiming warranty or limiting liability differently from the
terms of sections 15 and 16 of this License; or
b) Requiring preservation of specified reasonable legal notices or
author attributions in that material or in the Appropriate Legal
Notices displayed by works containing it; or
c) Prohibiting misrepresentation of the origin of that material, or
requiring that modified versions of such material be marked in
reasonable ways as different from the original version; or
d) Limiting the use for publicity purposes of names of licensors or
authors of the material; or
e) Declining to grant rights under trademark law for use of some
trade names, trademarks, or service marks; or
f) Requiring indemnification of licensors and authors of that
material by anyone who conveys the material (or modified versions of
it) with contractual assumptions of liability to the recipient, for
any liability that these contractual assumptions directly impose on
those licensors and authors.
All other non-permissive additional terms are considered "further
restrictions" within the meaning of section 10. If the Program as you
received it, or any part of it, contains a notice stating that it is
governed by this License along with a term that is a further
restriction, you may remove that term. If a license document contains
a further restriction but permits relicensing or conveying under this
License, you may add to a covered work material governed by the terms
of that license document, provided that the further restriction does
not survive such relicensing or conveying.
If you add terms to a covered work in accord with this section, you
must place, in the relevant source files, a statement of the
additional terms that apply to those files, or a notice indicating
where to find the applicable terms.
Additional terms, permissive or non-permissive, may be stated in the
form of a separately written license, or stated as exceptions;
the above requirements apply either way.
8. Termination.
You may not propagate or modify a covered work except as expressly
provided under this License. Any attempt otherwise to propagate or
modify it is void, and will automatically terminate your rights under
this License (including any patent licenses granted under the third
paragraph of section 11).
However, if you cease all violation of this License, then your
license from a particular copyright holder is reinstated (a)
provisionally, unless and until the copyright holder explicitly and
finally terminates your license, and (b) permanently, if the copyright
holder fails to notify you of the violation by some reasonable means
prior to 60 days after the cessation.
Moreover, your license from a particular copyright holder is
reinstated permanently if the copyright holder notifies you of the
violation by some reasonable means, this is the first time you have
received notice of violation of this License (for any work) from that
copyright holder, and you cure the violation prior to 30 days after
your receipt of the notice.
Termination of your rights under this section does not terminate the
licenses of parties who have received copies or rights from you under
this License. If your rights have been terminated and not permanently
reinstated, you do not qualify to receive new licenses for the same
material under section 10.
9. Acceptance Not Required for Having Copies.
You are not required to accept this License in order to receive or
run a copy of the Program. Ancillary propagation of a covered work
occurring solely as a consequence of using peer-to-peer transmission
to receive a copy likewise does not require acceptance. However,
nothing other than this License grants you permission to propagate or
modify any covered work. These actions infringe copyright if you do
not accept this License. Therefore, by modifying or propagating a
covered work, you indicate your acceptance of this License to do so.
10. Automatic Licensing of Downstream Recipients.
Each time you convey a covered work, the recipient automatically
receives a license from the original licensors, to run, modify and
propagate that work, subject to this License. You are not responsible
for enforcing compliance by third parties with this License.
An "entity transaction" is a transaction transferring control of an
organization, or substantially all assets of one, or subdividing an
organization, or merging organizations. If propagation of a covered
work results from an entity transaction, each party to that
transaction who receives a copy of the work also receives whatever
licenses to the work the party's predecessor in interest had or could
give under the previous paragraph, plus a right to possession of the
Corresponding Source of the work from the predecessor in interest, if
the predecessor has it or can get it with reasonable efforts.
You may not impose any further restrictions on the exercise of the
rights granted or affirmed under this License. For example, you may
not impose a license fee, royalty, or other charge for exercise of
rights granted under this License, and you may not initiate litigation
(including a cross-claim or counterclaim in a lawsuit) alleging that
any patent claim is infringed by making, using, selling, offering for
sale, or importing the Program or any portion of it.
11. Patents.
A "contributor" is a copyright holder who authorizes use under this
License of the Program or a work on which the Program is based. The
work thus licensed is called the contributor's "contributor version".
A contributor's "essential patent claims" are all patent claims
owned or controlled by the contributor, whether already acquired or
hereafter acquired, that would be infringed by some manner, permitted
by this License, of making, using, or selling its contributor version,
but do not include claims that would be infringed only as a
consequence of further modification of the contributor version. For
purposes of this definition, "control" includes the right to grant
patent sublicenses in a manner consistent with the requirements of
this License.
Each contributor grants you a non-exclusive, worldwide, royalty-free
patent license under the contributor's essential patent claims, to
make, use, sell, offer for sale, import and otherwise run, modify and
propagate the contents of its contributor version.
In the following three paragraphs, a "patent license" is any express
agreement or commitment, however denominated, not to enforce a patent
(such as an express permission to practice a patent or covenant not to
sue for patent infringement). To "grant" such a patent license to a
party means to make such an agreement or commitment not to enforce a
patent against the party.
If you convey a covered work, knowingly relying on a patent license,
and the Corresponding Source of the work is not available for anyone
to copy, free of charge and under the terms of this License, through a
publicly available network server or other readily accessible means,
then you must either (1) cause the Corresponding Source to be so
available, or (2) arrange to deprive yourself of the benefit of the
patent license for this particular work, or (3) arrange, in a manner
consistent with the requirements of this License, to extend the patent
license to downstream recipients. "Knowingly relying" means you have
actual knowledge that, but for the patent license, your conveying the
covered work in a country, or your recipient's use of the covered work
in a country, would infringe one or more identifiable patents in that
country that you have reason to believe are valid.
If, pursuant to or in connection with a single transaction or
arrangement, you convey, or propagate by procuring conveyance of, a
covered work, and grant a patent license to some of the parties
receiving the covered work authorizing them to use, propagate, modify
or convey a specific copy of the covered work, then the patent license
you grant is automatically extended to all recipients of the covered
work and works based on it.
A patent license is "discriminatory" if it does not include within
the scope of its coverage, prohibits the exercise of, or is
conditioned on the non-exercise of one or more of the rights that are
specifically granted under this License. You may not convey a covered
work if you are a party to an arrangement with a third party that is
in the business of distributing software, under which you make payment
to the third party based on the extent of your activity of conveying
the work, and under which the third party grants, to any of the
parties who would receive the covered work from you, a discriminatory
patent license (a) in connection with copies of the covered work
conveyed by you (or copies made from those copies), or (b) primarily
for and in connection with specific products or compilations that
contain the covered work, unless you entered into that arrangement,
or that patent license was granted, prior to 28 March 2007.
Nothing in this License shall be construed as excluding or limiting
any implied license or other defenses to infringement that may
otherwise be available to you under applicable patent law.
12. No Surrender of Others' Freedom.
If conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot convey a
covered work so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you may
not convey it at all. For example, if you agree to terms that obligate you
to collect a royalty for further conveying from those to whom you convey
the Program, the only way you could satisfy both those terms and this
License would be to refrain entirely from conveying the Program.
13. Use with the GNU Affero General Public License.
Notwithstanding any other provision of this License, you have
permission to link or combine any covered work with a work licensed
under version 3 of the GNU Affero General Public License into a single
combined work, and to convey the resulting work. The terms of this
License will continue to apply to the part which is the covered work,
but the special requirements of the GNU Affero General Public License,
section 13, concerning interaction through a network will apply to the
combination as such.
14. Revised Versions of this License.
The Free Software Foundation may publish revised and/or new versions of
the GNU General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the
Program specifies that a certain numbered version of the GNU General
Public License "or any later version" applies to it, you have the
option of following the terms and conditions either of that numbered
version or of any later version published by the Free Software
Foundation. If the Program does not specify a version number of the
GNU General Public License, you may choose any version ever published
by the Free Software Foundation.
If the Program specifies that a proxy can decide which future
versions of the GNU General Public License can be used, that proxy's
public statement of acceptance of a version permanently authorizes you
to choose that version for the Program.
Later license versions may give you additional or different
permissions. However, no additional obligations are imposed on any
author or copyright holder as a result of your choosing to follow a
later version.
15. Disclaimer of Warranty.
THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. Limitation of Liability.
IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
SUCH DAMAGES.
17. Interpretation of Sections 15 and 16.
If the disclaimer of warranty and limitation of liability provided
above cannot be given local legal effect according to their terms,
reviewing courts shall apply local law that most closely approximates
an absolute waiver of all civil liability in connection with the
Program, unless a warranty or assumption of liability accompanies a
copy of the Program in return for a fee.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
state the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
Also add information on how to contact you by electronic and paper mail.
If the program does terminal interaction, make it output a short
notice like this when it starts in an interactive mode:
<program> Copyright (C) <year> <name of author>
This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, your program's commands
might be different; for a GUI interface, you would use an "about box".
You should also get your employer (if you work as a programmer) or school,
if any, to sign a "copyright disclaimer" for the program, if necessary.
For more information on this, and how to apply and follow the GNU GPL, see
<http://www.gnu.org/licenses/>.
The GNU General Public License does not permit incorporating your program
into proprietary programs. If your program is a subroutine library, you
may consider it more useful to permit linking proprietary applications with
the library. If this is what you want to do, use the GNU Lesser General
Public License instead of this License. But first, please read
<http://www.gnu.org/philosophy/why-not-lgpl.html>.

View file

@ -0,0 +1,250 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
* Copyright (C) 2010-2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
/**
* Universal Feed Writer
*
* FeedItem class - Used as feed element in FeedWriter class
*
* @package UniversalFeedWriter
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @link http://www.ajaxray.com/projects/rss
*/
class FeedItem
{
private $elements = array(); //Collection of feed elements
private $version;
/**
* Constructor
*
* @param contant (RSS1/RSS2/ATOM) RSS2 is default.
*/
function __construct($version = RSS2)
{
$this->version = $version;
}
/**
* Add an element to elements array
*
* @access public
* @param string The tag name of an element
* @param string The content of tag
* @param array Attributes(if any) in 'attrName' => 'attrValue' format
* @param boolean Specifies, if an already existing element is overwritten.
* @return void
*/
public function addElement($elementName, $content, $attributes = null, $overwrite = FALSE)
{
// return if element already exists & if overwriting is disabled.
if (isset($this->elements[$elementName]) && !$overwrite)
return;
$this->elements[$elementName]['name'] = $elementName;
$this->elements[$elementName]['content'] = $content;
$this->elements[$elementName]['attributes'] = $attributes;
}
/**
* Set multiple feed elements from an array.
* Elements which have attributes cannot be added by this method
*
* @access public
* @param array array of elements in 'tagName' => 'tagContent' format.
* @return void
*/
public function addElementArray($elementArray)
{
if (!is_array($elementArray))
return;
foreach ($elementArray as $elementName => $content)
{
$this->addElement($elementName, $content);
}
}
/**
* Return the collection of elements in this feed item
*
* @access public
* @return array
*/
public function getElements()
{
return $this->elements;
}
/**
* Return the type of this feed item
*
* @access public
* @return string The feed type, as defined in FeedWriter.php
*/
public function getVersion()
{
return $this->version;
}
// Wrapper functions ------------------------------------------------------
/**
* Set the 'dscription' element of feed item
*
* @access public
* @param string The content of 'description' or 'summary' element
* @return void
*/
public function setDescription($description)
{
$tag = ($this->version == ATOM) ? 'summary' : 'description';
$this->addElement($tag, $description);
}
/**
* @desc Set the 'title' element of feed item
* @access public
* @param string The content of 'title' element
* @return void
*/
public function setTitle($title)
{
$this->addElement('title', $title);
}
/**
* Set the 'date' element of feed item
*
* @access public
* @param string The content of 'date' element
* @return void
*/
public function setDate($date)
{
if(!is_numeric($date))
{
if ($date instanceof DateTime)
{
if (version_compare(PHP_VERSION, '5.3.0', '>='))
$date = $date->getTimestamp();
else
$date = strtotime($date->format('r'));
}
else
$date = strtotime($date);
}
if($this->version == ATOM)
{
$tag = 'updated';
$value = date(DATE_ATOM, $date);
}
elseif($this->version == RSS2)
{
$tag = 'pubDate';
$value = date(DATE_RSS, $date);
}
else
{
$tag = 'dc:date';
$value = date("Y-m-d", $date);
}
$this->addElement($tag, $value);
}
/**
* Set the 'link' element of feed item
*
* @access public
* @param string The content of 'link' element
* @return void
*/
public function setLink($link)
{
if($this->version == RSS2 || $this->version == RSS1)
{
$this->addElement('link', $link);
}
else
{
$this->addElement('link','',array('href'=>$link));
$this->addElement('id', FeedWriter::uuid($link,'urn:uuid:'));
}
}
/**
* Set the 'encloser' element of feed item
* For RSS 2.0 only
*
* @access public
* @param string The url attribute of encloser tag
* @param string The length attribute of encloser tag
* @param string The type attribute of encloser tag
* @return void
*/
public function setEncloser($url, $length, $type)
{
if ($this->version != RSS2)
return;
$attributes = array('url'=>$url, 'length'=>$length, 'type'=>$type);
$this->addElement('enclosure','',$attributes);
}
/**
* Set the 'author' element of feed item
* For ATOM only
*
* @access public
* @param string The author of this item
* @return void
*/
public function setAuthor($author)
{
if ($this->version != ATOM)
return;
$this->addElement('author', array('name' => $author));
}
/**
* Set the unique identifier of the feed item
*
* @access public
* @param string The unique identifier of this item
* @return void
*/
public function setId($id)
{
if ($this->version == RSS2)
{
$this->addElement('guid', $id, array('isPermaLink' => 'false'));
}
else if ($this->version == ATOM)
{
$this->addElement('id', FeedWriter::uuid($id,'urn:uuid:'), NULL, TRUE);
}
}
} // end of class FeedItem

View file

@ -0,0 +1,62 @@
<?php
/*
* Copyright (C) 2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if (!class_exists('FeedWriter'))
require dirname(__FILE__) . '/FeedWriter.php';
/**
* Wrapper for creating RSS1 feeds
*
* @package UniversalFeedWriter
*/
class RSS1FeedWriter extends FeedWriter
{
function __construct()
{
parent::__construct(RSS1);
}
}
/**
* Wrapper for creating RSS2 feeds
*
* @package UniversalFeedWriter
*/
class RSS2FeedWriter extends FeedWriter
{
function __construct()
{
parent::__construct(RSS2);
}
}
/**
* Wrapper for creating ATOM feeds
*
* @package UniversalFeedWriter
*/
class ATOMFeedWriter extends FeedWriter
{
function __construct()
{
parent::__construct(ATOM);
}
}

View file

@ -0,0 +1,513 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
* Copyright (C) 2010-2012 Michael Bemmerl <mail@mx-server.de>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// RSS 0.90 Officially obsoleted by 1.0
// RSS 0.91, 0.92, 0.93 and 0.94 Officially obsoleted by 2.0
// So, define constants for RSS 1.0, RSS 2.0 and ATOM
define('RSS1', 'RSS 1.0', true);
define('RSS2', 'RSS 2.0', true);
define('ATOM', 'ATOM', true);
if (!class_exists('FeedItem'))
require dirname(__FILE__) . '/FeedItem.php';
/**
* Universal Feed Writer class
*
* Generate RSS 1.0, RSS2.0 and ATOM Feeds
*
* @package UniversalFeedWriter
* @author Anis uddin Ahmad <anisniit@gmail.com>
* @link http://www.ajaxray.com/projects/rss
*/
abstract class FeedWriter
{
private $channels = array(); // Collection of channel elements
private $items = array(); // Collection of items as object of FeedItem class.
private $data = array(); // Store some other version wise data
private $CDATAEncoding = array(); // The tag names which have to encoded as CDATA
private $version = null;
/**
* Constructor
*
* @param constant the version constant (RSS1/RSS2/ATOM).
*/
protected function __construct($version = RSS2)
{
$this->version = $version;
// Setting default value for essential channel elements
$this->channels['title'] = $version . ' Feed';
$this->channels['link'] = 'http://www.ajaxray.com/blog';
//Tag names to encode in CDATA
$this->CDATAEncoding = array('description', 'content:encoded', 'summary');
}
// Start # public functions ---------------------------------------------
/**
* Set a channel element
* @access public
* @param string name of the channel tag
* @param string content of the channel tag
* @return void
*/
public function setChannelElement($elementName, $content)
{
$this->channels[$elementName] = $content;
}
/**
* Set multiple channel elements from an array. Array elements
* should be 'channelName' => 'channelContent' format.
*
* @access public
* @param array array of channels
* @return void
*/
public function setChannelElementsFromArray($elementArray)
{
if (!is_array($elementArray))
return;
foreach ($elementArray as $elementName => $content)
{
$this->setChannelElement($elementName, $content);
}
}
/**
* Genarate the actual RSS/ATOM file
*
* @access public
* @param bool FALSE if the specific feed media type should be send.
* @return void
*/
public function generateFeed($useGenericContentType = FALSE)
{
$contentType = "text/xml";
if (!$useGenericContentType)
{
switch($this->version)
{
case RSS2 : $contentType = "application/rss+xml";
break;
case RSS1 : $contentType = "application/rdf+xml";
break;
case ATOM : $contentType = "application/atom+xml";
break;
}
}
header("Content-Type: " . $contentType . "; charset=UTF-8");
$this->printHeader();
$this->printChannels();
$this->printItems();
$this->printFooter();
}
/**
* Create a new FeedItem.
*
* @access public
* @return object instance of FeedItem class
*/
public function createNewItem()
{
$Item = new FeedItem($this->version);
return $Item;
}
/**
* Add a FeedItem to the main class
*
* @access public
* @param object instance of FeedItem class
* @return void
*/
public function addItem(FeedItem $feedItem)
{
if ($feedItem->getVersion() != $this->version)
die('Feed type mismatch: This instance can handle ' . $this->version . ' feeds only, but item with type ' . $feedItem->getVersion() . ' given.');
$this->items[] = $feedItem;
}
// Wrapper functions -------------------------------------------------------------------
/**
* Set the 'title' channel element
*
* @access public
* @param string value of 'title' channel tag
* @return void
*/
public function setTitle($title)
{
$this->setChannelElement('title', $title);
}
/**
* Set the 'updated' channel element of an ATOM feed
*
* @access public
* @param string value of 'updated' channel tag
* @return void
*/
public function setDate($date)
{
if ($this->version != ATOM)
return;
if ($date instanceof DateTime)
$date = $date->format(DateTime::ATOM);
else if(is_numeric($date))
$date = date(DATE_ATOM, $date);
else
$date = date(DATE_ATOM, strtotime($date));
$this->setChannelElement('updated', $date);
}
/**
* Set the 'description' channel element
*
* @access public
* @param string value of 'description' channel tag
* @return void
*/
public function setDescription($desciption)
{
if ($this->version != ATOM)
$this->setChannelElement('description', $desciption);
}
/**
* Set the 'link' channel element
*
* @access public
* @param string value of 'link' channel tag
* @return void
*/
public function setLink($link)
{
$this->setChannelElement('link', $link);
}
/**
* Set the 'image' channel element
*
* @access public
* @param string title of image
* @param string link url of the image
* @param string path url of the image
* @return void
*/
public function setImage($title, $link, $url)
{
$this->setChannelElement('image', array('title'=>$title, 'link'=>$link, 'url'=>$url));
}
/**
* Set the 'about' channel element. Only for RSS 1.0
*
* @access public
* @param string value of 'about' channel tag
* @return void
*/
public function setChannelAbout($url)
{
$this->data['ChannelAbout'] = $url;
}
/**
* Generates an UUID
* @author Anis uddin Ahmad <admin@ajaxray.com>
* @param string an optional prefix
* @return string the formated uuid
*/
public static function uuid($key = null, $prefix = '')
{
$key = ($key == null)? uniqid(rand()) : $key;
$chars = md5($key);
$uuid = substr($chars,0,8) . '-';
$uuid .= substr($chars,8,4) . '-';
$uuid .= substr($chars,12,4) . '-';
$uuid .= substr($chars,16,4) . '-';
$uuid .= substr($chars,20,12);
return $prefix . $uuid;
}
// End # public functions ----------------------------------------------
// Start # private functions ----------------------------------------------
/**
* Prints the xml and rss namespace
*
* @access private
* @return void
*/
private function printHeader()
{
$out = '<?xml version="1.0" encoding="utf-8"?>' . PHP_EOL;
if($this->version == RSS2)
{
$out .= '<rss version="2.0" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:wfw="http://wellformedweb.org/CommentAPI/">';
}
elseif($this->version == RSS1)
{
$out .= '<rdf:RDF xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns="http://purl.org/rss/1.0/" xmlns:dc="http://purl.org/dc/elements/1.1/">';
}
else if($this->version == ATOM)
{
$out .= '<feed xmlns="http://www.w3.org/2005/Atom">';
}
$out .= PHP_EOL;
echo $out;
}
/**
* Closes the open tags at the end of file
*
* @access private
* @return void
*/
private function printFooter()
{
if($this->version == RSS2)
{
echo '</channel>' . PHP_EOL . '</rss>';
}
elseif($this->version == RSS1)
{
echo '</rdf:RDF>';
}
else if($this->version == ATOM)
{
echo '</feed>';
}
}
/**
* Creates a single node as xml format
*
* @access private
* @param string name of the tag
* @param mixed tag value as string or array of nested tags in 'tagName' => 'tagValue' format
* @param array Attributes(if any) in 'attrName' => 'attrValue' format
* @return string formatted xml tag
*/
private function makeNode($tagName, $tagContent, $attributes = null)
{
$nodeText = '';
$attrText = '';
if(is_array($attributes) && count($attributes) > 0)
{
foreach ($attributes as $key => $value)
{
$value = htmlspecialchars($value);
$attrText .= " $key=\"$value\" ";
}
// Get rid of the last whitespace
$attrText = substr($attrText, 0, strlen($attrText) - 1);
}
if(is_array($tagContent) && $this->version == RSS1)
{
$attrText = ' rdf:parseType="Resource"';
}
$attrText .= (in_array($tagName, $this->CDATAEncoding) && $this->version == ATOM) ? ' type="html"' : '';
$nodeText .= "<{$tagName}{$attrText}>";
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? '<![CDATA[' : '';
if(is_array($tagContent))
{
foreach ($tagContent as $key => $value)
{
$nodeText .= $this->makeNode($key, $value);
}
}
else
{
$nodeText .= (in_array($tagName, $this->CDATAEncoding))? $this->sanitizeCDATA($tagContent) : htmlspecialchars($tagContent);
}
$nodeText .= (in_array($tagName, $this->CDATAEncoding)) ? ']]>' : '';
$nodeText .= "</$tagName>" . PHP_EOL;
return $nodeText;
}
/**
* @desc Print channels
* @access private
* @return void
*/
private function printChannels()
{
//Start channel tag
switch ($this->version)
{
case RSS2:
echo '<channel>' . PHP_EOL;
break;
case RSS1:
echo (isset($this->data['ChannelAbout']))? "<channel rdf:about=\"{$this->data['ChannelAbout']}\">" : "<channel rdf:about=\"{$this->channels['link']}\">";
break;
}
//Print Items of channel
foreach ($this->channels as $key => $value)
{
if($this->version == ATOM && $key == 'link')
{
// ATOM prints link element as href attribute
echo $this->makeNode($key,'', array('href' => $value));
//Add the id for ATOM
echo $this->makeNode('id', FeedWriter::uuid($value, 'urn:uuid:'));
}
else
{
echo $this->makeNode($key, $value);
}
}
//RSS 1.0 have special tag <rdf:Seq> with channel
if($this->version == RSS1)
{
echo "<items>" . PHP_EOL . "<rdf:Seq>" . PHP_EOL;
foreach ($this->items as $item)
{
$thisItems = $item->getElements();
echo "<rdf:li resource=\"{$thisItems['link']['content']}\"/>" . PHP_EOL;
}
echo "</rdf:Seq>" . PHP_EOL . "</items>" . PHP_EOL . "</channel>" . PHP_EOL;
}
}
/**
* Prints formatted feed items
*
* @access private
* @return void
*/
private function printItems()
{
foreach ($this->items as $item)
{
$thisItems = $item->getElements();
//the argument is printed as rdf:about attribute of item in rss 1.0
echo $this->startItem($thisItems['link']['content']);
foreach ($thisItems as $feedItem)
{
echo $this->makeNode($feedItem['name'], $feedItem['content'], $feedItem['attributes']);
}
echo $this->endItem();
}
}
/**
* Make the starting tag of channels
*
* @access private
* @param string The vale of about tag which is used for RSS 1.0 only.
* @return void
*/
private function startItem($about = false)
{
if($this->version == RSS2)
{
echo '<item>' . PHP_EOL;
}
else if($this->version == RSS1)
{
if($about)
{
echo "<item rdf:about=\"$about\">" . PHP_EOL;
}
else
{
die("link element is not set." . PHP_EOL . "It's required for RSS 1.0 to be used as the about attribute of the item tag.");
}
}
else if($this->version == ATOM)
{
echo "<entry>" . PHP_EOL;
}
}
/**
* Closes feed item tag
*
* @access private
* @return void
*/
private function endItem()
{
if($this->version == RSS2 || $this->version == RSS1)
{
echo '</item>' . PHP_EOL;
}
else if($this->version == ATOM)
{
echo "</entry>" . PHP_EOL;
}
}
/**
* Sanitizes data which will be later on returned as CDATA in the feed.
*
* A "]]>" respectively "<![CDATA" in the data would break the CDATA in the
* XML, so the brackets are converted to a HTML entity.
*
* @access private
* @param string Data to be sanitized
* @return string Sanitized data
*/
private function sanitizeCDATA($text)
{
$text = str_replace("]]>", "]]&gt;", $text);
$text = str_replace("<![CDATA[", "&lt;![CDATA[", $text);
return $text;
}
// End # private functions ----------------------------------------------
} // end of class FeedWriter

View file

@ -0,0 +1,23 @@
This package can be used to generate feeds in either RSS 1.0, RSS 2.0 or ATOM
formats.
There are three main classes that abstracts the feed information and another to
encapsulate the feed items information.
Applications can create feed writer object, several feed item objects, set
several types of properties of either feeds and feed items, and add items to
the feed.
Once a feed is fully composed with its items, the feed writer class can generate
the necessary XML structure to describe the feed in the RSS or ATOM formats.
The feed is generated as part of the current feed output.
Origin
============
Written by: Anis uddin Ahmad <anisniit@gmail.com>
Posted on: http://ajaxray.com/blog/php-universal-feed-generator-supports-rss-10-rss-20-and-atom
Requirements
============
PHP >= 5.0

View file

@ -0,0 +1,59 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
include("../FeedTypes.php");
// IMPORTANT : No need to add id for feed or channel. It will be automatically created from link.
//Creating an instance of ATOMFeedWriter class.
//The constant ATOM is passed to mention the version
$TestFeed = new ATOMFeedWriter();
//Setting the channel elements
//Use wrapper functions for common elements
$TestFeed->setTitle('Testing the RSS writer class');
$TestFeed->setLink('http://www.ajaxray.com/rss2/channel/about');
//For other channel elements, use setChannelElement() function
$TestFeed->setChannelElement('updated', date(DATE_ATOM , time()));
$TestFeed->setChannelElement('author', array('name'=>'Anis uddin Ahmad'));
//Adding a feed. Genarally this protion will be in a loop and add all feeds.
//Create an empty FeedItem
$newItem = $TestFeed->createNewItem();
//Add elements to the feed item
//Use wrapper functions to add common feed elements
$newItem->setTitle('The first feed');
$newItem->setLink('http://www.yahoo.com');
$newItem->setDate(time());
//Internally changed to "summary" tag for ATOM feed
$newItem->setDescription('This is a test of adding CDATA encoded description by the php <b>Universal Feed Writer</b> class');
//Now add the feed item
$TestFeed->addItem($newItem);
//OK. Everything is done. Now genarate the feed.
$TestFeed->generateFeed();
?>

View file

@ -0,0 +1,58 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
// This is a minimum example of using the class
include("../FeedTypes.php");
//Creating an instance of RSS2FeedWriter class.
$TestFeed = new RSS2FeedWriter();
//Setting the channel elements
//Use wrapper functions for common channel elements
$TestFeed->setTitle('Testing & Checking the RSS writer class');
$TestFeed->setLink('http://www.ajaxray.com/projects/rss');
$TestFeed->setDescription('This is a test of creating a RSS 2.0 feed Universal Feed Writer');
//Image title and link must match with the 'title' and 'link' channel elements for valid RSS 2.0
$TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/_resources/img/logo.png');
//Let's add some feed items: Create two empty FeedItem instances
$itemOne = $TestFeed->createNewItem();
$itemTwo = $TestFeed->createNewItem();
//Add item details
$itemOne->setTitle('The title of the first entry.');
$itemOne->setLink('http://www.google.de');
$itemOne->setDate(time());
$itemOne->setDescription('And here\'s the description of the entry.');
$itemTwo->setTitle('Lorem ipsum');
$itemTwo->setLink('http://www.example.com');
$itemTwo->setDate(1234567890);
$itemTwo->setDescription('Lorem ipsum dolor sit amet, consectetur, adipisci velit');
//Now add the feed item
$TestFeed->addItem($itemOne);
$TestFeed->addItem($itemTwo);
//OK. Everything is done. Now genarate the feed.
$TestFeed->generateFeed();
?>

View file

@ -0,0 +1,66 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
include("../FeedTypes.php");
//Creating an instance of RSS1FeedWriter class.
//The constant RSS1 is passed to mention the version
$TestFeed = new RSS1FeedWriter();
//Setting the channel elements
//Use wrapper functions for common elements
//For other optional channel elements, use setChannelElement() function
$TestFeed->setTitle('Testing the RSS writer class');
$TestFeed->setLink('http://www.ajaxray.com/rss2/channel/about');
$TestFeed->setDescription('This is test of creating a RSS 1.0 feed by Universal Feed Writer');
//It's important for RSS 1.0
$TestFeed->setChannelAbout('http://www.ajaxray.com/rss2/channel/about');
//Adding a feed. Genarally this protion will be in a loop and add all feeds.
//Create an empty FeedItem
$newItem = $TestFeed->createNewItem();
//Add elements to the feed item
//Use wrapper functions to add common feed elements
$newItem->setTitle('The first feed');
$newItem->setLink('http://www.yahoo.com');
//The parameter is a timestamp for setDate() function
$newItem->setDate(time());
$newItem->setDescription('This is test of adding CDATA encoded description by the php <b>Universal Feed Writer</b> class');
//Use core addElement() function for other supported optional elements
$newItem->addElement('dc:subject', 'Nothing but test');
//Now add the feed item
$TestFeed->addItem($newItem);
//Adding multiple elements from array
//Elements which have an attribute cannot be added by this way
$newItem = $TestFeed->createNewItem();
$newItem->addElementArray(array('title'=>'The 2nd feed', 'link'=>'http://www.google.com', 'description'=>'This is a test of the FeedWriter class'));
$TestFeed->addItem($newItem);
//OK. Everything is done. Now genarate the feed.
$TestFeed->generateFeed();
?>

View file

@ -0,0 +1,72 @@
<?php
/*
* Copyright (C) 2008 Anis uddin Ahmad <anisniit@gmail.com>
*
* This file is part of the "Universal Feed Writer" project.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
include("../FeedTypes.php");
//Creating an instance of RSS2FeedWriter class.
//The constant RSS2 is passed to mention the version
$TestFeed = new RSS2FeedWriter();
//Setting the channel elements
//Use wrapper functions for common channel elements
$TestFeed->setTitle('Testing & Checking the RSS writer class');
$TestFeed->setLink('http://www.ajaxray.com/projects/rss');
$TestFeed->setDescription('This is a test of creating a RSS 2.0 feed with Universal Feed Writer');
//Image title and link must match with the 'title' and 'link' channel elements for RSS 2.0
$TestFeed->setImage('Testing the RSS writer class','http://www.ajaxray.com/projects/rss','http://www.rightbrainsolution.com/_resources/img/logo.png');
//Use core setChannelElement() function for other optional channels
$TestFeed->setChannelElement('language', 'en-us');
$TestFeed->setChannelElement('pubDate', date(DATE_RSS, time()));
//Adding a feed. Genarally this portion will be in a loop and add all feeds.
//Create an empty FeedItem
$newItem = $TestFeed->createNewItem();
//Add elements to the feed item
//Use wrapper functions to add common feed elements
$newItem->setTitle('The first feed');
$newItem->setLink('http://www.yahoo.com');
//The parameter is a timestamp for setDate() function
$newItem->setDate(time());
$newItem->setDescription('This is a test of adding CDATA encoded description by the php <b>Universal Feed Writer</b> class');
$newItem->setEncloser('http://www.attrtest.com', '1283629', 'audio/mpeg');
//Use core addElement() function for other supported optional elements
$newItem->addElement('author', 'admin@ajaxray.com (Anis uddin Ahmad)');
//Attributes have to passed as array in 3rd parameter
$newItem->addElement('guid', 'http://www.ajaxray.com',array('isPermaLink'=>'true'));
//Now add the feed item
$TestFeed->addItem($newItem);
//Another method to add feeds from array()
//Elements which have attribute cannot be added by this way
$newItem = $TestFeed->createNewItem();
$newItem->addElementArray(array('title'=>'The 2nd feed', 'link'=>'http://www.google.com', 'description'=>'This is a test of the FeedWriter class'));
$TestFeed->addItem($newItem);
//OK. Everything is done. Now genarate the feed.
$TestFeed->generateFeed();
?>

View file

@ -0,0 +1,10 @@
<?php
# Use this file if you cannot use class autoloading. It will include all the
# files needed for the Markdown parser.
#
# Take a look at the PSR-0-compatible class autoloading implementation
# in the Readme.php file if you want a simple autoloader setup.
require_once dirname(__FILE__) . '/MarkdownInterface.php';
require_once dirname(__FILE__) . '/Markdown.php';

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,11 @@
<?php
# Use this file if you cannot use class autoloading. It will include all the
# files needed for the MarkdownExtra parser.
#
# Take a look at the PSR-0-compatible class autoloading implementation
# in the Readme.php file if you want a simple autoloader setup.
require_once dirname(__FILE__) . '/MarkdownInterface.php';
require_once dirname(__FILE__) . '/Markdown.php';
require_once dirname(__FILE__) . '/MarkdownExtra.php';

View file

@ -0,0 +1,38 @@
<?php
#
# Markdown Extra - A text-to-HTML conversion tool for web writers
#
# PHP Markdown Extra
# Copyright (c) 2004-2014 Michel Fortin
# <http://michelf.com/projects/php-markdown/>
#
# Original Markdown
# Copyright (c) 2004-2006 John Gruber
# <http://daringfireball.net/projects/markdown/>
#
namespace Michelf;
# Just force Michelf/Markdown.php to load. This is needed to load
# the temporary implementation class. See below for details.
\Michelf\Markdown::MARKDOWNLIB_VERSION;
#
# Markdown Extra Parser Class
#
# Note: Currently the implementation resides in the temporary class
# \Michelf\MarkdownExtra_TmpImpl (in the same file as \Michelf\Markdown).
# This makes it easier to propagate the changes between the three different
# packaging styles of PHP Markdown. Once this issue is resolved, the
# _MarkdownExtra_TmpImpl will disappear and this one will contain the code.
#
class MarkdownExtra extends \Michelf\_MarkdownExtra_TmpImpl {
### Parser Implementation ###
# Temporarily, the implemenation is in the _MarkdownExtra_TmpImpl class.
# See note above.
}

View file

@ -0,0 +1,9 @@
<?php
# Use this file if you cannot use class autoloading. It will include all the
# files needed for the MarkdownInterface interface.
#
# Take a look at the PSR-0-compatible class autoloading implementation
# in the Readme.php file if you want a simple autoloader setup.
require_once dirname(__FILE__) . '/MarkdownInterface.php';

View file

@ -0,0 +1,37 @@
<?php
#
# Markdown - A text-to-HTML conversion tool for web writers
#
# PHP Markdown
# Copyright (c) 2004-2014 Michel Fortin
# <http://michelf.com/projects/php-markdown/>
#
# Original Markdown
# Copyright (c) 2004-2006 John Gruber
# <http://daringfireball.net/projects/markdown/>
#
namespace Michelf;
#
# Markdown Parser Interface
#
interface MarkdownInterface {
#
# Initialize the parser and return the result of its transform method.
# This will work fine for derived classes too.
#
public static function defaultTransform($text);
#
# Main function. Performs some preprocessing on the input text
# and pass it through the document gamut.
#
public function transform($text);
}
?>

View file

@ -0,0 +1,21 @@
## Nibble Forms 2 library
Copyright (c) 2013 Luke Rotherfield, Nibble Development
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.
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.

View file

@ -0,0 +1,39 @@
<?php
namespace Nibble\NibbleForms;
abstract class Field
{
public $custom_error = array();
protected $form;
public $html = array(
'open_field' => false,
'close_field' => false,
'open_html' => false,
'close_html' => false
);
public function setForm($form)
{
$this->form = $form;
}
/**
* Return the current field, i.e label and input
*/
abstract public function returnField($form_name, $name, $value = '');
/**
* Validate the current field
*/
abstract public function validate($val);
/**
* Apply custom error message from user to field
*/
public function errorMessage($message)
{
$this->custom_error[] = $message;
}
}

View file

@ -0,0 +1,43 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Field;
abstract class BaseOptions extends Field
{
protected $label, $options = array();
protected $required = true;
protected $false_values = array();
public $error = array();
public function __construct($label, $attributes = array())
{
$this->label = $label;
if (isset($attributes["choices"])) {
$this->options = $attributes["choices"];
}
if (isset($attributes['required'])) {
$this->required = $attributes['required'];
}
if (isset($attributes['false_values'])) {
$this->false_values = $attributes['false_values'];
}
}
public function getAttributeString($val)
{
$attribute_string = '';
if (is_array($val)) {
$attributes = $val;
$val = $val[0];
unset($attributes[0]);
foreach ($attributes as $attribute => $arg) {
$attribute_string .= $arg ? ' ' . ($arg === true ? $attribute : "$attribute=\"$arg\"") : '';
}
}
return array('val' => $val, 'string' => $attribute_string);
}
}

View file

@ -0,0 +1,88 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Field;
class Captcha extends Field
{
public $error = array();
protected $label;
public function __construct($label = 'Humanity Check')
{
$this->label = $label;
}
public function returnField($form_name, $name, $value = '')
{
$field = <<<FIELD
<script type="text/javascript"
src="http://www.google.com/recaptcha/api/challenge?k=%1\$s">
</script>
<noscript>
<iframe src="http://www.google.com/recaptcha/api/noscript?k=%1\$s"
height="300" width="500" frameborder="0"></iframe><br>
<textarea name="recaptcha_challenge_field" rows="3" cols="40">
</textarea>
<input type="hidden" name="{$form_name}[recaptcha_response_field]"
value="manual_challenge">
</noscript>
FIELD;
$class = !empty($this->error) ? ' class="error"' : '';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label for="%s"%s>%s</label>', $name, $class, $this->label),
'field' => sprintf($field, 'YOUR_PUBLIC_KEY'),
'html' => $this->html
);
}
public function validate($val)
{
$url = 'http://www.google.com/recaptcha/api/verify';
$data = array(
'privatekey' => urlencode('YOUR_PRIVATE_KEY'),
'remoteip' => urlencode($_SERVER['REMOTE_ADDR']),
'challenge' => urlencode($_REQUEST['recaptcha_challenge_field']),
'response' => urlencode($_REQUEST['recaptcha_response_field']),
);
$data_string = '';
foreach ($data as $key => $val) {
$data_string .= $key . '=' . $val . '&';
}
$data_string = rtrim($data_string, '&');
$host = 'www.google.com';
$http_request = "POST /recaptcha/api/verify HTTP/1.0\r\n";
$http_request .= "Host: $host\r\n";
$http_request .= "Content-Type: application/x-www-form-urlencoded;\r\n";
$http_request .= "Content-Length: " . strlen($data_string) . "\r\n";
$http_request .= "User-Agent: reCAPTCHA/PHP\r\n";
$http_request .= "\r\n";
$http_request .= $data_string;
$response = '';
if (false == ( $fs = @fsockopen($host, 80, $errno, $errstr, 10) )) {
die('Could not open socket');
}
fwrite($fs, $http_request);
while (!feof($fs)) {
$response .= fgets($fs, 1160); // One TCP-IP packet
}
fclose($fs);
$response = explode("\r\n\r\n", $response);
$response = explode("\n", $response[1]);
if (!isset($response[0]) || $response[0] != 'true') {
$this->error[] = 'You failed to prove you humanity';
}
//curl_close($ch);
return empty($this->error) ? true : false;
}
}

View file

@ -0,0 +1,28 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Checkbox extends MultipleOptions
{
public function returnField($form_name, $name, $value = '')
{
$field = '';
foreach ($this->options as $key => $val) {
$attributes = $this->getAttributeString($val);
$field .= sprintf('<input type="checkbox" name="%6$s[%1$s][]" id="%6$s_%3$s" value="%2$s" %4$s/>' .
'<label for="%6$s_%3$s">%5$s</label>'
, $name, $key, Useful::slugify($name) . '_' . Useful::slugify($key), (is_array($value) && in_array((string) $key, $value) ? 'checked="checked"' : '') . $attributes['string'], $attributes['val'], $form_name);
}
$class = !empty($this->error) ? 'error choice_label' : 'choice_label';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label class="%s">%s</label>', $class, $this->label),
'field' => $field,
'html' => $this->html
);
}
}

View file

@ -0,0 +1,47 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Email extends Text
{
private $confirm = false;
public function validate($val)
{
if (!empty($this->error)) {
return false;
}
if (parent::validate($val)) {
if (Useful::stripper($val) !== false) {
if (!filter_var($val, FILTER_VALIDATE_EMAIL)) {
$this->error[] = 'must be a valid email address';
}
}
}
if ($this->confirm) {
$request = strtoupper($this->form->getMethod()) == 'POST' ? $_POST : $_GET;
if ($val != $request[$this->form->getName()][$this->confirm]) {
$this->error[] = 'The email addresses provided do not match';
}
}
return !empty($this->error) ? false : true;
}
public function addConfirmation($field_name, array $attributes = array())
{
$this->form->addField($field_name, 'email', $attributes + $this->attributes);
$this->confirm = Useful::slugify($field_name, '_');;
}
public function returnField($form_name, $name, $value = '')
{
$this->field_type = 'email';
return parent::returnField($form_name, $name, $value);
}
}

View file

@ -0,0 +1,120 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Field;
class File extends Field
{
private $label;
private $type;
private $required;
private $max_size;
public $error = array();
private $height;
private $width;
private $min_height;
private $min_width;
private $mime_types = array(
'image' => array(
'image/gif', 'image/gi_', 'image/png', 'application/png', 'application/x-png',
'image/jp_', 'application/jpg', 'application/x-jpg', 'image/pjpeg', 'image/jpeg'
),
'document' => array(
'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',
'application/vnd.openxmlformats-officedocument.presentationml.presentation',
'application/vnd.openxmlformats-officedocument.wordprocessingml.document',
'application/mspowerpoint', 'application/powerpoint', 'application/vnd.ms-powerpoint',
'application/x-mspowerpoint', 'application/plain', 'text/plain', 'application/pdf',
'application/x-pdf', 'application/acrobat', 'text/pdf', 'text/x-pdf', 'application/msword',
'pplication/vnd.ms-excel', 'application/msexcel', 'application/doc',
'application/vnd.oasis.opendocument.text', 'application/x-vnd.oasis.opendocument.text',
'application/vnd.oasis.opendocument.spreadsheet', 'application/x-vnd.oasis.opendocument.spreadsheet',
'application/vnd.oasis.opendocument.presentation', 'application/x-vnd.oasis.opendocument.presentation'
),
'archive' => array(
'application/x-compressed', 'application/gzip-compressed', 'gzip/document',
'application/x-zip-compressed', 'application/zip', 'multipart/x-zip',
'application/tar', 'application/x-tar', 'applicaton/x-gtar', 'multipart/x-tar',
'application/gzip', 'application/x-gzip', 'application/x-gunzip', 'application/gzipped'
)
);
private $error_types = array(
'image' => 'must be an image, e.g example.jpg or example.gif',
'archive' => 'must be and archive, e.g example.zip or example.tar',
'document' => 'must be a document, e.g example.doc or example.pdf',
'all' => 'must be a document, archive or image',
'custom' => 'is invalid'
);
public function __construct($label, $type = 'all', $required = true, $max_size = 2097152, $width = 1600, $height = 1600, $min_width = 0, $min_height = 0)
{
$this->label = $label;
$this->required = $required;
$this->max_size = $max_size;
$this->width = $width;
$this->height = $height;
$this->min_width = $min_width;
$this->min_height = $min_height;
if (is_array($type)) {
$this->mime_types = $type;
$this->type = 'custom';
} else {
$this->type = $type;
if (isset($this->mime_types[$type])) {
$this->mime_types = $this->mime_types[$type];
} else {
$temp = array();
foreach ($this->mime_types as $mime_array)
foreach ($mime_array as $mime_type)
$temp[] = $mime_type;
$this->mime_types = $temp;
$this->type = 'all';
unset($temp);
}
}
}
public function returnField($form_name, $name, $value = '')
{
$class = !empty($this->error) ? ' class="error"' : '';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label for="%s_%s"%s>%s</label>', $form_name, $name, $class, $this->label),
'field' => sprintf('<input type="file" name="%2$s[%1$s]" id="%2$s_%1$s"/>', $name, $form_name),
'html' => $this->html
);
}
public function validate($val)
{
if ($this->required) {
if ($val['error'] != 0 || $val['size'] == 0) {
$this->error[] = 'is required';
}
}
if ($val['error'] == 0) {
if ($val['size'] > $this->max_size) {
$this->error[] = sprintf('must be less than %sMb', $this->max_size / 1024 / 1024);
}
if ($this->type == 'image') {
$image = getimagesize($val['tmp_name']);
if ($image[0] > $this->width || $image[1] > $this->height) {
$this->error[] = sprintf('must contain an image no more than %s pixels wide and %s pixels high', $this->width, $this->height);
}
if ($image[0] < $this->min_width || $image[1] < $this->min_height) {
$this->error[] = sprintf('must contain an image at least %s pixels wide and %s pixels high', $this->min_width, $this->min_height);
}
if (!in_array($image['mime'], $this->mime_types)) {
$this->error[] = $this->error_types[$this->type];
}
} elseif (!in_array($val['type'], $this->mime_types)) {
$this->error[] = $this->error_types[$this->type];
}
}
return !empty($this->error) ? false : true;
}
}

View file

@ -0,0 +1,20 @@
<?php
namespace Nibble\NibbleForms\Field;
class Hidden extends Text
{
public function __construct($label = false, $attributes = array())
{
parent::__construct($label, $attributes);
}
public function returnField($form_name, $name, $value = '')
{
$this->field_type = 'hidden';
$this->label = false;
return parent::returnField($form_name, $name, $value);
}
}

View file

@ -0,0 +1,36 @@
<?php
namespace Nibble\NibbleForms\Field;
abstract class MultipleOptions extends BaseOptions
{
protected $minimum_selected = false;
public function __construct($label, $attributes = array())
{
parent::__construct($label, $attributes);
if (isset($attributes['minimum_selected'])) {
$this->minimum_selected = $attributes['minimum_selected'];
}
}
public function validate($val)
{
if (is_array($val)) {
if ($this->minimum_selected && count($val) < $this->minimum_selected) {
$this->error[] = sprintf('at least %s options must be selected', $this->minimum_selected);
}
foreach ($val as $answer) {
if (in_array($answer, $this->false_values)) {
$this->error[] = "$answer is not a valid choice";
}
}
} elseif ($this->required) {
$this->error[] = 'is required';
}
return !empty($this->error) ? false : true;
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Nibble\NibbleForms\Field;
class MultipleSelect extends MultipleOptions
{
public function __construct($label, $attributes = array())
{
parent::__construct($label, $attributes);
}
public function returnField($form_name, $name, $value = '')
{
$field = sprintf('<select name="%2$s[%1$s][]" id="%2$s_%1$s" multiple="multiple">', $name, $form_name);
foreach ($this->options as $key => $val) {
$attributes = $this->getAttributeString($val);
$field .= sprintf('<option value="%s" %s>%s</option>', $key, (is_array($value) && in_array((string) $key, $value) ? 'selected="selected"' : '') . $attributes['string'], $attributes['val']);
}
$field .= '</select>';
$class = !empty($this->error) ? 'error choice_label' : 'choice_label';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label for="%s_%s" class="%s">%s</label>', $form_name, $name, $class, $this->label),
'field' => $field,
'html' => $this->html
);
}
}

View file

@ -0,0 +1,32 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Number extends Text
{
public function validate($val)
{
if (!empty($this->error)) {
return false;
}
if (parent::validate($val))
if (Useful::stripper($val) !== false) {
if (!filter_var($val, FILTER_VALIDATE_FLOAT)) {
$this->error[] = 'must be numeric';
}
}
return !empty($this->error) ? false : true;
}
public function returnField($form_name, $name, $value = '')
{
$this->field_type = 'number';
return parent::returnField($form_name, $name, $value);
}
}

View file

@ -0,0 +1,24 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
abstract class Options extends BaseOptions
{
public function validate($val)
{
if ($this->required) {
if (Useful::stripper($val) === false) {
$this->error[] = 'is required';
}
}
if (in_array($val, $this->false_values)) {
$this->error[] = "$val is not a valid choice";
}
return !empty($this->error) ? false : true;
}
}

View file

@ -0,0 +1,63 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Password extends Text
{
private $confirm = false;
private $min_length = false;
private $alphanumeric = false;
public function __construct($label, $attributes = array())
{
parent::__construct($label, $attributes);
if (isset($attributes['alphanumeric'])) {
$this->alphanumeric = $attributes['alphanumeric'];
}
if (isset($attributes['min_length'])) {
$this->min_length = $attributes['min_length'];
}
}
public function validate($val)
{
if (!empty($this->error)) {
return false;
}
if (parent::validate($val)) {
if (Useful::stripper($val) !== false) {
if ($this->min_length && strlen($val) < $this->min_length) {
$this->error[] = sprintf('must be more than %s characters', $this->min_length);
}
if ($this->alphanumeric && (!preg_match("/[A-Za-z]+/", $val) || !preg_match("/[0-9]+/", $val))) {
$this->error[] = 'must have at least one alphabetic character and one numeric character';
}
}
}
if ($this->confirm) {
$request = strtoupper($this->form->getMethod()) == 'POST' ? $_POST : $_GET;
if ($val != $request[$this->form->getName()][$this->confirm]) {
$this->error[] = 'The passwords provided do not match password';
}
}
return !empty($this->error) ? false : true;
}
public function returnField($form_name, $name, $value = '')
{
$this->field_type = 'password';
return parent::returnField($form_name, $name, $value);
}
public function addConfirmation($field_name, $attributes = array())
{
$this->form->addField($field_name, 'password', $attributes + $this->attributes);
$this->confirm = $field_name;
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Radio extends Options
{
public function returnField($form_name, $name, $value = '')
{
$field = '';
foreach ($this->options as $key => $val) {
$attributes = $this->getAttributeString($val);
$field .= sprintf('<input type="radio" name="%6$s[%1$s]" id="%6$s_%3$s" value="%2$s" %4$s/>' .
'<label for="%6$s_%3$s">%5$s</label>'
, $name, $key, Useful::slugify($name) . '_' . Useful::slugify($key), ((string) $key === (string) $value ? 'checked="checked"' : '') . $attributes['string'], $attributes['val'], $form_name);
}
$class = !empty($this->error) ? 'error choice_label' : 'choice_label';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label class="%s">%s</label>', $class, $this->label),
'field' => $field,
'html' => $this->html
);
}
}

View file

@ -0,0 +1,29 @@
<?php
namespace Nibble\NibbleForms\Field;
class Select extends Options
{
public function __construct($label, array $attributes = array())
{
parent::__construct($label, $attributes);
}
public function returnField($form_name, $name, $value = '')
{
$field = sprintf('<select name="%2$s[%1$s]" id="%2$s_%1$s">', $name, $form_name);
foreach ($this->options as $key => $val) {
$attributes = $this->getAttributeString($val);
$field .= sprintf('<option value="%s" %s>%s</option>', $key, ((string) $key === (string) $value ? 'selected="selected"' : '') . $attributes['string'], $attributes['val']);
}
$field .= '</select>';
$class = !empty($this->error) ? 'error choice_label' : 'choice_label';
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label for="%s_%s" class="%s">%s</label>', $form_name, $name, $class, $this->label),
'field' => $field,
'html' => $this->html
);
}
}

View file

@ -0,0 +1,76 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
use Nibble\NibbleForms\Field;
class Text extends Field
{
protected $label,
$content = '/.*/',
$attribute_string = '',
$class = '',
$required = true;
public $error = array(),
$field_type = 'text';
public function __construct($label, $attributes = array())
{
$this->label = $label;
if (isset($attributes['required'])) {
$this->required = $attributes['required'];
} else {
$attributes['required'] = true;
}
if (isset($attributes['content'])) {
$this->content = $attributes['content'];
}
$this->attributes = $attributes;
}
public function attributeString()
{
if (!empty($this->error)) {
$this->class = 'error';
}
$this->attribute_string = '';
foreach ($this->attributes as $attribute => $val) {
if ($attribute == 'class') {
$this->class.= ' ' . $val;
} else {
$this->attribute_string .= $val ? ' ' . ($val === true ? $attribute : "$attribute=\"$val\"") : '';
}
}
}
public function returnField($form_name, $name, $value = '')
{
$this->attributeString();
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label === false ? false : sprintf('<label for="%s_%s" class="%s">%s</label>', $form_name, $name, $this->class, $this->label),
'field' => sprintf('<input type="%1$s" name="%6$s[%2$s]" id="%6$s_%2$s" value="%3$s" %4$s class="%5$s" />', $this->field_type, $name, $value, $this->attribute_string, $this->class, $form_name),
'html' => $this->html
);
}
public function validate($val)
{
if ($this->required) {
if (Useful::stripper($val) === false) {
$this->error[] = 'is required';
}
}
if (Useful::stripper($val) !== false) {
if (!preg_match($this->content, $val)) {
$this->error[] = 'is not valid';
}
}
return !empty($this->error) ? false : true;
}
}

View file

@ -0,0 +1,30 @@
<?php
namespace Nibble\NibbleForms\Field;
class TextArea extends Text
{
public function __construct($label, $attributes)
{
parent::__construct($label, $attributes);
if (!isset($attributes['rows'])) {
$attributes['rows'] = 6;
}
if (!isset($attributes['cols'])) {
$attributes['cols'] = 60;
}
}
public function returnField($form_name, $name, $value = '')
{
$this->attributeString();
return array(
'messages' => !empty($this->custom_error) && !empty($this->error) ? $this->custom_error : $this->error,
'label' => $this->label == false ? false : sprintf('<label for="%s_%s" class="%s">%s</label>', $form_name, $name, $this->class, $this->label),
'field' => sprintf('<textarea name="%5$s[%1$s]" id="%5$s_%1$s" class="%2$s" %4$s>%3$s</textarea>', $name, $this->class, $value, $this->attribute_string, $form_name),
'html' => $this->html
);
}
}

View file

@ -0,0 +1,33 @@
<?php
namespace Nibble\NibbleForms\Field;
use Nibble\NibbleForms\Useful;
class Url extends Text
{
public function validate($val)
{
if (!empty($this->error)) {
return false;
}
if (parent::validate($val)) {
if (Useful::stripper($val) !== false) {
if (!filter_var($val, FILTER_VALIDATE_URL)) {
$this->error[] = 'must be a valid URL';
}
}
}
return !empty($this->error) ? false : true;
}
public function returnField($form_name, $name, $value = '')
{
$this->field_type = 'url';
return parent::returnField($form_name, $name, $value);
}
}

View file

@ -0,0 +1,570 @@
<?php
/**
* Nibble Forms 2 library
* Copyright (c) 2013 Luke Rotherfield, Nibble Development
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* 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.
*/
namespace Nibble\NibbleForms;
class NibbleForm
{
protected $action, $method, $submit_value, $fields, $sticky, $format, $message_type, $multiple_errors, $html5;
protected $valid = true;
protected $name = 'nibble_form';
protected $messages = array();
protected $data = array();
protected $formats
= array(
'list' => array(
'open_form' => '<ul>',
'close_form' => '</ul>',
'open_form_body' => '',
'close_form_body' => '',
'open_field' => '',
'close_field' => '',
'open_html' => "<li>\n",
'close_html' => "</li>\n",
'open_submit' => "<li>\n",
'close_submit' => "</li>\n"
),
'table' => array(
'open_form' => '<table>',
'close_form' => '</table>',
'open_form_body' => '<tbody>',
'close_form_body' => '</tbody>',
'open_field' => "<tr>\n",
'close_field' => "</tr>\n",
'open_html' => "<td>\n",
'close_html' => "</td>\n",
'open_submit' => '<tfoot><tr><td>',
'close_submit' => '</td></tr></tfoot>'
)
);
protected static $instance = array();
/**
* @param string $action
* @param string $submit_value
* @param string $method
* @param boolean $sticky
* @param string $message_type
* @param string $format
* @param string $multiple_errors
*
* @return NibbleForm
*/
public function __construct(
$action,
$submit_value,
$html5,
$method,
$sticky,
$message_type,
$format,
$multiple_errors
) {
$this->fields = new \stdClass();
$this->action = $action;
$this->method = $method;
$this->html5 = $html5;
$this->submit_value = $submit_value;
$this->sticky = $sticky;
$this->format = $format;
$this->message_type = $message_type;
$this->multiple_errors = $multiple_errors;
spl_autoload_register(array($this, 'nibbleLoader'));
}
/**
* Singleton method
*
* @param string $action
* @param string $method
* @param boolean $sticky
* @param string $submit_value
* @param string $message_type
* @param string $format
* @param string $multiple_errors
*
* @return NibbleForm
*/
public static function getInstance(
$name = '',
$action = '',
$html5 = true,
$method = 'post',
$submit_value = 'Submit',
$format = 'list',
$sticky = true,
$message_type = 'list',
$multiple_errors = false
) {
if (!isset(self::$instance[$name])) {
self::$instance[$name]
= new NibbleForm($action, $submit_value, $html5, $method, $sticky, $message_type, $format, $multiple_errors);
}
return self::$instance[$name];
}
/**
* Autoloader for nibble forms
*
* @param string $class
*/
public static function nibbleLoader($class)
{
$namespace = explode('\\', trim($class));
foreach ($namespace as $key => $value) {
if (empty($value)) {
unset($namespace[$key]);
}
}
$filepath = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . implode(DIRECTORY_SEPARATOR, $namespace) . '.php';
if (file_exists($filepath)) {
require_once $filepath;
}
}
/**
* Add a field to the form instance
*
* @param string $field_name
* @param string $type
* @param array $attributes
* @param boolean $overwrite
*
* @return boolean
*/
public function addField($field_name, $type = 'text', array $attributes = array(), $overwrite = false)
{
$namespace = "\\Nibble\\NibbleForms\\Field\\" . ucfirst($type);
if (isset($attributes['label'])) {
$label = $attributes['label'];
} else {
$label = ucfirst(str_replace('_', ' ', $field_name));
}
$field_name = Useful::slugify($field_name, '_');
if (isset($this->fields->$field_name) && !$overwrite) {
return false;
}
$this->fields->$field_name = new $namespace($label, $attributes);
$this->fields->$field_name->setForm($this);
return $this->fields->$field_name;
}
/**
* Set the name of the form
*
* @param string $name
*/
public function setName($name)
{
$this->name = $name;
}
/**
* Get form name
*
* @return string
*/
public function getName()
{
return $this->name;
}
/**
* Get form method
*
* @return string
*/
public function getMethod()
{
return $this->method;
}
/**
* Add data to populate the form
*
* @param array $data
*/
public function addData(array $data)
{
$this->data = array_merge($this->data, $data);
}
/**
* Validate the submitted form
*
* @return boolean
*/
public function validate()
{
$request = strtoupper($this->method) == 'POST' ? $_POST : $_GET;
if (isset($request[$this->name])) {
$form_data = $request[$this->name];
} else {
$this->valid = false;
return false;
}
if ((isset($_SESSION["nibble_forms"]["_crsf_token"], $_SESSION["nibble_forms"]["_crsf_token"][$this->name])
&& $form_data["_crsf_token"] !== $_SESSION["nibble_forms"]["_crsf_token"][$this->name])
|| !isset($_SESSION["nibble_forms"]["_crsf_token"])
|| !isset($form_data["_crsf_token"])
) {
$this->setMessages('CRSF token invalid', 'CRSF error');
$this->valid = false;
}
$_SESSION["nibble_forms"]["_crsf_token"] = array();
if ($this->sticky) {
$this->addData($form_data);
}
foreach ($this->fields as $key => $value) {
if (!$value->validate(
(isset($form_data[$key])
? $form_data[$key] : (isset($_FILES[$this->name][$key]) ? $_FILES[$this->name][$key] : ''))
)
) {
$this->valid = false;
return false;
}
}
return $this->valid;
}
public function getData($key)
{
return isset($this->data[$key]) ? $this->data[$key] : false;
}
/**
* Render the entire form including submit button, errors, form tags etc
*
* @return string
*/
public function render()
{
$fields = '';
$error = $this->valid ? ''
: '<p class="error">Sorry there were some errors in the form, problem fields have been highlighted</p>';
$format = (object) $this->formats[$this->format];
$this->setToken();
foreach ($this->fields as $key => $value) {
$format = (object) $this->formats[$this->format];
$temp = isset($this->data[$key]) ? $value->returnField($this->name, $key, $this->data[$key])
: $value->returnField($this->name, $key);
$fields .= $format->open_field;
if ($temp['label']) {
$fields .= $format->open_html . $temp['label'] . $format->close_html;
}
if (isset($temp['messages'])) {
foreach ($temp['messages'] as $message) {
if ($this->message_type == 'inline') {
$fields .= "$format->open_html <p class=\"error\">$message</p> $format->close_html";
} else {
$this->setMessages($message, $key);
}
if (!$this->multiple_errors) {
break;
}
}
}
$fields .= $format->open_html . $temp['field'] . $format->close_html . $format->close_field;
}
if (!empty($this->messages)) {
$this->buildMessages();
} else {
$this->messages = false;
}
self::$instance = false;
$attributes = $this->getFormAttributes();
return <<<FORM
$error
$this->messages
<form class="form" action="$this->action" method="$this->method" {$attributes['enctype']} {$attributes['html5']}>
$format->open_form
$format->open_form_body
$fields
$format->close_form_body
$format->open_submit
<input type="submit" name="submit" value="$this->submit_value" />
$format->close_submit
$format->close_form
</form>
FORM;
}
/**
* Returns the HTML for a specific form field ususally in the form of input tags
*
* @param string $name
*
* @return string
*/
public function renderField($name)
{
return $this->getFieldData($name, 'field');
}
/**
* Returns the HTML for a specific form field's label
*
* @param string $name
*
* @return string
*/
public function renderLabel($name)
{
return $this->getFieldData($name, 'label');
}
/**
* Returns the error string for a specific form field
*
* @param string $name
*
* @return string
*/
public function renderError($name)
{
$error_string = '';
if (!is_array($this->getFieldData($name, 'messages'))) {
return false;
}
foreach ($this->getFieldData($name, 'messages') as $error) {
$error_string .= "<li>$error</li>";
}
return $error_string === '' ? false : "<ul>$error_string</ul>";
}
/**
* Returns the boolean depending on existance of errors for specified
* form field
*
* @param string $name
*
* @return boolean
*/
public function hasError($name)
{
$errors = $this->getFieldData($name, 'messages');
if (!$errors || !is_array($errors)) {
return false;
}
return true;
}
/**
* Returns the entire HTML structure for a form field
*
* @param string $name
*
* @return string
*/
public function renderRow($name)
{
$row_string = $this->renderError($name);
$row_string .= $this->renderLabel($name);
$row_string .= $this->renderField($name);
return $row_string;
}
/**
* Returns HTML for all hidden fields including crsf protection
*
* @return string
*/
public function renderHidden()
{
$this->setToken();
$fields = array();
foreach ($this->fields as $name => $field) {
if (get_class($field) == 'Nibble\\NibbleForms\\Field\\Hidden') {
if (isset($this->data[$name])) {
$field_data = $field->returnField($this->name, $name, $this->data[$name]);
} else {
$field_data = $field->returnField($this->name, $name);
}
$fields[] = $field_data['field'];
}
}
return implode("\n", $fields);
}
/**
* Returns HTML string for all errors in the form
*
* @return string
*/
public function renderErrors()
{
$error_string = '';
foreach (array_keys($this->fields) as $name) {
foreach ($this->getFieldData($name, 'messages') as $error) {
$error_string .= "<li>$error</li>\n";
}
}
return $error_string === '' ? false : "<ul>$error_string</ul>";
}
/**
* Returns the HTML string for opening a form with the correct enctype, action and method
*
* @return string
*/
public function openForm()
{
$attributes = $this->getFormAttributes();
return "<form class=\"form\" action=\"$this->action\" method=\"$this->method\" {$attributes['enctype']} {$attributes['html5']}>";
}
/**
* Return close form tag
*
* @return string
*/
public function closeForm()
{
return "</form>";
}
/**
* Check if a field exists
*
* @param string $field
*
* @return boolean
*/
public function checkField($field)
{
return isset($this->fields->$field);
}
/**
* Get the attributes for the form tag
*
* @return array
*/
private function getFormAttributes()
{
$enctype = '';
foreach ($this->fields as $field) {
if (get_class($field) == 'File') {
$enctype = 'enctype="multipart/form-data"';
}
}
$html5 = $this->html5 ? '' : 'novalidate';
return array(
'enctype' => $enctype,
'html5' => $html5
);
}
/**
* Adds a message string to the class messages array
*
* @param string $message
* @param string $title
*/
private function setMessages($message, $title)
{
$title = preg_replace('/_/', ' ', ucfirst($title));
if ($this->message_type == 'list') {
$this->messages[] = array('title' => $title, 'message' => ucfirst($message));
}
}
/**
* Sets the messages array as an HTML string
*/
private function buildMessages()
{
$messages = '<ul class="error">';
foreach ($this->messages as $message_array) {
$messages .= sprintf(
'<li>%s: %s</li>%s',
ucfirst(preg_replace('/_/', ' ', $message_array['title'])),
ucfirst($message_array['message']),
"\n"
);
}
$this->messages = $messages . '</ul>';
}
/**
* Gets a specific field HTML string from the field class
*
* @param string $name
* @param string $key
*
* @return string
*/
private function getFieldData($name, $key)
{
if (!$this->checkField($name)) {
return false;
}
$field = $this->fields->$name;
if (isset($this->data[$name])) {
$field = $field->returnField($this->name, $name, $this->data[$name]);
} else {
$field = $field->returnField($this->name, $name);
}
return $field[$key];
}
/**
* Creates a new CRSF token
*
* @return string
*/
private function setToken()
{
if (!isset($_SESSION["nibble_forms"])) {
$_SESSION["nibble_forms"] = array();
}
if (!isset($_SESSION["nibble_forms"]["_crsf_token"])) {
$_SESSION["nibble_forms"]["_crsf_token"] = array();
}
$_SESSION["nibble_forms"]["_crsf_token"][$this->name] = Useful::randomString(20);
$this->addField("_crsf_token", "hidden");
$this->addData(array("_crsf_token" => $_SESSION["nibble_forms"]["_crsf_token"][$this->name]));
}
}

View file

@ -0,0 +1,55 @@
<?php
namespace Nibble\NibbleForms;
class Useful
{
/**
* Strip out all empty characters from a string
*
* @param string $val
*
* @return string
*/
public static function stripper($val)
{
foreach (array(' ', '&nbsp;', '\n', '\t', '\r') as $strip) {
$val = str_replace($strip, '', (string) $val);
}
return $val === '' ? false : $val;
}
/**
* Slugify a string using a specified replacement for empty characters
*
* @param string $text
* @param string $replacement
*
* @return string
*/
public static function slugify($text, $replacement = '-')
{
return strtolower(trim(preg_replace('/\W+/', $replacement, $text), '-'));
}
/**
* Return a random string of specified length
*
* @param int $length
* @param string $return
*
* @return string
*/
public static function randomString($length = 10, $return = '')
{
$string = 'qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890';
while ($length-- > 0){
$return .= $string[mt_rand(0, strlen($string) - 1)];
}
return $return;
}
}

View file

@ -0,0 +1,176 @@
## Nibble Forms 2, PHP form class
[Nibble Forms 2][15] is a PHP form class that allows developers to quickly create
HTML5 forms and validate submitted results. Nibble Forms 2 is an evolution
of the original [Nibble Forms][1] class, it follows some of the key principles
of Nibble Forms;
* Simple to instantiate: Nibble Forms 2 can be insantiated without any
arguments, this means getting a form object to add fields to can be as simple as
`$form = \NibbleForms\NibbleForm::getInstance();`
* Simple form field calls: Each form field in Nibble Forms 2 can be instantiated
with just a name and type (or name, type and choices if its a choice field like a select).
This means just one line of code sets up all the HTML5 markup and all the PHP
validation methods. `$form->addField('example_text_field', 'text');`
* Flexible: Nibble forms 2 still allows developers to choose the default form
markup, add extra field attributes, change field validation, markup forms with
custom HTML, turn on HTML5 validation and much more.
* Validation out of the box: Each form field in Nibble Forms 2 has standard
validation built in. E.g. Email fields accept only valid emails etc
In addition, it is evident that there are some flaws with the originial Nibble
Forms when using it in a large application. These flaws were the starting
drive for making Nibble Forms 2:
* Attributes array: The original Nibble Forms had many arguments per form field and
the arguments were not always in the same order. This made developing with
Nibble Forms a slower process because each set of arguments has to be remembered
or looked up for each form field. Nibble forms 2 only has 3 arguments, field_name,
field_type and field_arguments. The field arguments is always an array of arguments which
means no order has to be remembered. All fields have standard arguments that can
be defined in the array (like `"required" => true`) and some (like option fields)
have additional arguments that can be defined too (like the array of choices).
* Render individual form elements: In the original Nibble Forms there was a
method for each field to add extra HTML markup around it. When trying to
customise the layout of the form anything more than just adding a div around a
field, this method made the layout very messy and often broken. Nibble Forms 2
allows the developer to render individual form rows (label, field and errors)
or even individual elements of a row so they can mark up the form with any
structure needed. `$form->renderRow('example_text_field')`
* PHP namespaces: To make the code more legible, Nibble Forms 2 has each field
in its own file in the NibbleForms\Field namespace. There is an autoloader
so that each field can be easily loaded and extended, and, new fields can be
created by developers without messing around with the core code file.
* Add field method: This function was needed for two reasons;
- The original Nibble Forms used magic getters and setters to make form fields which
falls down when a field name is used that is also used as a class variable.
- Because of the namespaces, creating a form would require writing the namespace
for each field each time one was added, the addField method makes adding a field
a very simple call.
## Simple usage
Each form used in one server request requires its own instance of Nibble Forms,
the class must be included in order to get an instance:
``` php
/* Require the Nibble Forms class */
require_once dirname(__FILE__) . '/Nibble/NibbleForms/NibbleForm.php';
/* Get an instance of the form called "form_one" */
$form = \Nibble\NibbleForms\NibbleForm::getInstance('form_one');
```
Form fields can then be added to a form instance using the addField method:
``` php
/* Add field using 3 arguments; field name, field type and field options */
$form->addField('first_name', 'text', array('required' => false));
```
There are numerous form field types pre-defined in Nibble Forms, the below
fields can be added with no field options array:
* [text][2]
* [textarea][3]
* [password][4]
* [email][5]
* [url][6]
* [number][14]
* [file][7]
* [captcha][8]
* [hidden][9]
There are also 4 choice style fields that require an array of choices with
the array key "choices" in the field options array
`array('choices' => array('one', 'two', 'three'))`:
* [radio][10]
* [checkbox][11]
* [select][12]
* [multipleSelect][13]
Now that the form has form fields it can be rendered:
``` php
<? /* Render whole form */ ?>
<?php echo $form->render() ?>
<? /* Or render form elements individually with elements or whole rows */ ?>
<?php echo $form->openForm() ?>
<?php echo $form->renderHidden() ?>
<?php echo $form->renderLabel('field_one') ?>
<?php echo $form->renderField('field_one') ?>
<?php echo $form->renderError('field_one') ?>
<?php echo $form->renderRow('field_two') ?>
<button type="submit">Submit</button>
<?php echo $form->closeForm() ?>
````
Finally once the data is submitted, validate the form:
``` php
/* In order to render errors, this method must be called before the form is rendered */
$form->validate();
```
An example form instantition (without rendering) will look something like:
``` php
<?php
/* Require Nibble Forms 2 */
require_once __DIR__ . '/Nibble/NibbleForms/NibbleForm.php';
/* Get Nibble Forms 2 instance called mega_form */
$form = \Nibble\NibbleForms\NibbleForm::getInstance('mega_form');
/* Text field with custom class and max length attribute */
$form->addField('text_field', 'text', array(
'class' => 'testy classes',
'max_length' => 20
));
/* Email field, not required and custom label text */
$email = $form->addfield('email', 'email', array(
'required' => false,
'label' => 'Please enter your email address'
));
/* Email confirmation field which must match the value for email */
$email->addConfirmation('confirm_email', array(
'label' => 'Please confirm your email address'
));
/* Radio button field with two options, first option has an additional attribute */
$form->addField('choice', 'radio', array(
'choices' => array(
"one" => array('data-example' => 'data-attribute-value', 'Choice One'),
"two" => "Choice Two"),
'false_values' => array("two")
));
/* If the form is valid, do something */
if ($form->validate()) {
echo "Form has validated";
}
```
[1]: http://nibble-development.com/nibble-forms-php-form-class
[15]: http://nibble-development.com/nibble-forms-2-php-form-class
[2]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Text.php
[3]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/TextArea.php
[4]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Password.php
[5]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Email.php
[6]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Url.php
[14]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Number.php
[7]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/File.php
[8]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Captcha.php
[9]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Hidden.php
[10]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Radio.php
[11]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Checkbox.php
[12]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/Select.php
[13]: https://github.com/LRotherfield/Nibble-Forms/blob/master/Nibble/NibbleForms/Field/MultipleSelect.php

Binary file not shown.

View file

@ -0,0 +1,36 @@
<?php
/* Require Nibble Forms 2 */
require_once __DIR__ . '/Nibble/NibbleForms/NibbleForm.php';
/* Get Nibble Forms 2 instance called mega_form */
$form = \Nibble\NibbleForms\NibbleForm::getInstance('mega_form');
/* Text field with custom class and max length attribute */
$form->addField('text_field', 'text', array(
'class' => 'testy classes',
'max_length' => 20
));
/* Email field, not required and custom label text */
$email = $form->addfield('email', 'email', array(
'required' => false,
'label' => 'Please enter your email address'
));
/* Email confirmation field which must match the value for email */
$email->addConfirmation('confirm_email', array(
'label' => 'Please confirm your email address'
));
/* Radio button field with two options, first option has an additional attribute */
$form->addField('choice', 'radio', array(
'choices' => array(
"one" => array('data-example' => 'data-attribute-value', 'Choice One'),
"two" => "Choice Two"),
'false_values' => array("two")
));
/* If the form is valid, do something */
if ($form->validate()) {
echo "Form has validated";
}

View file

@ -0,0 +1,34 @@
<?php
error_reporting(E_ALL | E_STRICT);
ini_set('display_errors', 1);
session_name('nibble');
ini_set('session.gc_maxlifetime', 30 * 60);
session_set_cookie_params(30 * 60);
session_start();
include_once __DIR__.('/form_example.php');
?>
<!doctype html>
<html>
<head>
<title>Nibble Forms Demo</title>
<script src="http://www.google.com/jsapi" type="text/javascript"></script>
<link rel="stylesheet" type="text/css" media="screen" href="style.css" />
</head>
<body>
<?php echo $form->openForm() ?>
<?php echo $form->renderHidden() ?>
<?php echo $form->renderLabel('text_field') ?>
<?php echo $form->renderField('text_field') ?>
<?php echo $form->renderError('text_field') ?>
<?php echo $form->renderRow('email') ?>
<?php echo $form->renderRow('confirm_email') ?>
<?php echo $form->renderRow('choice') ?>
<p>
<button type="submit">Submit</button>
</p>
<?php echo $form->closeForm() ?>
</body>
</html>

View file

@ -0,0 +1,142 @@
form {
margin-bottom: 20px;
}
fieldset {
margin-bottom: 20px;
}
input[type="text"],
input[type="password"],
input[type="email"],
textarea,
select {
border: 1px solid #ccc;
padding: 6px 4px;
outline: none;
-moz-border-radius: 2px;
-webkit-border-radius: 2px;
border-radius: 2px;
font: 13px "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
color: #777;
margin: 0;
width: 210px;
max-width: 100%;
display: block;
margin-bottom: 20px;
background: #fff;
}
select {
padding: 0;
}
input[type="text"]:focus,
input[type="password"]:focus,
input[type="email"]:focus,
textarea:focus {
border: 1px solid #aaa;
color: #444;
-moz-box-shadow: 0 0 3px rgba(0,0,0,.2);
-webkit-box-shadow: 0 0 3px rgba(0,0,0,.2);
box-shadow: 0 0 3px rgba(0,0,0,.2);
}
textarea {
min-height: 60px;
}
label,
legend {
display: block;
font-weight: bold;
font-size: 13px;
}
select {
width: 220px;
}
input[type="checkbox"] {
display: inline;
}
label span,
legend span {
font-weight: normal;
font-size: 13px;
color: #444;
}
.button,
button,
input[type="submit"],
input[type="reset"],
input[type="button"] {
background: #eee; /* Old browsers */
background: #eee -moz-linear-gradient(top, rgba(255,255,255,.2) 0%, rgba(0,0,0,.2) 100%); /* FF3.6+ */
background: #eee -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.2)), color-stop(100%,rgba(0,0,0,.2))); /* Chrome,Safari4+ */
background: #eee -webkit-linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* Chrome10+,Safari5.1+ */
background: #eee -o-linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* Opera11.10+ */
background: #eee -ms-linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* IE10+ */
background: #eee linear-gradient(top, rgba(255,255,255,.2) 0%,rgba(0,0,0,.2) 100%); /* W3C */
border: 1px solid #aaa;
border-top: 1px solid #ccc;
border-left: 1px solid #ccc;
-moz-border-radius: 3px;
-webkit-border-radius: 3px;
border-radius: 3px;
color: #444;
display: inline-block;
font-size: 11px;
font-weight: bold;
text-decoration: none;
text-shadow: 0 1px rgba(255, 255, 255, .75);
cursor: pointer;
margin-bottom: 20px;
line-height: normal;
padding: 8px 10px;
font-family: "HelveticaNeue", "Helvetica Neue", Helvetica, Arial, sans-serif;
}
.button:hover,
button:hover,
input[type="submit"]:hover,
input[type="reset"]:hover,
input[type="button"]:hover {
color: #222;
background: #ddd; /* Old browsers */
background: #ddd -moz-linear-gradient(top, rgba(255,255,255,.3) 0%, rgba(0,0,0,.3) 100%); /* FF3.6+ */
background: #ddd -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.3)), color-stop(100%,rgba(0,0,0,.3))); /* Chrome,Safari4+ */
background: #ddd -webkit-linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* Chrome10+,Safari5.1+ */
background: #ddd -o-linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* Opera11.10+ */
background: #ddd -ms-linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* IE10+ */
background: #ddd linear-gradient(top, rgba(255,255,255,.3) 0%,rgba(0,0,0,.3) 100%); /* W3C */
border: 1px solid #888;
border-top: 1px solid #aaa;
border-left: 1px solid #aaa;
}
.button:active,
button:active,
input[type="submit"]:active,
input[type="reset"]:active,
input[type="button"]:active {
border: 1px solid #666;
background: #ccc; /* Old browsers */
background: #ccc -moz-linear-gradient(top, rgba(255,255,255,.35) 0%, rgba(10,10,10,.4) 100%); /* FF3.6+ */
background: #ccc -webkit-gradient(linear, left top, left bottom, color-stop(0%,rgba(255,255,255,.35)), color-stop(100%,rgba(10,10,10,.4))); /* Chrome,Safari4+ */
background: #ccc -webkit-linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* Chrome10+,Safari5.1+ */
background: #ccc -o-linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* Opera11.10+ */
background: #ccc -ms-linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* IE10+ */
background: #ccc linear-gradient(top, rgba(255,255,255,.35) 0%,rgba(10,10,10,.4) 100%); /* W3C */
}
.button.full-width,
button.full-width,
input[type="submit"].full-width,
input[type="reset"].full-width,
input[type="button"].full-width {
width: 100%;
padding-left: 0 !important;
padding-right: 0 !important;
text-align: center;
}
/* Fix for odd Mozilla border & padding issues */
button::-moz-focus-inner,
input::-moz-focus-inner {
border: 0;
padding: 0;
}

View file

@ -0,0 +1,47 @@
Class that generates HTML forms supporting:
- Multiple inputs may be interconnected in such way that client side events that occur on one input can trigger actions on the context of other inputs. Developers may use input interconnection support without writing Javascript code.
- Can be extended with new types of input controls plug-in classes.
- Custom input plug-in classes can be used to support for handling client site events on the server side without submitting the form or redrawing the whole form page
- Some control plug-in classes are made available:
* AJAX based form submission (without reloading the whole page)
* Auto-complete text inputs
* Select a location on a map using Google Maps API
* Calendar date input
* CAPTCHA test to prevent automated access by robots
* Linked select input to switch select options when the value of another input changes. An unlimited number of selected can be linked in cascade. Additional plug-in subclasses are provided to retrive option groups from a MySQL database or many other SQL databases using the Metabase PEAR::MDB2 PHP database abstraction layer APIs
* Manage animations that apply visual effects to the page form elements, like: fade-in, fade-out, show, hide, update content, etc..
- XHTML compliant output.
- Load submitted form field values even with register_globals option Off and strip slashes when magic_quotes_gpc option is On.
- Keyboard navigation support:
* Attachment of labels with activation keys to each form field.
* Tab navigation order index.
- Built-in server side (PHP based) and client side (Javascript 1.0 or better) field validation for:
* E-mail address
* Credit card numbers (Visa, Mastercard, American Express, Discover, Diners Club, Carte Blanche, enRoute, JCB, any of these or even determined by a select field).
* Regular expressions.
* Field not empty.
* Field equal to another (useful for password confirmation fields).
* Field different from another (useful for reminder fields that must not be equal to the actual password).
* As set (for check boxes, radio buttons and select multiple fields).
* As integer number (with range limitation).
* As floating point number (with range limitation).
* Programmer defined client and server validation functions.
- Highlight invalid fields rendering them distinct CSS styles
- Security attack prevention by optionally discarding invalid values passed in fields that could not be edited by users but may be spoofed by attackers.
- Option to define a value that, when used in a field, it is accepted without performing any of the validations defined for the field.
- Ability to stop the user from submiting a form more than once inadvertdly.
- Sub form validation (validate only smaller set of field depending on the submit button that was used).
- Composition and generation of the form HTML output with fields displayed as fully accessible or in read-only mode.
- Generation of Javascript functions (useful to set to the page ONLOAD event):
* Set the input focus to a field.
* Select the text of a field.
* Set the input focus and select the text of a field.
* Enable and disable input fields
- Automatic capitalization of the text of a field:
* Upper case.
* Lower case.
* Word initials
- Replacement of text field expressions to perform adjustments like trimming whitespace or auto-complete values based on rules defined by regular expressions
- Compose forms with templates using plain HTML files with embedded PHP code or using the Smarty template engine with a supplied pre-filter plugin
- Etc.

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 6.2 KiB

View file

@ -0,0 +1,186 @@
<?php
/*
* Example class to demonstrate how to create a data source class to store
* and retrieve information of entries to be viewed and manipulated with
* the scaffolding and crud plug-ins.
*
* @(#) $Id: blog_post_data_source.php,v 1.1 2012/12/31 11:07:36 mlemos Exp $
*
*/
class blog_post_data_source_class extends form_crud_data_source_class
{
var $model;
var $view;
/*
* The Initialize function can be used to initialize some variables that
* the class may need in the future to access the records of information
* to be viewed or manipulated using the CRUD user interface.
*
* The $arguments parameter is the array of parameters passed to the
* AddInput function
*/
Function Initialize(&$form, $arguments)
{
if(!IsSet($arguments['Model']))
return('it was not specified the posts model object');
$this->model = &$arguments['Model'];
if(!IsSet($arguments['View']))
return('it was not specified the posts view object');
$this->view = &$arguments['View'];
return('');
}
/*
* Retrieve the records of the entries to list, as well the
* configuration to generate the listing
*/
Function GetListing(&$form, &$listing)
{
$page = $listing['Page'];
if(!$this->model->GetEntries($page, $posts, $total_posts))
{
return($model->error);
}
if(!$this->view->GetPostListingFormat($columns, $id_column, $page_entries))
{
return($this->view->error);
}
$listing['Rows'] = $posts;
$listing['TotalEntries'] = $total_posts;
$listing['PageEntries'] = $page_entries;
$listing['IDColumn'] = $id_column;
$listing['Columns'] = $columns;
return('');
}
/*
* Generate the output to view a single entry.
* The base class can generate the output using a template set to the
* entry_template class variable. The entry_template_properties variable
* can be set to configure details of presentation of entry property.
*/
Function ViewEntry(&$form, &$entry, &$values)
{
if(!$this->view->GetPostFormat($this->entry_template, $this->entry_template_properties))
{
return($this->view->error);
}
return(parent::ViewEntry($form, $entry, $values));
}
/*
* Retrieve the values of an entry for display, editing or deleting
*/
Function GetEntry(&$form, &$entry, &$invalid, &$values)
{
/*
* If the entry must be an integer, verify that the requested value
* is an integer and cancel the entry retrieval otherwise.
*/
$id = intval($entry['ID']);
if(strcmp($id, $entry['ID']))
{
$invalid = true;
return '';
}
if(!$this->model->ReadEntry($id, $values))
{
return($this->model->error);
}
if(!IsSet($values))
{
/*
* If the entry does not exist or maybe the user does not have
* permissions to access it, cancel the entry access as this may be
* an attempt to access unauthorized information.
*/
$invalid = true;
return '';
}
UnSet($values['id']);
return '';
}
/*
* Save an entry that is being created or updated
*/
Function SaveEntry(&$form, $creating, &$entry, &$values)
{
/*
* First validate the entry values
* In this example it is tested if there is already an entry with the
* same title
*/
if(!$this->model->FindEntryByTitle($values['title'], $duplicated))
{
/*
* If there was a problem searching for the entry, return the
* error, so the application can deal with it.
*/
return($this->model->error);
}
if(IsSet($duplicated)
&& ($creating
|| $entry['ID'] != $duplicated['id']))
{
/*
* Flag the title input as invalid because there is already an
* entry with the specified title.
*/
$form->FlagInvalidInput('title', 'There is already a post with the title '.$values['title']);
return('');
}
/*
* Are we creating a new entry or updating an existing entry?
*/
if($creating)
{
if(!$this->model->CreateEntry($values))
{
/*
* If there was a problem creating an entry, return the error,
* so the application can deal with it.
*/
return($this->model->error);
}
/*
* If the entry was created successfully, the entry ID parameter
* must be set with the new entry record identifier.
*/
$entry['ID'] = $values['id'];
}
else
{
if(!$this->model->UpdateEntry($entry['ID'], $values))
{
/*
* If there was a problem updating an entry, return the error,
* so the application can deal with it.
*/
return($this->model->error);
}
}
return('');
}
/*
* Delete a given entry
*/
Function DeleteEntry(&$form, &$entry)
{
if(!$this->model->DeleteEntry($entry['ID']))
{
/*
* If there was a problem deleting an entry, return the error,
* so the application can deal with it.
*/
return($this->model->error);
}
return('');
}
};
?>

View file

@ -0,0 +1,188 @@
<?php
/*
* Example class to demonstrate how to store and retrieve information of
* the entries to be manipulated by the scaffolding plug-in.
*
* A real model access class would probably be a sub-class of a base class
* that would provide common functionality to create, read, update and
* delete database records. The sub-class would customize the details that
* vary from case to case, like the name of the table, name of the fields,
* condition clauses, etc..
*
* @(#) $Id: blog_post_model.php,v 1.7 2012/12/31 10:56:45 mlemos Exp $
*
*/
class blog_post_model_class
{
var $error = '';
var $page_entries = 10;
var $session = 'posts_storage';
/*
* Initialize the class to prepare the access to the storage container.
* If the storage container is a database, here you would probably
* establish the database connection.
*/
Function Initialize()
{
if(!session_start())
{
$this->error = 'could not start a session';
return(0);
}
if(!IsSet($_SESSION[$this->session]))
$_SESSION[$this->session] = array();
return(1);
}
/*
* Get a bidimensional array with all entries to be listed in the
* current page.
* If the storage container is a database, here you would execute a
* database query to retrieve the records to be listed in the current
* page and probably another query to count the total number of
* accessible records.
*/
Function GetEntries(&$page, &$entries, &$total_entries)
{
$all = $_SESSION[$this->session];
$total_entries = count($all);
if($total_entries == 0)
{
$page = 1;
$entries = array();
}
else
{
for($g = $e = 0; $e < $total_entries; ++$e)
{
if(IsSet($all[$e]))
++$g;
}
$t = $total_entries;
$total_entries = $g;
$p = $this->page_entries;
if($page < 1)
$page = 1;
if(($page - 1) * $p > $total_entries)
$page = intval($total_entries / $p) + 1;
$start = ($page - 1) * $p;
$entries = array();
for($e = $g = 0; $g < $start && $e < $t; ++$e)
{
if(IsSet($all[$e]))
++$g;
}
for($g = 0; $g < $p && $e < $t; ++$e)
{
if(IsSet($all[$e]))
{
$entries[] = array(
$e + 1,
$all[$e]['title']
);
++$g;
}
}
}
return(1);
}
/*
* Create a new entry with the given entry values.
* If the storage container is a database, here you would execute a
* database insert query to store a new record. The new record
* identifier should be set to the id entry value.
*/
Function CreateEntry(&$entry)
{
$id = count($_SESSION[$this->session]);
$entry['id'] = $id + 1;
$_SESSION[$this->session][$id] = $entry;
return(1);
}
/*
* Get a array with values of entry with a given identifier.
* If the storage container is a database, here you would execute a
* database query to retrieve the record with the given identifier.
*/
Function ReadEntry($id, &$entry)
{
--$id;
if(!IsSet($_SESSION[$this->session][$id]))
{
$entry = null;
return(1);
}
$entry = $_SESSION[$this->session][$id];
return(1);
}
/*
* Search for an entry with a given title and return an array with
* values of entry if found.
*/
Function FindEntryByTitle($title, &$entry)
{
Reset($_SESSION[$this->session]);
$total = Count($_SESSION[$this->session]);
for($id = 0; $id < $total; Next($_SESSION[$this->session]), ++$id)
{
if(!strcmp($_SESSION[$this->session][$id]['title'], $title))
{
$entry = $_SESSION[$this->session][$id];
$entry['id'] = $id + 1;
return(1);
}
}
$entry = null;
return(1);
}
/*
* Update an existing entry with the given entry values.
* If the storage container is a database, here you would execute a
* database update query to store the record changes.
*/
Function UpdateEntry($id, &$entry)
{
--$id;
if(!IsSet($_SESSION[$this->session][$id]))
{
$this->error = 'the entry does not exist';
return(1);
}
$_SESSION[$this->session][$id] = $entry;
return(1);
}
/*
* Delete an existing entry with a given identifier.
* If the storage container is a database, here you would execute a
* database delete query to remove the record.
*/
Function DeleteEntry($id)
{
--$id;
if(!IsSet($_SESSION[$this->session][$id]))
{
$this->error = 'the entry does not exist';
return(1);
}
$_SESSION[$this->session][$id] = null;
return(1);
}
/*
* Finalize the class to free any resources allocated during the access
* to the storage container.
* If the storage container is a database, here you would probably
* close the database connection.
*/
Function Finalize()
{
return(1);
}
};

View file

@ -0,0 +1,173 @@
<?php
/*
* Example class to demonstrate customize details of presentation of
* scaffolding forms and listings.
*
* @(#) $Id: blog_post_view.php,v 1.6 2012/12/31 10:56:10 mlemos Exp $
*
*/
class blog_post_view_class
{
var $error = '';
var $page_entries = 10;
var $columns = array(
array(
'Header'=>'ID',
'Style'=>'text-align: center; font-family: monospace; font-weight: bold',
),
array(
'Header'=>'Title',
'HTML'=>1
),
);
var $id_column = 0;
var $post_format = '<div align="center"><div class="article"><h2 class="articletitle">{title}</h2><div class="articlebody">{body}</div></div></div>';
var $post_format_properties = array(
'title'=>array(
'HTML'=>1,
),
'body'=>array(
'HTML'=>1,
),
);
var $error_message_format = '<div align="center"><table class="errormessage"><tr><td>{errormessage}</td></tr></table></div>';
var $form_header = '<center><table class="form" summary="Form">
<tr>
<td class="formtitle">Blog post</td>
</tr>
<tr>
<td>';
var $form_footer = '</td>
</tr>
</table></center>';
var $invalid_mark = '<span class="invalidmark">X</span>';
var $invalid_inputs_class = 'invalid';
var $css_styles =
".rounded, .box, .article, .errormessage, .invalidmark { border-radius: 8px ; -moz-border-radius: 8px; -webkit-border-radius: 8px; }
.box, .article, .form, .invalidmark, .errormessage { border-style: solid ; border-top-color: #fcfcff ; border-left-color: #fcfcff ; border-bottom-color: #707078 ; border-right-color: #707078 ; border-width: 1px ; }
.listing { background-color: #e4e4e8; padding: 4px; margin: 4px }
.highlightrow { background-color: #b0e0b0 }
.oddrow { background-color: #d0d0d4 }
.evenrow { background-color: #dcdce0 }
.article { text-align: left; background-color: #e4e4e8; margin: 4px; width: 40em }
.articletitle { padding: 4px ; margin: 0px; text-align: left }
.articlebody { padding: 4px; text-align: left }
.form { background-color: #e4e4e8 }
.formtitle { background-color: #000080; border-style: none; color: #ffffff; font-weight: bold; padding: 2px }
.errormessage, .invalidmark { background-color: #ffb366 }
.invalid { background-color: #ffcccc }
.errormessage { font-weight: bold; padding: 4px; margin: 4px; text-align: left }
.invalidmark { font-weight: bold; padding: 3px; margin: 0px; display: inline; vertical-align: top }
";
/*
* Initialize the class to initialize resources that may be necessary.
*/
Function Initialize()
{
return(1);
}
/*
* Get the options that define how post listings will appear, like the
* the listing table columns, number of the column that contains the
* listing entry identifiers and the number of entries to display per
* page.
*/
Function GetPostListingFormat(&$columns, &$id_column, &$page_entries)
{
$columns = $this->columns;
$id_column = $this->id_column;
$page_entries = $this->page_entries;
return(1);
}
/*
* Get the options that define how post listings will appear, like the
* the listing table columns, number of the column that contains the
* listing entry identifiers and the number of entries to display per
* page.
*/
Function GetPostFormat(&$template, &$properties)
{
$template = $this->post_format;
$properties = $this->post_format_properties;
return(1);
}
/*
* Generate HTML to show how an entry will appear.
*/
Function GetPostOutput($entry, &$output)
{
$output = str_replace(
'{title}', HtmlSpecialChars($entry['title']), str_replace(
'{body}', nl2br(HtmlSpecialChars($entry['body'])),
$this->entry_format));
return(1);
}
/*
* Get the HTML that defines how the validation error messages will be
* presented.
*/
Function GetErrorMessageFormat()
{
return($this->error_message_format);
}
/*
* Get the HTML that defines the beginning of a section within which
* the create, update and delete entry form will appear.
*/
Function GetFormHeader()
{
return($this->form_header);
}
/*
* Get the HTML that defines the end of a section within which the
* create, update and delete entry form will appear.
*/
Function GetFormFooter()
{
return($this->form_footer);
}
/*
* Get the HTML that defines how will appear the marks that identify
* invalid form fields.
*/
Function GetInvalidMark()
{
return($this->invalid_mark);
}
/*
* Get the name of CSS style that will be used to denote invalid form
* fields.
*/
Function GetInvalidInputsClass()
{
return($this->invalid_inputs_class);
}
/*
* Get the definition of CSS styles that are used in the different HTML
* templates.
*/
Function GetCSSStyles()
{
return($this->css_styles);
}
/*
* Finalize the class to free resources that may have been allocated.
*/
Function Finalize()
{
return(1);
}
};

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.7 KiB

View file

@ -0,0 +1,274 @@
<?php
/*
* country_codes.php
*
* @(#) $Header: /opt2/ena/metal/forms/country_codes.php,v 1.1 2009/10/24 04:49:36 mlemos Exp $
*
*/
$country_codes = array(
""=>"",
"ac"=>"Ascencion Island",
"ad"=>"Andorra",
"ae"=>"United Arab Emirates",
"af"=>"Afghanistan",
"ag"=>"Antigua and Barbuda",
"ai"=>"Anguilla",
"al"=>"Albania",
"am"=>"Armenia",
"an"=>"Netherlands Antilles",
"ao"=>"Angola",
"aq"=>"Antarctica",
"ar"=>"Argentina",
"as"=>"American Samoa",
"at"=>"Austria",
"au"=>"Australia",
"aw"=>"Aruba",
"ax"=>"Aland Islands",
"az"=>"Azerbaijan",
"ba"=>"Bosnia and Herzegovina",
"bb"=>"Barbados",
"bd"=>"Bangladesh",
"be"=>"Belgium",
"bf"=>"Burkina Faso",
"bg"=>"Bulgaria",
"bh"=>"Bahrain",
"bi"=>"Burundi",
"bj"=>"Benin",
"bm"=>"Bermuda",
"bn"=>"Brunei Darussalam",
"bo"=>"Bolivia",
"br"=>"Brazil",
"bs"=>"Bahamas",
"bt"=>"Bhutan",
"bv"=>"Bouvet Island",
"bw"=>"Botswana",
"by"=>"Belarus",
"bz"=>"Belize",
"ca"=>"Canada",
"cc"=>"Cocos Islands",
"cd"=>"Congo",
"cf"=>"Central African Republic",
"cg"=>"Congo",
"ch"=>"Switzerland",
"ci"=>"Ivory Coast",
"ck"=>"Cook Islands",
"cl"=>"Chile",
"cm"=>"Cameroon",
"cn"=>"China",
"co"=>"Colombia",
"cr"=>"Costa Rica",
"cs"=>"Czechoslovakia",
"cu"=>"Cuba",
"cv"=>"Cape Verde",
"cx"=>"Christmas Island",
"cy"=>"Cyprus",
"cz"=>"Czech Republic",
"de"=>"Germany",
"dj"=>"Djibouti",
"dk"=>"Denmark",
"dm"=>"Dominica",
"do"=>"Dominican Republic",
"dz"=>"Algeria",
"ec"=>"Ecuador",
"ee"=>"Estonia",
"eg"=>"Egypt",
"eh"=>"Western Sahara",
"er"=>"Eritrea",
"es"=>"Spain",
"et"=>"Ethiopia",
"fi"=>"Finland",
"fj"=>"Fiji",
"fk"=>"Falkland Islands",
"fm"=>"Micronesia",
"fo"=>"Faroe Islands",
"fr"=>"France",
"fx"=>"France, Metropolitan",
"ga"=>"Gabon",
"gb"=>"Great Britain",
"gd"=>"Grenada",
"ge"=>"Georgia",
"gf"=>"French Guiana",
"gg"=>"French Guiana",
"gh"=>"Ghana",
"gi"=>"Gibraltar",
"gl"=>"Greenland",
"gm"=>"Gambia",
"gn"=>"Guinea",
"gp"=>"Guadeloupe",
"gq"=>"Equatorial Guinea",
"gr"=>"Greece",
"gs"=>"S. Georgia and S. Sandwich Islands",
"gt"=>"Guatemala",
"gu"=>"Guam",
"gw"=>"Guinea-Bissau",
"gy"=>"Guyana",
"hk"=>"Hong Kong",
"hm"=>"Heard and McDonald Islands",
"hn"=>"Honduras",
"hr"=>"Croatia",
"ht"=>"Haiti",
"hu"=>"Hungary",
"id"=>"Indonesia",
"ie"=>"Ireland",
"il"=>"Israel",
"im"=>"Isle of Man",
"in"=>"India",
"io"=>"British Indian Ocean Territory",
"iq"=>"Iraq",
"ir"=>"Iran",
"is"=>"Iceland",
"it"=>"Italy",
"jm"=>"Jamaica",
"jo"=>"Jordan",
"jp"=>"Japan",
"ke"=>"Kenya",
"kg"=>"Kyrgyzstan",
"kh"=>"Cambodia",
"ki"=>"Kiribati",
"km"=>"Comoros",
"kn"=>"Saint Kitts and Nevis",
"ko"=>"Kosovo",
"kp"=>"North Korea",
"kr"=>"South Korea",
"kw"=>"Kuwait",
"ky"=>"Cayman Islands",
"kz"=>"Kazakhstan",
"la"=>"Laos",
"lb"=>"Lebanon",
"lc"=>"Saint Lucia",
"li"=>"Liechtenstein",
"lk"=>"Sri Lanka",
"lr"=>"Liberia",
"ls"=>"Lesotho",
"lt"=>"Lithuania",
"lu"=>"Luxembourg",
"lv"=>"Latvia",
"ly"=>"Libya",
"ma"=>"Morocco",
"mc"=>"Monaco",
"md"=>"Moldova",
"me"=>"Montenegro",
"mg"=>"Madagascar",
"mh"=>"Marshall Islands",
"mk"=>"Macedonia",
"ml"=>"Mali",
"mm"=>"Myanmar",
"mn"=>"Mongolia",
"mo"=>"Macau",
"mp"=>"Northern Mariana Islands",
"mq"=>"Martinique",
"mr"=>"Mauritania",
"ms"=>"Montserrat",
"mt"=>"Malta",
"mu"=>"Mauritius",
"mv"=>"Maldives",
"mw"=>"Malawi",
"mx"=>"Mexico",
"my"=>"Malaysia",
"mz"=>"Mozambique",
"na"=>"Namibia",
"nc"=>"New Caledonia",
"ne"=>"Niger",
"nf"=>"Norfolk Island",
"ng"=>"Nigeria",
"ni"=>"Nicaragua",
"nl"=>"The Netherlands",
"no"=>"Norway",
"np"=>"Nepal",
"nr"=>"Nauru",
"nt"=>"Neutral Zone",
"nu"=>"Niue",
"nz"=>"New Zealand",
"om"=>"Oman",
"pa"=>"Panama",
"pe"=>"Peru",
"pf"=>"French Polynesia",
"pg"=>"Papua New Guinea",
"ph"=>"Philippines",
"pk"=>"Pakistan",
"pl"=>"Poland",
"pm"=>"St. Pierre and Miquelon",
"pn"=>"Pitcairn",
"pr"=>"Puerto Rico",
"ps"=>"Palestine",
"pt"=>"Portugal",
"pw"=>"Palau",
"py"=>"Paraguay",
"qa"=>"Qatar",
"re"=>"Reunion",
"ro"=>"Romania",
"rs"=>"Serbia",
"ru"=>"Russian Federation",
"rw"=>"Rwanda",
"sa"=>"Saudi Arabia",
"sb"=>"Solomon Islands",
"sc"=>"Seychelles",
"sd"=>"Sudan",
"se"=>"Sweden",
"sg"=>"Singapore",
"sh"=>"St. Helena",
"si"=>"Slovenia",
"sj"=>"Svalbard and Jan Mayen Islands",
"sk"=>"Slovak Republic",
"sl"=>"Sierra Leone",
"sm"=>"San Marino",
"sn"=>"Senegal",
"so"=>"Somalia",
"sr"=>"Suriname",
"st"=>"Sao Tome and Principe",
"su"=>"USSR (former)",
"sv"=>"El Salvador",
"sy"=>"Syria",
"sz"=>"Swaziland",
"tc"=>"Turks and Caicos Islands",
"td"=>"Chad",
"tf"=>"French Southern Territories",
"tg"=>"Togo",
"th"=>"Thailand",
"tj"=>"Tajikistan",
"tk"=>"Tokelau",
"tm"=>"Turkmenistan",
"tn"=>"Tunisia",
"to"=>"Tonga",
"tp"=>"East Timor",
"tr"=>"Turkey",
"tt"=>"Trinidad and Tobago",
"tv"=>"Tuvalu",
"tw"=>"Taiwan",
"tz"=>"Tanzania",
"ua"=>"Ukraine",
"ug"=>"Uganda",
"uk"=>"United Kingdom",
"um"=>"US Minor Outlying Islands",
"us"=>"United States",
"uy"=>"Uruguay",
"uz"=>"Uzbekistan",
"va"=>"Vatican",
"vc"=>"Saint Vincent and the Grenadines",
"ve"=>"Venezuela",
"vg"=>"British Virgin Islands",
"vi"=>"U.S. Virgin Islands",
"vn"=>"Viet Nam",
"vu"=>"Vanuatu",
"wf"=>"Wallis and Futuna Islands",
"ws"=>"Samoa",
"ye"=>"Yemen",
"yt"=>"Mayotte",
"yu"=>"Serbia and Montenegro",
"za"=>"South Africa",
"zm"=>"Zambia",
"zr"=>"Zaire",
"zw"=>"Zimbabwe",
);
$global_options->locale_text["Continents"]=array(
"af"=>"Africa",
"as"=>"Asia",
"ca"=>"Central America",
"eu"=>"Europe",
"na"=>"North America",
"oc"=>"Oceania",
"sa"=>"South America"
);
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 3.6 KiB

View file

@ -0,0 +1,513 @@
<?php
/*
*
* @(#) $Id: form_ajax_submit.php,v 1.38 2011/03/17 09:58:34 mlemos Exp $
*
*/
class form_ajax_submit_class extends form_custom_class
{
var $timeout = 60.000;
var $poll_interval = 10;
var $feedback_element = '';
var $submit_feedback = '';
var $complete_feedback;
var $timeout_feedback = '';
var $target_input = '';
var $sub_form = '';
var $debug_console = '';
var $response_header='';
var $connections=array(
"ONCOMPLETE"=>array(),
"ONSUBMITTED"=>array(),
"ONTIMEOUT"=>array()
);
var $events=array(
"ONTIMEOUT"=>"alert('The communication with the server has timed out.');"
);
var $debug_console_template='<fieldset style="width: 80ex; margin: auto">
<legend><b>Debug console</b></legend>
<div id="{ELEMENT}" style="background-color: black; color: white; padding: 4px; font-family: monospace; height: 10em; overflow: auto"></div>
</fieldset>';
var $sub_form_parameter="___sub_form";
var $submit_form = '';
var $actions=array();
var $action_header_sent = 0;
var $start_script_sent = 0;
var $sending_ajax_response = 0;
Function AddInput(&$form, $arguments)
{
if(IsSet($arguments["Timeout"]))
{
$timeout=doubleval($arguments["Timeout"]);
if(strcmp($arguments["Timeout"], $timeout)
|| $timeout<0)
return("it was not specified a valid timeout value");
$this->timeout = $timeout;
}
if(IsSet($arguments["ONTIMEOUT"]))
$this->events["ONTIMEOUT"] = $arguments["ONTIMEOUT"];
if(IsSet($arguments["ONCOMPLETE"]))
$this->events["ONCOMPLETE"] = $arguments["ONCOMPLETE"];
if(IsSet($arguments["ONSUBMITTED"]))
$this->events["ONSUBMITTED"] = $arguments["ONSUBMITTED"];
if(IsSet($arguments["FeedbackElement"]))
{
if(strlen($arguments["FeedbackElement"])==0)
return("it was not specified a valid feedback element identifier");
$this->feedback_element = $arguments["FeedbackElement"];
if(IsSet($arguments["SubmitFeedback"]))
$this->submit_feedback = $arguments["SubmitFeedback"];
if(IsSet($arguments["TimeoutFeedback"]))
$this->timeout_feedback = $arguments["TimeoutFeedback"];
if(IsSet($arguments["CompleteFeedback"]))
$this->complete_feedback = $arguments["CompleteFeedback"];
}
if(IsSet($arguments["TargetInput"]))
{
if(strlen($arguments["TargetInput"])==0)
return("it was not specified a valid target input identifier");
$this->target_input = $arguments["TargetInput"];
}
if(IsSet($arguments["DebugConsole"]))
{
if(strlen($arguments["DebugConsole"])==0)
return("it was not specified a valid debug console identifier");
$this->debug_console = $arguments["DebugConsole"];
}
if(IsSet($arguments["ResponseHeader"]))
{
if(strlen($arguments["ResponseHeader"])==0)
return("it was not specified a valid response header");
$this->response_header = $arguments["ResponseHeader"];
}
$this->submit_form = $this->GenerateInputID($form, $this->input, "sf");
return("");
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case "FeedbackElement":
if(strlen($value)==0)
return("it was not specified a valid feedback element identifier");
$this->feedback_element = $value;
break;
case "Feedback":
if(strlen($this->feedback_element)==0)
return("the feedback element identifier is not set");
if(!$this->sending_ajax_response)
return("it is only possible to update the feedback element when the AJAX response is being sent");
$this->actions[]=array(
"Action"=>"ReplaceContent",
"Container"=>$this->feedback_element,
"Content"=>$value
);
if(strlen($error = $this->FlushActions($form, 1)))
return($error);
break;
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
Function AddInputPart(&$form)
{
if(strcmp(strtolower($form->METHOD),"post"))
return("currently the AJAX submit input only supports forms submitted with the POST method");
$eol=$form->end_of_line;
$b="";
$javascript="<script type=\"text/javascript\" defer=\"defer\">".$eol."<!--\n";
$javascript.="var ".$this->submit_form."_s=false;".$eol;
$javascript.="var ".$this->submit_form."_r=false;".$eol;
$javascript.="var ".$this->submit_form."_t=0;".$eol;
$javascript.="var ".$this->submit_form."_o=".intval($this->timeout*1000).";".$eol;
$javascript.="var ".$this->submit_form."_f;".$eol;
$javascript.="function ".$this->submit_form."()".$b."{".$b;
$javascript.="if(!".$this->submit_form."_s)".$b."return;".$b;
$javascript.="if(".$this->submit_form."_r)".$b."{".$b."if((i=document.getElementById(".$form->EncodeJavascriptString($this->submit_form."_i").")))".$b."i.src='';".$b.$this->submit_form."_s=false;".$b.$this->GetEventActions($form, $this->submit_form."_f", "ONCOMPLETE").$b."return;".$b."}".$b;
$javascript.=$this->submit_form."_t+=".$this->poll_interval.";".$b;
$javascript.="if(".$this->submit_form."_t>=".$this->submit_form."_o)".$b."{".$b.$this->submit_form."_s=false;".$b."if((i=document.getElementById(".$form->EncodeJavascriptString($this->submit_form."_i").")))".$b."i.src='';".$b.(strlen($this->feedback_element) ? "if((fb=document.getElementById(".$form->EncodeJavascriptString($this->feedback_element)."))) { fb.innerHTML=".$form->EncodeJavascriptString($this->timeout_feedback).';} ;'.$b :'').$this->GetEventActions($form, $this->submit_form."_f", "ONTIMEOUT").$b."return;".$b."}".$b;
$javascript.="setTimeout('".$this->submit_form."()',".$this->poll_interval.");".$b;
$javascript.="}".$eol."// -->".$eol."</script>";
$javascript.="<iframe id=\"".$this->submit_form."_i\" name=\"".$this->submit_form."_i\" width=\"0\" height=\"0\" frameborder=\"0\"></iframe>";
return($form->AddDataPart($javascript));
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case "Submit":
$parameters=array();
if(IsSet($context["SubForm"]))
{
if(strlen($sub_form=$form->GetJavascriptSetFormProperty($form_object, "SubForm", $form->EncodeJavascriptString($context["SubForm"])))==0)
return("could not set the AJAX form submit SubForm");
$sub_form.="; ";
$parameters[$this->sub_form_parameter]=$context["SubForm"];
}
else
$sub_form='';
if(strlen($error=$form->GetInputEventURL($this->input,"submit",$parameters,$form_action)))
return($error);
$javascript="if(".$this->submit_form."_s) return false; ".$this->submit_form."_r=false; ".$this->submit_form."_f=f=".$form_object.";";
if(IsSet($context["SetInputValue"]))
{
for($i=0, Reset($context["SetInputValue"]); $i<count($context["SetInputValue"]); Next($context["SetInputValue"]), $i++)
{
$input=Key($context["SetInputValue"]);
if(strlen($j = $form->GetJavascriptSetInputProperty("f", $input, "VALUE", $form->EncodeJavascriptString($context["SetInputValue"][$input])))==0)
{
$javascript="";
return("could not set the value of the input \"".$input."\"");
}
$javascript.=" ".$j;
}
}
$validate = (!IsSet($context['Validate']) || $context['Validate']);
$javascript.=" ".$sub_form.($validate ? "if(f.onsubmit && !f.onsubmit()) return false; " : "")."t=f.target; a=f.action; f.target='".$this->submit_form."_i'; f.action=".$form->EncodeJavascriptString($form_action)."; f.submit(); f.action=a; f.target=t; ".$this->submit_form."_t=0; ".$this->submit_form."_s=true; ".$this->submit_form."(); ".(strlen($this->feedback_element) ? "if((fb=document.getElementById(".$form->EncodeJavascriptString($this->feedback_element)."))) { fb.innerHTML=".$form->EncodeJavascriptString($this->submit_feedback).';} ;' :'').($s=$this->GetEventActions($form, "f", "ONSUBMITTED")).'return false';
break;
case "Load":
if(IsSet($context["Parameters"]))
$parameters=$context["Parameters"];
else
$parameters=array();
if(IsSet($context['RandomParameter']))
$parameters[$context['RandomParameter']]=uniqid($this->input);
if(strlen($error=$form->GetInputEventURL($this->input,"load",$parameters,$form_action)))
return($error);
$javascript="if(".$this->submit_form."_s) return false; ".$this->submit_form."_r=false; ".$this->submit_form."_f=f=".$form_object.";";
$javascript.=" if((i=document.getElementById(".$form->EncodeJavascriptString($this->submit_form."_i")."))) i.src=".$form->EncodeJavascriptString($form_action)."; ".$this->submit_form."_t=0; ".$this->submit_form."_s=true; ".$this->submit_form."(); ".(strlen($this->feedback_element) ? "if((fb=document.getElementById(".$form->EncodeJavascriptString($this->feedback_element)."))) { fb.innerHTML=".$form->EncodeJavascriptString($this->submit_feedback).';} ;' :'').'return false';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return("");
}
Function ValidateInput(&$form)
{
return("");
}
Function SetupMessage(&$message, $event)
{
$message=array(
"Event"=>$event,
"From"=>$this->input,
"ReplyTo"=>$this->input,
"More"=>0,
"Window"=>"_p",
"Document"=>"_d",
"Form"=>"_p.".$this->submit_form."_f",
);
if(strlen($this->target_input))
$message["Target"]=$this->target_input;
if(strlen($this->sub_form))
$message["SubForm"]=$this->sub_form;
}
Function HandleEvent(&$form, $event, $parameters, &$processed)
{
global $HTTP_GET_VARS;
switch($event)
{
case "submit":
if(IsSet($_GET[$this->sub_form_parameter]))
$this->sub_form=$_GET[$this->sub_form_parameter];
elseif(IsSet($HTTP_GET_VARS[$this->sub_form_parameter]))
$this->sub_form=$HTTP_GET_VARS[$this->sub_form_parameter];
case "load":
$this->sending_ajax_response = 1;
$this->SetupMessage($message, $event);
if(strlen($error=$form->PostMessage($message)))
return($error);
$processed=0;
break;
default:
return($this->DefaultHandleEvent($form,$event,$parameters,$processed));
}
return("");
}
Function Output($output)
{
echo $output;
}
Function DebugOutput(&$form, $output)
{
if(strlen($this->debug_console))
{
$content=$form->EncodeJavascriptString(HtmlSpecialChars($output)."<br />\n");
$this->Output("if(_g\n&& (_de=_d.getElementById(".$form->EncodeJavascriptString($this->debug_console.'_output').")))\n");
$this->Output("{\n _de.innerHTML+=".$content.";\n if('undefined' != typeof _de.scrollTop)\n _de.scrollTop=_de.scrollHeight;\n}\n");
flush();
}
}
Function SendStartScript()
{
if(!$this->start_script_sent)
{
$this->Output("<script type=\"text/javascript\"><!--\nif(parent.".$this->submit_form."_s)\n{\n");
$this->start_script_sent = 1;
}
}
Function SendEndScript(&$form, $flush)
{
if($this->start_script_sent)
{
$this->Output("_p.".$this->submit_form."_t=0;\n");
$this->Output("}\n// --></script>\n");
$this->start_script_sent = 0;
if($flush)
flush();
}
}
Function SendActionHeader(&$form)
{
$start=!$this->action_header_sent;
if($start)
{
Header("Content-Type: text/html");
if(strlen($this->response_header))
Header($this->response_header);
$this->Output("<html><head><title>submit</title></head><body>");
$this->action_header_sent = 1;
}
$this->SendStartScript();
$this->Output("_p=parent;\n_d=_p.document;\n_g=_d.getElementById;\n");
if($start
&& strlen($this->debug_console))
{
$element=$this->debug_console.'_output';
$content=$form->EncodeJavascriptString(str_replace('{ELEMENT}', $element, $this->debug_console_template));
$this->Output("if(_g\n&& (_de=_d.getElementById(".$form->EncodeJavascriptString($this->debug_console).")))\n");
$this->Output(" _de.innerHTML=".$content.";\n");
flush();
}
}
Function SendAction(&$form, $action)
{
switch($this->actions[$action]["Action"])
{
case "AppendContent":
case "PrependContent":
case "ReplaceContent":
if(!IsSet($this->actions[$action]["Container"]))
return("it was not specified the container element to replace the content");
if(!IsSet($this->actions[$action]["Content"]))
return("it was not specified the content to the content in the container");
$this->Output("if(_g\n&& (_e=_d.getElementById(".$form->EncodeJavascriptString($this->actions[$action]["Container"]).")))\n");
$content=$form->EncodeJavascriptString($this->actions[$action]["Content"]);
switch($this->actions[$action]["Action"])
{
case "AppendContent":
if(strlen($this->debug_console))
$this->DebugOutput($form, 'AppendContent(Container='.$this->actions[$action]["Container"].')');
$this->Output(" _e.innerHTML+=".$content.";\n");
break;
case "PrependContent":
if(strlen($this->debug_console))
$this->DebugOutput($form, 'PrependContent(Container='.$this->actions[$action]["Container"].')');
$this->Output(" _e.innerHTML=".$content."+_e.innerHTML;\n");
break;
case "ReplaceContent":
if(strlen($this->debug_console))
$this->DebugOutput($form, 'ReplaceContent(Container='.$this->actions[$action]["Container"].')');
$this->Output(" _e.innerHTML=".$content.";\n");
break;
}
break;
case "SetValue":
if(!IsSet($this->actions[$action]["Element"]))
return("it was not specified the element to set the value");
if(!IsSet($this->actions[$action]["Property"]))
return("it was not specified the property of the element to set");
if(!IsSet($this->actions[$action]["Value"]))
return("it was not specified the property value of the element to set");
switch(IsSet($this->actions[$action]["Type"]) ? $this->actions[$action]["Type"] : "string")
{
case "string":
$value=$form->EncodeJavascriptString($this->actions[$action]["Value"]);
break;
case "number":
case "integer":
case "float":
case "boolean":
case "opaque":
$value=$this->actions[$action]["Value"];
break;
case "null":
case "undefined":
$value=$this->actions[$action]["Type"];
break;
default:
return($this->actions[$action]["Value"]." is not a valid element property value type");
}
if(strlen($this->debug_console))
$this->DebugOutput($form, 'SetValue(Element='.$this->actions[$action]["Element"].', Property='.$this->actions[$action]["Property"].', Value='.$value.')');
$this->Output("if(_g\n&& (_e=_d.getElementById(".$form->EncodeJavascriptString($this->actions[$action]["Element"]).")))\n_e.".$this->actions[$action]["Property"].'='.$value.";\n");
break;
case "Redirect":
if(!IsSet($this->actions[$action]["URL"])
|| strlen($this->actions[$action]["URL"])==0)
return("it was not specified the redirection URL");
if(strlen($this->debug_console))
$this->DebugOutput($form, 'Redirect(URL='.$this->actions[$action]["URL"].')');
$this->Output("_d.location=".$form->EncodeJavascriptString($this->actions[$action]["URL"])."\n");
break;
case "Wait":
if(!IsSet($this->actions[$action]["Time"])
|| doubleval($this->actions[$action]["Time"])==0.0)
return("it was not specified a valid wait time period");
if(strlen($this->debug_console))
$this->DebugOutput($form, 'Wait(Time='.$this->actions[$action]["Time"].')');
$this->SendEndScript($form, 1);
usleep($this->actions[$action]["Time"]*1000000);
$this->SendStartScript();
break;
case "Command":
if(!IsSet($this->actions[$action]["Command"]))
return("it was not specified the command to execute");
if(strlen($this->debug_console))
$this->DebugOutput($form, 'Command(Command='.$this->actions[$action]["Command"].')');
$this->Output($this->actions[$action]["Command"]);
break;
case "Connect":
$to=(IsSet($this->actions[$action]["To"]) ? $this->actions[$action]["To"] : "");
$connect_action=(IsSet($this->actions[$action]["ConnectAction"]) ? $this->actions[$action]["ConnectAction"] : "");
$context=(IsSet($this->actions[$action]["Context"]) ? $this->actions[$action]["Context"] : array());
if(strlen($error=$form->GetJavascriptConnectionAction(($this->sending_ajax_response ? '_p.' : '').$this->submit_form."_f", $this->input, $to, "", $connect_action, $context, $javascript)))
return($error);
if(strlen($this->debug_console))
$this->DebugOutput($form, 'Connect(To='.$to.', ConnectAction='.$connect_action.')');
$this->Output($javascript);
$this->Output("\n");
break;
case "SetInputValue":
if(!IsSet($this->actions[$action]["Input"]))
return("it was not specified the input to set the value");
if(!IsSet($this->actions[$action]["Value"]))
return("it was not specified the value of the input to set");
$input = $this->actions[$action]["Input"];
$value = $this->actions[$action]["Value"];
if(strlen($this->debug_console))
$this->DebugOutput($form, 'SetInputValue(Input='.$input.', Value='.$value.')');
$this->Output($form->GetJavascriptSetInputValue(($this->sending_ajax_response ? '_p.' : '').$this->submit_form."_f", $input, $value));
break;
case "SetInputProperty":
if(!IsSet($this->actions[$action]["Input"]))
return("it was not specified the input to set the value");
if(!IsSet($this->actions[$action]["Property"]))
return("it was not specified the property of the input to set");
if(!IsSet($this->actions[$action]["Value"]))
return("it was not specified the value of the input to set");
$input = $this->actions[$action]["Input"];
$property = $this->actions[$action]["Property"];
$value = $this->actions[$action]["Value"];
if(strlen($this->debug_console))
$this->DebugOutput($form, 'SetInputProperty(Input='.$input.', Property='.$property.', Value='.$value.')');
$this->Output($form->GetJavascriptSetInputProperty(($this->sending_ajax_response ? '_p.' : '').$this->submit_form."_f", $input, $property, $value));
break;
default:
$error = "AJAX action ".$this->actions[$action]["Action"]." is not supported";
if(strlen($this->debug_console))
$this->DebugOutput($form, $error);
return($error);
}
}
Function SendActionFooter(&$form, $end)
{
if($end)
{
if(strlen($this->feedback_element)
&& IsSet($this->complete_feedback))
$this->Output("if(_g\n&&\n(_fb=_d.getElementById(".$form->EncodeJavascriptString($this->feedback_element).")))\n{\n_fb.innerHTML=".$form->EncodeJavascriptString($this->complete_feedback).';'."\n".'}'."\n");
$this->Output("_p.".$this->submit_form."_r=true;\n");
}
$this->SendEndScript($form, !$end);
if($end)
{
$this->Output("</body></html>\n");
flush();
}
}
Function FlushActions(&$form, $more)
{
$this->SendActionHeader($form);
for($error = '', $action = 0; $action<count($this->actions); $action++)
{
if(strlen($error=$this->SendAction($form, $action)))
break;
}
$this->actions=array();
$this->SendActionFooter($form, !$more);
return($error);
}
Function ReplyMessage(&$form, $message, &$processed)
{
if(!$this->sending_ajax_response)
return("the AJAX response is not being sent");
if(!IsSet($message["Event"])
|| (strcmp($message["Event"], "submit")
&& strcmp($message["Event"], "load")))
return("it was specified an invalid message event to reply");
if(IsSet($message["Actions"]))
{
for($new = 0; $new<count($message["Actions"]); $new++)
{
$this->actions[] = $message["Actions"][$new];
if(!strcmp($message["Actions"][$new]["Action"],"Wait"))
{
$this->SendActionHeader($form);
for($action = 0; $action<count($this->actions); $action++)
{
if(strlen($error=$this->SendAction($form, $action)))
return($error);
}
$this->actions=array();
}
}
}
$more = (IsSet($message["More"]) && $message["More"]);
$immediate = (IsSet($message["Immediate"]) && $message["Immediate"]);
if($more)
{
$this->SetupMessage($next_message, $message["Event"]);
if(strlen($error=$form->PostMessage($next_message)))
return($error);
$processed = 0;
}
else
{
$immediate = 1;
$processed = 1;
}
if($immediate
&& strlen($error = $this->FlushActions($form, $more)))
return($error);
if($processed)
$this->sending_ajax_response = 0;
return("");
}
};
?>

View file

@ -0,0 +1,147 @@
<?php
/*
*
* @(#) $Id: form_animation.php,v 1.13 2008/09/07 06:24:27 mlemos Exp $
*
*/
class form_animation_class extends form_custom_class
{
var $server_validate=0;
var $javascript_path='';
Function AddInput(&$form, $arguments)
{
if(IsSet($arguments['JavascriptPath']))
{
$this->javascript_path=$arguments['JavascriptPath'];
if(($length=strlen($this->javascript_path))
&& strcmp($this->javascript_path[$length-1], '/'))
$this->javascript_path.='/';
}
return('');
}
Function AddInputPart(&$form)
{
return('');
}
Function ClassPageHead(&$form)
{
return('<script type="text/javascript" src="'.HtmlSpecialChars($this->javascript_path).'animation.js"></script>'."\n");
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'AddAnimation':
if(!IsSet($context['Effects']))
return('it were not specified any animation effects');
$animation='{ ';
if(IsSet($context['Name']))
$animation.='name: '.$form->EncodeJavascriptString($context['Name']).', ';
if(IsSet($context['Debug'])
&& $context['Debug'])
$animation.='debug: '.intval($context['Debug']).', ';
$animation.='effects: [ ';
for($e = 0; $e<count($context['Effects']); $e++)
{
if(!IsSet($context['Effects'][$e]['Type']))
return('it was not specified the type of animation effect '.$e);
if($e>0)
$animation.=', ';
$type = $context['Effects'][$e]['Type'];
$animation.='{ type: '.$form->EncodeJavascriptString($type);
switch($type)
{
case 'Show':
case 'Hide':
if(IsSet($context['Effects'][$e]['Element']))
$element = $form->EncodeJavascriptString($context['Effects'][$e]['Element']);
elseif(IsSet($context['Effects'][$e]['DynamicElement']))
$element = $context['Effects'][$e]['DynamicElement'];
else
return('it was not specified the element of the '.$type.' effect '.$e);
if(IsSet($context['Effects'][$e]['Visibility']))
{
switch(($visibility = $context['Effects'][$e]['Visibility']))
{
case 'visibility':
case 'display':
break;
default:
return('it was not specified a valid visilibity control mode for '.$type.' effect');
}
}
else
$visibility = 'visibility';
$animation.=', element: '.$element.
', visibility: '.$form->EncodeJavascriptString($visibility);
break;
case 'FadeIn':
case 'FadeOut':
if(IsSet($context['Effects'][$e]['Element']))
$element = $form->EncodeJavascriptString($context['Effects'][$e]['Element']);
elseif(IsSet($context['Effects'][$e]['DynamicElement']))
$element = $context['Effects'][$e]['DynamicElement'];
else
return('it was not specified the element of the '.$type.' effect '.$e);
if(!IsSet($context['Effects'][$e]['Duration']))
return('it was not specified the duration of the '.$type.' effect '.$e);
if(IsSet($context['Effects'][$e]['Visibility']))
{
switch(($visibility = $context['Effects'][$e]['Visibility']))
{
case 'visibility':
case 'display':
break;
default:
return('it was not specified a valid visilibity control mode for '.$type.' effect');
}
}
else
$visibility = 'visibility';
$animation.=', element: '.$element.
', duration: '.doubleval($context['Effects'][$e]['Duration']).
', visibility: '.$form->EncodeJavascriptString($visibility);
break;
case 'CancelAnimation':
if(!IsSet($context['Effects'][$e]['Animation']))
return('it was not specified the animation of the cancel-animation effect '.$e);
$animation.=', animation: '.$form->EncodeJavascriptString($context['Effects'][$e]['Animation']);
break;
case 'AppendContent':
case 'PrependContent':
case 'ReplaceContent':
if(!IsSet($context['Effects'][$e]['Element']))
return('it was not specified the element of the '.$type.' effect '.$e);
if(!IsSet($context['Effects'][$e]['Content']))
return('it was not specified the content of the '.$type.' effect '.$e);
$animation.=', element: '.$form->EncodeJavascriptString($context['Effects'][$e]['Element']);
$animation.=', content: '.$form->EncodeJavascriptString($context['Effects'][$e]['Content']);
break;
case 'Wait':
if(!IsSet($context['Effects'][$e]['Duration']))
return('it was not specified the duration of the '.$type.' effect '.$e);
$animation.=', duration: '.doubleval($context['Effects'][$e]['Duration']);
break;
default:
return('animation effect of type '.$type.' is not yet supported');
}
$animation.=' }';
}
$animation.=' ] }';
$w=(IsSet($context['Window']) ? $context['Window'].'.' : '');
$javascript='var a=new '.$w.'ML.Animation.Animate(); a.addAnimation('.$animation.');';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
};
?>

View file

@ -0,0 +1,452 @@
<?php
/*
*
* @(#) $Id: form_auto_complete.php,v 1.24 2012/06/22 02:51:44 mlemos Exp $
*
*/
class form_auto_complete_class extends form_custom_class
{
var $text='';
var $complete='';
var $ajax='';
var $minimum_complete=3;
var $dynamic=1;
var $complete_delay=500;
var $complete_values=array();
var $menu_style='background-color: #ffffff; border-width: 1px; border-color: #000000; border-style: solid; padding: 1px;';
var $menu_class='';
var $item_style='padding: 1px; color: #000000;';
var $item_class='';
var $selected_item_style='padding: 1px; color: #ffffff; background-color: #000080;';
var $selected_item_class='';
var $button='';
var $server_validate=0;
var $item_style_attributes='';
Function SerializeItems(&$form, $items)
{
Reset($items);
for($results='[', $f = 0; $f<count($items); Next($items), $f++)
{
if($f>0)
$results.=', ';
$v=Key($items);
$results.='{ "v": '.$form->EncodeJavascriptString($v).', "e": '.$form->EncodeJavascriptString($form->EncodeJavascriptString(HtmlSpecialChars($v))).', "d": '.$form->EncodeJavascriptString($items[$v]).' }';
}
return($results.']');
}
Function GetCompleteValues(&$form, $arguments)
{
if(!IsSet($arguments['CompleteValues'])
|| GetType($complete_values=$arguments['CompleteValues'])!='array'
|| count($complete_values)==0)
return('it were not specified valid complete values');
$this->complete_values=$complete_values;
return('');
}
Function SearchCompleteValues(&$form, $text, &$found)
{
if(strlen($text)==0)
$found=$this->complete_values;
else
{
$t=strtolower($text);
for($found=array(), Reset($this->complete_values), $v=0; $v<count($this->complete_values); $v++, Next($this->complete_values))
{
$c=Key($this->complete_values);
if(!strcmp($t, strtolower(substr($c, 0, strlen($t)))))
$found[$c]=$this->complete_values[$c];
}
}
return('');
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['CompleteInput'])
|| strlen($arguments['CompleteInput'])==0)
return('it was not specified a valid text input to complete');
$this->text=$arguments['CompleteInput'];
if(IsSet($arguments['CompleteMinimumLength']))
{
$minimum_complete=intval($arguments['CompleteMinimumLength']);
if($minimum_complete<=0)
return('it was not specified a valid minimum length to complete the text');
$this->minimum_complete=$minimum_complete;
}
if(IsSet($arguments['CompleteDelay']))
{
$complete_delay=intval($arguments['CompleteDelay']*1000);
if($complete_delay<=0)
return('it was not specified a valid complete delay period');
$this->complete_delay=$complete_delay;
}
if(IsSet($arguments['ShowButton']))
{
$button=$arguments['ShowButton'];
if(strlen($button)==0)
return('it was not specified a valid button input to show all options');
$this->button=$button;
}
if(IsSet($arguments['Dynamic'])
&& !$arguments['Dynamic'])
$this->dynamic=0;
if(IsSet($arguments['MenuClass']))
$this->menu_class=$arguments['MenuClass'];
if(IsSet($arguments['MenuStyle']))
$this->menu_style=$arguments['MenuStyle'];
if(IsSet($arguments['ItemClass']))
$this->item_class=$arguments['ItemClass'];
if(IsSet($arguments['ItemStyle']))
$this->item_style=$arguments['ItemStyle'];
if(IsSet($arguments['SelectedItemClass']))
$this->selected_item_class=$arguments['SelectedItemClass'];
if(IsSet($arguments['SelectedItemStyle']))
$this->selected_item_style=$arguments['SelectedItemStyle'];
$this->complete=$this->GenerateInputID($form, $this->input, '_');
if($this->dynamic)
{
$this->ajax=$this->complete.'ajax';
$ajax_arguments=array(
'TYPE'=>'custom',
'NAME'=>$this->ajax,
'ID'=>$this->ajax,
'CustomClass'=>'form_ajax_submit_class',
'TargetInput'=>$this->input
);
if(IsSet($arguments['Timeout']))
$ajax_arguments['Timeout']=intval($arguments['Timeout']);
if(IsSet($arguments['FeedbackElement']))
{
$ajax_arguments['FeedbackElement']=$arguments['FeedbackElement'];
if(IsSet($arguments['SubmitFeedback']))
$ajax_arguments['SubmitFeedback']=$arguments['SubmitFeedback'];
if(IsSet($arguments['TimeoutFeedback']))
{
$ajax_arguments['TimeoutFeedback']=$arguments['TimeoutFeedback'];
$ajax_arguments['ONTIMEOUT']='';
}
if(IsSet($arguments['CompleteFeedback']))
$ajax_arguments['CompleteFeedback']=$arguments['CompleteFeedback'];
}
}
if(strlen($error=$this->GetCompleteValues($form, $arguments)))
return($error);
if((!$this->dynamic
|| (strlen($error=$form->AddInput($ajax_arguments))==0
&& strlen($error=$form->Connect($this->ajax, $this->input, 'ONCOMPLETE', 'Reposition', array()))==0))
&& (strlen($this->button)==0
|| ((!$this->dynamic
|| strlen($error=$form->AddInput(array(
'TYPE'=>'hidden',
'NAME'=>$this->complete.'t',
'ID'=>$this->complete.'t',
'VALUE'=>''
)))==0)
&& strlen($error=$form->Connect($this->button, $this->input, 'ONCLICK', 'Show', array()))==0))
&& strlen($error=$form->Connect($this->text, $this->input, 'ONBLUR', 'Hide', array('Delay'=>0.2)))==0
&& strlen($error=$form->Connect($this->text, $this->input, 'ONKEYDOWN', 'ControlKeys', array()))==0)
$error=$form->Connect($this->text, $this->input, 'ONKEYUP', 'Complete', array());
return($error);
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'Complete':
$value=$form->GetJavascriptInputValue($form_object, $this->text);
if(strlen($value)==0)
return('it was not possible to determine how to retrieve value of '.$this->text);
$javascript='if('.(strcmp($event,'ONKEYUP') ? '' : 'event.keyCode!=40 && event.keyCode!=38 && event.keyCode!=27 && event.keyCode!=13 && ').$value.'.length>='.$this->minimum_complete.'){ '.$this->complete.'w++; '.$this->complete.'f='.$form_object.'; setTimeout('."'".$this->complete."()',".$this->complete_delay.'); return false;};';
break;
case 'Hide':
$javascript=$this->complete.'h();';
$delay=(IsSet($context['Delay']) ? intval($context['Delay']*1000) : 0);
if($delay)
$javascript='setTimeout('.$form->EncodeJavascriptString($javascript).', '.$delay.');';
break;
case 'Show':
if($this->dynamic)
{
$submit_context=array('Validate'=>0);
if(strlen($error=$form->GetJavascriptConnectionAction($form_object, $this->input, $this->ajax, 'ONSHOW', 'Submit', $submit_context, $complete_javascript)))
return($error);
$javascript=$this->complete.'f='.$form_object.'; '.$form->GetJavascriptSetInputValue($this->complete.'f', $this->complete.'t', $form->EncodeJavascriptString('a')).' '.$complete_javascript.';';
}
else
$javascript=$this->complete.'f='.$form_object.'; '.$this->complete.'bm('.$this->complete.'i, false); '.$form->GetJavascriptInputObject($form_object, $this->text).'.focus();';
$javascript='if(!'.$this->complete.'o) {'.$javascript.'} return false;';
break;
case 'Reposition':
$javascript=$this->complete.'rp(document.getElementById('.$form->EncodeJavascriptString($this->complete.'m').'), '.$form->GetJavascriptInputObject($form_object, $this->text).');';
break;
case 'ControlKeys':
$javascript='if('.$this->complete.'o) { if(event.keyCode==40 && '.$this->complete.'is<'.$this->complete.'co.length-1) { '.$this->complete.'si('.$this->complete.'is+1); '.$this->complete.'so(t,'.$this->complete.'is); return false; } if(event.keyCode==38 && '.$this->complete.'is>0) { '.$this->complete.'si('.$this->complete.'is-1);'.$this->complete.'so(t,'.$this->complete.'is); return false; } if(event.keyCode==27) { '.$this->complete.'h(); return false; } if(event.keyCode==13) { '.$this->complete.'h(); return true; } };';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
Function AddInputPart(&$form)
{
if($this->dynamic)
{
$submit_context=array('Validate'=>0);
if(strlen($error=$form->GetJavascriptConnectionAction($this->complete.'f', $this->input, $this->ajax, 'ONCOMPLETE', 'Submit', $submit_context, $complete_javascript)))
return($error);
}
$eol=$form->end_of_line;
$b="\n";
$item_style=(strlen($this->item_style) ? $this->item_style : ';');
$selected_item_style=(strlen($this->selected_item_style) ? $this->selected_item_style : ';');
if(strlen($this->item_style_attributes)==0)
{
$this->item_style_attributes=(strlen($this->item_class) ? ' class="'.HtmlSpecialChars($this->item_class).'"' : '').((strlen($this->item_style) || strlen($this->selected_item_style)) ? ' style="'.HtmlSpecialChars($item_style).'"' : '');
}
$menu=$form->EncodeJavascriptString($this->complete.'m');
$text_object = $form->GetJavascriptInputObject($this->complete.'f', $this->text);
$html='<div id="'.HtmlSpecialChars($this->complete.'m').'"'.(strlen($this->menu_class) ? ' class="'.HtmlSpecialChars($this->menu_class).'"' : '').' style="display: block; position: absolute; overflow: auto; visibility: hidden;'.HtmlSpecialChars($this->menu_style).'"></div>'.$b.
'<script type="text/javascript" defer="defer">'.$eol.'<!--'."\n".
'var '.$this->complete.'w=0;'.$b.
'var '.$this->complete.'s=\'\';'.$b.
'var '.$this->complete.'f;'.$b.
'var '.$this->complete.'i'.($this->dynamic ? '' : '='.$this->SerializeItems($form, $this->complete_values)).';'.$b.
'var '.$this->complete.'is=-1;'.$b.
'var '.$this->complete.'o=false;'.$b.
'var '.$this->complete.'co=[];'.$b.
'var '.$this->complete.'l=0;'.$b.
(
$this->dynamic
?
'var '.$this->complete.'c={};'.$b
:
''
).
$eol.
'function '.$this->complete.'()'.$b.
'{'.$b.
'if(--'.$this->complete.'w==0)'.$b.
'{'.$b.
's='.$form->GetJavascriptInputValue($this->complete.'f', $this->text).'.toLowerCase();'.$b.
'if('.$this->complete.'s!=s)'.$b.
'{'.$b.
'm=document.getElementById('.$menu.');'.$b.
'm.style.visibility=\'hidden\'; '.$b.
$this->complete.'o=false;'.$b.
$this->complete.'is=-1;'.$b.
'if(s.length>='.$this->minimum_complete.')'.$b.
'{'.$b.
(
$this->dynamic
?
'if('.$this->complete.'c[s])'.$b.
'{'.$b.
$this->complete.'s=s;'.$b.
$this->complete.'bm('.$this->complete.'c[s], true);'.$b.
'}'.$b.
'else'.$b.
'{'.$b.
$this->complete.'s=s;'.$b.
(
strlen($this->button)
?
$form->GetJavascriptSetInputValue($this->complete.'f', $this->complete.'t', $form->EncodeJavascriptString('')).$b
:
''
).
$complete_javascript.
'}'.$b
:
'o=[];'.$b.
'for (var i=0; i<'.$this->complete.'i.length; i++)'.$b.
'{'.$b.
'if('.$this->complete.'i[i].v.toLowerCase().substr(0,s.length)==s)'.$b.
'o[o.length]='.$this->complete.'i[i];'.$b.
'}'.$b.
'if(o.length)'.$b.
''.$this->complete.'bm(o, true);'.$b
).
'}'.$b.
'}'.$b.
'}'.$b.
'}'.$eol.
'function '.$this->complete.'ss(e,s)'.$b.
'{'.$b.
'if(e.currentStyle)'.$b.
'{'.$b.
'e.style.cssText=s;'.$b.
'}'.$b.
'else'.$b.
'{'.$b.
'e.setAttribute(\'style\', s);'.$b.
'}'.$b.
'}'.$eol.
'function '.$this->complete.'rp(m,t)'.$b.
'{'.$b.
'if(document.getBoxObjectFor)'.$b.
'{'.$b.
'b=document.getBoxObjectFor(t);'.$b.
'x=b.x;'.$b.
'y=b.y+b.height;'.$b.
'w=b.width;'.$b.
'if(window.getComputedStyle)'.$b.
'{'.$b.
's=window.getComputedStyle(t,null);'.$b.
'x-=parseInt(s.borderLeftWidth);'.$b.
'y-=parseInt(s.borderTopWidth);'.$b.
'w-=parseInt(s.borderLeftWidth)+parseInt(s.borderRightWidth);'.$b.
's=window.getComputedStyle(m,null);'.$b.
'w+=parseInt(s.borderLeftWidth)+parseInt(s.borderRightWidth)-parseInt(s.paddingLeft)-parseInt(s.paddingRight);'.$b.
'}'.$b.
'}'.$b.
'else'.$b.
'{'.$b.
'p=t.style.position;'.$b.
't.style.position="relative";'.$b.
'x=t.offsetLeft;'.$b.
'y=t.offsetTop+t.offsetHeight;'.$b.
'w=t.offsetWidth;'.$b.
't.style.position=p;'.$b.
'}'.$b.
'm.style.left=x+"px";'.$b.
'm.style.top=y+"px";'.$b.
'm.style.width=w+"px";'.$b.
'}'.$eol.
'function '.$this->complete.'si(i)'.$b.
'{'.$b.
'if('.$this->complete.'is!=-1)'.$b.
'{'.$b.
's=document.getElementById('.$form->EncodeJavascriptString($this->complete.'m').' + '.$this->complete.'is);'.$b.
((strlen($this->item_class) || strlen($this->selected_item_class)) ? 's.className='.$form->EncodeJavascriptString($this->item_class).';'.$b : '').
((strlen($this->item_style) || strlen($this->selected_item_style)) ? $this->complete.'ss(s, '.$form->EncodeJavascriptString($item_style).');'.$b : '').
'}'.$b.
'if(i!=-1)'.$b.
'{'.$b.
's=document.getElementById('.$form->EncodeJavascriptString($this->complete.'m').' + i);'.$b.
((strlen($this->selected_item_class) || strlen($this->item_class)) ? 's.className='.$form->EncodeJavascriptString($this->selected_item_class).';'.$b : '').
((strlen($this->selected_item_style) || strlen($this->item_style)) ? $this->complete.'ss(s, '.$form->EncodeJavascriptString($selected_item_style).');'.$b : '').
'}'.$b.
$this->complete.'is=i;'.$b.
'}'.$eol.
'function '.$this->complete.'so(t,i)'.$b.
'{'.$b.
'o='.$this->complete.'co;'.$b.
$this->complete.'si(i);'.$b.
'var b=t.value;'.$b.
't.value=o[i].v;'.$b.
'if(b != t.value && t.onchange)'.$b.
' t.onchange()'.$b.
'if(t.createTextRange)'.$b.
'{'.$b.
'if(r=t.createTextRange())'.$b.
'{'.$b.
'r.collapse(true);'.$b.
'r.moveEnd(\'character\', o[i].v.length);'.$b.
'r.moveStart(\'character\', '.$this->complete.'l);'.$b.
'r.select();'.$b.
'}'.$b.
'}'.$b.
'else'.$b.
'{'.$b.
'if(t.setSelectionRange)'.$b.
't.setSelectionRange('.$this->complete.'l,o[i].v.length);'.$b.
'else'.$b.
'{'.$b.
't.selectionStart='.$this->complete.'l;'.$b.
't.selectionEnd=o[i].v.length;'.$b.
'}'.$b.
'}'.$b.
'}'.$eol.
'function '.$this->complete.'bm(o, sv)'.$b.
'{'.$b.
'for(d=\'\',i=0; i<o.length; i++)'.$b.
'{'.$b.
'd+='.$form->EncodeJavascriptString('<div id="'.$this->complete.'m').' + i + '.$form->EncodeJavascriptString('"'.$this->item_style_attributes.' onmouseover="'.$this->complete.'si(').' + i +'.$form->EncodeJavascriptString(');" onmouseout="'.$this->complete.'si(-1);" onmousedown="'.$this->complete.'s=\'\'; var b='.$text_object.'.value;'.$text_object.'.value=').'+o[i].e+'.$form->EncodeJavascriptString('; document.getElementById('.$menu.').style.visibility=\'hidden\';'.$this->complete.'o=false; '.$this->complete.'is=-1; if('.$text_object.'.value != b && '.$text_object.'.onchange) '.$text_object.'.onchange();">').'+o[i].d+'.$form->EncodeJavascriptString('</div>'.$b).';'.$b.
'}'.$b.
'm=document.getElementById('.$menu.');'.$b.
'm.innerHTML=d;'.$b.
't='.$text_object.';'.$b.
$this->complete.'rp(m,t);'.$b.
'm.style.visibility=\'visible\';'.$b.
$this->complete.'o=true;'.$b.
$this->complete.'co=o;'.$b.
'if(sv)'.$b.
'{'.$b.
$this->complete.'l=t.value.length'.$b.
$this->complete.'so(t,0);'.$b.
'}'.$b.
'else'.$b.
'{'.$b.
$this->complete.'l=0'.$b.
$this->complete.'is=-1;'.$b.
'}'.$b.
'}'.$eol.
'function '.$this->complete.'h()'.$b.
'{'.$b.
$this->complete.'s=\'\';'.$b.
'm=document.getElementById('.$form->EncodeJavascriptString($this->complete.'m').');'.$b.
'm.style.visibility=\'hidden\';'.$b.
$this->complete.'o=false;'.$b.
$this->complete.'is=-1;'.$b.
'}'.$eol.
'// -->'.$eol.'</script>';
if(strlen($error=$form->AddDataPart($html))
|| ($this->dynamic
&& strlen($error=$form->AddInputPart($this->ajax)))
|| (strlen($this->button)
&& (strlen($error=$form->AddInputPart($this->button))
|| ($this->dynamic
&& strlen($error=$form->AddInputPart($this->complete.'t'))))))
return($error);
return('');
}
Function Connect(&$form, $to, $event, $action, &$context)
{
switch($action)
{
case 'Complete':
case 'Hide':
case 'Show':
case 'ControlKeys':
return('');
default:
return($this->DefaultConnect($form, $to, $event, $action, $context));
}
}
Function PostMessage(&$form, $message, &$processed)
{
if(strlen($error = $form->LoadInputValues()))
return($error);
$text=$form->GetInputValue($this->text);
$all=(strlen($this->button) && !strcmp($form->GetInputValue($this->complete.'t'), 'a'));
$found=array();
if(($all
|| strlen($text)>=$this->minimum_complete)
&& strlen($error=$this->SearchCompleteValues($form, $s=($all ? '' : strtolower($text)), $found)))
$form->OutputError($error, $this->input);
elseif(count($found))
{
$results=$this->SerializeItems($form, $found);
$s=$form->EncodeJavascriptString($s);
$command=$message['Window'].'.'.$this->complete.'i='.$message['Window'].'.'.$this->complete.'c['.$s.']='.$results.'; if('.$message['Window'].'.'.$this->complete.'s.toLowerCase()=='.$s.') {'.$message['Window'].'.'.$this->complete.'bm('.$message['Window'].'.'.$this->complete.'i, '.($all ? 'false' : 'true').'); '.$form->GetJavascriptInputObject($message['Form'], $this->text).'.focus();}';
$message['Actions']=array(
array(
'Action'=>'Command',
'Command'=>$command
)
);
}
return($form->ReplyMessage($message, $processed));
}
};
?>

View file

@ -0,0 +1,456 @@
<?php
/*
*
* @(#) $Id: form_captcha.php,v 1.23 2012/07/14 08:39:44 mlemos Exp $
*
*/
class form_captcha_class extends form_custom_class
{
var $format="{image} {text} {redraw}{validation}";
var $image_parameter="___image";
var $image_width=80;
var $image_height=20;
var $image_align="top";
var $image_format="gif";
var $verification_style="";
var $verification_class="";
var $text_color="#000000";
var $background_color="";
var $noise_image="";
var $noise_image_format="";
var $text_length=4;
var $text_characters="0123456789abcdefghijklmnopqrstuvwxyz";
var $font=2;
var $expiry_time=0;
var $expiry_time_validation_error_message="";
var $validation_error_message="It was not entered the correct text.";
var $reset_incorrect_text=0;
var $key="";
var $text="";
var $redraw_text="Redraw";
var $redraw_sub_form="redraw";
var $validation="";
var $loaded_text="";
var $remaining_time=0;
var $requirements=array(
"imagecreate"=>"the GD extension is not available",
"imagegif"=>"the GD extension is not able to save in the GIF format",
"imagecreatefromgif"=>"the GD extension is not able to read image files in the GIF format",
"mcrypt_cfb"=>"the mcrypt extension is not available"
);
Function CheckRequirements()
{
if(IsSet($this->requirements["imagegif"])
&& strcmp($this->image_format,"gif"))
{
$this->requirements["image".$this->image_format]="the GD extension is not able to save in the ".strtoupper($this->image_format)." format";
UnSet($this->requirements["imagegif"]);
}
if(IsSet($this->requirements["imagecreatefromgif"])
&& strcmp($this->noise_image_format,"gif"))
{
if(strlen($this->noise_image_format))
$this->requirements["imagecreatefrom".$this->noise_image_format]="the GD extension is not able to read image files in the ".strtoupper($this->noise_image_format)." format";
UnSet($this->requirements["imagecreatefromgif"]);
}
Reset($this->requirements);
$end=(GetType($function=Key($this->requirements))!="string");
for(;!$end;)
{
if(!function_exists($function))
return($this->requirements[$function]);
Next($this->requirements);
$end=(GetType($function=Key($this->requirements))!="string");
}
return("");
}
Function EncodeText($text)
{
$encode_time=time();
$iv_size=mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$iv=str_repeat(chr(0),$iv_size);
$key_size=mcrypt_get_key_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$key=$encode_time.$this->key;
if(strlen($key)>$key_size)
$key=substr($key,0,$key_size);
return(base64_encode(mcrypt_cfb(MCRYPT_3DES,$key,$text,MCRYPT_ENCRYPT,$iv)).":".$encode_time);
}
Function DecodeText($encoded, &$encode_time)
{
if(GetType($colon=strpos($encoded,":"))!="integer"
|| ($encode_time=intval(substr($encoded,$colon+1)))==0
|| $encode_time>time()
|| !($encrypted=base64_decode(substr($encoded,0,$colon))))
return("");
$iv_size=mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$iv=str_repeat(chr(0),$iv_size);
$key_size=mcrypt_get_key_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$key=$encode_time.$this->key;
if(strlen($key)>$key_size)
$key=substr($key,0,$key_size);
return(mcrypt_cfb(MCRYPT_3DES,$key,$encrypted,MCRYPT_DECRYPT,$iv));
}
Function GenerateText()
{
for($text="",$c=0;$c<$this->text_length;$c++)
$text.=substr($this->text_characters,rand(0,strlen($this->text_characters)-1),1);
return($text);
}
Function ValidateText($text)
{
if(strlen($text) != $this->text_length)
return('the verification text length is not '.$this->text_length.' as required');
for($c=0;$c<$this->text_length;$c++)
if(GetType(strpos($this->text_characters,$text[$c])) != 'integer')
return('the character '.$c.' of the verification text is invalid');
return('');
}
Function SetKey(&$form,$encrypted,$format)
{
if(strlen($error=$form->GetInputEventURL($this->input,"getimage",array($this->image_parameter=>$encrypted),$image_url)))
return($error);
$this->valid_marks["data"]["image"]="<img alt=\"CAPTCHA image\" width=\"".$this->image_width."\" height=\"".$this->image_height."\"".(strlen($this->image_align) ? " align=\"".$this->image_align."\"" : "").(strlen($this->verification_style) ? " style=\"".$this->verification_style."\"" : "").(strlen($this->verification_class) ? " class=\"".$this->verification_class."\"" : "")." src=\"".HtmlEntities($image_url)."\" />";
if(strlen($error=$form->SetInputValue($this->validation,$encrypted)))
return($error);
return($this->DefaultSetInputProperty($form, "Format", $format));
}
Function DrawNoiseImage($image,$noise_image,$noise_image_format)
{
$function="imagecreatefrom".$noise_image_format;
if(!@($noise=$function($noise_image)))
return("could not read the noise ".strtoupper($noise_image_format)." image file ".$noise_image);
$width=imagesx($noise);
$height=imagesy($noise);
$offset_x=-rand(0,$width/2);
$offset_y=-rand(0,$height/2);
for($x=$offset_x;$x<$this->image_width;$x+=$width)
for($y=$offset_y;$y<$this->image_height;$y+=$height)
imagecopy($image,$noise,$x,$y,0,0,$width,$height);
imagedestroy($noise);
return("");
}
Function ClearImage($image,$color)
{
$rgb=(strlen($color) ? $color : "#FFFFFF");
if(($background_color=imagecolorallocate($image, HexDec(substr($rgb,1,2)), HexDec(substr($rgb,3,2)), HexDec(substr($rgb,5,2))))==-1)
return("could not allocate the background color");
if(strlen($color)==0)
$background_color=imagecolortransparent($image,$background_color);
imagefilledrectangle($image, 0, 0, $this->image_width-1, $this->image_height-1, $background_color);
return("");
}
Function DrawText($image,$text,$color)
{
$rgb=(strlen($color) ? $color : "#000000");
if(($text_color=imagecolorallocate($image, HexDec(substr($rgb,1,2)), HexDec(substr($rgb,3,2)), HexDec(substr($rgb,5,2))))==-1)
return("could not allocate the text color");
if(strlen($color)==0)
$text_color=imagecolortransparent($image,$text_color);
$text_width=strlen($text)*imagefontwidth($this->font);
$text_height=imagefontheight($this->font);
imagestring($image, $this->font, rand(0,$this->image_width-$text_width), rand(0,$this->image_height-$text_height), $text, $text_color);
return("");
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case "TextLength":
case "ImageWidth":
case "ImageHeight":
if(strcmp($value,intval($value))
|| intval($value)<=0)
return("it was not specified a valid ".$property." value");
switch($property)
{
case "TextLength":
$this->text_length=intval($value);
break;
case "ImageWidth":
$this->image_width=intval($value);
break;
case "ImageHeight":
$this->image_height=intval($value);
break;
}
break;
case "Font":
if(strcmp($value,intval($value))
|| intval($value)<0)
return("it was not specified a valid ".$property." value");
$this->font=intval($value);
break;
case "TextColor":
case "BackgroundColor":
if(!preg_match('/^#[0-9a-fA-F]{6}$/', $value))
return("it was not specified a valid ".$property." value");
switch($property)
{
case "TextColor":
$this->text_color=$value;
break;
case "BackgroundColor":
$this->background_color=$value;
break;
}
break;
case "ImageFormat":
switch($value)
{
case "gif":
case "jpeg":
case "png":
$this->image_format=$value;
break;
default:
return($value." is not a supported image format");
}
break;
case "ImageAlign":
$this->image_align=$value;
break;
case "VerificationStyle":
$this->verification_style=$value;
break;
case "VerificationClass":
$this->verification_class=$value;
break;
case "NoiseFromGIFImage":
$this->noise_image=$value;
$this->noise_image_format="gif";
break;
case "NoiseFromPNGImage":
$this->noise_image=$value;
$this->noise_image_format="png";
break;
case "RedrawText":
if(strlen($value)==0)
return("it was not specified a valid redraw button text value");
$this->redraw_text=$value;
break;
case "RedrawSubForm":
if(strlen($value)==0)
return("it was not specified a valid redraw button sub-form value");
$this->redraw_sub_form=$value;
break;
case "ResetIncorrectText":
$this->reset_incorrect_text=(intval($value)!=0);
break;
case 'VALUE':
if(strlen($value))
{
if(strlen($error = $this->ValidateText($value)))
return($error);
}
else
$value = $this->GenerateText();
$form->SetInputValue($this->text, $this->loaded_text = '');
return($this->SetKey($form,$this->EncodeText($value),$this->format));
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
Function SetInputProperties(&$form, $arguments)
{
$properties=array(
"TextLength",
"TextColor",
"BackgroundColor",
"ImageFormat",
"ImageHeight",
"ImageWidth",
"ImageAlign",
"VerificationStyle",
"VerificationClass",
"NoiseFromGIFImage",
"NoiseFromJPEGImage",
"NoiseFromPNGImage",
"RedrawText",
"RedrawSubForm",
"Font",
"ResetIncorrectText",
);
for($property=0; $property<count($properties); $property++)
{
$name=$properties[$property];
if(IsSet($arguments[$name])
&& strlen($error=$this->SetInputProperty($form,$name,$arguments[$name])))
return($error);
}
return("");
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments["Key"])
|| strlen($arguments["Key"])==0)
return("it was not specified a valid key");
$this->key=$arguments["Key"];
if(IsSet($arguments["ExpiryTime"]))
{
if(($this->expiry_time=intval($arguments["ExpiryTime"]))<=0)
return("it was not specified a valid expiry time value");
if(IsSet($arguments["ExpiryTimeValidationErrorMessage"])
&& strlen($arguments["ExpiryTimeValidationErrorMessage"]))
$this->expiry_time_validation_error_message=$arguments["ExpiryTimeValidationErrorMessage"];
else
return("it was not specified a valid expiry time validation error message");
}
if(IsSet($arguments["ValidationErrorMessage"])
&& strlen($arguments["ValidationErrorMessage"]))
$this->validation_error_message=$arguments["ValidationErrorMessage"];
else
return("it was not specified a valid validation error message");
if(strlen($error=$this->SetInputProperties($form,$arguments)))
return($error);
if(strlen($error=$this->CheckRequirements()))
return($error);
$this->text=$this->GenerateInputID($form, $this->input, "text");
$this->redraw=$this->GenerateInputID($form, $this->input, "redraw");
$this->validation=$this->GenerateInputID($form, $this->input, "validation");
$this->valid_marks=array(
"input"=>array(
"text"=>$this->text,
"redraw"=>$this->redraw,
"validation"=>$this->validation
),
"data"=>array(
"image"=>""
)
);
$input_arguments=array(
"NAME"=>$this->text,
"ID"=>$this->text,
"TYPE"=>"text",
"ValidateAsNotEmpty"=>1,
"ValidationErrorMessage"=>$this->validation_error_message,
"ONKEYPRESS"=>"return(event.keyCode!=13)"
);
if(IsSet($arguments['DependentValidation']))
$input_arguments['DependentValidation'] = $arguments['DependentValidation'];
if(IsSet($arguments["InputClass"]))
$input_arguments["CLASS"]=$arguments["InputClass"];
if(IsSet($arguments["InputStyle"]))
$input_arguments["STYLE"]=$arguments["InputStyle"];
if(IsSet($arguments["InputTabIndex"]))
$input_arguments["TABINDEX"]=$arguments["InputTabIndex"];
if(IsSet($arguments["InputExtraAttributes"]))
$input_arguments["ExtraAttributes"]=$arguments["InputExtraAttributes"];
if(strlen($error=$form->AddInput($input_arguments)))
return($error);
$redraw_arguments=array(
"NAME"=>$this->redraw,
"ID"=>$this->redraw,
"TYPE"=>"submit",
"VALUE"=>$this->redraw_text,
"SubForm"=>$this->redraw_sub_form
);
if(IsSet($arguments["RedrawClass"]))
$redraw_arguments["CLASS"]=$arguments["RedrawClass"];
if(IsSet($arguments["RedrawStyle"]))
$redraw_arguments["STYLE"]=$arguments["RedrawStyle"];
if(strlen($error=$form->AddInput($redraw_arguments)))
return($error);
if(strlen($error=$form->AddInput(array(
"NAME"=>$this->validation,
"ID"=>$this->validation,
"TYPE"=>"hidden",
"VALUE"=>""
))))
return($error);
if(IsSet($arguments["Format"]))
$this->format = $arguments["Format"];
if(IsSet($arguments['VALUE'])
&& strlen($text = $arguments['VALUE']))
{
if(strlen($error = $this->ValidateText($text)))
return($error);
}
else
$text = $this->GenerateText();
return($this->SetKey($form,$this->EncodeText($text),$this->format));
}
Function LoadInputValues(&$form, $submitted)
{
if(IsSet($form->Changes[$this->validation]))
{
$encrypted=$form->GetInputValue($this->validation);
$this->loaded_text=$this->DecodeText($encrypted,$encode_time);
$this->remaining_time=$encode_time+$this->expiry_time-time();
if(strlen($this->loaded_text)==$this->text_length
&& ($this->expiry_time==0
|| $this->remaining_time>0))
$this->SetKey($form, $encrypted,$this->format);
else
{
$form->SetInputValue($this->validation,$form->Changes[$this->validation]);
$this->loaded_text="";
}
}
return('');
}
Function ValidateInput(&$form)
{
if($this->expiry_time
&& $this->remaining_time<=0)
return($this->expiry_time_validation_error_message);
if(strcmp($this->loaded_text,$form->GetInputValue($this->text)))
{
if($this->reset_incorrect_text)
{
$this->SetKey($form,$this->EncodeText($this->GenerateText()),$this->format);
$form->SetInputValue($this->text, $this->loaded_text="");
}
return($this->validation_error_message);
}
return("");
}
Function HandleEvent(&$form, $event, $parameters, &$processed)
{
switch($event)
{
case "getimage":
if(!IsSet($parameters[$this->image_parameter]))
return("the image parameter is not being passed to the captcha input getimage event handler");
$text=$this->DecodeText(strval($parameters[$this->image_parameter]),$encode_time);
if(!($image=imagecreate($this->image_width,$this->image_height)))
return("could not create the CAPTCHA image");
if(strlen($error=$this->ClearImage($image,$this->background_color)))
return($error);
if(strlen($this->noise_image)
&& strlen($error=$this->DrawNoiseImage($image,$this->noise_image,$this->noise_image_format)))
return($error);
if(strlen($error=$this->DrawText($image,$text,$this->text_color)))
return($error);
Header("Content-Type: image/".$this->image_format);
$function="image".$this->image_format;
$function($image);
imagedestroy($image);
$processed=1;
break;
default:
return($this->DefaultHandleEvent($form,$event,$parameters,$processed));
}
return("");
}
};
?>

View file

@ -0,0 +1,351 @@
<?php
/*
*
* @(#) $Id: form_crud.php,v 1.16 2014/02/07 06:29:57 mlemos Exp $
*
*/
class form_crud_data_source_class
{
var $crud = '';
var $scaffolding_input = '';
var $placeholder_start = '{';
var $placeholder_end = '}';
var $placeholder_section_end = '{/';
var $entry_template = 'the entry template was not defined';
var $entry_template_properties = array(
);
Function Initialize(&$form, $arguments)
{
return('');
}
Function Finalize(&$form)
{
}
Function GetListing(&$form, &$listing)
{
return('data source object does not implement the GetListing function');
}
Function InitializeEntry(&$form, &$entry, &$invalid, &$values)
{
$invalid = 0;
return('');
}
Function GetEntry(&$form, &$entry, &$invalid, &$values)
{
return('data source object does not implement the GetEntry function');
}
Function GetSaveInputs(&$form, &$inputs)
{
return($form->GetInputProperty($this->scaffolding_input, 'EntryFieldNames', $inputs));
}
Function SaveEntry(&$form, $creating, &$entry, &$values)
{
return('data source object does not implement the SaveEntry function');
}
Function ViewEntry(&$form, &$entry, &$values)
{
$output = $this->entry_template;
$s = $this->placeholder_start;
$e = $this->placeholder_end;
$se = $this->placeholder_section_end;
$properties = $this->entry_template_properties;
$tv = count($properties);
for($v = 0, Reset($properties); $v < $tv; Next($properties), ++$v)
{
$p = Key($properties);
if(IsSet($properties[$p]['ConditionalSection']))
$output = preg_replace('/'.str_replace('/', '\\/', preg_quote($s.$p.$e)).'(.*)'.str_replace('/', '\\/', preg_quote($se.$p.$e)).'/', IsSet($values[$p]) ? '\\1' : '', $output);
}
$tv = count($values);
for($v = 0, Reset($values); $v < $tv; Next($values), ++$v)
{
$placeholder = Key($values);
$value = $values[$placeholder];
if(!IsSet($properties[$placeholder]['HTML'])
|| $properties[$placeholder]['HTML'])
$value = nl2br(HtmlSpecialChars($value));
$output = str_replace($s.$placeholder.$e, $value, $output);
}
$entry['EntryOutput'] = $output;
return('');
}
Function DeleteEntry(&$form, &$entry)
{
return('data source object does not implement the DeleteEntry function');
}
};
class form_crud_class extends form_custom_class
{
var $source;
var $scaffolding_input;
var $server_validate=0;
Function SetInputProperties(&$form, $properties, $values)
{
$tp = count($properties);
for($p = 0; $p < $tp; ++$p)
{
$property = $properties[$p];
if(IsSet($values[$property])
&& strlen($error = $form->SetInputProperty($this->scaffolding_input, $property, $values[$property])))
return($error);
}
return('');
}
Function SaveEntry(&$form, $creating, $checkable, &$entry, &$values)
{
if(strlen($error_message = $form->Validate($verify, $this->scaffolding_input.'-submit')) == 0)
{
$tv = count($values);
for(Reset($values), $v = 0; $v < $tv; Next($values), ++$v)
{
$value = Key($values);
if(!IsSet($checkable[$value])
&& strlen($error = $form->GetCheckable($value, $checkable[$value])))
return($error);
$values[$value] = ($checkable[$value] ? $form->GetCheckedState($value) : $form->GetInputValue($value));
}
if(strlen($error = $this->source->SaveEntry($form, $creating, $entry, $values)))
return($error);
$properties = array(
$creating ? 'CreatedMessage' : 'UpdatedMessage',
);
$error = $this->SetInputProperties($form, $properties, $entry);
}
else
$error = '';
return($error);
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['DataSourceClass']))
return('it was not defined the CRUD data source class');
if(function_exists('class_exists')
&& !class_exists($arguments['DataSourceClass']))
return('it was specified an inexisting CRUD data source class '.$arguments['DataSourceClass']);
$this->source = new $arguments['DataSourceClass'];
if(!IsSet($arguments['ScaffoldingInput']))
return('it was not specified the scaffolding input identifier');
$this->source->scaffolding_input = $this->scaffolding_input = $arguments['ScaffoldingInput'];
return($this->source->Initialize($form, $arguments));
}
Function PostMessage(&$form, $message, &$processed)
{
switch($message['Event'])
{
case 'listing':
$listing = array(
'Page'=>$message['Page'],
);
if(strlen($error = $this->source->GetListing($form, $listing)))
return($error);
$properties = array(
'Rows',
'IDColumn',
'Columns',
'TotalEntries',
'PageEntries',
'Page',
'ListingMessage'
);
if(strlen($error = $this->SetInputProperties($form, $properties, $listing)))
return($error);
break;
case 'viewing':
$invalid = 0;
$entry = $values = array();
if(strlen($error = $form->GetInputProperty($this->scaffolding_input, 'Entry', $entry['ID']))
|| strlen($error = $this->source->GetEntry($form, $entry, $invalid, $values))
|| (!$invalid
&& strlen($error = $this->source->ViewEntry($form, $entry, $values))))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
$properties = array(
'ViewingMessage',
'EntryOutput'
);
if(strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
break;
case 'creating':
$invalid = 0;
$entry = $values = array();
if(strlen($error = $this->source->InitializeEntry($form, $entry, $invalid, $values)))
return($error);
$properties = array(
'CreateCanceledMessage',
'CreateMessage',
);
if(count($entry)
&& strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
$tv = count($values);
$checkable = array();
for(Reset($values), $v = 0; $v < $tv; Next($values), ++$v)
{
$value = Key($values);
if(strlen($error = $form->GetCheckable($value, $checkable[$value]))
|| strlen($error = ($checkable[$value] ? $form->SetCheckedState($value, $values[$value]) : $form->SetInputValue($value, $values[$value]))))
return($error);
}
if(strlen($error = $form->LoadInputValues(strlen($form->WasSubmitted('')) != 0)))
return($error);
break;
case 'created':
$invalid = 0;
$entry = $values = array();
if(strlen($error = $this->source->InitializeEntry($form, $entry, $invalid, $values)))
return($error);
$properties = array(
'CreateCanceledMessage',
'CreatedMessage',
);
if(count($entry)
&& strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
if(strlen($error = $this->source->GetSaveInputs($form, $inputs)))
return($error);
$values = array();
$tv = count($inputs);
for($v = 0; $v < $tv; ++$v)
$values[$inputs[$v]] = '';
$checkable = array();
$properties = array(
'CreatedMessage',
);
if(strlen($error = $this->SaveEntry($form, 1, $checkable, $entry, $values))
|| strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
break;
case 'updating':
case 'updated':
$invalid = 0;
$entry = $values = array();
if(strlen($error = $form->GetInputProperty($this->scaffolding_input, 'Entry', $entry['ID']))
|| strlen($error = $this->source->GetEntry($form, $entry, $invalid, $values)))
return($error);
$properties = array(
'UpdateCanceledMessage',
'UpdateMessage',
'UpdatedMessage',
);
if(strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
$tv = count($values);
$checkable = array();
for(Reset($values), $v = 0; $v < $tv; Next($values), ++$v)
{
$value = Key($values);
if(strlen($error = $form->GetCheckable($value, $checkable[$value]))
|| strlen($error = ($checkable[$value] ? $form->SetCheckedState($value, $values[$value]) : $form->SetInputValue($value, $values[$value]))))
return($error);
}
if(strlen($error = $form->LoadInputValues(strlen($form->WasSubmitted('')) != 0)))
return($error);
if(!strcmp($message['Event'], 'updated'))
{
$properties = array(
'UpdatedMessage',
);
if(strlen($error = $this->SaveEntry($form, 0, $checkable, $entry, $values))
|| strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
}
break;
case 'deleted':
case 'deleting':
$invalid = 0;
$entry = $values = array();
if(strlen($error = $form->GetInputProperty($this->scaffolding_input, 'Entry', $entry['ID']))
|| strlen($error = $this->source->GetEntry($form, $entry, $invalid, $values)))
return($error);
$properties = array(
'DeleteMessage',
'DeleteCanceledMessage',
'DeletedMessage',
);
if(strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
if($invalid)
{
$message['Cancel'] = 1;
break;
}
if(strlen($error_message = $form->Validate($verify, $this->scaffolding_input.'-delete')) == 0
&& !strcmp($message['Event'], 'deleted'))
{
$properties = array(
'DeletedMessage',
);
if(strlen($error = $this->source->DeleteEntry($form, $entry))
|| strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
}
break;
case 'update_canceled':
case 'delete_canceled':
if(strlen($error = $form->GetInputProperty($this->scaffolding_input, 'Entry', $entry['ID']))
|| strlen($error = $this->source->GetEntry($form, $entry, $invalid, $values)))
return($error);
$properties = array(
'DeleteMessage',
'DeleteCanceledMessage',
'DeletedMessage',
);
if(strlen($error = $this->SetInputProperties($form, $properties, $entry)))
return($error);
case 'create_canceled':
break;
default:
return($form->OutputError('form custom input is not yet ready to handle '.$message['Event'].' events', $this->input));
}
return($form->ReplyMessage($message, $processed));
}
};
?>

View file

@ -0,0 +1,148 @@
<?php
/*
*
* @(#) $Id: form_custom_validation.php,v 1.4 2008/06/04 20:55:06 mlemos Exp $
*
*/
if(!defined("PHP_LIBRARY_CUSTOM_VALIDATION_FORMS"))
{
define("PHP_LIBRARY_CUSTOM_VALIDATION_FORMS",1);
class form_custom_validation_class extends form_custom_class
{
/*
* Tell the forms class that this custom input will perform both server
* side and client side validation.
*/
var $client_validate=1;
var $server_validate=1;
var $first='';
var $second='';
var $first_validation_error_message='The first input value is contained in the second.';
var $second_validation_error_message='The second input value is contained in the first.';
Function AddInput(&$form, $arguments)
{
/*
* Get the identifiers of the inputs to validate
*/
if(!IsSet($arguments['FirstInput'])
|| strlen($this->first=$arguments['FirstInput'])==0)
return('It was not specified a valid first input identifier');
if(!IsSet($arguments['SecondInput'])
|| strlen($this->second=$arguments['SecondInput'])==0)
return('It was not specified a valid second input identifier');
/*
* Get the error messages to assign when the inputs are invalid.
*/
if(IsSet($arguments['FirstValidationErrorMessage']))
{
if(strlen($arguments['FirstValidationErrorMessage'])==0)
return('It was not specified a valid first validation error message');
$this->first_validation_error_message=$arguments['FirstValidationErrorMessage'];
}
if(IsSet($arguments['SecondValidationErrorMessage']))
{
if(strlen($arguments['SecondValidationErrorMessage'])==0)
return('It was not specified a valid second validation error message');
$this->second_validation_error_message=$arguments['SecondValidationErrorMessage'];
}
return('');
}
Function ValidateInput(&$form)
{
/*
* Perform server side validation by checking whether one of the
* input values contains the other.
*
* This function is called after all validations were performed on
* all basic inputs.
*/
$first=$form->GetInputValue($this->first);
$second=$form->GetInputValue($this->second);
if(strlen($first)
&& strstr($second, $first))
{
$form->FlagInvalidInput($this->first, $this->first_validation_error_message);
return('');
}
if(strlen($second)
&& strstr($first, $second))
{
$form->FlagInvalidInput($this->second, $this->second_validation_error_message);
return('');
}
return('');
}
Function GetJavascriptValidations(&$form, $form_object, &$validations)
{
/*
* Generate all the necessary Javascript to perform client side
* validation.
*/
if(strlen($first=$form->GetJavascriptInputValue($form_object,$this->first))==0)
return('it was not possible to retrieve the first input Javascript value');
if(strlen($second=$form->GetJavascriptInputValue($form_object,$this->second))==0)
return('it was not possible to retrieve the second input Javascript value');
/*
* Return an array with a list of all validation checks to be
* performed.
*/
$validations=array();
$validations[]=array(
/*
* Each.validation check may be preceed by a list of Javascript
* commands that are executed before each validation is performed.
*/
'Commands'=>array(
'first='.$first,
'second='.$second,
),
/*
* The condition is a boolean Javascript expression that is true
* when the input is invalid.
*/
'Condition'=>'second.indexOf(first) != -1',
/*
* Error message associated to the invalid input
*/
'ErrorMessage'=>$this->first_validation_error_message,
/*
* Input that gets the user input focus so the user fixes its value
* to make the input valid
*/
'Focus'=>$this->first
);
$validations[]=array(
'Commands'=>array(),
'Condition'=>'first.indexOf(second) != -1',
'ErrorMessage'=>$this->second_validation_error_message,
'Focus'=>$this->second
);
return('');
}
Function AddInputPart(&$form)
{
/*
* Inputs that do not appear in the form must implement an empty
* AddInputPart function.
*/
return('');
}
};
}
?>

View file

@ -0,0 +1,734 @@
<?php
/*
*
* @(#) $Id: form_date.php,v 1.34 2013/01/09 10:20:33 mlemos Exp $
*
*/
if(!defined("PHP_LIBRARY_DATE_FORMS"))
{
define("PHP_LIBRARY_DATE_FORMS",1);
class form_date_class extends form_custom_class
{
var $format="{year}-{month}-{day}";
var $hide_day_format = '{year}-{month}';
var $choose_format = '{choose} {date}';
var $validation_start_date="";
var $validation_start_date_error_message="";
var $validation_end_date="";
var $validation_end_date_error_message="";
var $invalid_date_error_message="It was not specified a valid date.";
var $invalid_year_error_message="It was not specified a valid year.";
var $invalid_month_error_message="It was not specified a valid month.";
var $invalid_day_error_message="It was not specified a valid day.";
var $client_validate=1;
var $server_validate=1;
var $select_years=20;
var $fixed_day = 0;
var $hide_day = 0;
var $ask_age = 0;
var $year="";
var $month="";
var $day="";
var $optional=0;
var $choose_control = 0;
var $choose = 1;
var $choose_input = '';
var $value = '';
var $choice_default_value;
Function ValidateDateValue($year, $month, $day)
{
if(strlen($year))
{
while(!strcmp($year[0],"0"))
$year=substr($year,1);
}
if(strcmp($year,intval($year))
|| intval($year)<=0)
return($this->invalid_year_error_message);
switch($month)
{
case "01":
case "03":
case "05":
case "07":
case "08":
case "10":
case "12":
$month_days=31;
break;
case "02":
$is_leap_year=(($year % 4)==0 && (($year % 100)!=0 || ($year % 400)==0));
$month_days=($is_leap_year ? 29 : 28);
break;
case "04":
case "06":
case "09":
case "11":
$month_days=30;
break;
default:
return($this->invalid_month_error_message);
}
if(strlen($day))
{
while(!strcmp($day[0],"0"))
$day=substr($day,1);
}
if(strcmp($day,intval($day))
|| $day>$month_days)
return($this->invalid_day_error_message);
return("");
}
Function ValidateDate($date, &$year, &$month, &$day)
{
if(!preg_match('/^([0-9]{4})-([0-9]{2})-([0-9]{2})$/', $date, $matches))
return($this->invalid_date_error_message);
$year=$matches[1];
$month=$matches[2];
$day=$matches[3];
return($this->ValidateDateValue($year, $month, $day));
}
Function AddInput(&$form, $arguments)
{
$this->year=$this->GenerateInputID($form, $this->input, "year");
$this->month=$this->GenerateInputID($form, $this->input, "month");
$this->day=$this->GenerateInputID($form, $this->input, "day");
$this->valid_marks=array(
"input"=>array(
"year"=>$this->year,
"month"=>$this->month,
"day"=>$this->day
)
);
$validation_error_message=(IsSet($arguments["ValidationErrorMessage"]) ? $arguments["ValidationErrorMessage"] : "");
if(IsSet($arguments["ValidationDateErrorMessage"])
&& strlen($this->invalid_date_error_message = $arguments["ValidationDateErrorMessage"])==0)
return("it was not specified a valid date validation error message");
if(IsSet($arguments["ValidationYearErrorMessage"])
&& strlen($this->invalid_year_error_message = $arguments["ValidationYearErrorMessage"])==0)
return("it was not specified a valid year validation error message");
if(IsSet($arguments["ValidationMonthErrorMessage"])
&& strlen($this->invalid_month_error_message = $arguments["ValidationMonthErrorMessage"])==0)
return("it was not specified a valid month validation error message");
if(IsSet($arguments["ValidationDayErrorMessage"])
&& strlen($this->invalid_day_error_message = $arguments["ValidationDayErrorMessage"])==0)
return("it was not specified a valid day validation error message");
$today = strftime('%Y-%m-%d');
if(IsSet($arguments["ValidationStartDate"]))
{
$start_date = $arguments["ValidationStartDate"];
if(!strcmp($start_date, 'now'))
$start_date = $today;
if(strlen($error=$this->ValidateDate($start_date, $start_year, $start_month, $start_day)))
return($error);
$this->validation_start_date_error_message=(IsSet($arguments["ValidationStartDateErrorMessage"]) ? $arguments["ValidationStartDateErrorMessage"] : $validation_error_message);
if(strlen($this->validation_start_date_error_message)==0)
return("it was not specified a valid start date validation error message");
$this->validation_start_date=$start_date;
}
else
$start_year=0;
if(IsSet($arguments["ValidationEndDate"]))
{
$end_date = $arguments["ValidationEndDate"];
if(!strcmp($end_date, 'now'))
$end_date = $today;
if(strlen($error=$this->ValidateDate($end_date, $end_year, $end_month, $end_day)))
return($error);
$this->validation_end_date_error_message=(IsSet($arguments["ValidationEndDateErrorMessage"]) ? $arguments["ValidationEndDateErrorMessage"] : $validation_error_message);
if(strlen($this->validation_end_date_error_message)==0)
return("it was not specified a valid end date validation error message");
$this->validation_end_date=$end_date;
}
else
$end_year=0;
$this->optional=(IsSet($arguments["Optional"]) && $arguments["Optional"]);
$this->choose_control=(IsSet($arguments["ChooseControl"]) && $arguments["ChooseControl"]);
if($this->choose_control)
{
$this->choose=(!IsSet($arguments["Choose"]) || $arguments["Choose"]);
$this->choose_input=$this->GenerateInputID($form, $this->input, "choose");
$this->valid_marks["input"]["choose"] = $this->choose_input;
if(IsSet($arguments['ChoiceDefaultValue']))
{
$value = $arguments['ChoiceDefaultValue'];
if(strlen($value))
{
if(!strcmp($value, 'now'))
$value = $today;
if(strlen($error=$this->ValidateDate($value, $current_year, $current_month, $current_day)))
return($error);
}
$this->choice_default_value = $value;
}
}
if(IsSet($arguments["VALUE"])
&& strlen($arguments["VALUE"]))
{
$value = $arguments["VALUE"];
if(!strcmp($value, 'now'))
$value = $today;
if(strlen($error=$this->ValidateDate($value, $current_year, $current_month, $current_day)))
return($error);
$this->value = $value;
}
else
$this->value = $current_year = $current_month = $current_day = "";
if(IsSet($arguments['AskAge'])
&& $arguments['AskAge'])
$this->ask_age = 1;
if(IsSet($arguments['FixedDay']))
{
$fixed_day = $arguments['FixedDay'];
if($fixed_day <= 0
|| $fixed_day > 31)
return("it was not specified a valid fixed day");
$current_day = ($fixed_day < 10 ? '0' : '').strval($this->fixed_day = $fixed_day);
}
if(IsSet($arguments['HideDay'])
&& $arguments['HideDay'])
{
if(!$this->fixed_day)
return("days can only be hidden if a fixed day was set");
$this->hide_day = 1;
}
$format=(IsSet($arguments["Format"]) ? $arguments["Format"] : ($this->hide_day ? $this->hide_day_format : $this->format));
if($this->choose_control)
{
$format = str_replace('{date}', $format, $this->choose_format);
if(strlen($error = $form->AddInput(array(
"NAME"=>$this->choose_input,
"ID"=>$this->choose_input,
"TYPE"=>"checkbox",
"CHECKED"=>$this->choose,
"ONCHANGE"=>$form->GetJavascriptInputObject('this.form', $this->year).'.disabled = '.$form->GetJavascriptInputObject('this.form', $this->month).'.disabled = '.($this->hide_day ? '' : $form->GetJavascriptInputObject('this.form', $this->day).'.disabled = ').'!this.checked;'
))))
return($error);
}
if(strlen($error=$this->DefaultSetInputProperty($form, "Format", $format)))
return($error);
$month_options=array();
if($this->optional
|| strlen($current_month) == 0)
$month_options[''] = '';
if($this->ask_age)
{
for($month=0; $month<12; $month++)
$month_options[$month]=$month;
}
elseif(IsSet($arguments["Months"]))
{
for($month=1; $month<=12; $month++)
{
$month_value=sprintf("%02d", $month);
if(!IsSet($arguments["Months"][$month_value]))
return("it was not specified the value for month ".$month_value);
$month_options[$month_value]=$arguments["Months"][$month_value];
}
}
else
{
for($month=1; $month<=12; $month++)
{
$month_value=sprintf("%02d", $month);
$month_options[$month_value]=$month_value;
}
}
$day_options=array(""=>"");
for($day=1; $day<=31; $day++)
$day_options[sprintf("%02d",$day)]=sprintf("%2d",$day);
if(IsSet($arguments["SelectYears"]))
{
if(GetType($select_years=$arguments["SelectYears"])!="integer"
|| $select_years<0)
return("it was not specified a valid select years value");
$this->select_years=$select_years;
}
$this_year = intval(substr($today, 0, 4));
$current_year = ((strlen($current_year) && $this->ask_age) ? $this_year - $current_year : $current_year);
if(strlen($current_month)
&& $this->ask_age)
{
$this_month = intval(strftime('%m'));
$current_month = $this_month - $current_month;
if($current_month < 0)
{
$current_month += 12;
--$current_year;
}
}
if($start_year
&& $end_year
&& $start_year<=$end_year
&& $end_year-$start_year<$this->select_years)
{
$years=array();
if($this->optional
|| strlen($current_year) == 0)
$years[""]="";
if($this->ask_age)
{
for($year = $end_year; $year >= $start_year; --$year)
{
$age = $this_year - $year;
$years[strval($age)]=sprintf('%4d', $age);
}
}
else
{
for($year=$start_year;$year<=$end_year;$year++)
$years[strval($year)]=strval($year);
}
$year_arguments=array(
"NAME"=>$this->year,
"ID"=>$this->year,
"TYPE"=>"select",
"VALUE"=>$current_year,
"OPTIONS"=>$years,
"ValidationErrorMessage"=>$this->invalid_year_error_message
);
}
else
{
$year_arguments=array(
"NAME"=>$this->year,
"ID"=>$this->year,
"TYPE"=>"text",
"MAXLENGTH"=>4,
"SIZE"=>5,
"VALUE"=>$current_year,
"ValidateAsInteger"=>1,
"ValidationLowerLimit"=>1,
"ValidationErrorMessage"=>$this->invalid_year_error_message
);
}
$month_arguments=array(
"NAME"=>$this->month,
"ID"=>$this->month,
"TYPE"=>"select",
"OPTIONS"=>$month_options,
"VALUE"=>$current_month,
"ValidationErrorMessage"=>$this->invalid_month_error_message
);
$day_arguments=array(
"NAME"=>$this->day,
"ID"=>$this->day,
"TYPE"=>"select",
"OPTIONS"=>$day_options,
"VALUE"=>$current_day,
"ValidationErrorMessage"=>$this->invalid_day_error_message
);
if(IsSet($arguments['DependentValidation']))
$year_arguments['DependentValidation'] = $month_arguments['DependentValidation'] = $day_arguments['DependentValidation'] = $arguments['DependentValidation'];
if($this->choose_control)
{
/* $day_arguments['DependentValidation'] = $month_arguments['DependentValidation'] = $year_arguments['DependentValidation'] = $this->choose_input;
*/
if(!$this->choose)
$day_arguments['ExtraAttributes']['disabled'] = $month_arguments['ExtraAttributes']['disabled'] = $year_arguments['ExtraAttributes']['disabled'] = "disabled";
}
if($this->optional)
$year_arguments["ValidateOptionalValue"]="";
elseif(!$this->ask_age)
$month_arguments["ValidateAsNotEmpty"]=$day_arguments["ValidateAsNotEmpty"]=1;
if(IsSet($arguments["TABINDEX"]))
{
$tab_index = $arguments["TABINDEX"];
$year_arguments["TABINDEX"] = $tab_index++;
$month_arguments["TABINDEX"] = $tab_index++;
$day_arguments["TABINDEX"] = $tab_index;
}
if(IsSet($arguments["STYLE"]))
$year_arguments["STYLE"]=$month_arguments["STYLE"]=$day_arguments["STYLE"]=$arguments["STYLE"];
if(IsSet($arguments["CLASS"]))
$year_arguments["CLASS"]=$month_arguments["CLASS"]=$day_arguments["CLASS"]=$arguments["CLASS"];
if(IsSet($arguments["YearClass"]))
$year_arguments["CLASS"]=$arguments["YearClass"];
if(IsSet($arguments["YearStyle"]))
$year_arguments["STYLE"]=$arguments["YearStyle"];
if(IsSet($arguments["MonthClass"]))
$month_arguments["CLASS"]=$arguments["MonthClass"];
if(IsSet($arguments["MonthStyle"]))
$month_arguments["STYLE"]=$arguments["MonthStyle"];
if(IsSet($arguments["DayClass"]))
$day_arguments["CLASS"]=$arguments["DayClass"];
if(IsSet($arguments["DayStyle"]))
$day_arguments["STYLE"]=$arguments["DayStyle"];
if($this->fixed_day)
$day_arguments['Accessible'] = 0;
if(strlen($error=$form->AddInput($year_arguments))
|| strlen($error=$form->AddInput($month_arguments))
|| strlen($error=$form->AddInput($day_arguments)))
return($error);
return("");
}
Function GetValue(&$form, &$year, &$month, &$day)
{
if($this->choose_control
&& !$this->choose)
{
$value = (IsSet($this->choice_default_value) ? $this->choice_default_value : $this->value);
if(strlen($value))
{
$year = substr($value, 0, 4);
$month = substr($value, 5, 2);
$day = substr($value, 8, 2);
}
else
$year = $day = $month = '';
return;
}
$year=$form->GetInputValue($this->year);
$month=$form->GetInputValue($this->month);
$day=($this->fixed_day ? ((strlen($year) || strlen($month)) ? $this->fixed_day : '') : $form->GetInputValue($this->day));
if($this->ask_age)
{
$this_year = intval(strftime('%Y'));
$this_month = intval(strftime('%m'));
$this_day = intval(strftime('%d'));
if(strlen($day)
|| strlen($month)
|| strlen($year))
{
if(!$this->fixed_day)
{
if(strlen($day) == 0)
$day = '0';
$this_day -= intval($day);
}
if(strlen($month) == 0)
$month='0';
$this_month -= intval($month);
if(strlen($year) == 0)
$year='0';
$this_year -= intval($year);
if(!$this->fixed_day)
{
while($this_day < 1)
{
$this_day += 30;
--$this_month;
}
$day=strval($this_day);
}
if(strlen($day < 2))
$day = '0'.$day;
while($this_month < 1)
{
$this_month += 12;
--$this_year;
}
$month = strval($this_month);
if(strlen($month) < 2)
$month = '0'.$month;
$year = strval($this_year);
if(strlen($year) < 2)
$year = '00' + $year;
if(strlen($year) < 3)
$year = '0'.$year;
}
}
}
Function ValidateInput(&$form)
{
$this->GetValue($form, $year, $month, $day);
if($this->optional
&& strlen($year)==0
&& strlen($month)==0
&& strlen($day)==0)
return("");
if(strlen($error=$this->ValidateDateValue($year, $month, $day)))
return($error);
$date=sprintf("%04d-%02d-%02d", $year, $month, $day);
if(strlen($this->validation_start_date)
&& strcmp($date,$this->validation_start_date)<0)
return($this->validation_start_date_error_message);
if(strlen($this->validation_end_date)
&& strcmp($date,$this->validation_end_date)>0)
return($this->validation_end_date_error_message);
return("");
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case "VALUE":
$today = strftime('%Y-%m-%d');
if($this->optional
&& strlen($value)==0)
$this->value = $year = $month = $day = "";
else
{
if(!strcmp($value, 'now'))
$value = $today;
if(strlen($error=$this->ValidateDate($value, $year, $month, $day)))
return($error);
if(strlen($this->validation_start_date)
&& strcmp($value, $this->validation_start_date)<0)
return($this->validation_start_date_error_message);
if(strlen($this->validation_end_date)
&& strcmp($value, $this->validation_end_date)>0)
return($this->validation_end_date_error_message);
if($this->ask_age)
{
$this_year = intval(substr($today, 0, 4));
$year = $this_year - intval(substr($value, 0, 4));
$this_month = intval(substr($today, 5, 2));
$month = $this_month - intval(substr($value, 5, 2));
$this_day = intval(substr($today, 8, 2));
$day = $this_day - intval(substr($value, 8, 2));
while($day < 0)
{
$day += 30;
--$month;
}
while($month < 0)
{
$month += 12;
--$year;
}
}
else
{
$this_year = $year;
$this_month = $month;
$this_day = $day;
}
$this->value = sprintf("%04d-%02d-%02d", $this_year, $this_month, $this_day);
}
if(strlen($error=$form->SetInputProperty($this->year, "VALUE", $year))
|| strlen($error=$form->SetInputProperty($this->month, "VALUE", $month))
|| (!$this->hide_day
&& strlen($error=$form->SetInputProperty($this->day, "VALUE", $day))))
return($error);
break;
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
Function GetInputValue(&$form)
{
$this->GetValue($form, $year, $month, $day);
if(strlen($year)==0
|| strlen($month)==0
|| strlen($day)==0)
return("");
return(sprintf("%04d-%02d-%02d", $year, $month, $day));
}
Function GetJavascriptDayValue(&$form, $form_object)
{
return($this->fixed_day ? $form->EncodeJavascriptString(sprintf('%02d', $this->fixed_day)) : $form->GetJavascriptInputValue($form_object,$this->day));
}
Function GetJavascriptValidations(&$form, $form_object, &$validations)
{
if(strlen($day=$this->GetJavascriptDayValue($form, $form_object))==0)
return("it was not possible to retrieve the day input Javascript value");
if(strlen($month=$form->GetJavascriptInputValue($form_object,$this->month))==0)
return("it was not possible to retrieve the day input Javascript value");
if(strlen($year=$form->GetJavascriptInputValue($form_object,$this->year))==0)
return("it was not possible to retrieve the day input Javascript value");
$validations = $commands = array();
if($this->choose_control)
{
$value = (IsSet($this->choice_default_value) ? $this->choice_default_value : $this->value);
$commands[] = 'var choose='.$form->GetJavascriptCheckedState($form_object, $this->choose_input);
$year = '(choose ? '.$year.' : '.$form->EncodeJavascriptString(strlen($value) ? substr($value, 0, 4) : '').')';
$month = '(choose ? '.$month.' : '.$form->EncodeJavascriptString(strlen($value) ? substr($value, 5, 2) : '').')';
$day = '(choose ? '.$day.' : '.$form->EncodeJavascriptString(strlen($value) ? substr($value, 7, 2) : '').')';
}
$commands[] = "var year=".$year;
$commands[] = "var month=".$month;
$commands[] = "var day=".($this->fixed_day ? '((year.length || month.length) ? '.$day.' : \'\')' : $day);
if($this->ask_age)
{
if(!$this->optional
|| $this->choose_format)
{
$validations[]=array(
"Commands"=>$commands,
"Condition"=>($this->choose_control ? 'choose && ' : '').'!year.length && !month.length'.($this->fixed_day ? '' : ' && !day.length'),
"ErrorMessage"=>$this->invalid_year_error_message,
"Focus"=>$this->year
);
$commands = array();
}
$this_year = intval(strftime('%Y'));
$this_month = intval(strftime('%m'));
$this_day = intval(strftime('%d'));
$commands[] = 'if('.($this->fixed_day ? '' : 'day.length || ').'month.length || year.length)';
$commands[] = '{';
if(!$this->fixed_day)
{
$commands[] = ' if(day.length==0)';
$commands[] = ' day=\'0\'';
$commands[] = ' var this_day='.$this_day.'-parseInt(day)';
}
$commands[] = ' if(month.length==0)';
$commands[] = ' month=\'0\'';
$commands[] = ' var this_month='.$this_month.'-parseInt(month)';
$commands[] = ' if(year.length==0)';
$commands[] = ' year=\'0\'';
$commands[] = ' var this_year='.$this_year.'-parseInt(year)';
if(!$this->fixed_day)
{
$commands[] = ' while(this_day<1)';
$commands[] = ' {';
$commands[] = ' this_day+=30';
$commands[] = ' --this_month';
$commands[] = ' }';
$commands[] = ' day=this_day+\'\'';
$commands[] = ' if(day.length<2)';
$commands[] = ' day=\'0\'+day';
}
$commands[] = ' while(this_month<1)';
$commands[] = ' {';
$commands[] = ' this_month+=12';
$commands[] = ' --this_year';
$commands[] = ' }';
$commands[] = ' month=this_month+\'\'';
$commands[] = ' if(month.length<2)';
$commands[] = ' month=\'0\'+month';
$commands[] = ' year=this_year+\'\'';
$commands[] = ' if(year.length<2)';
$commands[] = ' year=\'00\'+year';
$commands[] = ' if(year.length<3)';
$commands[] = ' year=\'0\'+year';
$commands[] = '}';
}
$validations[]=array(
"Commands"=>$commands,
"Condition"=>'!year.length && ('.($this->choose_control ? 'choose || ' : '').'month.length || day.length)',
"ErrorMessage"=>$this->invalid_year_error_message,
"Focus"=>$this->year
);
$validations[]=array(
"Commands"=>array(),
"Condition"=>'!month.length && ('.($this->choose_control ? 'choose || ' : '').'year.length || day.length)',
"ErrorMessage"=>$this->invalid_month_error_message,
"Focus"=>$this->month
);
if(!$this->fixed_day)
{
$validations[]=array(
"Commands"=>array(),
"Condition"=>'!day.length && ('.($this->choose_control ? 'choose || ' : '').'year.length || month.length)',
"ErrorMessage"=>$this->invalid_day_error_message,
"Focus"=>$this->day
);
}
if($this->fixed_day)
$commands = array();
else
{
$commands = array(
'var month_days',
"if(month=='04'",
"|| month=='06'",
"|| month=='09'",
"|| month=='11')",
"\tmonth_days=30",
"else",
"{",
"\tif(month=='02')",
"\t{",
"\t\tvar date_year=parseInt(year)",
"\t\tif((date_year % 4)==0",
"\t\t&& ((date_year % 100)!=0",
"\t\t|| (date_year % 400)==0))",
"\t\t\tmonth_days=29",
"\t\telse",
"\t\t\tmonth_days=28",
"\t}",
"\telse",
"\t\tmonth_days=31",
"}"
);
}
if((!$this->fixed_day
&& $this->optional)
|| strlen($this->validation_start_date)
|| strlen($this->validation_end_date))
$commands[]="var date=".($this->optional ? "((year.length && month.length && day.length) ? " : "")."(year.length<3 ? '00' : '') + ((year.length % 2) ? '0' : '') + year + '-' + month + '-' + day".($this->optional ? " : '')" : "");
if(!$this->fixed_day)
{
$validations[]=array(
"Commands"=>$commands,
"Condition"=>($this->optional ? "date.length && " : "")."month_days<parseInt(day)",
"ErrorMessage"=>$this->invalid_day_error_message,
"Focus"=>$this->day
);
$commands = array();
}
if(strlen($this->validation_start_date))
{
$validations[]=array(
"Commands"=>$commands,
"Condition"=>($this->optional ? "date.length && " : "")."date<".$form->EncodeJavascriptString($this->validation_start_date),
"ErrorMessage"=>$this->validation_start_date_error_message
);
$commands = array();
}
if(strlen($this->validation_end_date))
{
$validations[]=array(
"Commands"=>$commands,
"Condition"=>($this->optional ? "date.length && " : "").$form->EncodeJavascriptString($this->validation_end_date)."<date",
"ErrorMessage"=>$this->validation_end_date_error_message
);
}
return("");
}
Function GetJavascriptInputValue(&$form, $form_object)
{
if($this->ask_age)
{
$this->OutputError("retrieve the Javascript input value for date inputs with AskAge option is not yet implemented", $this->input);
return("");
}
if(strlen($day=$this->GetJavascriptDayValue($form, $form_object))==0
|| strlen($month=$form->GetJavascriptInputValue($form_object,$this->month))==0
|| strlen($year=$form->GetJavascriptInputValue($form_object,$this->year))==0)
return("");
$value = "((".$year.".length && ".$month.".length && ".$day.".length) ? (".$year.".length<3 ? '00' : '') + ((".$year.".length % 2) ? '0' : '') + ".$year." + '-' + ".$month." + '-' + ".$day." : '')";
if($this->choose_control)
$value = '('.$form->GetJavascriptCheckedState($form_object, $this->choose_input).' ? '.$value.' '.$form->EncodeJavascriptString(IsSet($this->choice_default_value) ? $this->choice_default_value : $this->value).')';
return($value);
}
Function LoadInputValues(&$form, $submitted)
{
if($this->choose_control)
{
$choose = $form->GetCheckedState($this->choose_input);
if(!$this->choose != !$choose)
{
$value = ($choose ? array() : array('disabled' => 'disabled'));
$form->SetInputProperty($this->year, 'ExtraAttributes', $value);
$form->SetInputProperty($this->month, 'ExtraAttributes', $value);
$form->SetInputProperty($this->day, 'ExtraAttributes', $value);
$this->choose = $choose;
}
}
return('');
}
};
}
?>

Binary file not shown.

After

Width:  |  Height:  |  Size: 39 KiB

View file

@ -0,0 +1,199 @@
<?php
/*
*
* @(#) $Id: form_html_editor.php,v 1.31 2010/05/07 09:32:54 mlemos Exp $
*
*/
class form_html_editor_class extends form_custom_class
{
var $server_validate = 0;
var $javascript_path = '';
var $external_css = array();
var $textarea = array();
var $debug = 1;
var $template_variables = array();
var $mode = 'visual';
var $show_toolbars = 1;
Function AddInput(&$form, $arguments)
{
if(IsSet($arguments['TemplateVariables']))
$this->template_variables = $arguments['TemplateVariables'];
if(IsSet($arguments['Debug']))
$this->debug = intval($arguments['Debug']);
if(IsSet($arguments['ShowToolbars']))
$this->show_toolbars = intval($arguments['ShowToolbars']);
$this->textarea = $arguments;
$this->textarea['TYPE'] = 'textarea';
if(IsSet($arguments['JavascriptPath']))
{
$this->javascript_path = $arguments['JavascriptPath'];
if(($length = strlen($this->javascript_path))
&& strcmp($this->javascript_path[$length - 1], '/'))
$this->javascript_path .= '/';
UnSet($this->textarea['JavascriptPath']);
}
if(IsSet($arguments['ExternalCSS']))
{
$this->external_css = $arguments['ExternalCSS'];
UnSet($this->textarea['ExternalCSS']);
}
if(IsSet($arguments['Mode']))
{
switch($mode = $arguments['Mode'])
{
case 'visual':
case 'html':
$this->mode = $mode;
break;
default:
return($mode.' is not support editing mode');
}
}
UnSet($this->textarea['CustomClass']);
$this->focus_input = $this->textarea['ID'] = $this->GenerateInputID($form, $this->input, 'textarea');
if(!IsSet($this->textarea['NAME']))
$this->textarea['NAME'] = $this->textarea['ID'];
if(strlen($error = $form->AddInput($this->textarea)))
return($error);
$context = array();
return($form->ConnectFormToInput($this->input, 'ONSUBMIT', 'Synchronize', $context));
}
Function AddInputPart(&$form)
{
if(strlen($error = $form->AddDataPart('<div id="'.$this->input.'"><noscript>'))
|| strlen($error = $form->AddInputPart($this->textarea['ID']))
|| strlen($error = $form->AddDataPart('</noscript></div>')))
return($error);
return('');
}
Function ClassPageHead(&$form)
{
return('<script type="text/javascript" src="'.HtmlSpecialChars($this->javascript_path).'html_editor.js"></script>'."\n");
}
Function PageLoad(&$form)
{
$tv = $this->template_variables;
$ttv = count($tv);
for($t = '', Reset($tv), $v = 0; $v < $ttv; Next($tv), ++$v)
{
$k = Key($tv);
if($v > 0)
$t .= ',';
$t .= ' '.$form->EncodeJavascriptString($k).': { ';
if(IsSet($tv[$k]['Inline']))
{
$t .= 'inline: '.($tv[$k]['Inline'] ? 'true' : 'false');
if(IsSet($tv[$k]['Preview']))
$t .= ', preview: '.$form->EncodeJavascriptString($tv[$k]['Preview']);
}
else
$t .= 'value: '.$form->EncodeJavascriptString(IsSet($tv[$k]['Value']) ? $tv[$k]['Value'] : $k);
if(IsSet($tv[$k]['Title']))
$t .=', title: '.$form->EncodeJavascriptString($tv[$k]['Title']);
if(IsSet($tv[$k]['Alternatives']))
{
$t .= ', alternatives: {';
$va = $tv[$k]['Alternatives'];
$tva = count($va);
for(Reset($va), $a = 0; $a < $tva; Next($va), ++$a)
{
$ka = Key($va);
if($a > 0)
$t .= ', ';
$t .= ' '.$form->EncodeJavascriptString($ka).': { ';
if(IsSet($tv[$k]['Inline']))
{
if(IsSet($va[$ka]['Preview']))
$t .= 'preview: '.$form->EncodeJavascriptString($va[$ka]['Preview']);
if(IsSet($va[$ka]['Title']))
{
if(IsSet($va[$ka]['Preview']))
$t .= ', ';
$t .= 'title: '.$form->EncodeJavascriptString($va[$ka]['Title']);
}
}
else
$t .= 'value: '.$form->EncodeJavascriptString(IsSet($va[$ka]['Value']) ? $va[$ka]['Value'] : $ka);
$t .= ' }';
}
$t .= ' }';
}
$t .= ' }';
}
$css = $this->external_css;
$tc = count($css);
for($e = '', $c = 0; $c < $tc; ++$c)
{
if($c > 0)
$e .= ',';
$e .= ' '.$form->EncodeJavascriptString($css[$c]);
}
$editor = $form->EncodeJavascriptString($this->input);
return('if(document.getElementById('.$editor.')) { var e = new ML.HTMLEditor.Editor();'."\n".'e.debug = '.($this->debug ? 'true' : 'false').'; e.showToolbars = '.($this->show_toolbars ? 'true' : 'false').'; e.mode = '.$form->EncodeJavascriptString($this->mode).';'.(strlen($t) ? ' e.templateVariables = {'.$t.'};' : '').(strlen($e) ? ' e.externalCSS = ['.$e.'];' : '').' e.insertEditor('.$editor.', { id: '.$form->EncodeJavascriptString($this->textarea['ID']).', name: '.$form->EncodeJavascriptString($this->textarea['NAME']).(IsSet($this->textarea['VALUE']) ? ', value: '.$form->EncodeJavascriptString($this->textarea['VALUE']) : '').(IsSet($this->textarea['ROWS']) ? ', rows: '.$form->EncodeJavascriptString($this->textarea['ROWS']) : '').(IsSet($this->textarea['COLS']) ? ', cols: '.$form->EncodeJavascriptString($this->textarea['COLS']) : '').(IsSet($this->textarea['STYLE']) ? ', style: '.$form->EncodeJavascriptString($this->textarea['STYLE']).(IsSet($this->textarea['CLASS']) ? ', className: '.$form->EncodeJavascriptString($this->textarea['CLASS']) : '') : '').' }); }');
}
Function GetInputValue(&$form)
{
return($this->textarea['VALUE'] = $form->GetInputValue($this->textarea['ID']));
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case 'VALUE':
if(strlen($error = $form->SetInputValue($this->textarea['ID'], $value)) == 0)
$this->textarea['VALUE'] = $value;
return($error);
case 'Mode':
switch($value)
{
case 'visual':
case 'html':
$this->mode = $value;
return('');
default:
return($value.' is not support editing mode');
}
case 'ShowToolbars':
$this->show_toolbars = intval($value);
return('');
case 'TemplateVariables':
$this->template_variables = $value;
return('');
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
}
Function GetJavascriptSetInputProperty(&$form, $form_object, $property, $value)
{
switch($property)
{
case 'VALUE':
return('var e = ('.$form_object.'.ownerDocument.defaultView ? '.$form_object.'.ownerDocument.defaultView : '.$form_object.'.ownerDocument.parentWindow).ML.HTMLEditor.HTMLEditors['.$form->EncodeJavascriptString($this->textarea['ID']).']; e.setValue('.$value.');');
default:
return('');
}
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'Synchronize':
$javascript = 'var e = ML.HTMLEditor.HTMLEditors['.$form->EncodeJavascriptString($this->textarea['ID']).']; e.synchronize();';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
};
?>

View file

@ -0,0 +1,566 @@
<?php
/*
*
* @(#) $Id: form_layout_paged.php,v 1.28 2014/09/28 04:44:56 mlemos Exp $
*
*/
class form_layout_paged_class extends form_custom_class
{
var $pages = array();
var $current_page = '';
var $styles = array();
var $side = 'top';
var $border_width = 1;
var $page_border_width = 2;
var $border_radius=8;
var $border_color = '';
var $foreground_color = '';
var $background_color = '';
var $lighter_border_color = '#eeeeee';
var $darker_border_color = '#777777';
var $color_offset = 50;
var $tab_padding = 2;
var $row_gap = 4;
var $tab = '';
var $button = '';
var $page = '';
var $switch = '';
var $class = '';
var $page_class = '';
var $tab_class = '';
var $gap_class = '';
var $page_button_class = '';
var $tab_button_class = '';
var $fade_pages_time = 0;
var $contained = array();
var $caption = '';
var $caption_header = '<div style="margin-top: 1ex; text-align: center; font-weight: bold">{caption}</div>';
var $caption_footer = '';
var $auto_adjust_size = 0;
var $adjust = '';
var $show_tabs = 1;
Function ColorChangeIntensity($color,$intensity_offset)
{
if(preg_match('/^#([a-fA-F0-9]{2})([a-fA-F0-9]{2})([a-fA-F0-9]{2})$/', $color, $components) != 7)
return($color);
if(($red = intval(HexDec($components[1]) * (100 + $intensity_offset) / 100)) > 255)
$red = 255;
if(($green = intval(HexDec($components[2]) * (100 + $intensity_offset) / 100)) > 255)
$green = 255;
if(($blue = intval(HexDec($components[3]) * (100 + $intensity_offset) / 100)) > 255)
$blue = 255;
return(sprintf('#%02X%02X%02X', $red, $green, $blue));
}
Function SetStyles()
{
$border=' border-width: '.strval($this->border_width).'px ;';
$page_border=' border-width: '.strval($this->page_border_width).'px ;';
$border_color=(strlen($this->border_color) ? $this->border_color : (strlen($this->foreground_color) ? $this->foreground_color : (strlen($this->background_color) ? $this->background_color : '')));
$lighter=(strlen($this->lighter_border_color) ? $this->lighter_border_color : (strlen($border_color) ? $this->ColorChangeIntensity($border_color, $this->color_offset) : ''));
$darker=(strlen($this->darker_border_color) ? $this->darker_border_color : (strlen($border_color) ? $this->ColorChangeIntensity($border_color, -$this->color_offset) : ''));
$nowrap=' white-space: nowrap ;';
switch($this->side)
{
case 'bottom':
$page_style=' border-bottom-style: solid; border-bottom-color: '.$darker.'; border-top-style: none; border-left-style: solid; border-left-color: '.$lighter.'; border-right-style: solid; border-right-color: '.$darker.'; border-bottom-left-radius: {BORDERRADIUS} ; border-bottom-right-radius: {BORDERRADIUS} ; -moz-border-radius-bottomright: {BORDERRADIUS} ; -moz-border-radius-bottomleft: {BORDERRADIUS} ; -webkit-border-bottom-right-radius: {BORDERRADIUS} ; -webkit-border-bottom-left-radius: {BORDERRADIUS}';
$tab_style=' border-style: solid; border-bottom-color: '.$darker.'; border-top-color: '.$darker.'; border-left-color: '.$lighter.'; border-right-color: '.$darker.'; border-bottom-left-radius: {BORDERRADIUS} ; border-bottom-right-radius: {BORDERRADIUS} ; -moz-border-radius-bottomright: {BORDERRADIUS} ; -moz-border-radius-bottomleft: {BORDERRADIUS} ; -webkit-border-bottom-right-radius: {BORDERRADIUS} ; -webkit-border-bottom-left-radius: {BORDERRADIUS}';
$gap_style=' padding: 0px ; border-bottom-style: none; border-top-style: solid; border-top-color: '.$darker.'; border-left-style: none; border-right-style: none';
break;
case 'top':
default:
$page_style=' border-top-style: solid; border-top-color: '.$lighter.'; border-bottom-style: none; border-left-style: solid; border-left-color: '.$lighter.'; border-right-style: solid; border-right-color: '.$darker.'; border-top-left-radius: {BORDERRADIUS} ; border-top-right-radius: {BORDERRADIUS} ; -moz-border-radius-topright: {BORDERRADIUS} ; -moz-border-radius-topleft: {BORDERRADIUS} ; -webkit-border-top-right-radius: {BORDERRADIUS} ; -webkit-border-top-left-radius: {BORDERRADIUS}';
$tab_style=' border-style: solid; border-top-color: '.$lighter.'; border-bottom-color: '.$lighter.'; border-left-color: '.$lighter.'; border-right-color: '.$darker.'; border-top-left-radius: {BORDERRADIUS} ; border-top-right-radius: {BORDERRADIUS} ; -moz-border-radius-topright: {BORDERRADIUS} ; -moz-border-radius-topleft: {BORDERRADIUS} ; -webkit-border-top-right-radius: {BORDERRADIUS} ; -webkit-border-top-left-radius: {BORDERRADIUS}';
$gap_style=' padding: 0px ; border-top-style: none; border-bottom-style: solid; border-bottom-color: '.$lighter.'; border-left-style: none; border-right-style: none';
break;
}
$this->styles=array(
'page'=>$page_border.$nowrap.str_replace('{BORDERRADIUS}',$this->border_radius.'px',$page_style),
'tab'=>$border.$nowrap.str_replace('{BORDERRADIUS}',$this->border_radius.'px',$tab_style),
'gap'=>$border.$nowrap.$gap_style,
'page_button'=>'border-width: 0px; font-weight: bold; background-color: inherit',
'tab_button'=>'border-width: 0px; background-color: inherit'
);
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['Pages'])
|| GetType($arguments['Pages']) != 'array'
|| count(($arguments['Pages']))==0)
return('it was not specified a valid list of pages to layout');
if(IsSet($arguments['AutoAdjustSize'])
&& $arguments['AutoAdjustSize'])
$this->auto_adjust_size = 1;
if(IsSet($arguments['ShowTabs'])
&& !$arguments['ShowTabs'])
$this->show_tabs = 0;
$this->pages = $arguments['Pages'];
if(IsSet($arguments['CurrentPage']))
{
$this->current_page = $arguments['CurrentPage'];
if(!IsSet($this->pages[$this->current_page]))
return($this->current_page.' is not a valid current page');
}
else
{
Reset($this->pages);
$this->current_page = Key($this->pages);
}
$this->tab = $this->GenerateInputID($form, $this->input, 'tab');
$this->button = $this->GenerateInputID($form, $this->input, 'button');
$this->page = $this->GenerateInputID($form, $this->input, 'page');
$this->switch = $this->GenerateInputID($form, $this->input, 'switch');
if($this->auto_adjust_size)
$this->adjust = $this->GenerateInputID($form, $this->input, 'adjust');
$this->class = $this->GenerateInputID($form, $this->input, 'class');
if(strlen($error = $form->AddInput(array(
'TYPE'=>'hidden',
'ID'=>$this->page,
'NAME'=>$this->page,
'VALUE'=>$this->current_page,
'Accessible'=>1
))))
return($error);
if(IsSet($arguments['PageClass']))
$this->page_class = $arguments['PageClass'];
if(IsSet($arguments['TabClass']))
$this->tab_class = $arguments['TabClass'];
if(IsSet($arguments['GapClass']))
$this->gap_class = $arguments['GapClass'];
if(IsSet($arguments['PageButtonClass']))
$this->page_button_class = $arguments['PageButtonClass'];
if(IsSet($arguments['TabButtonClass']))
$this->tab_button_class = $arguments['TabButtonClass'];
$this->SetStyles();
$t = count($this->pages);
for(Reset($this->pages), $p = 0; $p < $t; Next($this->pages), ++$p)
{
$page = Key($this->pages);
if(strlen($page) == 0)
return('it was specified a page with an empty name');
if(IsSet($this->pages[$page]['Caption'])
&& strlen($this->pages[$page]['Caption']) == 0)
return('it was not specified a valid caption for page '.$page);
if(IsSet($this->pages[$page]['Break']))
{
switch($this->pages[$page]['Break'])
{
case 'before':
case 'after':
break;
default:
return('it was not specified a valid break mode for page '.$page);
}
}
if(strlen($error = $form->AddInput(array(
'TYPE'=>'submit',
'ID'=>$this->button.$page,
'NAME'=>$this->button.$page,
'VALUE'=>(IsSet($this->pages[$page]['Name']) ? $this->pages[$page]['Name'] : $page),
'SubForm'=>(IsSet($this->pages[$page]['SubForm']) ? $this->pages[$page]['SubForm'] : $this->button.'_sub_form'),
'IgnoreAnonymousSubmitCheck'=>1,
'DisableResubmitCheck'=>1,
'ONMOUSEUP'=>'this.clicked = true',
'ONKEYDOWN'=>'this.clicked = (event.keyCode == 13)',
'ONCLICK'=>'if(!this.clicked) return false; this.clicked = false; '.$this->switch.'(this.form, '.$form->EncodeJavascriptString($page).'); return false;',
'Accessible'=>1
))))
return($error);
}
if(IsSet($arguments['FadePagesTime']))
{
$time_type = GetType($this->fade_pages_time = $arguments['FadePagesTime']);
if((strcmp($time_type,'double')
&& strcmp($time_type,'integer'))
|| $this->fade_pages_time < 0)
return('it was not specified a valid fade pages time');
}
if($this->fade_pages_time > 0
&& strlen($error = $form->AddInput(array(
'TYPE'=>'custom',
'ID'=>$this->page.'animation',
'CustomClass'=>'form_animation_class',
'JavascriptPath'=>(IsSet($arguments['JavascriptPath']) ? $arguments['JavascriptPath'] : '')
))))
return($error);
return($form->ConnectFormToInput($this->input, 'ONERROR', 'SwitchPage', array('InputsPage'=>'Invalid')));
}
Function AddInputPart(&$form)
{
$page_class = (strlen($this->page_class) ? $this->page_class : $this->class.'page');
$tab_class = (strlen($this->tab_class) ? $this->tab_class : $this->class.'tab');
$gap_class = (strlen($this->gap_class) ? $this->gap_class : $this->class.'gap');
$page_button_class = (strlen($this->page_button_class) ? $this->page_button_class : $this->class.'page_button');
$tab_button_class = (strlen($this->tab_button_class) ? $this->tab_button_class : $this->class.'tab_button');
$row_start = '<table width="100%" cellpadding="'.$this->tab_padding.'" cellspacing="0" style="margin-bottom: '.$this->row_gap.'px"><tr>';
$row_end = '<td class="'.HtmlSpecialChars($gap_class).'" width="99%">&nbsp;</td></tr></table>';
if(strlen($error = $form->AddInputPart($this->page)))
return($error);
$t = count($this->pages);
if($this->show_tabs)
{
if(strlen($error = $form->AddDataPart($row_start)))
return($error);
for(Reset($this->pages), $p = 0; $p < $t; Next($this->pages), ++$p)
{
$page = Key($this->pages);
$button = $this->button.$page;
$is_page = !strcmp($page, $this->current_page);
$break = (IsSet($this->pages[$page]['Break']) ? $this->pages[$page]['Break'] : '');
if(strlen($error = $form->SetInputProperty($button, 'CLASS', $is_page ? $page_button_class : $tab_button_class))
|| (!strcmp($break, 'before')
&& strlen($error = $form->AddDataPart($row_end.$row_start)))
|| strlen($error = $form->AddDataPart('<td class="'.HtmlSpecialChars($gap_class).'">&nbsp;</td><td id="'.HtmlSpecialChars($this->tab.$page).'" class="'.HtmlSpecialChars($is_page ? $page_class : $tab_class).'">'))
|| strlen($error = $form->AddInputPart($button))
|| strlen($error = $form->AddDataPart('</td>'))
|| (!strcmp($break, 'after')
&& strlen($error = $form->AddDataPart($row_end.$row_start))))
return($error);
}
if(strlen($error = $form->AddDataPart($row_end)))
return($error);
}
if($this->auto_adjust_size
&& strlen($error = $form->AddDataPart('<div id="'.HtmlSpecialChars($this->page).'_parent">')))
return($error);
for(Reset($this->pages), $p = 0; $p < $t; Next($this->pages), ++$p)
{
$page = Key($this->pages);
$is_page = !strcmp($page, $this->current_page);
$header = '<div id="'.HtmlSpecialChars($this->page.$page).'" style="display: '.($is_page ? 'block' : 'none').'">';
$footer = '</div>';
if(IsSet($this->pages[$page]['Caption'])
&& strlen($caption = $this->pages[$page]['Caption']))
{
$header .= str_replace('{caption}', $caption, $this->caption_header);
$footer = str_replace('{caption}', $caption, $this->caption_footer).$footer;
}
if(strlen($error = $form->AddDataPart($header))
|| strlen($error = $this->AddPagePart($form, $page))
|| strlen($error = $form->AddDataPart($footer)))
return($error);
}
if($this->auto_adjust_size
&& strlen($error = $form->AddDataPart('</div>')))
return($error);
return('');
}
Function LoadInputValues(&$form, $submitted)
{
$t = count($this->pages);
for(Reset($this->pages), $p = 0; $p < $t; Next($this->pages), ++$p)
{
$page = Key($this->pages);
if($form->WasSubmitted($this->button.$page))
{
$form->SetInputValue($this->page, $this->current_page = $page);
return;
}
}
$page = $form->GetInputValue($this->page);
if(IsSet($this->pages[$page]))
$this->current_page = $page;
else
$form->SetInputValue($this->page, $this->current_page);
return('');
}
Function PageHead(&$form)
{
$eol = $form->end_of_line;
$page_class = (strlen($this->page_class) ? $this->page_class : $this->class.'page');
$tab_class = (strlen($this->tab_class) ? $this->tab_class : $this->class.'tab');
$page_button_class = (strlen($this->page_button_class) ? $this->page_button_class : $this->class.'page_button');
$tab_button_class = (strlen($this->tab_button_class) ? $this->tab_button_class : $this->class.'tab_button');
Reset($this->pages);
$context=array(
'Name'=>'Fade tab',
'Effects'=>array(
array(
'Type'=>'CancelAnimation',
'Animation'=>'Fade tab'
),
array(
'Type'=>'FadeIn',
'DynamicElement'=>'\''.$this->page.'\' + page',
'Duration'=>$this->fade_pages_time,
'Visibility'=>'display'
),
)
);
if($this->fade_pages_time>0
&& strlen($fade_error = $form->GetJavascriptConnectionAction('form', $this->input, $this->page.'animation', 'ONCHANGE', 'AddAnimation', $context, $fade_javascript)))
$form->OutputDebug('could not setup fade animation for paged layout input '.$this->input.': '.$fade_error);
if($this->auto_adjust_size)
{
$tp = count($this->pages);
for($pages = '', Reset($this->pages), $p = 0; $p < $tp; ++$p, Next($this->pages))
{
if($p > 0)
$pages .= ', ';
$pages .= '\''.Key($this->pages).'\'';
}
}
$head = '<script type="text/javascript"><!--'.$eol.
'function '.$this->switch.'(form, page)'.$eol.
'{'.$eol.
' var old_page'.$eol.
' var e'.$eol.$eol.
' old_page = '.$form->GetJavascriptInputValue('form', $this->page).$eol.
' '.$form->GetJavascriptSetInputValue('form', $this->page, 'page').$eol.
' if((e = document.getElementById(\''.$this->tab.'\' + old_page)))'.$eol.
' e.className = \''.$tab_class.'\''.$eol.
' if((e = document.getElementById(\''.$this->button.'\' + old_page)))'.$eol.
' e.className = \''.$tab_button_class.'\''.$eol.
' if((e = document.getElementById(\''.$this->page.'\' + old_page)))'.$eol.
' e.style.display = \'none\''.$eol.
' if((e = document.getElementById(\''.$this->tab.'\' + page)))'.$eol.
' e.className = \''.$page_class.'\''.$eol.
' if((e = document.getElementById(\''.$this->button.'\' + page)))'.$eol.
' e.className = \''.$page_button_class.'\''.$eol.
(($this->fade_pages_time>0 && strlen($fade_error) == 0) ?
' if(page != old_page)'.$eol.
' {'.$eol.
' '.$fade_javascript.$eol.
' }'.$eol
: '').
' if((e = document.getElementById(\''.$this->page.'\' + page)))'.$eol.
' e.style.display = \'block\''.$eol.
'}'.$eol.
($this->auto_adjust_size ? $eol.
'function '.$this->adjust.'_size(e)'.$eol.
'{'.$eol.
' if(document.getBoxObjectFor)'.$eol.
' {'.$eol.
' var b=document.getBoxObjectFor(e)'.$eol.
' var size={width: parseInt(b.width), height: parseInt(b.height)}'.$eol.
' if(window.getComputedStyle)'.$eol.
' {'.$eol.
' var s=window.getComputedStyle(e,null)'.$eol.
' size.width-=parseInt(s.borderLeftWidth)+parseInt(s.borderRightWidth)+parseInt(s.paddingLeft)+parseInt(s.paddingRight)'.$eol.
' size.height-=parseInt(s.borderTopWidth)+parseInt(s.borderBottomWidth)+parseInt(s.paddingTop)+parseInt(s.paddingRight)'.$eol.
' }'.$eol.
' }'.$eol.
' else'.$eol.
' var size={width: parseInt(e.offsetWidth), height: parseInt(e.offsetHeight)}'.$eol.
' return(size)'.$eol.
' }'.$eol.$eol.
'function '.$this->adjust.'()'.$eol.
'{'.$eol.
' var width = 0'.$eol.
' var height = 0'.$eol.
' var pages = ['.$pages.'];'.$eol.
' var parent = document.getElementById(\''.$this->page.'_parent\')'.$eol.
' var ad = [];'.$eol.
' var l = 0;'.$eol.
' for(var a = parent; a && a.style; a = a.parentNode, ++l)'.$eol.
' {'.$eol.
' if((ad[l] = a.style.display) == \'none\')'.$eol.
' a.style.display = \'block\''.$eol.
' }'.$eol.
' for(var p = 0; p < pages.length; ++p)'.$eol.
' {'.$eol.
' var e = document.getElementById(\''.$this->page.'\' + pages[p])'.$eol.
' if(!e) continue'.$eol.
' var d = e.style.display'.$eol.
' if(d == \'none\')'.$eol.
' {'.$eol.
' e.style.visibility = \'hidden\''.$eol.
' e.style.display = \'block\''.$eol.
' }'.$eol.
' var s = '.$this->adjust.'_size(e)'.$eol.
' width = Math.max(width, s.width)'.$eol.
' height = Math.max(height, s.height)'.$eol.
' if(d == \'none\')'.$eol.
' {'.$eol.
' e.style.display = d'.$eol.
' e.style.visibility = \'\''.$eol.
' }'.$eol.
' }'.$eol.
' l = 0'.$eol.
' for(var a = parent; a && a.style; a = a.parentNode, ++l)'.$eol.
' {'.$eol.
' if(ad[l] == \'none\')'.$eol.
' a.style.display = \'none\''.$eol.
' }'.$eol.
' if(parent)'.$eol.
' {'.$eol.
' if(width)'.$eol.
' parent.style.width = width + "px"'.$eol.
' if(height)'.$eol.
' parent.style.height = height + "px"'.$eol.
' }'.$eol.
'}'.$eol
: '').
'// --></script>'.$eol;
if(strlen($this->page_class)==0
|| strlen($this->tab_class)==0
|| strlen($this->gap_class)==0
|| strlen($this->page_button_class)==0
|| strlen($this->tab_button_class)==0)
{
$head .= '<style type="text/css"><!--'.$eol.
(strlen($this->page_class) ? '' : '.'.$this->class.'page {'.$this->styles['page'].' }'.$eol).
(strlen($this->tab_class) ? '' : '.'.$this->class.'tab {'.$this->styles['tab'].' }'.$eol).
(strlen($this->gap_class) ? '' : '.'.$this->class.'gap {'.$this->styles['gap'].' }'.$eol).
(strlen($this->page_button_class) ? '' : '.'.$this->class.'page_button {'.$this->styles['page_button'].' }'.$eol).
(strlen($this->tab_button_class) ? '' : '.'.$this->class.'tab_button {'.$this->styles['tab_button'].' }'.$eol).
'// --></style>'.$eol;
}
return($head);
}
Function PageLoad(&$form)
{
return($this->auto_adjust_size ? $this->adjust.'();' : '');
}
Function AddPagePart(&$form, $page)
{
return($form->AddInputPart($page));
}
Function GetContainedPageInputs(&$form, $page, &$contained)
{
if(IsSet($this->contained[$page]))
{
$contained = $this->contained[$page];
return('');
}
if(strlen($error = $form->GetContainedInputs($page, '', $contained)))
return($error);
$this->contained[$page] = $contained ;
return('');
}
Function ValidateInput(&$form)
{
if(count($form->Invalid) == 0)
return('');
Reset($form->Invalid);
$invalid = Key($form->Invalid);
$flip = function_exists('array_flip');
$tp = count($this->pages);
for($found = 0, Reset($this->pages), $p = 0; $p < $tp; ++$p, Next($this->pages))
{
$page = Key($this->pages);
if(strlen($error = $this->GetContainedPageInputs($form, $page, $page_contained)))
return($error);
if($flip)
{
$contained = array_flip($page_contained);
if(($found = IsSet($contained[$invalid])))
break;
}
else
{
$tc = count($page_contained);
for($c = 0; $c < $tc; ++$c)
{
if(($found = !strcmp($invalid, $page_contained[$c])))
break 2;
}
}
}
return($found ? $form->SetInputValue($this->page, $this->current_page = $page) : '');
}
Function GetContainedInputs(&$form, $kind, &$contained)
{
$contained = array($this->input);
$tp = count($this->pages);
for(Reset($this->pages), $p = 0; $p < $tp; ++$p, Next($this->pages))
{
$page = Key($this->pages);
if(strlen($kind) == 0)
{
if(strlen($error = $this->GetContainedPageInputs($form, $page, $page_contained)))
return($error);
}
elseif(strlen($error = $form->GetContainedInputs($page, $kind, $page_contained)))
return($error);
$tc = count($page_contained);
for($c = 0; $c < $tc; ++$c)
$contained[] = $page_contained[$c];
}
return('');
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'SwitchPage':
$javascript = '';
if(IsSet($context['Page']))
{
if(!IsSet($this->pages[$context['Page']]))
return($context['Page'].' is not a valid page to switch');
$page = $form->EncodeJavascriptString($context['Page']);
$conditional = 0;
}
elseif(IsSet($context['PageValue']))
{
if(strlen($context['PageValue']) == 0)
return($context['PageValue'].' is not a valid expression of a page to switch');
$page = $context['PageValue'];
$conditional = 1;
}
elseif(IsSet($context['InputsPage']))
{
$inputs = $context['InputsPage'];
$javascript.='var pages = {';
$tp = count($this->pages);
for(Reset($this->pages), $p = 0; $p < $tp; ++$p, Next($this->pages))
{
$page = Key($this->pages);
if(strlen($error = $this->GetContainedPageInputs($form, $page, $contained)))
return($error);
$page_value = $form->EncodeJavascriptString($page);
$tc = count($contained);
for($c = 0; $c < $tc; ++$c)
{
if($c > 0
|| $p > 0)
$javascript.=', ';
$javascript.=$form->EncodeJavascriptString($contained[$c]).': '.$page_value;
}
}
$javascript.=' }; var page = \'\'; for(var i in '.$inputs.') { if(pages[i]) { page = pages[i]; break; } }; ';
$page = 'page';
$conditional = 1;
}
else
return('it was not specified a valid page to switch');
$javascript .= ($conditional ? 'if('.$page.'.length) ' : '').$this->switch.'('.$form_object.', '.$page.');';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case 'CurrentPage':
if(!IsSet($this->pages[$value]))
return($value.' is not a valid current page');
$this->current_page = $value;
break;
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
};
?>

View file

@ -0,0 +1,349 @@
<?php
/*
*
* @(#) $Id: form_layout_vertical.php,v 1.16 2013/08/12 13:32:10 mlemos Exp $
*
*/
class form_layout_vertical_class extends form_custom_class
{
var $inputs = array();
var $columns = array();
var $data = array();
var $properties = array();
var $header = '<table>';
var $footer = '</table>';
var $columns_header = '<table><tr>';
var $columns_footer = '</tr></table>';
var $column_start = '<td valign="top">';
var $column_end = '</td>';
var $input_format = "<tr><td>{label}:</td><td>{input}&nbsp;<span id=\"mark_{id}\">{mark}</span></td></tr>\n";
var $switched_position_input_format = "<tr><td align=\"right\">{input}</td><td>{label}&nbsp;<span id=\"mark_{id}\">{mark}</span></td></tr>\n";
var $no_label_input_format = "<tr><td colspan=\"2\" align=\"center\">{input}</td></tr>\n";
var $centered_group_left_input_format='<tr><td colspan="2" align="center">{input}';
var $centered_group_middle_input_format="&nbsp;{input}";
var $centered_group_right_input_format="&nbsp;{input}</td></tr>\n";
var $invalid_mark = '[X]';
var $default_mark = '';
var $server_validate = 0;
var $mark_prefix = 'mark_';
Function AddInput(&$form, $arguments)
{
if(IsSet($arguments['Columns']))
{
if(GetType($arguments['Columns']) != 'array'
|| count(($arguments['Columns']))==0)
return('it was not specified a valid list of input columns to layout');
$this->columns = $arguments['Columns'];
}
elseif(!IsSet($arguments['Inputs'])
|| GetType($arguments['Inputs']) != 'array'
|| count(($this->inputs = $arguments['Inputs']))==0)
return('it was not specified a valid list of inputs to layout');
if(IsSet($arguments['Data']))
{
if(GetType($arguments['Data']) != 'array')
return('it was not specified a valid list of data elements to layout');
$this->data = $arguments['Data'];
}
if(IsSet($arguments['Properties']))
{
if(GetType($arguments['Properties']) != 'array')
return('it was not specified a valid list of input properties');
$this->properties = $arguments['Properties'];
}
if(IsSet($arguments['DefaultMark']))
$this->default_mark = $arguments['DefaultMark'];
if(IsSet($arguments['InvalidMark']))
{
if(strlen($arguments['InvalidMark'])==0)
return('it was not specified a valid input invalid mark');
$this->invalid_mark = $arguments['InvalidMark'];
}
if(IsSet($arguments['InputFormat']))
{
if(strlen($arguments['InputFormat'])==0)
return('it was not specified a valid input format template');
$this->input_format = $arguments['InputFormat'];
}
if(IsSet($arguments['SwitchedPositionInputFormat']))
{
if(strlen($arguments['SwitchedPositionInputFormat'])==0)
return('it was not specified a valid switched position input format template');
$this->switched_position_input_format = $arguments['SwitchedPositionInputFormat'];
}
if(IsSet($arguments['CenteredGroupLeftInputFormat']))
{
if(strlen($arguments['CenteredGroupLeftInputFormat'])==0)
return('it was not specified a valid centered group left input format template');
$this->centered_group_left_input_format = $arguments['CenteredGroupLeftInputFormat'];
}
if(IsSet($arguments['CenteredGroupMiddleInputFormat']))
{
if(strlen($arguments['CenteredGroupMiddleInputFormat'])==0)
return('it was not specified a valid centered group middle input format template');
$this->centered_group_middle_input_format = $arguments['CenteredGroupMiddleInputFormat'];
}
if(IsSet($arguments['CenteredGroupRightInputFormat']))
{
if(strlen($arguments['CenteredGroupRightInputFormat'])==0)
return('it was not specified a valid centered group right input format template');
$this->centered_group_right_input_format = $arguments['CenteredGroupRightInputFormat'];
}
if(IsSet($arguments['NoLabelInputFormat']))
{
if(strlen($arguments['NoLabelInputFormat'])==0)
return('it was not specified a valid no label input format template');
$this->no_label_input_format = $arguments['NoLabelInputFormat'];
}
if(IsSet($arguments['Header']))
{
if(strlen($arguments['Header'])==0)
return('it was not specified a valid header template');
$this->header = $arguments['Header'];
}
if(IsSet($arguments['Footer']))
{
if(strlen($arguments['Footer'])==0)
return('it was not specified a valid footer template');
$this->footer = $arguments['Footer'];
}
return('');
}
Function AddInputParts(&$form, $inputs)
{
if(strlen($error = $form->AddDataPart($this->header)))
return($error);
$ti = count($inputs);
$valid_marks=array(
'dynamicinput'=>array(
'input'=>'input',
),
'dynamiclabel'=>array(
'label'=>'input'
),
'dynamicdata'=>array(
'mark'=>'mark',
'id'=>'id'
)
);
$parsed = $parsed_switched_position = $parsed_no_label = $parsed_centered_group_left = $parsed_centered_group_middle = $parsed_centered_group_right = 0;
$hidden = array();
for($i = 0; $i < $ti; $i++)
{
$input = $inputs[$i];
if(IsSet($this->properties[$input]['Hidden'])
&& $this->properties[$input]['Hidden'])
{
$hidden[] = $input;
continue;
}
if(IsSet($this->properties[$input]['Visible'])
&& !$this->properties[$input]['Visible'])
continue;
if(IsSet($this->data[$input]))
{
if(strlen(($error=$form->AddDataPart($this->data[$input]))))
return($error);
continue;
}
$read_only=(IsSet($this->properties[$input]['ReadOnly']) && $this->properties[$input]['ReadOnly']);
$dynamic=array(
'input'=>$input,
'mark'=>(IsSet($form->Invalid[$input]) ? (IsSet($this->properties[$input]['InvalidMark']) ? $this->properties[$input]['InvalidMark'] : $this->invalid_mark) : (IsSet($this->properties[$input]['DefaultMark']) ? $this->properties[$input]['DefaultMark'] : $this->default_mark)),
'id'=>$input
);
if(IsSet($this->properties[$input]['InputFormat']))
{
if(strlen($error = $this->ParseFormat($this->properties[$input]['InputFormat'], $valid_marks, $custom_data, $custom_marks))
|| strlen($error = $this->AddFormattedDynamicPart($form, $custom_data, $custom_marks, 0, $read_only, $dynamic)))
return($error);
}
else
{
UnSet($label);
$form->GetInputProperty($input, 'LABEL', $label);
if(IsSet($label))
{
if(IsSet($this->properties[$input]['SwitchedPosition'])
&& $this->properties[$input]['SwitchedPosition'])
{
if(!$parsed_switched_position)
{
if(strlen($error = $this->ParseFormat($this->switched_position_input_format, $valid_marks, $data_switched_position, $marks_switched_position)))
return($error);
$parsed_switched_position = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data_switched_position, $marks_switched_position, 0, $read_only, $dynamic)))
return($error);
}
else
{
if(!$parsed)
{
if(strlen($error = $this->ParseFormat($this->input_format, $valid_marks, $data, $marks)))
return($error);
$parsed = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data, $marks, 0, $read_only, $dynamic)))
return($error);
}
}
else
{
if(IsSet($this->properties[$input]['CenteredGroup']))
{
switch($this->properties[$input]['CenteredGroup'])
{
case 'left':
if(!$parsed_centered_group_left)
{
if(strlen($error = $this->ParseFormat($this->centered_group_left_input_format, $valid_marks, $data_centered_group_left, $marks_centered_group_left)))
return($error);
$parsed_centered_group_left = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data_centered_group_left, $marks_centered_group_left, 0, $read_only, $dynamic)))
return($error);
break;
case 'middle':
if(!$parsed_centered_group_middle)
{
if(strlen($error = $this->ParseFormat($this->centered_group_middle_input_format, $valid_marks, $data_centered_group_middle, $marks_centered_group_middle)))
return($error);
$parsed_centered_group_middle = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data_centered_group_middle, $marks_centered_group_middle, 0, $read_only, $dynamic)))
return($error);
break;
case 'right':
if(!$parsed_centered_group_right)
{
if(strlen($error = $this->ParseFormat($this->centered_group_right_input_format, $valid_marks, $data_centered_group_right, $marks_centered_group_right)))
return($error);
$parsed_centered_group_right = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data_centered_group_right, $marks_centered_group_right, 0, $read_only, $dynamic)))
return($error);
break;
}
}
else
{
if(!$parsed_no_label)
{
if(strlen($error = $this->ParseFormat($this->no_label_input_format, $valid_marks, $data_no_label, $marks_no_label)))
return($error);
$parsed_no_label = 1;
}
if(strlen($error = $this->AddFormattedDynamicPart($form, $data_no_label, $marks_no_label, 0, $read_only, $dynamic)))
return($error);
}
}
}
}
if(strlen($error = $form->AddDataPart($this->footer)))
return($error);
$ti = count($hidden);
for($i = 0; $i < $ti; ++$i)
{
if(strlen($error = $form->AddInputHiddenPart($hidden[$i])))
return($error);
}
return '';
}
Function MarkValidated(&$form, $form_object, $document_object, $event, $context, $inputs, &$javascript)
{
$ti = count($inputs);
for($i = 0; $i < $ti; $i++)
{
$input = $inputs[$i];
if((IsSet($this->properties[$input]['Visible'])
&& !$this->properties[$input]['Visible'])
|| IsSet($this->data[$input]))
continue;
$mark = (IsSet($form->Invalid[$input]) ? (IsSet($this->properties[$input]['InvalidMark']) ? $this->properties[$input]['InvalidMark'] : $this->invalid_mark) : (IsSet($this->properties[$input]['DefaultMark']) ? $this->properties[$input]['DefaultMark'] : $this->default_mark));
$id = $this->mark_prefix.$input;
if(strlen($error = $form->GetJavascriptConnectionAction($form_object, $this->input, $input, $event, 'MarkValidated', $context, $js)))
return($error);
$javascript .= $js.'if(d='.$document_object.'.getElementById('.$form->EncodeJavascriptString($id).')) d.innerHTML='.$form->EncodeJavascriptString($mark).';';
}
return('');
}
Function AddInputPart(&$form)
{
if(($tc = count($this->columns)))
{
if(strlen($error = $form->AddDataPart($this->columns_header)))
return($error);
for($c = 0; $c < $tc; ++$c)
{
if(strlen($error = $form->AddDataPart($this->column_start))
|| strlen($error = $this->AddInputParts($form, $this->columns[$c]))
|| strlen($error = $form->AddDataPart($this->column_end)))
return($error);
}
return($form->AddDataPart($this->columns_footer));
}
return($this->AddInputParts($form, $this->inputs));
}
Function GetInputsContainedInputs(&$form, $kind, &$contained, $inputs)
{
$ti = count($inputs);
for($i = 0; $i < $ti; ++$i)
{
$input = $inputs[$i];
if(IsSet($this->data[$input]))
continue;
if(strlen($error = $form->GetContainedInputs($input, $kind, $input_contained)))
return($error);
$tc = count($input_contained);
for($c = 0; $c < $tc; ++$c)
$contained[] = $input_contained[$c];
}
}
Function GetContainedInputs(&$form, $kind, &$contained)
{
$contained = array($this->input);
if(($tc = count($this->columns)))
{
for($c = 0; $c < $tc; ++$c)
{
if(strlen($error = $this->GetInputsContainedInputs($form, $kind, $contained, $this->columns[$c])))
return($error);
}
return('');
}
return($this->GetInputsContainedInputs($form, $kind, $contained, $this->inputs));
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'MarkValidated':
$document_object = (IsSet($context['Document']) ? $context['Document'] : 'document');
$javascript = 'var d;';
if(($tc = count($this->columns)))
{
for($c = 0; $c < $tc; ++$c)
{
if(strlen($error = $this->MarkValidated($form, $form_object, $document_object, $event, $context, $this->columns[$c], $javascript)))
return($error);
}
}
return($this->MarkValidated($form, $form_object, $document_object, $event, $context, $this->inputs, $javascript));
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $document_object, $from, $event, $action, $context, $javascript));
}
return('');
}
};
?>

View file

@ -0,0 +1,342 @@
<?php
/*
*
* @(#) $Id: form_linked_select.php,v 1.18 2012/04/19 10:02:00 mlemos Exp $
*
*/
class form_linked_select_class extends form_custom_class
{
var $select="";
var $group="";
var $switch_group="";
var $linked_input="";
var $selected_group="";
var $groups=array();
var $server_validate=0;
var $multiple=0;
var $dynamic=0;
var $default_dynamic=0;
var $group_parameter="___group";
Function GetGroupOptions(&$options,$group)
{
if(IsSet($this->groups[$group]))
$options=$this->groups[$group];
else
Unset($options);
return("");
}
Function GetGroups(&$groups)
{
$groups=array();
Reset($this->groups);
for($g=0;$g<count($this->groups);$g++)
{
$groups[]=strval(Key($this->groups));
Next($this->groups);
}
return("");
}
Function ValidateGroups(&$arguments)
{
if(!IsSet($arguments["Groups"])
|| GetType($arguments["Groups"])!="array")
return("it were not specified the groups of options");
$this->groups=$arguments["Groups"];
if(!IsSet($this->groups[$this->selected_group]))
return("the current linked input value does not match any of the select options groups");
if(!IsSet($this->groups[$this->selected_group]))
{
if((!IsSet($arguments["Group"])
|| !IsSet($arguments["Groups"][$arguments["Group"]])))
return("it was not specified a valid group for the current options");
$this->selected_group=$arguments["Group"];
}
UnSet($arguments["Groups"]);
UnSet($arguments["Group"]);
return("");
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments["LinkedInput"]))
return("it was not specified a valid input to link the select input");
$this->linked_input=$arguments["LinkedInput"];
$this->selected_group=$form->GetInputValue($this->linked_input);
if(strlen($error=$this->ValidateGroups($arguments)))
return($error);
$this->dynamic=(IsSet($arguments["Dynamic"]) ? intval($arguments["Dynamic"]) : $this->default_dynamic);
if(!$this->dynamic
&& (IsSet($arguments["AutoWidthLimit"])
|| IsSet($arguments["AutoHeightLimit"])))
{
if(strlen($error=$this->GetGroups($groups)))
return($error);
$w=$h=0;
for($g=0;$g<count($groups);$g++)
{
$group=$groups[$g];
if(strlen($error=$this->GetGroupOptions($options,$group)))
return($error);
Reset($options);
for($o=0;$o<count($options);$o++)
{
$option=strval(Key($options));
$w=max($w,strlen($options[$option]));
Next($options);
}
$h=max($h,$o);
}
if(IsSet($arguments["AutoWidthLimit"]))
{
if($arguments["AutoWidthLimit"]>0)
$w=min($w+1,$arguments["AutoWidthLimit"]);
$arguments["STYLE"]="width: ".strval($w)."em".(IsSet($arguments["STYLE"]) ? "; ".$arguments["STYLE"] : "");
}
if(IsSet($arguments["AutoHeightLimit"]))
{
if($arguments["AutoHeightLimit"]>0)
$h=min($h,$arguments["AutoHeightLimit"]);
$arguments["SIZE"]=strval($h);
}
}
UnSet($arguments["Dynamic"]);
UnSet($arguments["AutoWidthLimit"]);
UnSet($arguments["AutoHeightLimit"]);
if(strlen($error=$this->GetGroupOptions($selected_group,$this->selected_group)))
return($error);
$select_arguments=$arguments;
UnSet($select_arguments["LinkedInput"]);
$this->select=$this->GenerateInputID($form, $this->input, "select");
$this->group=$this->GenerateInputID($form, $this->input, "group");
$this->switch_group=$this->GenerateInputID($form, $this->input, "switch_group");
$select_arguments["NAME"]=$select_arguments["ID"]=$this->focus_input=$this->select;
$select_arguments["TYPE"]="select";
$select_arguments["OPTIONS"]=$selected_group;
$select_arguments["DiscardInvalidValues"]=0;
$this->multiple=IsSet($arguments["MULTIPLE"]);
if($this->multiple)
{
$select_arguments["MULTIPLE"]=1;
if(!IsSet($select_arguments["SELECTED"]))
$select_arguments["SELECTED"]=array();
}
else
UnSet($select_arguments["MULTIPLE"]);
UnSet($select_arguments["CustomClass"]);
if(strlen($error=$form->AddInput($select_arguments))==0
&& strlen($error=$form->AddInput(array(
"TYPE"=>"hidden",
"ID"=>$this->group,
"NAME"=>$this->group,
"VALUE"=>$this->selected_group
)))==0)
$error=$form->Connect($this->linked_input, $this->input, "ONCHANGE", "SwitchGroup", array("GroupProperty"=>"VALUE"));
return($error);
}
Function AddInputPart(&$form)
{
$eol=$form->end_of_line;
$b="";
$javascript="<script type=\"text/javascript\" defer=\"defer\">".$eol."<!--\n";
if($this->dynamic)
{
$javascript.="var ".$this->switch_group."_g=null;".$eol;
$javascript.="var ".$this->switch_group."_f=null;".$eol;
$javascript.="var ".$this->switch_group."_n=null;".$eol;
}
$javascript.="function ".$this->switch_group."(".($this->dynamic ? "" : "g,f").")".$b."{".$b;
$javascript.="var n, o, i, s, a, b, bi;".$b;
if($this->dynamic)
$javascript.="var n=".$this->switch_group."_n;".$b;
else
{
if(strlen($error=$this->GetGroups($groups)))
return($error);
for($g=0, $append="";$g<count($groups); $g++)
{
$group=$groups[$g];
if($g>0)
$javascript.="}".$b."else".$b."{".$b;
$javascript.="if(g==".$form->EncodeJavascriptString($group).")".$b."{".$b."n=[";
$append.="}".$b;
if(strlen($error=$this->GetGroupOptions($options,$group)))
return($error);
Reset($options);
for($o=0;$o<count($options);$o++)
{
$option=strval(Key($options));
if($o>0)
$javascript.=",";
$javascript.=$form->EncodeJavascriptString($options[$option]).",".$form->EncodeJavascriptString($option);
Next($options);
}
$javascript.="]".$b;
}
$javascript.="}".$b."else".$b."{".$b."n=null".$b.$append;
}
$javascript.="if(n!=null)".$b."{".$b;
if($this->dynamic)
$javascript.="var g=".$this->switch_group."_g;".$b."f=".$this->switch_group."_f;".$b;
$javascript.="s=f[".$form->EncodeJavascriptString($this->select)."];".$b."o=s.options;".$b;
if(!$this->multiple)
$javascript.="bi=bi=s.selectedIndex;".$b."if(bi>=0) { b=o[bi].value };".$b;
$javascript.="i=0;".$b."while(i<n.length)".$b."{".$b."o[i/2]=new Option(n[i],n[i+1]);".$b."i=i+2;".$b."}".$b."while(i<o.length*2)".$b."{".$b."o[i/2]=null".$b."}".$b."f[".$form->EncodeJavascriptString($this->group)."].value=g;".$b;
if(!$this->multiple)
$javascript.="o[0].selected=true;".$b."a=s.options[ai=s.selectedIndex].value;".$b."if(bi>=0 && a!=b && s.onchange) s.onchange();".$b;
$javascript.="}".$b;
if($this->dynamic)
$javascript.="else".$b."{".$b."setTimeout('".$this->switch_group."()',10)".$b."}".$b;
$javascript.="}".$eol."// -->".$eol."</script>";
if($this->dynamic)
$javascript.="<iframe id=\"".$this->switch_group."_i\" width=\"0\" height=\"0\" frameborder=\"0\"></iframe>";
if(strlen($error=$form->AddDataPart($javascript))==0
&& strlen($error=$form->AddInputPart($this->select))==0)
$error=$form->AddInputPart($this->group);
return($error);
}
Function GetInputValue(&$form)
{
return($form->GetInputValue($this->select));
}
Function Connect(&$form, $to, $event, $action, &$context)
{
return($form->Connect($this->select, $to, $event, $action, $context));
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case "SwitchGroup":
$property=(IsSet($context["GroupProperty"]) ? $context["GroupProperty"] : "VALUE");
if(strcmp($property, "VALUE"))
return("it is not supported to switch to a group defined by property ".$property);
$value=$form->GetJavascriptInputValue($form_object, $from);
if(strlen($value)==0)
return("it was not possible to determine how to retrieve ".$property." value");
if($this->dynamic)
{
if(strlen($error=$form->GetInputEventURL($this->input,"getoptions",array($this->group_parameter=>"GROUP"),$iframe_url)))
return($error);
$javascript="if(document.getElementById && (f=document.getElementById('".$this->switch_group."_i'))){g=".$value.";".$this->switch_group."_g=g;".$this->switch_group."_f=".$form_object.";".$this->switch_group."_n=null;"."g=escape(g);while((p=g.indexOf('+'))!=-1){g=g.substring(0,p)+'%2B'+g.substring(p+1,g.length)}f.src='".str_replace("GROUP", "'+g+'", $iframe_url)."';setTimeout('".$this->switch_group."()',10)}";
}
else
$javascript=$this->switch_group."(".$value.",".$form_object.")";
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return("");
}
Function LoadInputValues(&$form, $submitted)
{
$group=$form->GetInputValue($this->linked_input);
$selected_group=$form->GetInputValue($this->group);
$this->GetGroupOptions($options,$group);
if(!IsSet($options)
&& strcmp($group,$selected_group))
{
$group=$selected_group;
$this->GetGroupOptions($options,$group);
}
if(IsSet($options))
{
if($this->multiple)
{
$selected=$form->GetInputValue($this->select);
for($option=0; $option<count($selected); $option++)
{
if(!IsSet($options[$selected[$option]]))
break;
}
if($option<count($selected))
{
$selected=array();
$group=$this->selected_group;
$this->GetGroupOptions($options,$group);
}
else
$this->selected_group=$group;
$form->SetSelectOptions($this->select, $options, $selected);
}
else
{
$option=$form->GetInputValue($this->select);
if(IsSet($options[$option]))
{
$this->selected_group=$group;
$form->SetSelectOptions($this->select, $options, array($option));
}
else
{
$this->GetGroupOptions($options,$this->selected_group);
Reset($options);
$option=Key($options);
$form->SetInputValue($this->select, $option);
}
}
}
if(strcmp($group, $selected_group))
$form->SetInputValue($this->group, $this->selected_group=$group);
return('');
}
Function HandleEvent(&$form, $event, $parameters, &$processed)
{
switch($event)
{
case "getoptions":
if($this->dynamic)
{
if(!IsSet($parameters[$this->group_parameter])
&& GetType($parameters[$this->group_parameter])=="string")
return("the group parameter is not being passed to the linked select input getoptions event handler");
if(strlen($error=$this->GetGroupOptions($g,$parameters[$this->group_parameter])))
return($error);
$c=count($g);
$v="";
for($o=0;$o<$c;$o++)
{
if($o>0)
$v.=",\n";
$k=Key($g);
$v.=$form->EncodeJavascriptString($g[$k]).",".$form->EncodeJavascriptString($k);
Next($g);
}
Header("Content-Type: text/html");
echo "<html><head><title>getoptions</title><script type=\"text/javascript\"><!--\nfunction l()\n{\nparent.".$this->switch_group."_n=[\n".$v."\n];\n}\n// -->\n</script></head><body onload=\"l()\"></body></html>";
$processed=1;
break;
}
default:
return($this->DefaultHandleEvent($form,$event,$parameters,$processed));
}
return("");
}
Function GetInputProperty(&$form, $property, &$value)
{
switch($property)
{
case "SelectedOption":
return($form->GetInputProperty($this->select, $property, $value));
default:
return($this->DefaultGetInputProperty($form, $property, $value));
}
}
Function GetJavascriptInputValue(&$form, $form_object)
{
return($form->GetJavascriptInputValue($form_object, $this->select));
}
};
?>

View file

@ -0,0 +1,422 @@
<?php
/*
*
* @(#) $Id: form_list_select.php,v 1.14 2013/08/12 13:27:48 mlemos Exp $
*
*/
class form_list_select_class extends form_custom_class
{
var $server_validate=0;
var $options = array();
var $name = '';
var $STYLE = 'border-style: solid; border-color: #808080 #ffffff #ffffff #808080; border-width: 1px';
var $CLASS = '';
var $VALUE = '';
var $SIZE;
var $columns = array(
array(
'Type'=>'Input',
),
array(
'Type'=>'Option',
),
);
var $get_selected_option = '';
var $select_all = '';
var $select_all_input = '';
var $multiple = 0;
var $selected = array();
var $select_all_text = 'Select all';
var $accessible;
var $read_only_mark;
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['OPTIONS'])
|| GetType($arguments['OPTIONS'])!='array'
|| count($this->options = $arguments['OPTIONS']) == 0)
return('it were not specified the list select options');
$this->multiple = (IsSet($arguments['MULTIPLE']) && $arguments['MULTIPLE']);
if($this->multiple)
{
$selected = (IsSet($arguments['SELECTED']) ? $arguments['SELECTED'] : array());
if(strcmp(GetType($selected),"array"))
return("it was not defined a valid selected options array");
$this->selected=array();
$ts = count($selected);
for($option = 0; $option < $ts; ++$option)
{
$option_value = $selected[$option];
if(!IsSet($this->options[$option_value]))
return("it specified a selected value that is not a valid option");
if(IsSet($this->selected[$option_value]))
return("it specified a repeated selected option value");
$this->selected[$option_value]=1;
}
$validate_as_set = (IsSet($arguments['ValidateAsSet']) && $arguments['ValidateAsSet']);
$this->select_all = $this->GenerateInputID($form, $this->input, 'sa');
$this->select_all_input = $this->GenerateInputID($form, $this->input, 'select_all');
if(IsSet($arguments['SelectAllText']))
$this->select_all_text = $arguments['SelectAllText'];
if(strlen($error = $form->AddInput(array(
'ID'=>$this->select_all_input,
'TYPE'=>'checkbox',
'ONCHANGE'=>$this->select_all.'(this.form, this.checked);',
'TITLE'=>$this->select_all_text
))))
return($error);
}
else
{
if(!IsSet($arguments['VALUE'])
|| !IsSet($this->options[$this->VALUE = strval($arguments['VALUE'])]))
return('it was not specified a valid list select value');
}
if(IsSet($arguments['Columns'])
&& (GetType($arguments['Columns'])!='array'
|| count($this->columns = $arguments['Columns']) == 0))
return('it was not specified a valid list select columns');
if(IsSet($arguments['Rows']))
{
if(GetType($arguments['Rows'])!='array')
return('it was not specified a valid list select rows');
$this->rows = $arguments['Rows'];
}
if(IsSet($arguments['CLASS']))
$this->CLASS = $arguments['CLASS'];
if(IsSet($arguments['STYLE']))
$this->STYLE = $arguments['STYLE'];
if(IsSet($arguments['SIZE']))
$this->SIZE = $arguments['SIZE'];
$onchange = (IsSet($arguments['ONCHANGE']) ? $arguments['ONCHANGE'] : '');
if(IsSet($arguments['Accessible']))
{
$accessible = $arguments['Accessible'];
}
if(IsSet($arguments['ReadOnlyMark']))
$this->read_only_mark = $arguments['ReadOnlyMark'];
if(IsSet($arguments['OptionReadOnlyMark']))
$read_only_mark = $arguments['OptionReadOnlyMark'];
$this->name = $this->GenerateInputID($form, $this->input, $this->multiple ? 'checkbox' : 'radio');
$to = count($this->options);
for($o = 0, Reset($this->options); $o < $to; Next($this->options), ++$o)
{
$option = Key($this->options);
$a = array(
'NAME'=>$this->name,
'ID'=>$this->name.'_'.$option,
'VALUE'=>$option,
);
if($o == 0)
{
if(IsSet($arguments['LABEL']))
$a['LABEL'] = $arguments['LABEL'];
if(IsSet($arguments['ACCESSKEY']))
$a['ACCESSKEY'] = $arguments['ACCESSKEY'];
}
if($this->multiple)
{
$a['TYPE']='checkbox';
$a['MULTIPLE']=1;
if(IsSet($this->selected[$option]))
$a['CHECKED'] = 1;
if($o == 0
&& $validate_as_set)
{
$a['ValidateAsSet'] = 1;
if(IsSet($arguments['ValidateAsSetErrorMessage']))
$a['ValidateAsSetErrorMessage'] = $arguments['ValidateAsSetErrorMessage'];
if(IsSet($arguments['ValidationErrorMessage']))
$a['ValidationErrorMessage'] = $arguments['ValidationErrorMessage'];
}
}
else
{
$a['TYPE']='radio';
if(!strcmp($option, $this->VALUE))
$a['CHECKED'] = 1;
}
if(strlen($onchange))
$a['ONCHANGE'] = $onchange;
if(IsSet($accessible))
$a['Accessible'] = $accessible;
if(IsSet($read_only_mark))
$a['ReadOnlyMark'] = $read_only_mark;
if(strlen($error = $form->AddInput($a)))
return($error);
}
Reset($this->options);
$this->focus_input = $this->name.'_'.Key($this->options);
return('');
}
Function AddInputPart(&$form)
{
if(IsSet($this->accessible)
&& !$this->accessible
&& IsSet($this->read_only_mark))
return($form->AddDataPart($this->read_only_mark));
$co = $this->columns;
$tc = count($co);
for($start = '', $header = '<tr>', $h = $this->multiple, $i = $c = 0; $c < $tc; ++$c)
{
if(!IsSet($co[$c]['Type']))
return('list select column '.$c.' does not have a type');
$input = $co[$c]['Type'] == 'Input';
if(IsSet($co[$c]['Header']))
{
$header .= '<th>'.$co[$c]['Header'];
$end = '</th>';
$h = 1;
}
else
{
$header .= '<td>';
if(!$this->multiple
|| !$input)
$header .= '&nbsp;';
$end = '</td>';
}
if($input)
{
++$i;
if($this->multiple)
{
$start = $header;
$header = '';
}
}
$header .= $end;
}
if($i == 0)
return('it was not specified any column with type Input');
if($i > 1)
return('it was specified more than one column with type Input');
if(strlen($this->get_selected_option)
|| $this->multiple)
{
$begin = $end = $set = '';
$total = count($this->options);
for($o = 0, Reset($this->options); $o < $total; Next($this->options), ++$o)
{
$option = Key($this->options);
if(strlen($this->get_selected_option))
{
$checked = $form->GetJavascriptCheckedState('f', $this->name.'_'.$option);
if(strlen($checked)==0)
return('could not get Javascript to get the checked state of checkbox');
$begin .= '('.$checked.' ? '.$form->EncodeJavascriptString($option).' : ';
$end.=')';
}
if($this->multiple)
{
$checked = $form->GetJavascriptSetCheckedState('f', $this->name.'_'.$option, 'c');
if(strlen($checked)==0)
return('could not get Javascript to set the checked state of checkbox');
$set .= $checked."\n";
}
}
if(strlen($error = $form->AddDataPart('<script type="text/javascript"><!--'."\n".($this->get_selected_option ? 'function '.$this->get_selected_option.'(f)'."\n".'{'."\n".'return('.$begin.' null'.$end.')'."\n".'}'."\n" : '').($this->multiple ? 'function '.$this->select_all.'(f, c)'."\n".'{'."\n".$set.'}'."\n" : '').'// --></script>'."\n")))
return($error);
}
$to = count($this->options);
if(strlen($error = $form->AddDataPart('<div style="'.(IsSet($this->SIZE) ? 'height: '.$this->SIZE.'em; ' : '').'overflow: auto;'.HtmlSpecialChars($this->STYLE).'"'.(strlen($this->CLASS) ? ' CLASS="'.HtmlSpecialChars($this->CLASS).'"' : '').'><table>')))
return($error);
if($h
&& ((strlen($start)
&& strlen($error = $form->AddDataPart($start)))
|| ($this->multiple
&& strlen($error = $form->AddInputPart($this->select_all_input)))
|| strlen($error = $form->AddDataPart($header.'</tr>'))))
return($error);
for($o = 0, Reset($this->options); $o < $to; Next($this->options), ++$o)
{
if(strlen($error = $form->AddDataPart('<tr>')))
return($error);
$option = Key($this->options);
for($c = 0; $c < $tc; ++$c)
{
if(strlen($error = $form->AddDataPart('<td>')))
return($error);
switch($co[$c]['Type'])
{
case 'Input':
if(strlen($error = $form->AddInputPart($this->name.'_'.$option)))
return($error);
break;
case 'Option':
if(strlen($error = $form->AddDataPart(HtmlSpecialChars($this->options[$option]))))
return($error);
break;
case 'Data':
if(IsSet($co[$c]['Row'])
&& IsSet($this->rows[$option][$row = $co[$c]['Row']])
&& strlen($error = $form->AddDataPart($this->rows[$option][$row])))
return($error);
break;
}
if(strlen($error = $form->AddDataPart('</td>')))
return($error);
}
if(strlen($error = $form->AddDataPart('</tr>')))
return($error);
}
if(strlen($error = $form->AddDataPart('</table></div>')))
return($error);
return('');
}
Function AddInputHiddenPart(&$form)
{
$to = count($this->options);
for($o = 0, Reset($this->options); $o < $to; Next($this->options), ++$o)
{
$option = Key($this->options);
if(strlen($error = $form->AddInputHiddenPart($this->name.'_'.$option)))
return($error);
}
return('');
}
Function GetInputValue(&$form)
{
if($this->multiple)
{
$total = count($this->options);
$selected = array();
for($o = 0, Reset($this->options); $o < $total; Next($this->options), ++$o)
{
$option = Key($this->options);
if($form->GetCheckedState($this->name.'_'.$option))
$selected[] = $option;
}
return($selected);
}
else
return($form->GetCheckedRadioValue($this->name));
}
Function Connect(&$form, $to, $event, $action, &$context)
{
switch($event)
{
case 'ONCHANGE':
$total = count($this->options);
for($o = 0, Reset($this->options); $o < $total; Next($this->options), ++$o)
{
$option = Key($this->options);
if(strlen($error = $form->Connect($this->name.'_'.$option, $to, $event, $action, $context)))
return($error);
}
return('');
}
return($this->DefaultConnect($form, $to, $event, $action, $context));
}
Function GetJavascriptSelectedOption(&$form, $form_object)
{
if(strlen($this->get_selected_option) == 0)
$this->get_selected_option = $this->GenerateInputID($form, $this->input, 'gso');
return($this->get_selected_option.'('.$form_object.')');
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case 'ONCHANGE':
$total = count($this->options);
for($o = 0, Reset($this->options); $o < $total; Next($this->options), ++$o)
{
$option = Key($this->options);
if(strlen($error = $form->SetInputProperty($this->name.'_'.$option, 'ONCHANGE', $value)))
return($error);
}
return('');
case 'VALUE':
if($this->multiple)
{
if(GetType($value) != 'array')
return("it was not defined a valid selected options array");
$options = $this->options;
$tv = count($value);
for($v = 0; $v < $tv; ++$v)
{
$option = $value[$v];
if(!IsSet($options[$option]))
return($option.' is not a valid option to select');
$form->SetCheckedState($this->name.'_'.$option, 1);
UnSet($options[$option]);
}
$tv = count($options);
for(Reset($options), $v = 0; $v < $tv; Next($options), ++$v)
$form->SetCheckedState($this->name.'_'.Key($options), 0);
}
else
{
$old = $this->VALUE;
if(!IsSet($this->options[$this->VALUE = strval($value)]))
return('it was not specified a valid list select value');
if(strlen($error = $form->SetCheckedState($this->name.'_'.$this->VALUE, 1))
|| strlen($error = $form->SetCheckedState($this->name.'_'.$old, 0)))
return($error);
}
return('');
case 'Accessible':
$error = $this->DefaultSetInputProperty($form, $property, $value);
if(strlen($error) == 0)
$this->accessible = IsSet($value) ? intval($value) : $value;
return($error);
case 'ReadOnlyMark':
$this->read_only_mark = $value;
return('');
}
return($this->DefaultSetInputProperty($form, $property, $value));
}
Function LoadInputValues(&$form, $submitted)
{
$value = $this->GetInputValue($form);
if($this->multiple)
{
if($submitted)
{
$selected=array();
$changes=$this->selected;
for($value_key=0, Reset($changes); $value_key<count($changes); Next($changes), $value_key++)
$changes[Key($changes)]=0;
if(GetType($value)=="array")
{
for($value_key=0,Reset($value);$value_key<count($value);Next($value),$value_key++)
{
$entry_value=$value[Key($value)];
if(IsSet($changes[$entry_value]))
Unset($changes[$entry_value]);
else
$changes[$entry_value]=1;
$selected[$entry_value]=1;
}
}
$this->selected = $selected;
if(count($changes)==0)
Unset($form->Changes[$this->input]);
else
$form->Changes[$this->input] = $changes;
}
}
else
{
if(strcmp($this->VALUE, $value))
$form->Changes[$this->input] = $value;
else
Unset($form->Changes[$this->input]);
$this->VALUE = $value;
}
return('');
}
};
?>

View file

@ -0,0 +1,692 @@
<?php
/*
*
* @(#) $Id: form_map_location.php,v 1.30 2012/07/14 08:39:44 mlemos Exp $
*
*/
class form_map_location_class extends form_custom_class
{
var $key = '';
var $style = '';
var $class = '';
var $format = "{map}\n<br />\n<div>{latitudelabel} {latitude} {longitudelabel} {longitude}</div>\n{zoom}\n{maptype}";
var $no_coordinates_format = "{map}\n{latitude}\n{longitude}\n{zoom}\n{maptype}";
var $validation_error_message = 'It was not specified a valid location.';
var $controls=array();
var $clusters=array();
var $markers=array();
var $icons=array();
var $ads_manager = array();
var $server_validate=0;
var $use_focus_input_label = 0;
var $map = '';
var $latitude = '';
var $longitude = '';
var $zoom = '';
var $map_type = '';
var $marker_icon = '';
var $default_marker_icon = '';
var $cluster = '';
var $marker = '';
var $icon = '';
var $setup_marker = '';
var $map_script='';
var $accessible = 1;
var $hide_marker = 0;
var $coordinates = 1;
var $latitude_value = 0.0;
var $longitude_value = 0.0;
var $coordinates_set = 0;
var $zoom_value = 0;
var $zoom_bounds = array();
var $map_type_value = 'Normal';
var $map_types = array(
"Normal"=>"G_NORMAL_MAP",
"Satellite"=>"G_SATELLITE_MAP",
"Hybrid"=>"G_HYBRID_MAP"
);
Function SetLocation(&$form)
{
$eol = $form->end_of_line;
$used_icons = array();
if(strlen($this->marker_icon))
$used_icons[$this->marker_icon] = 0;
$tc = count($this->clusters);
for($markers = '', Reset($this->clusters), $c = 0; $c < $tc; Next($this->clusters), ++$c)
{
$cluster = Key($this->clusters);
$markers.='var '.$this->cluster.'_markers_'.$cluster.'=[];'.$eol;
}
for($marker = 0; $marker<count($this->markers); $marker++)
{
$icon = $this->default_marker_icon;
if(IsSet($this->markers[$marker]['Icon']))
{
$icon = $this->markers[$marker]['Icon'];
if(strlen($icon)
&& $this->icons[$icon])
{
if(!IsSet($used_icons[$icon]))
$used_icons[$icon] = count($used_icons);
}
else
{
$form->OutputError('it was specified an invalid icon ("'.$icon.'") for marker '.$marker, $this->input);
$icon = $this->default_marker_icon;
}
}
elseif(strlen($icon)
&& !IsSet($used_icons[$icon]))
$used_icons[$icon] = count($used_icons);
$options = '';
if(IsSet($this->markers[$marker]['Title']))
$options .= 'title:'.$form->EncodeJavascriptString($this->markers[$marker]['Title']);
if(strlen($icon))
{
if(strlen($options))
$options.=',';
$options .= 'icon:'.$this->icon.$used_icons[$icon];
}
if(IsSet($this->markers[$marker]['Cluster']))
{
$cluster = $this->markers[$marker]['Cluster'];
if(IsSet($this->clusters[$cluster]))
$cl = ',cl:'.$this->cluster.'_markers_'.$cluster;
else
{
$cl = '';
$form->OutputError('it was specified an invalid marker cluster ("'.$cluster.'") for marker '.$marker, $this->input);
}
}
else
$cl = '';
$markers.='var '.$this->marker.$marker.'='.$this->setup_marker.'('.$this->map.',{lt:'.strval($this->markers[$marker]['Latitude']).',ln:'.strval($this->markers[$marker]['Longitude']).(strlen($options) ? ',o:{'.$options.'}' : '').',i:'.$form->EncodeJavascriptString($this->markers[$marker]['Information']).(IsSet($this->markers[$marker]['Link']) ? ',lk:'.$form->EncodeJavascriptString($this->markers[$marker]['Link']) : '').(IsSet($this->markers[$marker]['Target']) ? ',t:'.$form->EncodeJavascriptString($this->markers[$marker]['Target']) : '').$cl.'});'.$eol;
}
$cluster_paths = array();
$tc = count($this->clusters);
for(Reset($this->clusters), $c = 0; $c < $tc; Next($this->clusters), ++$c)
{
$cluster = Key($this->clusters);
$manager = (IsSet($this->clusters[$cluster]['Manager']) ? $this->clusters[$cluster]['Manager'] : 'not specified');
switch($manager)
{
case 'MarkerClusterer':
$markers.='var '.$this->cluster.$cluster.'= new '.$manager.'('.$this->map.', '.$this->cluster.'_markers_'.$cluster.');'.$eol;
$path = 'markerclusterer.js';
break;
default:
$form->OutputError('it was specified an invalid marker cluster manager ("'.$manager.'") for cluster '.$cluster, $this->input);
break;
}
if(IsSet($this->clusters[$cluster]['Path']))
$path = $this->clusters[$cluster]['Path'];
$cluster_paths[$path] = $cluster;
}
$clusters = '';
$tc = count($cluster_paths);
for(Reset($cluster_paths), $c = 0; $c < $tc; Next($cluster_paths), ++$c)
$clusters.='<script src="'.HtmlSpecialChars(Key($cluster_paths)).'" type="text/javascript"></script>'.$eol;
for($icons = '', $i = 0, Reset($used_icons); $i<count($used_icons); Next($used_icons), $i++)
{
$icon = Key($used_icons);
$icons.='var '.$this->icon.$i.'=new GIcon();'.$eol;
for($p = 0, Reset($this->icons[$icon]); $p<count($this->icons[$icon]); ++$p, Next($this->icons[$icon]))
{
$property = Key($this->icons[$icon]);
switch($property)
{
case 'image':
case 'shadow':
case 'printImage':
case 'mozPrintImage':
case 'transparent':
case 'dragCrossImage':
$icons.=$this->icon.$i.'.'.$property.'='.$form->EncodeJavascriptString($this->icons[$icon][$property]).';'.$eol;
break;
case 'iconSize':
case 'shadowSize':
case 'dragCrossSize':
$icons.=$this->icon.$i.'.'.$property.'=new GSize('.$this->icons[$icon][$property][0].','.$this->icons[$icon][$property][1].');'.$eol;
break;
case 'iconAnchor':
case 'infoWindowAnchor':
case 'dragCrossAnchor':
$icons.=$this->icon.$i.'.'.$property.'=new GPoint('.$this->icons[$icon][$property][0].','.$this->icons[$icon][$property][1].');'.$eol;
break;
case 'maxHeight':
$icons.=$this->icon.$i.'.'.$property.'='.$this->icons[$icon][$property].';'.$eol;
break;
case 'imageMap';
$icons.=$this->icon.$i.'.'.$property.'=['.implode(',',$this->icons[$icon][$property]).'];'.$eol;
break;
default:
$form->OutputError('it was specified an unsupported icon property ("'.$property.'")', $this->input);
break;
}
}
}
$this->valid_marks['data']['map'] =
'<div'.(strlen($this->style) ? ' style="'.HtmlSpecialChars($this->style).'"' : '').(strlen($this->style) ? ' class="'.HtmlSpecialChars($this->class).'"' : '').' id="'.$this->map.'"></div>'.$eol;
$this->map_script='<script src="http://maps.google.com/maps?file=api&amp;v=2&amp;key='.HtmlSpecialChars($this->key).'" type="text/javascript"></script>'.$eol.
$clusters.
'<script type="text/javascript">'.$eol.
'// <![CDATA['.$eol.
'var '.$this->map.';'.$eol.
($this->hide_marker ? '' : 'var '.$this->marker.';'.$eol).
'function '.$this->setup_marker.'(map, options)'.$eol.
'{'.$eol.
' var marker=new GMarker(new GLatLng(options.lt, options.ln), options.o ? options.o : null);'.$eol.
' if(options.cl)'.$eol.
' options.cl.push(marker);'.$eol.
' else'.$eol.
' map.addOverlay(marker);'.$eol.
' if(options.i)'.$eol.
' {'.$eol.
' GEvent.addListener(marker, "mouseover", function() { marker.openInfoWindowHtml(options.i); });'.$eol.
' GEvent.addListener(marker, "mouseout", function() { map.closeInfoWindow(); });'.$eol.
' }'.$eol.
' if(options.lk)'.$eol.
' GEvent.addListener(marker, "click", function() { var w; if(!options.t || !(w = window.open(options.lk, options.t)) || !w.top) { window.location=options.lk;}} );'.$eol.
'}'.$eol.
'function '.$this->map.'load()'.$eol.'{'.$eol.'if(GBrowserIsCompatible())'.$eol.'{'.$eol.
$this->map.' = new GMap2(document.getElementById("'.$this->map.'"));'.$eol.
(count($this->controls) ?
(IsSet($this->controls['SmallMap']) ? $this->map.'.addControl(new GSmallMapControl());'.$eol : '').
(IsSet($this->controls['LargeMap']) ? $this->map.'.addControl(new GLargeMapControl());'.$eol : '').
(IsSet($this->controls['SmallZoom']) ? $this->map.'.addControl(new GSmallZoomControl());'.$eol : '').
(IsSet($this->controls['Scale']) ? $this->map.'.addControl(new GScaleControl());'.$eol : '').
(IsSet($this->controls['MapType']) ? $this->map.'.addControl(new GMapTypeControl());'.$eol : '').
(IsSet($this->controls['OverviewMap']) ? $this->map.'.addControl(new GOverviewMapControl());'.$eol : '')
: '').
$this->map.'.setCenter(new GLatLng('.(($this->coordinates_set || count($this->zoom_bounds)!=4) ? $this->latitude_value.', '.$this->longitude_value : (($this->zoom_bounds[0] + $this->zoom_bounds[2])/2).', '.(($this->zoom_bounds[1] + $this->zoom_bounds[3])/2)).'), '.(count($this->zoom_bounds)==4 ? $this->map.'.getBoundsZoomLevel(new GLatLngBounds(new GLatLng('.$this->zoom_bounds[0].','.$this->zoom_bounds[1].'),new GLatLng('.$this->zoom_bounds[2].','.$this->zoom_bounds[3].')))' : $this->zoom_value).');'.$eol.
$this->map.'.setMapType('.$this->map_types[$this->map_type_value].');'.$eol.
'GEvent.addListener('.$this->map.', "click", function(marker, point) { if(marker!=null) return false; c=new GLatLng(point.lat(), point.lng()); '.$this->map.'.panTo(c);'.($this->accessible ? ' l=document.getElementById("'.$this->latitude.'"); l.value=c.lat(); l=document.getElementById("'.$this->longitude.'"); l.value=c.lng();'.(!$this->hide_marker ? ' '.$this->marker.'.setPoint(c);'.($this->coordinates_set ? '' : $this->marker.'.show();') : '') : '').' });'.$eol.
'GEvent.addListener('.$this->map.', "zoomend", function(oldlevel, newlevel) { l=document.getElementById("'.$this->zoom.'"); l.value=newlevel; });'.$eol.
'GEvent.addListener('.$this->map.', "maptypechanged", function() { l=document.getElementById("'.$this->map_type.'"); t='.$this->map.'.getCurrentMapType(); if(t==G_NORMAL_MAP) l.value="Normal"; else { if(t==G_SATELLITE_MAP) l.value="Satellite"; else { if(t==G_HYBRID_MAP) l.value = "Hybrid"; } } });'.$eol.
$icons.
($this->hide_marker ? '' : $this->marker.'=new GMarker('.$this->map.'.getCenter(), { draggable: true '.(strlen($this->marker_icon) ? ', icon: '.$this->icon.$used_icons[$this->marker_icon] : '').' });'.$eol.
'GEvent.addListener('.$this->marker.', "dragend", function(marker) { var point='.$this->marker.'.getPoint(); var c=new GLatLng(point.lat(), point.lng()); '.$this->map.'.panTo(c);'.($this->accessible ? ' l=document.getElementById("'.$this->latitude.'"); l.value=c.lat(); l=document.getElementById("'.$this->longitude.'"); l.value=c.lng();'.(!$this->hide_marker ? ' '.$this->marker.'.setPoint(c);'.($this->coordinates_set ? '' : $this->marker.'.show();') : '') : '').' });'.$eol.
$this->map.'.addOverlay('.$this->marker.');'.$eol).
(($this->hide_marker || $this->coordinates_set) ? '' : $this->marker.'.hide();').
$markers.
(IsSet($this->ads_manager['Publisher']) ?
'(new GAdsManager('.$this->map.', '.$form->EncodeJavascriptString($this->ads_manager['Publisher']).','.$eol.
'{'.$eol.
' style: \'adunit\''.
(IsSet($this->ads_manager['MaxAdsOnMap']) ? ','.$eol.' maxAdsOnMap: '.intval($this->ads_manager['MaxAdsOnMap']) : '').
(IsSet($this->ads_manager['Channel']) ? ','.$eol.' channel: '.$form->EncodeJavascriptString($this->ads_manager['Channel']) : '').
$eol.'}'.$eol.
')).enable()'.$eol
: '').
'}'.$eol.'}'.$eol.'// ]]></script>'.$eol;
return($this->DefaultSetInputProperty($form, 'Format', $this->coordinates ? $this->format : $this->no_coordinates_format));
}
Function GetJavascriptSetInputProperty(&$form, $form_object, $property, $value)
{
switch($property)
{
case "Latitude":
return(($this->coordinates ? $this->latitude.'.value='.$value.';' : '').'c=new GLatLng('.$this->latitude.'.value,'.$this->longitude.'.value);'.$this->map.'.setCenter(c);'.($this->hide_marker ? '' : $this->marker.'.setPoint(c);'.($this->coordinates_set ? '' : $this->marker.'.show();')));
case "Longitude":
return(($this->coordinates ? $this->longitude.'.value='.$value.';' : '').'c=new GLatLng('.$this->latitude.'.value,'.$this->longitude.'.value);'.$this->map.'.setCenter(c);'.($this->hide_marker ? '' : $this->marker.'.setPoint(c);'.($this->coordinates_set ? '' : $this->marker.'.show();')));
}
return("");
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['Key'])
|| strlen($arguments['Key'])==0)
return('it was not specified a valid Google Maps API key');
$this->key = $arguments['Key'];
if(IsSet($arguments['STYLE']))
$this->style = $arguments['STYLE'];
if(IsSet($arguments['CLASS']))
$this->class = $arguments['CLASS'];
if(IsSet($arguments['Latitude']))
{
$this->latitude_value = doubleval($arguments['Latitude']);
if(strcmp($this->latitude_value, $arguments['Latitude'])
|| $this->latitude_value>90.0
|| $this->latitude_value<-90.0)
return('it was not specified a valid latitude value');
$this->longitude_value = 0.0;
$this->coordinates_set = 1;
}
if(IsSet($arguments['Longitude']))
{
$this->longitude_value = doubleval($arguments['Longitude']);
if(strcmp($this->longitude_value, $arguments['Longitude'])
|| $this->longitude_value>180.0
|| $this->longitude_value<-180.0)
return('it was not specified a valid longitude value');
if(!$this->coordinates_set)
{
$this->latitude_value = 0.0;
$this->coordinates_set = 1;
}
}
if(IsSet($arguments['Accessible'])
&& !$arguments['Accessible'])
$this->accessible = 0;
if(IsSet($arguments['HideMarker'])
&& $arguments['HideMarker'])
$this->hide_marker = 1;
if(IsSet($arguments['Icons']))
$this->icons=$arguments['Icons'];
if(IsSet($arguments['MarkerIcon']))
{
$this->marker_icon = $arguments['MarkerIcon'];
if(strlen($this->marker_icon) == 0
|| !IsSet($this->icons[$this->marker_icon]))
return('it was not specified a valid marker icon');
}
if(IsSet($arguments['DefaultMarkerIcon']))
{
$this->default_marker_icon = $arguments['DefaultMarkerIcon'];
if(strlen($this->default_marker_icon) == 0
|| !IsSet($this->icons[$this->default_marker_icon]))
return('it was not specified a valid default marker icon');
}
if(IsSet($arguments['Clusters']))
$this->clusters=$arguments['Clusters'];
if(IsSet($arguments['Markers']))
$this->markers=$arguments['Markers'];
if(IsSet($arguments['ZoomMarkers'])
&& $arguments['ZoomMarkers'])
{
if($this->hide_marker
|| !$this->coordinates_set
|| !$this->accessible)
{
if(count($this->markers)==0)
return('it were not specified any markers to zoom');
$start = 0;
}
else
{
$bounds=array(
$this->latitude_value,
$this->longitude_value,
$this->latitude_value,
$this->longitude_value
);
$start = 1;
}
for($m = 0; $m<count($this->markers); $m++)
{
$latitude = $this->markers[$m]['Latitude'];
$longitude = $this->markers[$m]['Longitude'];
if($latitude<-90
|| $latitude>90
|| $longitude<-180
|| $longitude>180)
return('it was specified a marker with invalid coordinates');
if(!$start)
{
$bounds=array(
$latitude,
$longitude,
$latitude,
$longitude
);
$start = 1;
}
else
{
if($latitude<$bounds[0])
$bounds[0]=$latitude;
elseif($latitude>$bounds[2])
$bounds[2]=$latitude;
if($longitude<$bounds[1])
$bounds[1]=$longitude;
elseif($longitude>$bounds[3])
$bounds[3]=$longitude;
}
}
if($this->hide_marker
|| !$this->coordinates_set
|| !$this->accessible)
{
$this->latitude_value = ($bounds[2]+$bounds[0])/2.0;
$this->longitude_value = ($bounds[3]+$bounds[1])/2.0;
}
if($bounds[0]!=$bounds[2]
|| $bounds[1]!=$bounds[3])
{
if(IsSet($arguments['BoundsOffset']))
{
$o=$arguments['BoundsOffset'];
$bounds[0]=max($bounds[0]-$o, -90);
$bounds[1]=max($bounds[1]-$o, -180);
$bounds[2]=min($bounds[2]+$o, 90);
$bounds[3]=min($bounds[3]+$o, 180);
}
$this->zoom_bounds=$bounds;
}
}
elseif(IsSet($arguments['ZoomBounds']))
{
$bounds=$arguments['ZoomBounds'];
if(count($bounds)!=4
|| $bounds[0]<-90
|| $bounds[0]>=$bounds[2]
|| $bounds[2]>90
|| $bounds[1]<-180
|| $bounds[1]>=$bounds[3]
|| $bounds[3]>180)
return('it were not specified a valid zoom bounds coordinates');
$this->zoom_bounds=$bounds;
}
if(count($this->zoom_bounds)!=4
&& IsSet($arguments['ZoomLevel']))
{
$this->zoom_value = intval($arguments['ZoomLevel']);
if(strcmp($this->zoom_value, $arguments['ZoomLevel'])
|| $this->zoom_value<0)
return('it was not specified a valid zoom level value');
}
if(IsSet($arguments['MapType']))
{
$this->map_type_value = $arguments['MapType'];
if(!IsSet($this->map_types[$this->map_type_value]))
return('it was not specified a valid map type value');
}
if(IsSet($arguments["ValidationErrorMessage"]))
$this->validation_error_message=$arguments["ValidationErrorMessage"];
$this->coordinates=(!IsSet($arguments["Coordinates"]) || $arguments["Coordinates"]);
$this->map = $this->GenerateInputID($form, $this->input, 'map');
$this->latitude = $this->GenerateInputID($form, $this->input, 'latitude');
$this->longitude = $this->GenerateInputID($form, $this->input, 'longitude');
$this->zoom = $this->GenerateInputID($form, $this->input, 'zoom');
$this->map_type = $this->GenerateInputID($form, $this->input, 'map_type');
$this->cluster = $this->GenerateInputID($form, $this->input, 'cluster');
$this->marker = $this->GenerateInputID($form, $this->input, 'marker');
$this->icon = $this->GenerateInputID($form, $this->input, 'icon');
$this->setup_marker = $this->GenerateInputID($form, $this->input, 'sm');
if($this->coordinates)
{
$this->valid_marks = array(
'input'=>array(
'latitude'=>$this->latitude,
'longitude'=>$this->longitude,
'zoom'=>$this->zoom,
'maptype'=>$this->map_type
),
'label'=>array(
'latitudelabel'=>$this->latitude,
'longitudelabel'=>$this->longitude
),
'data'=>array(
'map'=>''
)
);
}
else
{
$this->valid_marks = array(
'input'=>array(
'latitude'=>$this->latitude,
'longitude'=>$this->longitude,
'zoom'=>$this->zoom,
'maptype'=>$this->map_type
),
'data'=>array(
'map'=>''
)
);
}
if($this->coordinates)
{
$input_arguments=array(
"NAME"=>$this->latitude,
"ID"=>$this->latitude,
"TYPE"=>"text",
"SIZE"=>5,
"VALUE"=>($this->coordinates_set ? strval($this->latitude_value) : ''),
"LABEL"=>(IsSet($arguments["LatitudeLabel"]) ? $arguments["LatitudeLabel"] : 'Latitude:'),
"ONCHANGE"=>'if(!isNaN(parseFloat(this.value))) { c='.$this->map.'.getCenter(); '.$this->map.'.setCenter(new GLatLng(parseFloat(this.value), c.lng()));'.(!$this->hide_marker ? ' '.$this->marker.'.setPoint('.$this->map.'.getCenter());'.($this->coordinates_set ? '' : $this->marker.'.show();') : '').' }',
"ValidateAsFloat"=>1,
"ValidationLowerLimit"=>-90.0,
"ValidationUpperLimit"=>90.0,
"ValidationErrorMessage"=>$this->validation_error_message
);
}
else
{
$input_arguments=array(
"NAME"=>$this->latitude,
"ID"=>$this->latitude,
"TYPE"=>"hidden",
"VALUE"=>strval($this->latitude_value),
"ValidateAsFloat"=>1,
"ValidationLowerLimit"=>-180.0,
"ValidationUpperLimit"=>180.0,
"DiscardInvalidValues"=>1,
"ValidateOnlyOnServerSide"=>1
);
}
if(IsSet($arguments["LatitudeClass"]))
$input_arguments["CLASS"]=$arguments["LatitudeClass"];
if(IsSet($arguments["LatitudeStyle"]))
$input_arguments["STYLE"]=$arguments["LatitudeStyle"];
if(IsSet($arguments['DependentValidation']))
$input_arguments['DependentValidation'] = $arguments['DependentValidation'];
if(strlen($error=$form->AddInput($input_arguments)))
return($error);
if($this->coordinates)
{
$input_arguments=array(
"NAME"=>$this->longitude,
"ID"=>$this->longitude,
"TYPE"=>"text",
"SIZE"=>6,
"VALUE"=>($this->coordinates_set ? strval($this->longitude_value) : ''),
"LABEL"=>(IsSet($arguments["LongitudeLabel"]) ? $arguments["LongitudeLabel"] : 'Longitude:'),
"ONCHANGE"=>'if(!isNaN(parseFloat(this.value))) { c='.$this->map.'.getCenter(); '.$this->map.'.setCenter(new GLatLng(c.lat(), parseFloat(this.value)));'.(!$this->hide_marker ? ' '.$this->marker.'.setPoint('.$this->map.'.getCenter());'.($this->coordinates_set ? '' : $this->marker.'.show();') : '').' }',
"ValidateAsFloat"=>1,
"ValidationLowerLimit"=>-180.0,
"ValidationUpperLimit"=>180.0,
"ValidationErrorMessage"=>$this->validation_error_message
);
}
else
{
$input_arguments=array(
"NAME"=>$this->longitude,
"ID"=>$this->longitude,
"TYPE"=>"hidden",
"VALUE"=>strval($this->longitude_value),
"ValidateAsFloat"=>1,
"ValidationLowerLimit"=>-180.0,
"ValidationUpperLimit"=>180.0,
"DiscardInvalidValues"=>1,
"ValidateOnlyOnServerSide"=>1
);
}
if(IsSet($arguments["LongitudeClass"]))
$input_arguments["CLASS"]=$arguments["LongitudeClass"];
if(IsSet($arguments["LongitudeStyle"]))
$input_arguments["STYLE"]=$arguments["LongitudeStyle"];
if(IsSet($arguments['DependentValidation']))
$input_arguments['DependentValidation'] = $arguments['DependentValidation'];
if(strlen($error=$form->AddInput($input_arguments)))
return($error);
$input_arguments=array(
"NAME"=>$this->zoom,
"ID"=>$this->zoom,
"TYPE"=>"hidden",
"VALUE"=>strval($this->zoom_value),
"ValidateAsInteger"=>1,
"ValidationLowerLimit"=>0,
"DiscardInvalidValues"=>1,
"ValidateOnlyOnServerSide"=>1
);
if(IsSet($arguments['DependentValidation']))
$input_arguments['DependentValidation'] = $arguments['DependentValidation'];
if(strlen($error=$form->AddInput($input_arguments)))
return($error);
$input_arguments=array(
"NAME"=>$this->map_type,
"ID"=>$this->map_type,
"TYPE"=>"hidden",
"VALUE"=>strval($this->map_type_value)
);
if(strlen($error=$form->AddInput($input_arguments)))
return($error);
if(IsSet($arguments['Controls']))
$this->controls=$arguments['Controls'];
if(IsSet($arguments['AdsManager']))
$this->ads_manager=$arguments['AdsManager'];
if(IsSet($arguments['Format']))
$this->format=$arguments['Format'];
if(IsSet($arguments['NoCoordinatesFormat']))
$this->no_coordinates_format=$arguments['NoCoordinatesFormat'];
return($this->SetLocation($form));
}
Function PageHead(&$form)
{
return($this->map_script);
}
Function PageLoad(&$form)
{
return($this->map.'load();');
}
Function PageUnload(&$form)
{
return('GUnload();');
}
Function GetInputProperty(&$form, $property, &$value)
{
switch($property)
{
case 'Latitude':
$value = $form->GetInputValue($this->latitude);
if(strlen($value))
$value = min(max(-90, doubleval($value)), 90);
break;
case 'Longitude':
$value = $form->GetInputValue($this->longitude);
if(strlen($value))
$value = min(max(-180, doubleval($value)), 180);
break;
default:
return($this->DefaultGetInputProperty($form, $property, $value));
}
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case 'Latitude':
if($this->latitude_value != $value)
{
$this->latitude_value = doubleval($value);
$form->SetInputValue($this->latitude, strval($this->latitude_value));
$this->SetLocation($form);
}
break;
case 'Longitude':
if($this->longitude_value != $value)
{
$this->longitude_value = doubleval($value);
$form->SetInputValue($this->longitude, strval($this->longitude_value));
$this->SetLocation($form);
}
break;
case "Accessible":
return($this->DefaultSetInputProperty($form, $property, $value));
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
Function LoadInputValues(&$form, $submitted)
{
$latitude = $form->GetInputValue($this->latitude);
$longitude = $form->GetInputValue($this->longitude);
$zoom = intval($form->GetInputValue($this->zoom));
$map_type = $form->GetInputValue($this->map_type);
if(!IsSet($this->map_types[$map_type]))
$map_type = $this->map_type_value;
if(IsSet($form->Changes[$this->latitude])
|| IsSet($form->Changes[$this->longitude])
|| IsSet($form->Changes[$this->zoom])
|| IsSet($form->Changes[$this->map_type]))
{
if(IsSet($form->Changes[$this->latitude]))
{
$form->Changes[$this->input] = $form->Changes[$this->latitude];
UnSet($form->Changes[$this->latitude]);
}
if(IsSet($form->Changes[$this->longitude]))
{
$form->Changes[$this->input] = $form->Changes[$this->longitude];
UnSet($form->Changes[$this->longitude]);
}
if(IsSet($form->Changes[$this->zoom]))
UnSet($form->Changes[$this->zoom]);
if(IsSet($form->Changes[$this->map_type]))
UnSet($form->Changes[$this->map_type]);
if(strlen($latitude))
$latitude = min(max(-90, doubleval($latitude)), 90);
if(strlen($longitude))
$longitude = min(max(-180, doubleval($longitude)), 180);
if(strlen($latitude)
&& strlen($longitude))
$this->coordinates_set = 1;
$this->latitude_value = $latitude;
$this->longitude_value = $longitude;
$this->zoom_value = $zoom;
$this->map_type_value = $map_type;
$this->SetLocation($form);
}
return('');
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'LocateAddress':
if(!IsSet($context['Address'])
|| strlen($address = $form->GetJavascriptInputValue($form_object, $context['Address'])) == 0)
return('it was not specified a valid address input for LocateAddress action');
if(IsSet($context['Country']))
{
if(strlen($country = $form->GetJavascriptInputValue($form_object, $context['Country'])) == 0)
return('it was not specified a valid country input for LocateAddress action');
if(IsSet($context['CountryValue'])
&& $context['CountryValue'] == "SelectedOption")
{
if(strlen($country_name = $form->GetJavascriptSelectedOption($form_object, $context['Country'])) == 0)
return('it was not specified a valid country select input for LocateAddress action');
$address .= ' + ", " + '.$country_name;
}
else
$address .= ' + ", " + c';
}
else
$country = '';
$javascript='var g = new GClientGeocoder();'.(strlen($country) ? ' var c = '.$country.'; if(c.length == 2) g.setBaseCountryCode(c);' : '').' g.getLatLng('.$address.', function(c) { if(c) { '.$this->map.'.setCenter(c); '.($this->hide_marker ? '' : $this->marker.'.setPoint(c);'.($this->coordinates_set ? '' : $this->marker.'.show();')).' '.($this->coordinates ? $this->longitude.'.value=c.lng();'.$this->latitude.'.value=c.lat();' : '').'} } );';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
};
?>

View file

@ -0,0 +1,64 @@
<?php
/*
*
* @(#) $Id: form_mdb2_auto_complete.php,v 1.1 2006/07/17 07:26:36 mlemos Exp $
*
*/
class form_mdb2_auto_complete_class extends form_auto_complete_class
{
var $connection=0;
var $complete_values_query='';
var $complete_expression='';
var $complete_values_limit=0;
Function GetCompleteValues(&$form, $arguments)
{
if(!IsSet($arguments['Connection'])
|| !$arguments['Connection'])
return('it was not specified the database connection');
$this->connection=$arguments['Connection'];
$this->connection->loadModule('Datatype');
if(!IsSet($arguments['CompleteValuesQuery'])
|| strlen($this->complete_values_query=$arguments['CompleteValuesQuery'])==0)
return('it was not specified valid complete values query');
if(!IsSet($arguments['CompleteValuesLimit'])
|| ($this->complete_values_limit=$arguments['CompleteValuesLimit'])<0)
return('it was not specified valid complete values limit');
return('');
}
Function FormatCompleteValue($result)
{
return(HtmlSpecialChars($result[0]));
}
Function SearchCompleteValues(&$form, $text, &$found)
{
$error='';
$found=array();
$complete_expression=$this->connection->datatype->matchPattern(array($text, '%'), 'LIKE');
if(PEAR::isError($complete_expression))
return('it was not possible to build the complete query expression: '.$complete_expression->getMessage().' - '.$complete_expression->getUserinfo());
$complete_expression= $complete_expression;
if(!strcmp($complete_values_query=str_replace('{BEGINSWITH}', $complete_expression, $this->complete_values_query), $this->complete_values_query))
return('the complete values query does not contain the {BEGINSWITH} mark to insert the complete expression');
if(strlen($text)
&& $this->complete_values_limit)
$this->connection->setLimit($this->complete_values_limit, 0);
$r=$this->connection->query($complete_values_query);
if(!PEAR::isError($r))
{
while(($d = $r->fetchRow()))
{
$found[$d[0]]=$this->FormatCompleteValue($d);
}
$r->free();
}
else
$error='Complete values query execution failed: '.$r->getMessage().' - '.$r->getUserinfo();
return($error);
}
};
?>

View file

@ -0,0 +1,96 @@
<?php
/*
* form_mdb2_linked_select.php
*
* @(#) $Id: form_mdb2_linked_select.php,v 1.1 2006/01/16 16:43:10 mlemos Exp $
*
*/
class form_mdb2_linked_select_class extends form_linked_select_class
{
var $connection = 0;
var $groups_query = '';
var $options_statement = 0;
var $default_option;
var $default_option_value;
function GetGroupOptions(&$o, $group)
{
$o = array();
if (isset($this->default_option)) {
$o[$this->default_option] = $this->default_option_value;
}
$result =& $this->options_statement->execute(array($group));
$error = '';
if (PEAR::isError($result)) {
$error="Options query execution failed: ".$result->getMessage();
} else {
$data = $result->fetchAll(MDB2_FETCHMODE_ORDERED, true, false);
if (PEAR::isError($data)) {
$data = $result->getMessage();
} else {
$o+= $data;
}
if (count($o) == 0) {
$error = "there are no options for group $group";
}
}
$result->free();
if (strlen($error)) {
unset($o);
}
return $error;
}
function GetGroups(&$g)
{
if (strlen($this->groups_query) == 0) {
return("it was not specified a valid query to retrieve all the options groups");
}
$g = array();
if (isset($this->default_option)) {
$g[] = $this->default_option;
}
$error = '';
$data = $this->connection->queryCol($this->groups_query);
if (PEAR::isError($data)) {
$error="Groups query execution failed: ".$data->getMessage();
} else {
$g+= $data;
if(count($g) == 0) {
$error="there are no group options";
}
}
if (strlen($error)) {
unset($g);
}
return $error;
}
function ValidateGroups(&$arguments)
{
if (!isset($arguments["Connection"]) || !$arguments["Connection"]) {
return "it was not specified the database connection";
}
$this->connection =& $arguments["Connection"];
if (isset($arguments["GroupsQuery"])) {
$this->groups_query = $arguments["GroupsQuery"];
}
if (!isset($arguments["OptionsQuery"])) {
return "it was not specified the query to retrieve the options";
}
$this->options_statement =& $this->connection->prepare($arguments["OptionsQuery"], array('text'));
if (PEAR::isError($this->options_statement)) {
return "Options query preparation failed: ".$this->options_statement->getMessage();
}
if (isset($arguments["DefaultOption"])) {
$this->default_option = $arguments["DefaultOption"];
if (isset($arguments["DefaultOptionValue"])) {
$this->default_option_value = $arguments["DefaultOptionValue"];
}
}
return "";
}
};
?>

View file

@ -0,0 +1,65 @@
<?php
/*
*
* @(#) $Id: form_metabase_auto_complete.php,v 1.1 2006/07/12 00:35:06 mlemos Exp $
*
*/
class form_metabase_auto_complete_class extends form_auto_complete_class
{
var $connection=0;
var $complete_values_query='';
var $complete_expression='';
var $complete_values_limit=0;
Function GetCompleteValues(&$form, $arguments)
{
if(!IsSet($arguments['Connection'])
|| !$arguments['Connection'])
return('it was not specified the database connection');
$this->connection=$arguments['Connection'];
if(!IsSet($arguments['CompleteValuesQuery'])
|| strlen($this->complete_values_query=$arguments['CompleteValuesQuery'])==0)
return('it was not specified valid complete values query');
if(!IsSet($arguments['CompleteValuesLimit'])
|| ($this->complete_values_limit=$arguments['CompleteValuesLimit'])<0)
return('it was not specified valid complete values limit');
return('');
}
Function FormatCompleteValue($result)
{
return(HtmlSpecialChars($result[0]));
}
Function SearchCompleteValues(&$form, $text, &$found)
{
$error='';
$found=array();
if(strlen($complete_expression=MetabaseBeginsWith($this->connection, $text))==0)
return('it was not possible to build the complete query expression: '.MetabaseError($this->connection));
if(!strcmp($complete_values_query=str_replace('{BEGINSWITH}', $complete_expression, $this->complete_values_query), $this->complete_values_query))
return('the complete values query does not contain the {BEGINSWITH} mark to insert the complete expression');
if(strlen($text)
&& $this->complete_values_limit)
MetabaseSetSelectedRowRange($this->connection, 0, $this->complete_values_limit);
if(($r=MetabaseQuery($this->connection, $complete_values_query)))
{
for($l=0; !MetabaseEndOfResult($this->connection, $r); $l++)
{
if(!MetabaseFetchResultArray($this->connection, $r, $d, $l))
{
$error='Could not retrieve the complete values: '.MetabaseError($this->connection);
break;
}
$found[$d[0]]=$this->FormatCompleteValue($d);
}
MetabaseFreeResult($this->connection, $r);
}
else
$error='Complete values query execution failed: '.MetabaseError($this->connection);
return($error);
}
};
?>

View file

@ -0,0 +1,101 @@
<?php
/*
* form_metabase_linked_select.php
*
* @(#) $Id: form_metabase_linked_select.php,v 1.4 2006/01/02 01:14:11 mlemos Exp $
*
*/
class form_metabase_linked_select_class extends form_linked_select_class
{
var $connection=0;
var $groups_query="";
var $options_statement=0;
var $default_option;
var $default_option_value;
var $default_dynamic=1;
Function GetGroupOptions(&$o,$group)
{
$o=array();
if(IsSet($this->default_option))
$o[$this->default_option]=$this->default_option_value;
$error="";
MetabaseQuerySetText($this->connection, $this->options_statement, 1, $group);
if(($r=MetabaseExecuteQuery($this->connection, $this->options_statement)))
{
for($l=0; !MetabaseEndOfResult($this->connection, $r); $l++)
{
if(!MetabaseFetchResultArray($this->connection, $r, $d, $l))
{
$error="Could not retrieve the group ".$group." options: ".MetabaseError($this->connection);
break;
}
$o[$d[0]]=$d[1];
}
if(count($o)==0
&& strlen($error)==0)
$error="there are no options for group ".$group;
MetabaseFreeResult($this->connection, $r);
}
else
$error="Options query execution failed: ".MetabaseError($this->connection);
if(strlen($error))
UnSet($o);
return($error);
}
Function GetGroups(&$g)
{
if(strlen($this->groups_query)==0)
return("it was not specified a valid query to retrieve all the options groups");
$g=array();
if(IsSet($this->default_option))
$g[]=$this->default_option;
$error="";
if(($r=MetabaseQuery($this->connection, $this->groups_query)))
{
for($l=0; !MetabaseEndOfResult($this->connection, $r); $l++)
{
if(!MetabaseFetchResultArray($this->connection, $r, $d, $l))
{
$error="Could not retrieve the options group: ".MetabaseError($this->connection);
break;
}
$g[]=$d[0];
}
if(count($g)==0
&& strlen($error)==0)
$error="there are no group options";
MetabaseFreeResult($this->connection, $r);
}
else
$error="Groups query execution failed: ".MetabaseError($this->connection);
if(strlen($error))
UnSet($g);
return($error);
}
Function ValidateGroups(&$arguments)
{
if(!IsSet($arguments["Connection"])
|| !$arguments["Connection"])
return("it was not specified the database connection");
$this->connection=$arguments["Connection"];
if(IsSet($arguments["GroupsQuery"]))
$this->groups_query=$arguments["GroupsQuery"];
if(!IsSet($arguments["OptionsQuery"]))
return("it was not specified the query to retrieve the options");
if(!($this->options_statement=MetabasePrepareQuery($this->connection, $arguments["OptionsQuery"])))
return("Options query preparation failed: ".MetabaseError($this->connection));
if(IsSet($arguments["DefaultOption"]))
{
$this->default_option=$arguments["DefaultOption"];
if(IsSet($arguments["DefaultOptionValue"]))
$this->default_option_value=$arguments["DefaultOptionValue"];
}
return("");
}
};
?>

View file

@ -0,0 +1,57 @@
<?php
/*
*
* @(#) $Id: form_mysql_auto_complete.php,v 1.2 2006/12/20 06:05:52 mlemos Exp $
*
*/
class form_mysql_auto_complete_class extends form_auto_complete_class
{
var $connection=0;
var $complete_values_query='';
var $complete_expression='';
var $complete_values_limit=0;
Function GetCompleteValues(&$form, $arguments)
{
if(!IsSet($arguments['Connection'])
|| !$arguments['Connection'])
return('it was not specified the database connection');
$this->connection=$arguments['Connection'];
if(!IsSet($arguments['CompleteValuesQuery'])
|| strlen($this->complete_values_query=$arguments['CompleteValuesQuery'])==0)
return('it was not specified valid complete values query');
if(!IsSet($arguments['CompleteValuesLimit'])
|| ($this->complete_values_limit=$arguments['CompleteValuesLimit'])<0)
return('it was not specified valid complete values limit');
return('');
}
Function FormatCompleteValue($result)
{
return(HtmlSpecialChars($result[0]));
}
Function SearchCompleteValues(&$form, $text, &$found)
{
$error='';
$found=array();
$complete_expression="LIKE '".str_replace("_", "\\_", str_replace("%", "\\%", str_replace("'", "\\'", $text)))."%'";
if(!strcmp($complete_values_query=str_replace('{BEGINSWITH}', $complete_expression, $this->complete_values_query), $this->complete_values_query))
return('the complete values query does not contain the {BEGINSWITH} mark to insert the complete expression');
if(strlen($text)
&& $this->complete_values_limit)
$complete_values_query.=' LIMIT 0, '.$this->complete_values_limit;
if(($r=@mysql_query($complete_values_query, $this->connection)))
{
while(($d=@mysql_fetch_array($r)))
$found[$d[0]]=$this->FormatCompleteValue($d);
mysql_free_result($r);
}
else
$error='Complete values query execution failed: '.@mysql_error($this->connection);
return($error);
}
};
?>

View file

@ -0,0 +1,88 @@
<?php
/*
* form_mysql_linked_select.php
*
* @(#) $Id: form_mysql_linked_select.php,v 1.4 2006/01/02 01:14:11 mlemos Exp $
*
*/
class form_mysql_linked_select_class extends form_linked_select_class
{
var $connection=0;
var $groups_query="";
var $options_query="";
var $default_option;
var $default_option_value;
var $default_dynamic=1;
Function GetGroupOptions(&$o,$group)
{
$o=array();
if(IsSet($this->default_option))
$o[$this->default_option]=$this->default_option_value;
$error="";
$g=str_replace("'","\\'",str_replace("\\","\\\\",$group));
$query=str_replace("{GROUP}", "'".$g."'", $this->options_query);
if(($r=@mysql_query($query,$this->connection)))
{
while(($d=@mysql_fetch_array($r)))
{
$o[$d[0]]=$d[1];
}
if(count($o)==0)
$error="there are no options for group ".$group;
mysql_free_result($r);
}
else
$error="Options query execution failed: ".@mysql_error($this->connection);
if(strlen($error))
UnSet($o);
return($error);
}
Function GetGroups(&$g)
{
if(strlen($this->groups_query)==0)
return("it was not specified a valid query to retrieve all the options groups");
$g=array();
if(IsSet($this->default_option))
$g[]=$this->default_option;
$error="";
if(($r=@mysql_query($this->groups_query,$this->connection)))
{
while(($d=@mysql_fetch_array($r)))
$g[]=$d[0];
if(count($g)==0
&& strlen($error)==0)
$error="there are no group options";
mysql_free_result($r);
}
else
$error="Groups query execution failed: ".@mysql_error($this->connection);
if(strlen($error))
UnSet($g);
return($error);
}
Function ValidateGroups(&$arguments)
{
if(!IsSet($arguments["Connection"])
|| !$arguments["Connection"])
return("it was not specified the database connection");
$this->connection=$arguments["Connection"];
if(IsSet($arguments["GroupsQuery"]))
$this->groups_query=$arguments["GroupsQuery"];
if(!IsSet($arguments["OptionsQuery"]))
return("it was not specified the query to retrieve the options");
$this->options_query=$arguments["OptionsQuery"];
if(IsSet($arguments["DefaultOption"]))
{
$this->default_option=$arguments["DefaultOption"];
if(IsSet($arguments["DefaultOptionValue"]))
$this->default_option_value=$arguments["DefaultOptionValue"];
}
return("");
}
};
?>

View file

@ -0,0 +1,198 @@
<?php
/*
*
* @(#) $Id: form_recaptcha.php,v 1.1 2012/09/16 11:19:33 mlemos Exp $
*
*/
class form_recaptcha_class extends form_custom_class
{
var $format = '<div>{image}</div>
<div>{instructions_visual}{instructions_audio} {input}</div>
<div>{refresh_btn} {visual_challenge}{audio_challenge} {help_btn}</div>';
var $validation_error_message = 'It was not entered the correct text.';
var $key = '';
var $private_key = '';
var $valid = 0;
var $widget = '';
var $challenge = '';
var $response = '';
var $text = array(
'instructions_visual'=>'Enter the words above',
'instructions_audio'=>'Enter the numbers you hear',
'visual_challenge'=>'Enter text in an image instead',
'audio_challenge'=>'Enter numbers you hear instead',
'refresh_btn'=>'Try another',
'help_btn'=>'Help',
'play_again'=>'Play the sound again',
'cant_hear_this'=>'Download the sound as a MP3 file',
'image_alt_text'=>'Image with text to enter'
);
var $tab_index = '';
Function CheckRequirements()
{
if(!class_exists('http_class'))
return('the HTTP class to access the Recaptcha server is not available');
return('');
}
Function AddInput(&$form, $arguments)
{
if(strlen($error = $this->CheckRequirements()))
return($error);
if(!IsSet($arguments['Key'])
|| strlen($arguments['Key']) != 40)
return('it was not specified a valid Recaptcha public key');
$this->key = $arguments['Key'];
if(!IsSet($arguments['PrivateKey'])
|| strlen($arguments['PrivateKey']) != 40)
return('it was not specified a valid Recaptcha private key');
$this->private_key = $arguments['PrivateKey'];
if(IsSet($arguments['ValidationErrorMessage']))
{
if(strlen($arguments['ValidationErrorMessage']))
$this->validation_error_message = $arguments['ValidationErrorMessage'];
else
return('it was not specified a valid validation error message');
}
if(IsSet($arguments['Text']))
{
if(GetType($text = $arguments['Text']) != 'array')
return('it was not specified a valid array with Recaptcha text definitions');
Reset($text);
$tt = count($text);
for($t = 0; $t < $tt; ++$t)
{
$k = Key($text);
if(!IsSet($this->text[$k]))
return($k.' is not a supported reCAPTCHA text definition');
$this->text[$k] = $text[$k];
Next($text);
}
}
Reset($this->text);
$this->widget = $this->GenerateInputID($form, $this->input, 'widget');
$this->challenge = 'recaptcha_challenge_field';
$this->focus_input = $this->response = 'recaptcha_response_field';
$input_arguments = array(
'NAME'=>$this->challenge,
'TYPE'=>'textarea',
'COLS'=>40,
'ROWS'=>3
);
if(strlen($error = $form->AddInput($input_arguments)))
return($error);
$input_arguments = array(
'NAME'=>$this->response,
'ID'=>$this->response,
'TYPE'=>'text',
'ValidateAsNotEmpty'=>1,
'ValidationErrorMessage'=>$this->validation_error_message,
'ONKEYPRESS'=>'return(event.keyCode!=13)'
);
if(IsSet($arguments['DependentValidation']))
$input_arguments['DependentValidation'] = $arguments['DependentValidation'];
if(IsSet($arguments['InputClass']))
$input_arguments['CLASS'] = $arguments['InputClass'];
if(IsSet($arguments['InputStyle']))
$input_arguments['STYLE'] = $arguments['InputStyle'];
if(IsSet($arguments['InputTabIndex']))
$this->tab_index = $input_arguments['TABINDEX'] = $arguments['InputTabIndex'];
if(IsSet($arguments['InputExtraAttributes']))
$input_arguments['ExtraAttributes'] = $arguments['InputExtraAttributes'];
if(strlen($error = $form->AddInput($input_arguments)))
return($error);
if(IsSet($arguments['Format']))
$this->format = $arguments['Format'];
$this->valid_marks = array(
'input'=>array(
'input'=>$this->response,
),
'data'=>array(
'image'=>'<div id="recaptcha_image"></div>',
'instructions_visual'=>'<span class="recaptcha_only_if_image">'.HtmlSpecialChars($this->text['instructions_visual']).'</span>',
'instructions_audio'=>'<span class="recaptcha_only_if_audio">'.HtmlSpecialChars($this->text['instructions_audio']).'</span>',
'refresh_btn'=>'<span><a href="javascript:Recaptcha.reload()">'.HtmlSpecialChars($this->text['refresh_btn']).'</a></span>',
'audio_challenge'=>'<span class="recaptcha_only_if_image"><a href="javascript:Recaptcha.switch_type(\'audio\')">'.HtmlSpecialChars($this->text['audio_challenge']).'</a></span>',
'visual_challenge'=>'<span class="recaptcha_only_if_audio"><a href="javascript:Recaptcha.switch_type(\'image\')">'.HtmlSpecialChars($this->text['visual_challenge']).'</a></span>',
'help_btn'=>'<span><a href="javascript:Recaptcha.showhelp()">'.HtmlSpecialChars($this->text['help_btn']).'</a></span>'
)
);
return '';
}
Function LoadInputValues(&$form, $submitted)
{
if(!$submitted)
return('');
$http = new http_class;
$http->timeout = 60;
$http->data_timeout = 60;
$http->debug = 0;
$http->log_debug = 1;
$http->html_debug = 0;
$error = $http->GetRequestArguments('http://www.google.com/recaptcha/api/verify', $arguments);
$arguments['RequestMethod'] = 'POST';
$arguments['PostValues'] = array(
'privatekey'=>$this->private_key,
'remoteip'=>GetEnv('REMOTE_ADDR'),
'challenge'=>$form->GetInputValue($this->challenge),
'response'=>$form->GetInputValue($this->response),
);
if(strlen($error = $http->Open($arguments)))
return('recaptcha-not-reachable: '.$error);
if(strlen($error = $http->SendRequest($arguments)) == 0)
$error = $http->ReadWholeReplyBody($response);
$http->Close();
if(strlen($error))
return('recaptcha-not-reachable: '.$error);
$this->valid = !strcmp(strtok($response,"\n"), 'true');
if(!$this->valid)
{
switch($error = strtok("\n"))
{
case 'incorrect-captcha-sol':
break;
case 'invalid-site-private-key':
return($error.': the specified reCAPTCHA private key is incorrect');
case 'invalid-request-cookie':
return($error.': the reCAPTCHA challenge parameter is corrupted');
case 'recaptcha-not-reachable':
return($error.': it was not possible to access the reCAPTCHA server');
default:
return($error.': not yet supported reCAPTCHA error');
}
}
return('');
}
Function ValidateInput(&$form)
{
return($this->valid ? '' : $this->validation_error_message);
}
Function AddInputPart(&$form)
{
if(strlen($error = $form->AddDataPart('<div id="'.HtmlSpecialChars($this->widget).'" style="display:none">'))
|| ($error = parent::AddInputPart($form))
|| ($error = $form->AddDataPart('</div><script type="text/javascript"><!--
var RecaptchaOptions = {
theme : "custom",
custom_theme_widget: '.$form->EncodeJavaScriptString($this->widget).',
custom_translations: {
play_again: '.$form->EncodeJavaScriptString($this->text['play_again']).',
cant_hear_this: '.$form->EncodeJavaScriptString($this->text['cant_hear_this']).',
image_alt_text: '.$form->EncodeJavaScriptString($this->text['image_alt_text']).'
}'.(strlen($this->tab_index) ? ',
tabindex: '.$form->EncodeJavaScriptString($this->tab_index) : '').'
};
// --></script><script type="text/javascript" src="http://www.google.com/recaptcha/api/challenge?k='.HtmlSpecialChars($this->key).'"></script><noscript><iframe src="http://www.google.com/recaptcha/api/noscript?k='.HtmlSpecialChars($this->key).'" height="300" width="500" frameborder="0"></iframe>'))
|| strlen($error = $form->AddInputPart($this->challenge))
|| strlen($error = $form->AddDataPart('<input type="hidden" name="'.HtmlSpecialChars($this->response).'" value="manual_challenge"></noscript>')))
return($error);
return('');
}
};
?>

File diff suppressed because it is too large Load diff

View file

@ -0,0 +1,148 @@
<?php
/*
*
* @(#) $Id: form_secure_submit.php,v 1.5 2010/08/08 06:23:41 mlemos Exp $
*
*/
class form_secure_submit_class extends form_custom_class
{
var $server_validate=0;
var $key='';
var $validation='';
var $expiry_time=300;
var $expired=0;
var $requirements=array(
"mcrypt_cfb"=>"the mcrypt extension is not available"
);
Function CheckRequirements()
{
Reset($this->requirements);
$end=(GetType($function=Key($this->requirements))!="string");
for(;!$end;)
{
if(!function_exists($function))
return($this->requirements[$function]);
Next($this->requirements);
$end=(GetType($function=Key($this->requirements))!="string");
}
return("");
}
Function EncryptValidation()
{
$encrypt_time=time();
$iv_size=mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$iv=str_repeat(chr(0),$iv_size);
$key_size=mcrypt_get_key_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$salt=substr(md5(rand()),0,2);
$key=$salt.$this->key;
if(strlen($key)>$key_size)
$key=substr($key,0,$key_size);
return(base64_encode(mcrypt_cfb(MCRYPT_3DES,$key,$encrypt_time,MCRYPT_ENCRYPT,$iv)).':'.$salt.$encrypt_time);
}
Function DecryptValidation($encoded)
{
if(GetType($colon=strpos($encoded,':'))!='integer'
|| strlen($encoded)<=$colon+3
|| ($encrypt_time=intval(substr($encoded,$colon+3)))==0
|| $encrypt_time>time()
|| !($encrypted=base64_decode(substr($encoded,0,$colon))))
return('');
$iv_size=mcrypt_get_iv_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$iv=str_repeat(chr(0),$iv_size);
$key_size=mcrypt_get_key_size(MCRYPT_3DES,MCRYPT_MODE_CFB);
$salt=substr($encoded,$colon+1,2);
$key=$salt.$this->key;
if(strlen($key)>$key_size)
$key=substr($key,0,$key_size);
return(mcrypt_cfb(MCRYPT_3DES,$key,$encrypted,MCRYPT_DECRYPT,$iv));
}
Function AddInput(&$form, $arguments)
{
if(!IsSet($arguments['Key'])
|| strlen($arguments['Key'])==0)
return('it was not specified a valid key');
$this->key=$arguments['Key'];
if(IsSet($arguments['ExpiryTime']))
{
if(($this->expiry_time=intval($arguments['ExpiryTime']))<=0)
return('it was not specified a valid expiry time value');
}
if(strlen($error=$this->CheckRequirements()))
return($error);
$submit_arguments=$arguments;
$submit_arguments['TYPE']=(IsSet($arguments['SRC']) ? 'image' : 'submit');
$this->focus_input=$submit_arguments['ID']=$this->GenerateInputID($form, $this->input, 'submit');
$submit_arguments['NAME']=(IsSet($arguments['NAME']) ? $arguments['NAME'] : $this->focus_input);
$submit_arguments['IgnoreAnonymousSubmitCheck']=1;
if(strlen($error=$form->AddInput($submit_arguments)))
return($error);
$this->validation=$this->GenerateInputID($form, $this->input, 'validation');
$arguments=array(
'NAME'=>$this->validation,
'ID'=>$this->validation,
'TYPE'=>'hidden',
'VALUE'=>''
);
return($form->AddInput($arguments));
}
Function AddInputPart(&$form)
{
if(strlen($error=$form->SetInputValue($this->validation, $this->EncryptValidation()))
|| strlen($error=$form->AddInputPart($this->validation)))
return($error);
return($form->AddInputPart($this->focus_input));
}
Function WasSubmitted(&$form, $input='')
{
$name=$form->WasSubmitted($this->focus_input);
if(strcmp($name, $this->focus_input)
|| strcmp(strlen($form->METHOD) ? strtoupper($form->METHOD) : 'POST', Getenv('REQUEST_METHOD')))
return('');
$encoded=$form->GetSubmittedValue($this->validation);
$decrypted=$this->DecryptValidation($encoded);
if(strlen($decrypted)==0)
return('');
$remaining_time=intval($decrypted)+$this->expiry_time-time();
if($remaining_time<0)
{
$this->expired=1;
return('');
}
return($this->input);
}
Function GetInputProperty(&$form, $property, &$value)
{
switch($property)
{
case 'Expired':
$value = $this->expired;
return('');
}
return($this->DefaultGetInputProperty($form, $property, $value));
}
Function SetInputProperty(&$form, $property, $value)
{
switch($property)
{
case "Content":
case "VALUE":
if(strlen($value)==0)
return("it was not specified a valid feedback element identifier");
return($form->SetInputProperty($this->focus_input, $property, $value));
default:
return($this->DefaultSetInputProperty($form, $property, $value));
}
return("");
}
};
?>

View file

@ -0,0 +1,196 @@
<?php
/*
* form_upload_progress.php
*
* @(#) $Id: form_upload_progress.php,v 1.4 2011/03/14 08:38:29 mlemos Exp $
*
*/
class form_upload_progress_class extends form_custom_class
{
var $server_validate=0;
var $upload_identifier='';
var $monitor='';
var $monitor_action='';
var $feedback_element='';
var $feedback_format='{PROGRESS}%';
var $wait_time=10;
var $started = 0;
var $uploaded=0;
var $total=0;
var $remaining=0;
var $average_speed=0;
var $current_speed=0;
var $last_feedback='';
var $start_time=0;
Function AddInput(&$form, $arguments)
{
if(!function_exists('uploadprogress_get_info'))
return('the upload progress extension is not available in this PHP installation');
if(IsSet($arguments['FeedbackElement']))
{
if(strlen($arguments['FeedbackElement'])==0)
return('it was not specified a valid feedback element identifier');
if(IsSet($arguments['FeedbackFormat']))
{
if(strlen($arguments['FeedbackFormat'])==0)
return('it was not specified a valid feedback format');
$this->feedback_format=$arguments['FeedbackFormat'];
}
$this->feedback_element=$arguments['FeedbackElement'];
}
$this->upload_identifier=uniqid($this->input);
$this->monitor=$this->GenerateInputID($form, $this->input, 'monitor');
if(strlen($error=$form->ConnectFormToInput($this->input, 'ONSUBMITTING', 'Monitor', array()))
|| strlen($error=$form->AddInput(array(
'TYPE'=>'hidden',
'ID'=>'UPLOAD_IDENTIFIER',
'NAME'=>'UPLOAD_IDENTIFIER',
'VALUE'=>$this->upload_identifier
)))
|| strlen($error= $form->AddInput(array(
'TYPE'=>'custom',
'NAME'=>$this->monitor,
'ID'=>$this->monitor,
'CustomClass'=>'form_ajax_submit_class',
'TargetInput'=>$this->input,
'ONTIMEOUT'=>''
))))
return($error);
return('');
}
Function AddInputPart(&$form)
{
$context=array(
'Parameters'=>array(
'UPLOAD_IDENTIFIER'=>$this->upload_identifier
),
'RandomParameter'=>'r'
);
if(strlen($error=$form->GetJavascriptConnectionAction('f', $this->input, $this->monitor, 'ONMONITOR', 'Load', $context, $monitor)))
return($error);
$eol=$form->end_of_line;
$javascript='<script type="text/javascript" defer="defer">'.$eol."<!--\n";
$javascript.='function '.$this->input.'_monitor(f)'.$eol.'{'.$eol;
$javascript.=$monitor;
$javascript.='}'.$eol.'// -->'.$eol.'</script>';
if(strlen($error=$form->AddDataPart($javascript))
|| strlen($error=$form->AddInputPart('UPLOAD_IDENTIFIER'))
|| strlen($error=$form->AddInputPart($this->monitor)))
return($error);
return('');
}
Function GetJavascriptConnectionAction(&$form, $form_object, $from, $event, $action, &$context, &$javascript)
{
switch($action)
{
case 'Monitor':
$javascript='window.setTimeout('.$form->EncodeJavascriptString($this->input.'_monitor();').', 10);';
break;
default:
return($this->DefaultGetJavascriptConnectionAction($form, $form_object, $from, $event, $action, $context, $javascript));
}
return('');
}
Function FormatNumber($number)
{
if($number<1024)
return($number);
$number=intval($number/1024);
if($number<1024)
return($number.'K');
$number=intval($number/1024);
if($number<1024)
return($number.'M');
$number=intval($number/1024);
return($number.'G');
}
Function FormatTime($time)
{
if($time<60)
return(sprintf('00:%02d', $time));
if($time<3600)
return(sprintf('00:%02d:%02d', intval($time/60), $time % 60));
return(sprintf('%02d:%02d:%02d', intval($time/3600), intval($time/60) % 60, $time % 60));
}
Function PostMessage(&$form, $message, &$processed)
{
switch($message['Event'])
{
case 'load':
$more=0;
$id=$_REQUEST['UPLOAD_IDENTIFIER'];
if($this->started)
{
$progress=uploadprogress_get_info($id);
if(IsSet($progress))
$more=1;
else
$this->uploaded=$this->total;
}
else
{
if($this->start_time==0)
{
$this->uploaded=$this->total=$this->remaining=$this->average_speed=$this->current_speed=0;
$this->last_feedback='';
$this->start_time=time();
}
$progress=uploadprogress_get_info($id);
if(IsSet($progress))
{
$this->started=1;
$more=1;
}
elseif(time()-$this->start_time<$this->wait_time)
$more=1;
}
$message['Actions']=array();
if(strlen($this->feedback_element))
{
if(IsSet($progress))
{
$this->uploaded=$progress['bytes_uploaded'];
$this->total=$progress['bytes_total'];
$this->remaining=$progress['est_sec'];
$this->average_speed=$progress['speed_average'];
$this->current_speed=$progress['speed_last'];
}
$feedback=($this->total ? str_replace('{PROGRESS}', intval($this->uploaded*100.0/$this->total), str_replace('{ACCURATE_PROGRESS}', $this->uploaded*100.0/$this->total, str_replace('{UPLOADED}', $this->FormatNumber($this->uploaded), str_replace('{TOTAL}', $this->FormatNumber($this->total), str_replace('{REMAINING}', $this->FormatTime($this->remaining), str_replace('{AVERAGE_SPEED}', $this->FormatNumber($this->average_speed), str_replace('{CURRENT_SPEED}', $this->FormatNumber($this->current_speed), $this->feedback_format))))))) : '');
if(strcmp($this->last_feedback, $feedback))
{
$message['Actions'][]=array(
'Action'=>'ReplaceContent',
'Container'=>$this->feedback_element,
'Content'=>$feedback
);
$this->last_feedback=$feedback;
}
}
if($more)
{
$message['Actions'][]=array(
'Action'=>'Wait',
'Time'=>1
);
}
$message['More']=$more;
break;
}
return($form->ReplyMessage($message, $processed));
}
Function LoadInputValues(&$form, $submitted)
{
return($form->SetInputValue('UPLOAD_IDENTIFIER', $this->upload_identifier));
}
};
?>

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

File diff suppressed because it is too large Load diff

Binary file not shown.

After

Width:  |  Height:  |  Size: 825 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

View file

@ -0,0 +1,276 @@
<?xml version="1.0" encoding="ISO-8859-1" ?>
<!--
locations.schema
@(#) $Header: /opt2/ena/metal/forms/locations.schema,v 1.1 2005/12/30 20:48:05 mlemos Exp $
-->
<database>
<name><variable>name</variable></name>
<create><variable>create</variable></create>
<table>
<name>continents</name>
<declaration>
<field> <name>code</name> <type>text</type> <length>2</length> <notnull>1</notnull> <default></default> </field>
<field> <name>name</name> <type>text</type> <length>16</length> <notnull>1</notnull> <default></default> </field>
<primarykey>
<field> <name>code</name> </field>
</primarykey>
</declaration>
<initialization>
<insert>
<field> <name>code</name> <value>na</value> </field>
<field> <name>name</name> <value>North America</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>eu</value> </field>
<field> <name>name</name> <value>Europe</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>sa</value> </field>
<field> <name>name</name> <value>South America</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>as</value> </field>
<field> <name>name</name> <value>Asia</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>oc</value> </field>
<field> <name>name</name> <value>Oceania</value> </field>
</insert>
</initialization>
</table>
<table>
<name>countries</name>
<declaration>
<field> <name>code</name> <type>text</type> <length>2</length> <notnull>1</notnull> <default></default> </field>
<field> <name>name</name> <type>text</type> <length>16</length> <notnull>1</notnull> <default></default> </field>
<field> <name>continent</name> <type>text</type> <length>2</length> <notnull>1</notnull> <default></default> </field>
<primarykey>
<field> <name>code</name> </field>
<field> <name>continent</name> </field>
</primarykey>
</declaration>
<initialization>
<insert>
<field> <name>code</name> <value>us</value> </field>
<field> <name>name</name> <value>United States</value> </field>
<field> <name>continent</name> <value>na</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>ca</value> </field>
<field> <name>name</name> <value>Canada</value> </field>
<field> <name>continent</name> <value>na</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>pt</value> </field>
<field> <name>name</name> <value>Portugal</value> </field>
<field> <name>continent</name> <value>eu</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>de</value> </field>
<field> <name>name</name> <value>Germany</value> </field>
<field> <name>continent</name> <value>eu</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>br</value> </field>
<field> <name>name</name> <value>Brazil</value> </field>
<field> <name>continent</name> <value>sa</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>ar</value> </field>
<field> <name>name</name> <value>Argentina</value> </field>
<field> <name>continent</name> <value>sa</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>jp</value> </field>
<field> <name>name</name> <value>Japan</value> </field>
<field> <name>continent</name> <value>as</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>kr</value> </field>
<field> <name>name</name> <value>Korea</value> </field>
<field> <name>continent</name> <value>as</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>au</value> </field>
<field> <name>name</name> <value>Australia</value> </field>
<field> <name>continent</name> <value>oc</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>nz</value> </field>
<field> <name>name</name> <value>New Zeland</value> </field>
<field> <name>continent</name> <value>oc</value> </field>
</insert>
</initialization>
</table>
<table>
<name>locations</name>
<declaration>
<field> <name>code</name> <type>text</type> <length>2</length> <notnull>1</notnull> <default></default> </field>
<field> <name>name</name> <type>text</type> <length>16</length> <notnull>1</notnull> <default></default> </field>
<field> <name>country</name> <type>text</type> <length>2</length> <notnull>1</notnull> <default></default> </field>
<primarykey>
<field> <name>code</name> </field>
<field> <name>country</name> </field>
</primarykey>
</declaration>
<initialization>
<insert>
<field> <name>code</name> <value>ny</value> </field>
<field> <name>name</name> <value>New York</value> </field>
<field> <name>country</name> <value>us</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>la</value> </field>
<field> <name>name</name> <value>Los Angeles</value> </field>
<field> <name>country</name> <value>us</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>to</value> </field>
<field> <name>name</name> <value>Toronto</value> </field>
<field> <name>country</name> <value>ca</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>mo</value> </field>
<field> <name>name</name> <value>Montréal</value> </field>
<field> <name>country</name> <value>ca</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>li</value> </field>
<field> <name>name</name> <value>Lisbon</value> </field>
<field> <name>country</name> <value>pt</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>av</value> </field>
<field> <name>name</name> <value>Aveiro</value> </field>
<field> <name>country</name> <value>pt</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>fr</value> </field>
<field> <name>name</name> <value>Frankfurt</value> </field>
<field> <name>country</name> <value>de</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>be</value> </field>
<field> <name>name</name> <value>Berlin</value> </field>
<field> <name>country</name> <value>de</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>sa</value> </field>
<field> <name>name</name> <value>São Paulo</value> </field>
<field> <name>country</name> <value>br</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>ri</value> </field>
<field> <name>name</name> <value>Rio de Janeiro</value> </field>
<field> <name>country</name> <value>br</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>bu</value> </field>
<field> <name>name</name> <value>Buenos Aires</value> </field>
<field> <name>country</name> <value>ar</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>ma</value> </field>
<field> <name>name</name> <value>Mar del Plata</value> </field>
<field> <name>country</name> <value>ar</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>to</value> </field>
<field> <name>name</name> <value>Tokio</value> </field>
<field> <name>country</name> <value>jp</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>os</value> </field>
<field> <name>name</name> <value>Osaka</value> </field>
<field> <name>country</name> <value>jp</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>se</value> </field>
<field> <name>name</name> <value>Seoul</value> </field>
<field> <name>country</name> <value>ky</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>yo</value> </field>
<field> <name>name</name> <value>Yosu</value> </field>
<field> <name>country</name> <value>kr</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>sy</value> </field>
<field> <name>name</name> <value>Sydney</value> </field>
<field> <name>country</name> <value>au</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>me</value> </field>
<field> <name>name</name> <value>Melbourne</value> </field>
<field> <name>country</name> <value>au</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>we</value> </field>
<field> <name>name</name> <value>Wellington</value> </field>
<field> <name>country</name> <value>nz</value> </field>
</insert>
<insert>
<field> <name>code</name> <value>au</value> </field>
<field> <name>name</name> <value>Auckland</value> </field>
<field> <name>country</name> <value>nz</value> </field>
</insert>
</initialization>
</table>
</database>

View file

@ -0,0 +1,88 @@
-- MySQL dump 9.09
--
-- Host: localhost Database: locations
---------------------------------------------------------
-- Server version 4.0.15-Max
--
-- Table structure for table `continents`
--
CREATE TABLE continents (
code char(2) NOT NULL default '',
name char(16) NOT NULL default '',
PRIMARY KEY (code)
) TYPE=MyISAM;
--
-- Dumping data for table `continents`
--
INSERT INTO continents VALUES ('na','North America');
INSERT INTO continents VALUES ('eu','Europe');
INSERT INTO continents VALUES ('sa','South America');
INSERT INTO continents VALUES ('as','Asia');
INSERT INTO continents VALUES ('oc','Oceania');
--
-- Table structure for table `countries`
--
CREATE TABLE countries (
code char(2) NOT NULL default '',
name char(16) NOT NULL default '',
continent char(2) NOT NULL default '',
PRIMARY KEY (code,continent)
) TYPE=MyISAM;
--
-- Dumping data for table `countries`
--
INSERT INTO countries VALUES ('us','United States','na');
INSERT INTO countries VALUES ('ca','Canada','na');
INSERT INTO countries VALUES ('pt','Portugal','eu');
INSERT INTO countries VALUES ('de','Germany','eu');
INSERT INTO countries VALUES ('br','Brazil','sa');
INSERT INTO countries VALUES ('ar','Argentina','sa');
INSERT INTO countries VALUES ('jp','Japan','as');
INSERT INTO countries VALUES ('kr','Korea','as');
INSERT INTO countries VALUES ('au','Australia','oc');
INSERT INTO countries VALUES ('nz','New Zeland','oc');
--
-- Table structure for table `locations`
--
CREATE TABLE locations (
code char(2) NOT NULL default '',
name char(16) NOT NULL default '',
country char(2) NOT NULL default '',
PRIMARY KEY (code,country)
) TYPE=MyISAM;
--
-- Dumping data for table `locations`
--
INSERT INTO locations VALUES ('ny','New York','us');
INSERT INTO locations VALUES ('la','Los Angeles','us');
INSERT INTO locations VALUES ('to','Toronto','ca');
INSERT INTO locations VALUES ('mo','Montréal','ca');
INSERT INTO locations VALUES ('li','Lisbon','pt');
INSERT INTO locations VALUES ('av','Aveiro','pt');
INSERT INTO locations VALUES ('fr','Frankfurt','de');
INSERT INTO locations VALUES ('be','Berlin','de');
INSERT INTO locations VALUES ('sa','São Paulo','br');
INSERT INTO locations VALUES ('ri','Rio de Janeiro','br');
INSERT INTO locations VALUES ('bu','Buenos Aires','ar');
INSERT INTO locations VALUES ('ma','Mar del Plata','ar');
INSERT INTO locations VALUES ('to','Tokio','jp');
INSERT INTO locations VALUES ('os','Osaka','jp');
INSERT INTO locations VALUES ('se','Seoul','ky');
INSERT INTO locations VALUES ('yo','Yosu','kr');
INSERT INTO locations VALUES ('sy','Sydney','au');
INSERT INTO locations VALUES ('me','Melbourne','au');
INSERT INTO locations VALUES ('we','Wellington','nz');
INSERT INTO locations VALUES ('au','Auckland','nz');

Binary file not shown.

After

Width:  |  Height:  |  Size: 136 KiB

View file

@ -0,0 +1,735 @@
/**
* @name MarkerClusterer
* @version 1.0
* @author Xiaoxi Wu
* @copyright (c) 2009 Xiaoxi Wu
* @fileoverview
* This javascript library creates and manages per-zoom-level
* clusters for large amounts of markers (hundreds or thousands).
* This library was inspired by the <a href="http://www.maptimize.com">
* Maptimize</a> hosted clustering solution.
* <br /><br/>
* <b>How it works</b>:<br/>
* The <code>MarkerClusterer</code> will group markers into clusters according to
* their distance from a cluster's center. When a marker is added,
* the marker cluster will find a position in all the clusters, and
* if it fails to find one, it will create a new cluster with the marker.
* The number of markers in a cluster will be displayed
* on the cluster marker. When the map viewport changes,
* <code>MarkerClusterer</code> will destroy the clusters in the viewport
* and regroup them into new clusters.
*
*/
/*
* Licensed under the Apache License, Version 2.0 (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.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
/**
* @name MarkerClustererOptions
* @class This class represents optional arguments to the {@link MarkerClusterer}
* constructor.
* @property {Number} [maxZoom] The max zoom level monitored by a
* marker cluster. If not given, the marker cluster assumes the maximum map
* zoom level. When maxZoom is reached or exceeded all markers will be shown
* without cluster.
* @property {Number} [gridSize=60] The grid size of a cluster in pixel. Each
* cluster will be a square. If you want the algorithm to run faster, you can set
* this value larger.
* @property {Array of MarkerStyleOptions} [styles]
* Custom styles for the cluster markers.
* The array should be ordered according to increasing cluster size,
* with the style for the smallest clusters first, and the style for the
* largest clusters last.
*/
/**
* @name MarkerStyleOptions
* @class An array of these is passed into the {@link MarkerClustererOptions}
* styles option.
* @property {String} [url] Image url.
* @property {Number} [height] Image height.
* @property {Number} [height] Image width.
* @property {Array of Number} [opt_anchor] Anchor for label text, like [24, 12].
* If not set, the text will align center and middle.
* @property {String} [opt_textColor="black"] Text color.
*/
/**
* Creates a new MarkerClusterer to cluster markers on the map.
*
* @constructor
* @param {GMap2} map The map that the markers should be added to.
* @param {Array of GMarker} opt_markers Initial set of markers to be clustered.
* @param {MarkerClustererOptions} opt_opts A container for optional arguments.
*/
function MarkerClusterer(map, opt_markers, opt_opts) {
// private members
var clusters_ = [];
var map_ = map;
var maxZoom_ = null;
var me_ = this;
var gridSize_ = 60;
var sizes = [53, 56, 66, 78, 90];
var styles_ = [];
var leftMarkers_ = [];
var mcfn_ = null;
var i = 0;
for (i = 1; i <= 5; ++i) {
styles_.push({
'url': "http://gmaps-utility-library.googlecode.com/svn/trunk/markerclusterer/images/m" + i + ".png",
'height': sizes[i - 1],
'width': sizes[i - 1]
});
}
if (typeof opt_opts === "object" && opt_opts !== null) {
if (typeof opt_opts.gridSize === "number" && opt_opts.gridSize > 0) {
gridSize_ = opt_opts.gridSize;
}
if (typeof opt_opts.maxZoom === "number") {
maxZoom_ = opt_opts.maxZoom;
}
if (typeof opt_opts.styles === "object" && opt_opts.styles !== null && opt_opts.styles.length !== 0) {
styles_ = opt_opts.styles;
}
}
/**
* When we add a marker, the marker may not in the viewport of map, then we don't deal with it, instead
* we add the marker into a array called leftMarkers_. When we reset MarkerClusterer we should add the
* leftMarkers_ into MarkerClusterer.
*/
function addLeftMarkers_() {
if (leftMarkers_.length === 0) {
return;
}
var leftMarkers = [];
for (i = 0; i < leftMarkers_.length; ++i) {
me_.addMarker(leftMarkers_[i], true, null, null, true);
}
leftMarkers_ = leftMarkers;
}
/**
* Get cluster marker images of this marker cluster. Mostly used by {@link Cluster}
* @private
* @return {Array of String}
*/
this.getStyles_ = function () {
return styles_;
};
/**
* Remove all markers from MarkerClusterer.
*/
this.clearMarkers = function () {
for (var i = 0; i < clusters_.length; ++i) {
if (typeof clusters_[i] !== "undefined" && clusters_[i] !== null) {
clusters_[i].clearMarkers();
}
}
clusters_ = [];
leftMarkers_ = [];
GEvent.removeListener(mcfn_);
};
/**
* Check a marker, whether it is in current map viewport.
* @private
* @return {Boolean} if it is in current map viewport
*/
function isMarkerInViewport_(marker) {
return map_.getBounds().containsLatLng(marker.getLatLng());
}
/**
* When reset MarkerClusterer, there will be some markers get out of its cluster.
* These markers should be add to new clusters.
* @param {Array of GMarker} markers Markers to add.
*/
function reAddMarkers_(markers) {
var len = markers.length;
var clusters = [];
for (var i = len - 1; i >= 0; --i) {
me_.addMarker(markers[i].marker, true, markers[i].isAdded, clusters, true);
}
addLeftMarkers_();
}
/**
* Add a marker.
* @private
* @param {GMarker} marker Marker you want to add
* @param {Boolean} opt_isNodraw Whether redraw the cluster contained the marker
* @param {Boolean} opt_isAdded Whether the marker is added to map. Never use it.
* @param {Array of Cluster} opt_clusters Provide a list of clusters, the marker
* cluster will only check these cluster where the marker should join.
*/
this.addMarker = function (marker, opt_isNodraw, opt_isAdded, opt_clusters, opt_isNoCheck) {
if (opt_isNoCheck !== true) {
if (!isMarkerInViewport_(marker)) {
leftMarkers_.push(marker);
return;
}
}
var isAdded = opt_isAdded;
var clusters = opt_clusters;
var pos = map_.fromLatLngToDivPixel(marker.getLatLng());
if (typeof isAdded !== "boolean") {
isAdded = false;
}
if (typeof clusters !== "object" || clusters === null) {
clusters = clusters_;
}
var length = clusters.length;
var cluster = null;
for (var i = length - 1; i >= 0; i--) {
cluster = clusters[i];
var center = cluster.getCenter();
if (center === null) {
continue;
}
center = map_.fromLatLngToDivPixel(center);
// Found a cluster which contains the marker.
if (pos.x >= center.x - gridSize_ && pos.x <= center.x + gridSize_ &&
pos.y >= center.y - gridSize_ && pos.y <= center.y + gridSize_) {
cluster.addMarker({
'isAdded': isAdded,
'marker': marker
});
if (!opt_isNodraw) {
cluster.redraw_();
}
return;
}
}
// No cluster contain the marker, create a new cluster.
cluster = new Cluster(this, map);
cluster.addMarker({
'isAdded': isAdded,
'marker': marker
});
if (!opt_isNodraw) {
cluster.redraw_();
}
// Add this cluster both in clusters provided and clusters_
clusters.push(cluster);
if (clusters !== clusters_) {
clusters_.push(cluster);
}
};
/**
* Remove a marker.
*
* @param {GMarker} marker The marker you want to remove.
*/
this.removeMarker = function (marker) {
for (var i = 0; i < clusters_.length; ++i) {
if (clusters_[i].remove(marker)) {
clusters_[i].redraw_();
return;
}
}
};
/**
* Redraw all clusters in viewport.
*/
this.redraw_ = function () {
var clusters = this.getClustersInViewport_();
for (var i = 0; i < clusters.length; ++i) {
clusters[i].redraw_(true);
}
};
/**
* Get all clusters in viewport.
* @return {Array of Cluster}
*/
this.getClustersInViewport_ = function () {
var clusters = [];
var curBounds = map_.getBounds();
for (var i = 0; i < clusters_.length; i ++) {
if (clusters_[i].isInBounds(curBounds)) {
clusters.push(clusters_[i]);
}
}
return clusters;
};
/**
* Get max zoom level.
* @private
* @return {Number}
*/
this.getMaxZoom_ = function () {
return maxZoom_;
};
/**
* Get map object.
* @private
* @return {GMap2}
*/
this.getMap_ = function () {
return map_;
};
/**
* Get grid size
* @private
* @return {Number}
*/
this.getGridSize_ = function () {
return gridSize_;
};
/**
* Get total number of markers.
* @return {Number}
*/
this.getTotalMarkers = function () {
var result = 0;
for (var i = 0; i < clusters_.length; ++i) {
result += clusters_[i].getTotalMarkers();
}
return result;
};
/**
* Get total number of clusters.
* @return {int}
*/
this.getTotalClusters = function () {
return clusters_.length;
};
/**
* Collect all markers of clusters in viewport and regroup them.
*/
this.resetViewport = function () {
var clusters = this.getClustersInViewport_();
var tmpMarkers = [];
var removed = 0;
for (var i = 0; i < clusters.length; ++i) {
var cluster = clusters[i];
var oldZoom = cluster.getCurrentZoom();
if (oldZoom === null) {
continue;
}
var curZoom = map_.getZoom();
if (curZoom !== oldZoom) {
// If the cluster zoom level changed then destroy the cluster
// and collect its markers.
var mks = cluster.getMarkers();
for (var j = 0; j < mks.length; ++j) {
var newMarker = {
'isAdded': false,
'marker': mks[j].marker
};
tmpMarkers.push(newMarker);
}
cluster.clearMarkers();
removed++;
for (j = 0; j < clusters_.length; ++j) {
if (cluster === clusters_[j]) {
clusters_.splice(j, 1);
}
}
}
}
// Add the markers collected into marker cluster to reset
reAddMarkers_(tmpMarkers);
this.redraw_();
};
/**
* Add a set of markers.
*
* @param {Array of GMarker} markers The markers you want to add.
*/
this.addMarkers = function (markers) {
for (var i = 0; i < markers.length; ++i) {
this.addMarker(markers[i], true);
}
this.redraw_();
};
// initialize
if (typeof opt_markers === "object" && opt_markers !== null) {
this.addMarkers(opt_markers);
}
// when map move end, regroup.
mcfn_ = GEvent.addListener(map_, "moveend", function () {
me_.resetViewport();
});
}
/**
* Create a cluster to collect markers.
* A cluster includes some markers which are in a block of area.
* If there are more than one markers in cluster, the cluster
* will create a {@link ClusterMarker_} and show the total number
* of markers in cluster.
*
* @constructor
* @private
* @param {MarkerClusterer} markerClusterer The marker cluster object
*/
function Cluster(markerClusterer) {
var center_ = null;
var markers_ = [];
var markerClusterer_ = markerClusterer;
var map_ = markerClusterer.getMap_();
var clusterMarker_ = null;
var zoom_ = map_.getZoom();
/**
* Get markers of this cluster.
*
* @return {Array of GMarker}
*/
this.getMarkers = function () {
return markers_;
};
/**
* If this cluster intersects certain bounds.
*
* @param {GLatLngBounds} bounds A bounds to test
* @return {Boolean} Is this cluster intersects the bounds
*/
this.isInBounds = function (bounds) {
if (center_ === null) {
return false;
}
if (!bounds) {
bounds = map_.getBounds();
}
var sw = map_.fromLatLngToDivPixel(bounds.getSouthWest());
var ne = map_.fromLatLngToDivPixel(bounds.getNorthEast());
var centerxy = map_.fromLatLngToDivPixel(center_);
var inViewport = true;
var gridSize = markerClusterer.getGridSize_();
if (zoom_ !== map_.getZoom()) {
var dl = map_.getZoom() - zoom_;
gridSize = Math.pow(2, dl) * gridSize;
}
if (ne.x !== sw.x && (centerxy.x + gridSize < sw.x || centerxy.x - gridSize > ne.x)) {
inViewport = false;
}
if (inViewport && (centerxy.y + gridSize < ne.y || centerxy.y - gridSize > sw.y)) {
inViewport = false;
}
return inViewport;
};
/**
* Get cluster center.
*
* @return {GLatLng}
*/
this.getCenter = function () {
return center_;
};
/**
* Add a marker.
*
* @param {Object} marker An object of marker you want to add:
* {Boolean} isAdded If the marker is added on map.
* {GMarker} marker The marker you want to add.
*/
this.addMarker = function (marker) {
if (center_ === null) {
/*var pos = marker['marker'].getLatLng();
pos = map.fromLatLngToContainerPixel(pos);
pos.x = parseInt(pos.x - pos.x % (GRIDWIDTH * 2) + GRIDWIDTH);
pos.y = parseInt(pos.y - pos.y % (GRIDWIDTH * 2) + GRIDWIDTH);
center = map.fromContainerPixelToLatLng(pos);*/
center_ = marker.marker.getLatLng();
}
markers_.push(marker);
};
/**
* Remove a marker from cluster.
*
* @param {GMarker} marker The marker you want to remove.
* @return {Boolean} Whether find the marker to be removed.
*/
this.removeMarker = function (marker) {
for (var i = 0; i < markers_.length; ++i) {
if (marker === markers_[i].marker) {
if (markers_[i].isAdded) {
map_.removeOverlay(markers_[i].marker);
}
markers_.splice(i, 1);
return true;
}
}
return false;
};
/**
* Get current zoom level of this cluster.
* Note: the cluster zoom level and map zoom level not always the same.
*
* @return {Number}
*/
this.getCurrentZoom = function () {
return zoom_;
};
/**
* Redraw a cluster.
* @private
* @param {Boolean} isForce If redraw by force, no matter if the cluster is
* in viewport.
*/
this.redraw_ = function (isForce) {
if (!isForce && !this.isInBounds()) {
return;
}
// Set cluster zoom level.
zoom_ = map_.getZoom();
var i = 0;
var mz = markerClusterer.getMaxZoom_();
if (mz === null) {
mz = map_.getCurrentMapType().getMaximumResolution();
}
if (zoom_ >= mz || this.getTotalMarkers() === 1) {
// If current zoom level is beyond the max zoom level or the cluster
// have only one marker, the marker(s) in cluster will be showed on map.
for (i = 0; i < markers_.length; ++i) {
if (markers_[i].isAdded) {
if (markers_[i].marker.isHidden()) {
markers_[i].marker.show();
}
} else {
map_.addOverlay(markers_[i].marker);
markers_[i].isAdded = true;
}
}
if (clusterMarker_ !== null) {
clusterMarker_.hide();
}
} else {
// Else add a cluster marker on map to show the number of markers in
// this cluster.
for (i = 0; i < markers_.length; ++i) {
if (markers_[i].isAdded && (!markers_[i].marker.isHidden())) {
markers_[i].marker.hide();
}
}
if (clusterMarker_ === null) {
clusterMarker_ = new ClusterMarker_(center_, this.getTotalMarkers(), markerClusterer_.getStyles_(), markerClusterer_.getGridSize_());
map_.addOverlay(clusterMarker_);
} else {
if (clusterMarker_.isHidden()) {
clusterMarker_.show();
}
clusterMarker_.redraw(true);
}
}
};
/**
* Remove all the markers from this cluster.
*/
this.clearMarkers = function () {
if (clusterMarker_ !== null) {
map_.removeOverlay(clusterMarker_);
}
for (var i = 0; i < markers_.length; ++i) {
if (markers_[i].isAdded) {
map_.removeOverlay(markers_[i].marker);
}
}
markers_ = [];
};
/**
* Get number of markers.
* @return {Number}
*/
this.getTotalMarkers = function () {
return markers_.length;
};
}
/**
* ClusterMarker_ creates a marker that shows the number of markers that
* a cluster contains.
*
* @constructor
* @private
* @param {GLatLng} latlng Marker's lat and lng.
* @param {Number} count Number to show.
* @param {Array of Object} styles The image list to be showed:
* {String} url Image url.
* {Number} height Image height.
* {Number} width Image width.
* {Array of Number} anchor Text anchor of image left and top.
* {String} textColor text color.
* @param {Number} padding Padding of marker center.
*/
function ClusterMarker_(latlng, count, styles, padding) {
var index = 0;
var dv = count;
while (dv !== 0) {
dv = parseInt(dv / 10, 10);
index ++;
}
if (styles.length < index) {
index = styles.length;
}
this.url_ = styles[index - 1].url;
this.height_ = styles[index - 1].height;
this.width_ = styles[index - 1].width;
this.textColor_ = styles[index - 1].opt_textColor;
this.anchor_ = styles[index - 1].opt_anchor;
this.latlng_ = latlng;
this.index_ = index;
this.styles_ = styles;
this.text_ = count;
this.padding_ = padding;
}
ClusterMarker_.prototype = new GOverlay();
/**
* Initialize cluster marker.
* @private
*/
ClusterMarker_.prototype.initialize = function (map) {
this.map_ = map;
var div = document.createElement("div");
var latlng = this.latlng_;
var pos = map.fromLatLngToDivPixel(latlng);
pos.x -= parseInt(this.width_ / 2, 10);
pos.y -= parseInt(this.height_ / 2, 10);
var mstyle = "";
if (document.all) {
mstyle = 'filter:progid:DXImageTransform.Microsoft.AlphaImageLoader(sizingMethod=scale,src="' + this.url_ + '");';
} else {
mstyle = "background:url(" + this.url_ + ");";
}
if (typeof this.anchor_ === "object") {
if (typeof this.anchor_[0] === "number" && this.anchor_[0] > 0 && this.anchor_[0] < this.height_) {
mstyle += 'height:' + (this.height_ - this.anchor_[0]) + 'px;padding-top:' + this.anchor_[0] + 'px;';
} else {
mstyle += 'height:' + this.height_ + 'px;line-height:' + this.height_ + 'px;';
}
if (typeof this.anchor_[1] === "number" && this.anchor_[1] > 0 && this.anchor_[1] < this.width_) {
mstyle += 'width:' + (this.width_ - this.anchor_[1]) + 'px;padding-left:' + this.anchor_[1] + 'px;';
} else {
mstyle += 'width:' + this.width_ + 'px;text-align:center;';
}
} else {
mstyle += 'height:' + this.height_ + 'px;line-height:' + this.height_ + 'px;';
mstyle += 'width:' + this.width_ + 'px;text-align:center;';
}
var txtColor = this.textColor_ ? this.textColor_ : 'black';
div.style.cssText = mstyle + 'cursor:pointer;top:' + pos.y + "px;left:" +
pos.x + "px;color:" + txtColor + ";position:absolute;font-size:11px;" +
'font-family:Arial,sans-serif;font-weight:bold';
div.innerHTML = this.text_;
map.getPane(G_MAP_MAP_PANE).appendChild(div);
var padding = this.padding_;
GEvent.addDomListener(div, "click", function () {
var pos = map.fromLatLngToDivPixel(latlng);
var sw = new GPoint(pos.x - padding, pos.y + padding);
sw = map.fromDivPixelToLatLng(sw);
var ne = new GPoint(pos.x + padding, pos.y - padding);
ne = map.fromDivPixelToLatLng(ne);
var zoom = map.getBoundsZoomLevel(new GLatLngBounds(sw, ne), map.getSize());
map.setCenter(latlng, zoom);
});
this.div_ = div;
};
/**
* Remove this overlay.
* @private
*/
ClusterMarker_.prototype.remove = function () {
this.div_.parentNode.removeChild(this.div_);
};
/**
* Copy this overlay.
* @private
*/
ClusterMarker_.prototype.copy = function () {
return new ClusterMarker_(this.latlng_, this.index_, this.text_, this.styles_, this.padding_);
};
/**
* Redraw this overlay.
* @private
*/
ClusterMarker_.prototype.redraw = function (force) {
if (!force) {
return;
}
var pos = this.map_.fromLatLngToDivPixel(this.latlng_);
pos.x -= parseInt(this.width_ / 2, 10);
pos.y -= parseInt(this.height_ / 2, 10);
this.div_.style.top = pos.y + "px";
this.div_.style.left = pos.x + "px";
};
/**
* Hide this cluster marker.
*/
ClusterMarker_.prototype.hide = function () {
this.div_.style.display = "none";
};
/**
* Show this cluster marker.
*/
ClusterMarker_.prototype.show = function () {
this.div_.style.display = "";
};
/**
* Get whether the cluster marker is hidden.
* @return {Boolean}
*/
ClusterMarker_.prototype.isHidden = function () {
return this.div_.style.display === "none";
};

View file

@ -0,0 +1,381 @@
/*
* md5.jvs 1.0b 27/06/96
*
* Javascript implementation of the RSA Data Security, Inc. MD5
* Message-Digest Algorithm.
*
* Copyright (c) 1996 Henri Torgemane. All Rights Reserved.
*
* Permission to use, copy, modify, and distribute this software
* and its documentation for any purposes and without
* fee is hereby granted provided that this copyright notice
* appears in all copies.
*
* Of course, this soft is provided "as is" without express or implied
* warranty of any kind.
*/
function array(n) {
for(i=0;i<n;i++) this[i]=0;
this.length=n;
}
/* Some basic logical functions had to be rewritten because of a bug in
* Javascript.. Just try to compute 0xffffffff >> 4 with it..
* Of course, these functions are slower than the original would be, but
* at least, they work!
*/
function integer(n) { return n%(0x7fffffff+0x7fffffff+2); }
function shr(a,b) {
a=integer(a);
b=integer(b);
if (a-(0x7fffffff+1)>=0) {
a=a%(0x7fffffff+1);
a=a >> b;
a+=0x40000000>>(b-1);
} else
a=a >> b;
return a;
}
function shl1(a) {
a=a%(0x7fffffff+1);
if (a&0x40000000==0x40000000)
{
a-=0x40000000;
a*=2;
a+=(0x7fffffff+1);
} else
a*=2;
return a;
}
function shl(a,b) {
a=integer(a);
b=integer(b);
for (var i=0;i<b;i++) a=shl1(a);
return a;
}
function and(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-0x7fffffff-1);
var t2=(b-0x7fffffff-1);
if (t1>=0)
if (t2>=0)
return ((t1&t2)+(0x7fffffff+1));
else
return (t1&b);
else
if (t2>=0)
return (a&t2);
else
return (a&b);
}
function or(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-(0x7fffffff+1));
var t2=(b-(0x7fffffff+1));
if (t1>=0)
if (t2>=0)
return ((t1|t2)+(0x7fffffff+1));
else
return ((t1|b)+(0x7fffffff+1));
else
if (t2>=0)
return ((a|t2)+(0x7fffffff+1));
else
return (a|b);
}
function xor(a,b) {
a=integer(a);
b=integer(b);
var t1=(a-(0x7fffffff+1));
var t2=(b-(0x7fffffff+1));
if (t1>=0)
if (t2>=0)
return (t1^t2);
else
return ((t1^b)+(0x7fffffff+1));
else
if (t2>=0)
return ((a^t2)+(0x7fffffff+1));
else
return (a^b);
}
function not(a) {
a=integer(a);
return (0x7fffffff+0x7fffffff+1-a);
}
/* Here begin the real algorithm */
var state = new array(4);
var count = new array(2);
count[0] = 0;
count[1] = 0;
var buffer = new array(64);
var transformBuffer = new array(16);
var digestBits = new array(16);
var S11 = 7;
var S12 = 12;
var S13 = 17;
var S14 = 22;
var S21 = 5;
var S22 = 9;
var S23 = 14;
var S24 = 20;
var S31 = 4;
var S32 = 11;
var S33 = 16;
var S34 = 23;
var S41 = 6;
var S42 = 10;
var S43 = 15;
var S44 = 21;
function F(x,y,z) {
return or(and(x,y),and(not(x),z));
}
function G(x,y,z) {
return or(and(x,z),and(y,not(z)));
}
function H(x,y,z) {
return xor(xor(x,y),z);
}
function I(x,y,z) {
return xor(y ,or(x , not(z)));
}
function rotateLeft(a,n) {
return or(shl(a, n),(shr(a,(32 - n))));
}
function FF(a,b,c,d,x,s,ac) {
a = a+F(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function GG(a,b,c,d,x,s,ac) {
a = a+G(b, c, d) +x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function HH(a,b,c,d,x,s,ac) {
a = a+H(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function II(a,b,c,d,x,s,ac) {
a = a+I(b, c, d) + x + ac;
a = rotateLeft(a, s);
a = a+b;
return a;
}
function transform(buf,offset) {
var a=0, b=0, c=0, d=0;
var x = transformBuffer;
a = state[0];
b = state[1];
c = state[2];
d = state[3];
for (i = 0; i < 16; i++) {
x[i] = and(buf[i*4+offset],0xff);
for (j = 1; j < 4; j++) {
x[i]+=shl(and(buf[i*4+j+offset] ,0xff), j * 8);
}
}
/* Round 1 */
a = FF ( a, b, c, d, x[ 0], S11, 0x576aa479+0x7fffffff); /* 1 */
d = FF ( d, a, b, c, x[ 1], S12, 0x68c7b757+0x7fffffff); /* 2 */
c = FF ( c, d, a, b, x[ 2], S13, 0x242070db); /* 3 */
b = FF ( b, c, d, a, x[ 3], S14, 0x41bdceef+0x7fffffff); /* 4 */
a = FF ( a, b, c, d, x[ 4], S11, 0x757c0fb0+0x7fffffff); /* 5 */
d = FF ( d, a, b, c, x[ 5], S12, 0x4787c62a); /* 6 */
c = FF ( c, d, a, b, x[ 6], S13, 0x28304614+0x7fffffff); /* 7 */
b = FF ( b, c, d, a, x[ 7], S14, 0x7d469502+0x7fffffff); /* 8 */
a = FF ( a, b, c, d, x[ 8], S11, 0x698098d8); /* 9 */
d = FF ( d, a, b, c, x[ 9], S12, 0x0b44f7b0+0x7fffffff); /* 10 */
c = FF ( c, d, a, b, x[10], S13, 0x7fff5bb2+0x7fffffff); /* 11 */
b = FF ( b, c, d, a, x[11], S14, 0x095cd7bf+0x7fffffff); /* 12 */
a = FF ( a, b, c, d, x[12], S11, 0x6b901122); /* 13 */
d = FF ( d, a, b, c, x[13], S12, 0x7d987194+0x7fffffff); /* 14 */
c = FF ( c, d, a, b, x[14], S13, 0x2679438f+0x7fffffff); /* 15 */
b = FF ( b, c, d, a, x[15], S14, 0x49b40821); /* 16 */
/* Round 2 */
a = GG ( a, b, c, d, x[ 1], S21, 0x761e2563+0x7fffffff); /* 17 */
d = GG ( d, a, b, c, x[ 6], S22, 0x4040b341+0x7fffffff); /* 18 */
c = GG ( c, d, a, b, x[11], S23, 0x265e5a51); /* 19 */
b = GG ( b, c, d, a, x[ 0], S24, 0x69b6c7ab+0x7fffffff); /* 20 */
a = GG ( a, b, c, d, x[ 5], S21, 0x562f105e+0x7fffffff); /* 21 */
d = GG ( d, a, b, c, x[10], S22, 0x02441453); /* 22 */
c = GG ( c, d, a, b, x[15], S23, 0x58a1e682+0x7fffffff); /* 23 */
b = GG ( b, c, d, a, x[ 4], S24, 0x67d3fbc9+0x7fffffff); /* 24 */
a = GG ( a, b, c, d, x[ 9], S21, 0x21e1cde6); /* 25 */
d = GG ( d, a, b, c, x[14], S22, 0x433707d7+0x7fffffff); /* 26 */
c = GG ( c, d, a, b, x[ 3], S23, 0x74d50d88+0x7fffffff); /* 27 */
b = GG ( b, c, d, a, x[ 8], S24, 0x455a14ed); /* 28 */
a = GG ( a, b, c, d, x[13], S21, 0x29e3e906+0x7fffffff); /* 29 */
d = GG ( d, a, b, c, x[ 2], S22, 0x7cefa3f9+0x7fffffff); /* 30 */
c = GG ( c, d, a, b, x[ 7], S23, 0x676f02d9); /* 31 */
b = GG ( b, c, d, a, x[12], S24, 0x0d2a4c8b+0x7fffffff); /* 32 */
/* Round 3 */
a = HH ( a, b, c, d, x[ 5], S31, 0x7ffa3943+0x7fffffff); /* 33 */
d = HH ( d, a, b, c, x[ 8], S32, 0x0771f682+0x7fffffff); /* 34 */
c = HH ( c, d, a, b, x[11], S33, 0x6d9d6122); /* 35 */
b = HH ( b, c, d, a, x[14], S34, 0x7de5380d+0x7fffffff); /* 36 */
a = HH ( a, b, c, d, x[ 1], S31, 0x24beea45+0x7fffffff); /* 37 */
d = HH ( d, a, b, c, x[ 4], S32, 0x4bdecfa9); /* 38 */
c = HH ( c, d, a, b, x[ 7], S33, 0x76bb4b61+0x7fffffff); /* 39 */
b = HH ( b, c, d, a, x[10], S34, 0x3ebfbc71+0x7fffffff); /* 40 */
a = HH ( a, b, c, d, x[13], S31, 0x289b7ec6); /* 41 */
d = HH ( d, a, b, c, x[ 0], S32, 0x6aa127fb+0x7fffffff); /* 42 */
c = HH ( c, d, a, b, x[ 3], S33, 0x54ef3086+0x7fffffff); /* 43 */
b = HH ( b, c, d, a, x[ 6], S34, 0x04881d05); /* 44 */
a = HH ( a, b, c, d, x[ 9], S31, 0x59d4d03a+0x7fffffff); /* 45 */
d = HH ( d, a, b, c, x[12], S32, 0x66db99e6+0x7fffffff); /* 46 */
c = HH ( c, d, a, b, x[15], S33, 0x1fa27cf8); /* 47 */
b = HH ( b, c, d, a, x[ 2], S34, 0x44ac5666+0x7fffffff); /* 48 */
/* Round 4 */
a = II ( a, b, c, d, x[ 0], S41, 0x74292245+0x7fffffff); /* 49 */
d = II ( d, a, b, c, x[ 7], S42, 0x432aff97); /* 50 */
c = II ( c, d, a, b, x[14], S43, 0x2b9423a8+0x7fffffff); /* 51 */
b = II ( b, c, d, a, x[ 5], S44, 0x7c93a03a+0x7fffffff); /* 52 */
a = II ( a, b, c, d, x[12], S41, 0x655b59c3); /* 53 */
d = II ( d, a, b, c, x[ 3], S42, 0x0f0ccc93+0x7fffffff); /* 54 */
c = II ( c, d, a, b, x[10], S43, 0x7feff47e+0x7fffffff); /* 55 */
b = II ( b, c, d, a, x[ 1], S44, 0x05845dd2+0x7fffffff); /* 56 */
a = II ( a, b, c, d, x[ 8], S41, 0x6fa87e4f); /* 57 */
d = II ( d, a, b, c, x[15], S42, 0x7e2ce6e1+0x7fffffff); /* 58 */
c = II ( c, d, a, b, x[ 6], S43, 0x23014315+0x7fffffff); /* 59 */
b = II ( b, c, d, a, x[13], S44, 0x4e0811a1); /* 60 */
a = II ( a, b, c, d, x[ 4], S41, 0x77537e83+0x7fffffff); /* 61 */
d = II ( d, a, b, c, x[11], S42, 0x3d3af236+0x7fffffff); /* 62 */
c = II ( c, d, a, b, x[ 2], S43, 0x2ad7d2bb); /* 63 */
b = II ( b, c, d, a, x[ 9], S44, 0x6b86d392+0x7fffffff); /* 64 */
state[0] +=a;
state[1] +=b;
state[2] +=c;
state[3] +=d;
}
function init() {
count[0]=count[1] = 0;
state[0] = 0x67452301;
state[1] = 0x6fcdab8a+0x7fffffff;
state[2] = 0x18badcff+0x7fffffff;
state[3] = 0x10325476;
for (i = 0; i < digestBits.length; i++)
digestBits[i] = 0;
}
function update(b) {
var index,i;
index = and(shr(count[0],3) , 0x3f);
if (count[0]<0x7fffffff+0x7fffffff-6)
count[0] += 8;
else {
count[1]++;
count[0]-=0x7fffffff+0x7fffffff+2;
count[0]+=8;
}
buffer[index] = and(b,0xff);
if (index >= 63) {
transform(buffer, 0);
}
}
function finish() {
var bits = new array(8);
var padding;
var i=0, index=0, padLen=0;
for (i = 0; i < 4; i++) {
bits[i] = and(shr(count[0],(i * 8)), 0xff);
}
for (i = 0; i < 4; i++) {
bits[i+4]=and(shr(count[1],(i * 8)), 0xff);
}
index = and(shr(count[0], 3) ,0x3f);
padLen = (index < 56) ? (56 - index) : (120 - index);
padding = new array(64);
padding[0] = 0x80;
for (i=0;i<padLen;i++)
update(padding[i]);
for (i=0;i<8;i++)
update(bits[i]);
for (i = 0; i < 4; i++) {
for (j = 0; j < 4; j++) {
digestBits[i*4+j] = and(shr(state[i], (j * 8)) , 0xff);
}
}
}
/* End of the MD5 algorithm */
function hexa(n) {
var hexa_h = "0123456789abcdef";
var hexa_c="";
var hexa_m=n;
for (hexa_i=0;hexa_i<8;hexa_i++) {
hexa_c=hexa_h.charAt(Math.abs(hexa_m)%16)+hexa_c;
hexa_m=Math.floor(hexa_m/16);
}
return hexa_c;
}
var ascii="01234567890123456789012345678901" +
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ"+
"[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";
function MD5(entree)
{
var l,s,k,ka,kb,kc,kd;
init();
for (k=0;k<entree.length;k++) {
l=entree.charAt(k);
update(ascii.lastIndexOf(l));
}
finish();
ka=kb=kc=kd=0;
for (i=0;i<4;i++) ka+=shl(digestBits[15-i], (i*8));
for (i=4;i<8;i++) kb+=shl(digestBits[15-i], ((i-4)*8));
for (i=8;i<12;i++) kc+=shl(digestBits[15-i], ((i-8)*8));
for (i=12;i<16;i++) kd+=shl(digestBits[15-i], ((i-12)*8));
s=hexa(kd)+hexa(kc)+hexa(kb)+hexa(ka);
return s;
}
loaded_MD5=true

Binary file not shown.

After

Width:  |  Height:  |  Size: 70 B

Binary file not shown.

After

Width:  |  Height:  |  Size: 177 B

Some files were not shown because too many files have changed in this diff Show more